perf: optimize topk with heap selection, k=1 linear scan, and contiguous fast path - #36
Merged
Merged
Conversation
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.
This PR replaces the O(n log n) full-sort topk algorithm with O(n log k) binary-heap selection for moderate k, an O(n) linear scan for k=1 (greedy sampling), and a zero-copy contiguous fast path that bypasses extract_array allocation. Flank refactoring extracts a shared
is_c_contiguoushelper and adefine_extract_viewmacro to eliminate code duplication.Motivation and Context
topk() was a bottleneck in ML inference pipelines — taking up to 15ms per call (37% of a 40ms model step) while other operations ran in 1-5ms. The algorithm sorted every lane in full (O(n log n)) even when only k=1 or k=50 elements were needed. Additionally, every call allocated and copied the entire array via
extract_arrayregardless of whether the data was already contiguous.For a flat 152k-element array with k=50 (a real downstream sampling scenario), the full sort did ~2.6M comparisons. The heap-based approach does ~152k comparisons — a 17x algorithmic improvement, translating to roughly 18x wall-clock speedup (11.3ms → 0.63ms).
What's Changed
ArrayViewDdirectly from raw pointer instead of calling extract_array, eliminating one full-array allocation and copy per callis_c_contiguoushelper extracted to shared location, replacing 3 duplicate implementationsdefine_extract_viewmacro added — zero-copy immutable view extraction, symmetric with existingdefine_extract_view_muttopk_axis_arm/topk_flat_armmacrosBreaking Changes
None