Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Temporary solution to fix ivf_flat search result wrong when cosine #36

Merged
merged 1 commit into from
Aug 30, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/index/ivf/ivf.cc
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,10 @@ class IvfIndexNode : public IndexNode {
private:
std::unique_ptr<T> index_;
std::shared_ptr<ThreadPool> search_pool_;

// temporary solution to fix IVF_FLAT cosine
mutable bool normalized_ = false;
mutable std::mutex normalize_mtx_;
};

} // namespace knowhere
Expand Down Expand Up @@ -249,6 +253,7 @@ IvfIndexNode<T>::Train(const DataSet& dataset, const Config& cfg) {
if (IsMetricType(base_cfg.metric_type.value(), knowhere::metric::COSINE)) {
if constexpr (!(std::is_same_v<faiss::IndexIVFFlatCC, T>)&&!(std::is_same_v<faiss::IndexScaNN, T>)) {
Normalize(dataset);
normalized_ = true;
}
}

Expand Down Expand Up @@ -408,6 +413,17 @@ IvfIndexNode<T>::Search(const DataSet& dataset, const Config& cfg, const BitsetV
if (is_cosine) {
copied_query = CopyAndNormalizeFloatVec(cur_query, dim);
cur_query = copied_query.get();

// temporary solution to fix IVF_FLAT cosine
if (!normalized_) {
std::lock_guard<std::mutex> lock(normalize_mtx_);
if (!normalized_) {
faiss::IndexIVFFlat* ivf_index = static_cast<faiss::IndexIVFFlat*>(index_.get());
size_t nb = ivf_index->arranged_codes.size() / ivf_index->code_size;
NormalizeVecs((float*)(ivf_index->arranged_codes.data()), nb, dim);
normalized_ = true;
}
}
}
index_->search_without_codes_thread_safe(1, cur_query, k, distances + offset, ids + offset, nprobe,
0, bitset);
Expand Down Expand Up @@ -492,6 +508,17 @@ IvfIndexNode<T>::RangeSearch(const DataSet& dataset, const Config& cfg, const Bi
if (is_cosine) {
copied_query = CopyAndNormalizeFloatVec(cur_query, dim);
cur_query = copied_query.get();

// temporary solution to fix IVF_FLAT cosine
if (!normalized_) {
std::lock_guard<std::mutex> lock(normalize_mtx_);
if (!normalized_) {
faiss::IndexIVFFlat* ivf_index = static_cast<faiss::IndexIVFFlat*>(index_.get());
size_t nb = ivf_index->arranged_codes.size() / ivf_index->code_size;
NormalizeVecs((float*)(ivf_index->arranged_codes.data()), nb, dim);
normalized_ = true;
}
}
}
index_->range_search_without_codes_thread_safe(1, cur_query, radius, &res, index_->nlist, 0,
bitset);
Expand Down
Loading