-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Use nth_element for median computation in IndexLSH #4653
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
base: main
Are you sure you want to change the base?
Conversation
Replace std::sort with std::nth_element for median calculation in IndexLSH training.
|
@limqiying has imported this pull request. If you are a Meta employee, you can view this in D86234669. |
faiss/IndexLSH.cpp
Outdated
| // 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); | ||
| thresholds[i] = (xi[n / 2 - 1] + median_high) / 2; | ||
| } |
There was a problem hiding this comment.
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;
There was a problem hiding this comment.
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!
|
Hi @Ray0907 , thanks for your contribution. Ditto the other perf changes: did you try benchmarking it? Do you observe speedup? If yes, can you paste the script you used here? |
|
I agree that it's the proper way of computing the median but the performance improvement could be minimal. |
| 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); |
There was a problem hiding this comment.
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.
Replace std::sort with std::nth_element for median calculation in
IndexLSH training.