perf(knn): replace argsort+slice with top_k for neighbor search, ~5-9x speedup - #344
Merged
Conversation
Contributor
|
💚 💙 💜 💛 ❤️ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
BruteKNN.brute_force_search/3finds the K nearest neighbors by fully sortingall distances and then slicing the first K:
This is O(N log N) per query — sorting all N distances just to retrieve K.
For N >> K, this is wasteful: the sort comparator runs ~N log N times while
only K elements are ultimately needed.
Solution
Replace with
Nx.top_k/2on negated distances, which selects the K smallestvalues directly using XLA's native
chlo.top_koperator (on EXLA) or ablock-based fallback:
This reduces the complexity from O(N log N) to O(N log K) per query.
Benchmark
BruteKNN.fit/predicton random 64-dimensional float data (EXLA backend),averaged over 5 runs:
Speedup increases with N/K ratio, consistent with the complexity class change.
Benchmark script
Correctness
Nx.top_kreturns indices of the K largest values; negating the distancesconverts "smallest K distances" into "largest K negative distances". The
resulting indices match those from
argsort + slice.Compatibility
This change is transparent:
chlo.top_kXLA operatorargsort + take_along_axis + slice(same complexity as before, no regression for small K)
:u64indices) are preserved viaNx.as_typeAssisted by DeepSeek V4 Flash