Skip to content
Open
Changes from 1 commit
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
14 changes: 9 additions & 5 deletions faiss/IndexLSH.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,16 @@ void IndexLSH::train(idx_t n, const float* x) {

for (idx_t i = 0; i < nbits; i++) {
float* xi = transposed_x.get() + i * n;
// std::nth_element
std::sort(xi, xi + n);
if (n % 2 == 1)
// Use nth_element (O(n)) instead of sort (O(n log n)) for median
if (n % 2 == 1) {
std::nth_element(xi, xi + n / 2, xi + n);
thresholds[i] = xi[n / 2];
else
thresholds[i] = (xi[n / 2 - 1] + xi[n / 2]) / 2;
} else {
std::nth_element(xi, xi + n / 2, xi + n);
float median_high = xi[n / 2];
std::nth_element(xi, xi + n / 2 - 1, xi + n);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good, unless running 2x std::nth_element() is too costly.

thresholds[i] = (xi[n / 2 - 1] + median_high) / 2;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe we can do like this?

// Use nth_element (O(n)) instead of sort (O(n log n)) for median
std::nth_element(xi, xi + n / 2, xi + n);
float median = xi[n / 2];
if (n % 2 == 0) {
    std::nth_element(xi, xi + n / 2 - 1, xi + n);
    median = (median + xi[n / 2 - 1]) / 2;
}
thresholds[i] = median;

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point! Your version is cleaner!

}
}
is_trained = true;
Expand Down
Loading