Repository navigation
mlxvs: CAGRA-style graph search and k-NN graphs on MLX (1M vectors indexed in ~11 s on an M3 Pro) #4872
mikepapadim
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
I've been porting the GPU nearest-neighbor algorithms from NVIDIA's cuVS to MLX, and it's at a point where it's useful, so sharing it here: https://github.com/mikepapadim/mlxvs (
pip install mlxvs).It has exact k-NN, k-means, NN-Descent k-NN graphs, and CAGRA (graph pruning plus graph search), all as
mx.fast.metal_kernelkernels compiled at runtime. The NN-Descent kernels are ported from JVector's Metal backend, the rest is new.Numbers from my M3 Pro (18-core GPU), batches of 10k queries, compared with hnswlib on all 12 CPU cores:
The weak spot is one query at a time: about 0.95 ms on the GPU against 0.21 ms for single-threaded hnswlib, because one query is a long chain of small dependent steps sitting on one threadgroup. Batches of up to ~64 cost about the same as one query, so it does well under load, but for a lone query the CPU wins for now.
A few MLX-specific things I ran into, in case they help someone else (or someone can tell me I'm holding it wrong):
mx.array(numpy_view)keeps the view's strides. If you then pass it to a custom kernel withensure_row_contiguous=True, the whole array gets copied on every call. For a 1M x 128 dataset that was ~9 ms per search call, most of the single-query latency, until I made the NumPy array contiguous first.MTL_SHADER_VALIDATION=1, Metal counts threadgroup memory twice, so a kernel that fits in 32 KB fails validation above 16 KB. I size the search kernel's hash table to stay under 16 KB so CI can run with validation on.Happy to hear about results on other chips (M1/M2/M4, Max/Ultra), since I've only measured on the M3 Pro.
bench/bench_search.pyreproduces the table.All reactions