Repository navigation
Fuse the two WMMA local-join phases in NN-Descent - #2835
maxwbuckley wants to merge 13 commits into
Conversation
…ures Phase 1 (new x new) and phase 2 (new x old) each walked the feature dimension in 128-column tiles, so for dim > 128 every new-vector tile was gathered from global memory twice. Walk the dimension once, loading the new and old tiles per step and accumulating both products into separate fragments. The new x new block is stored once s_ov is dead, the phase-1 metric/insert runs, then the new x old block is stored and phase 2 runs as before. Per-fragment accumulation order is unchanged, so distances are bit-identical. Removes 1/3 of the gather traffic and half the barriers per block at dim 1024; no change at dim <= 128. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. Summary
Merge Risk:
|
sherylll
left a comment
There was a problem hiding this comment.
This looks like a very sensible improvement. Just curious: how did this reduce register usage (even though there are another set of accumulation register)?
Also, the sizes of new/old lists can vary across iterations, new_size grows from 64 towards 0, and old_size the other way around. #2751 added stop guard for each "phase", I wonder if the benefit still holds after incorporating that change.
| wmma::mma_sync(c_frag, a_frag, b_frag, c_frag); | ||
| __syncthreads(); | ||
| wmma::mma_sync(c_nn, a_frag, b_frag, c_nn); | ||
| if (has_old) { |
There was a problem hiding this comment.
I wonder what's the overhead of putting a conditional inside the critical loop. How does it compare to doing it unconditionally (more mma), or a second mma loop (more load_matrix)?
There was a problem hiding this comment.
Good call: the branch inside the k loop cost more than it saved. It compiled to 15 branches and about 2.6× the instructions per k loop, and it was slower than main for fp32 input. Since 4f8ab07 it's two straight-line MMA loops, each behind its own warp guard, reloading a_frag in the second one. That's your "second mma loop" option, and it's the version measured in the PR description.
| wmma::fill_fragment(c_frag, 0.0); | ||
| wmma::fill_fragment(c_nn, 0.0); | ||
| wmma::fill_fragment(c_no, 0.0); | ||
| // s_unique_counter aliases s_ov[0][0]: every thread must have read the list sizes above |
There was a problem hiding this comment.
I think it'd be cleaner to simply update the aliasing strategy. Now that the lifetime of s_ov/s_nv and distances may never overlap, we might create a single arena for all these variables.
NVIDIA#2751 reworked local_join_kernel_wmma (per-k-step barrier moved out of the k loop, per-warp guards). Take main's version of nn_descent.cuh here; the fused join is redone on top of it in the next commit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…MA loops Rework of the fused local join after main gained NVIDIA#2751 (per-warp MMA guards, per-k-step barrier already moved out of the k loop), following review: - One pass over the features: each tile step gathers the new rows and the old rows, so phase 2 no longer re-gathers every new-vector tile. - The new x new and new x old products are two MMA loops per tile, each behind its own NVIDIA#2751 warp guard, instead of a per-accumulator branch inside a single loop. The branchy loop compiled to 15 branches and ~2.6x the instructions per k loop, and was slower than main for fp32 input; the split loops are straight-line and reload a_frag instead. - The new/old tiles and the distance block share one shared-memory arena (their lifetimes never overlap), and s_unique_counter gets its own slot, so the extra barrier the aliasing needed is gone. Output is byte-identical to main (kernel harness, 42 cases, 0 mismatched pairs). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Thanks @sherylll, these were the right questions. Answering them properly meant rebasing onto #2751 and measuring each alternative you suggested, and the result changed the PR. It's now What changed. The fused pass is kept, so each new-vector tile is still gathered once. Within each tile step, though, new×new and new×old are now two separate MMA loops, each behind its #2751 warp guard. That is your "second mma loop" option. The tiles and the distance block also share one arena, with How the variants compare. Everything below is rebased on
Does it hold once #2751's guards are in, as new shrinks and old grows? Yes, with the split loops. Here is the per-iteration
Iteration 1 has no old lists, so there is nothing to share and it costs 1–3%. After that the gain is largest while both lists are substantial. On the device path it tapers off as the new lists shrink, which matches the sweep above. Registers: the reduction I reported came from collapsing the two separately unrolled k loops into one. Peak live registers went from 60 to 47. Moving the barrier alone left the PR's base at 64 registers. On today's
Occupancy stays at 2 blocks/SM, because shared memory is the limit and registers would only matter above 64. So registers aren't where the speedup comes from; avoiding the second gather of the new tiles is. End-to-end, CAGRA and NN-Descent builds with dim > 128 are 2–6% faster in Elastic's configuration, on both input paths. One exception: the cuVS-default config (degree 64/128, 20 iterations) with device input showed no significant change. There is no change at dim ≤ 128, where there is only one tile, and recall is unchanged. The full table is in the description. |
|
/ok to test 979efec |
|
This causes spill when launch bound of 4 is applied. I can have a look later if these are fixable, but time seems a bit tight for this release. Cross-compiled only
The fusion increases spills on all three targets using These are static |
divyegala
left a comment
There was a problem hiding this comment.
@sherylll I have attempted to fuse the 2 MMA passes in some experiments before, and found the fused version to not be performant on H200. I don't have the numbers anymore, but I recommend any such change to be benchmarked across several architectures - and looks like you will do that, I wanted to chime in with my anecdote.
On the arches where local_join_kernel_wmma is built with __launch_bounds__(BLOCK_SIZE, 4) (sm_70/80/90/100), the 32-register budget cannot hold both WMMA accumulators across the fused pass over the features, and ptxas spills (e.g. sm_90 fp32 24/32 -> 148/104 bytes, fp16 0/0 -> 164/240). Compile the original two-phase code there and keep the fused pass only where the kernel has no min-blocks bound. The arch test used by both local-join kernels' launch bounds is factored into CUVS_NN_DESCENT_MIN_BLOCKS_4 so the launch bounds and the code path cannot drift apart. Shared memory is static in both paths, so the host launch is unchanged. The generated SASS for sm_80/90/100 is identical to release/26.12, and for sm_75/86/89/103/120 identical to the fused version. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Thanks @sherylll for the spill report, and @divyegala for the review. Reproducing the spills. I compiled only
Your fp32 numbers reproduce exactly. fp16 input regresses too, and that matters because host fp32 data is downcast to fp16 for this kernel. sm_75/86/89/103/120 have no spills either way. The cause is the 32-register budget from A restructure that didn't work. A single k-loop sharing the A fragment, with the new×old block stored to the free half of the shared arena, cut fp32 spills to 0/0 on sm_80/90 and 4/4 on sm_100. But fp16 on sm_90 still spilled (24/152), and on sm_120 it was 4–12% slower than the fused version for fp32. I don't think that's the right fix. What 3d36a99 does instead: gate the fusion by arch.
Timing on an RTX 5090 (sm_120), kernel ms, base → this PR:
The output graph is identical to base in every case. What I couldn't measure. I have no sm_80/90/100 hardware, so I haven't run anything on A100, H100, H200 or B200. With this change those arches run exactly the base machine code, so the H200 concern no longer applies to this PR. Whether the fusion could pay off there with different launch bounds is a separate question, which would need someone with that hardware. I also haven't rebuilt and run the NN-Descent gtests for this commit. The device code on every arch is byte-identical to one of the two versions that were already tested, and the host code is unchanged. @achirkin could you 🤖 Generated with Claude Code |
|
We could enlarge SMEM usage to store distances earlier: sherylll@4d47c43 . This is safe because occupancy is not SMEM-bound. |
Reviewer measurements on H100 show the fused kernel winning on sm_90 once both products are stored to shared memory (next commit), so every arch uses the fused path again. This reverts commit 3d36a99. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Write new/new and new/old distances after the final feature-loop barrier, then reuse the stored matrices during metric conversion and graph insertion. Both accumulator lifetimes end before the epilogues. SMEM capacity review covered sm_80, sm_86, sm_90, sm_100, sm_103, sm_107, and sm_120 from the architecture matrix, plus the CUDA-table capacity classes sm_70/75/87/89/110/12.x. Two 64x68 float distance matrices reuse the two 64x136 half vector tiles: both occupy 34,816 bytes. The SMEM residency ceiling is unchanged on these architectures; this is capacity analysis, not an architecture-wide register or performance validation. SMEM-only block ceilings stay at 2 on sm_70; 1 on sm_75; 4 on sm_80/87; 2 on sm_86/89/12.x; 6 on sm_90/100/103/110; and 6 on sm_107 (9 with its oversized 328-KiB opt-in). Thread/register limits may be lower. Measured on H100 (sm_90), CUDA 13.3.73, Falcon 1M x 1024 FP32 input with FP16 WMMA, graph degree 64/intermediate 128, 20 iterations, 16 OpenMP threads. Three cooled trials per configuration: Original unfused + bound 4 (485ffcf): join 3.805831s, build 6.712011s. Fused loops + bound 4 + arena: join 3.164726s, build 6.063527s. This reduces join time 16.8% and GNND build time 9.7%; join time is included in build time. Baselines came from separate three-trial batches with brief thermal flags, so these are indicative, not fixed-clock timings. Against the existing fused/bound-4 kernel, static spill stores/loads fall from 148/104 to 112/84 bytes; registers stay at 32/thread, shared memory at 35,344 bytes/block, and predicted residency at four blocks/SM. Validation of this identical kernel body: sm_90 compilation, memcheck and racecheck at both bounds 4/off on 256 Falcon rows for two iterations, and full Falcon sampled recall around 95% with no invalid sampled IDs. Other architectures were reviewed for SMEM capacity only. No V100 runtime or achieved-occupancy claim is made.
|
Thanks @sherylll, that's convincing. I've dropped the arch gate and cherry-picked your commit as is (48d4ce9 reverts the gate, d5ac29d is your 4d47c43), so the PR tree now matches yours exactly. What I checked locally (nvcc 13.2, -O3): Spills of
Your sm_90 fp32 numbers reproduce. Your H100 timings show the spills cost less than the fusion saves there.
RTX 5090 (sm_120), kernel ms, three interleaved rounds, base → previous head → this commit:
So on sm_120 the extra store is neutral, and the output graph is identical to base in every case. I still have no A100 or B200, and they also spill more than base now (sm_80 less than sm_90 does). If anyone can run the same Falcon build on either, that would close the last gap. I haven't run the NN-Descent gtests on this commit locally; CI covers that. @divyegala, this should address the H200 concern from your review: sherylll measured H100 (same CC) 16.8% faster in the join. Could you take another look? @achirkin could you 🤖 Generated with Claude Code |
|
Hi @maxwbuckley I added 3 more commits and opened a PR to your repo: https://github.com/maxwbuckley/cuvs/pull/1/commits (The conflict is probably due to different hash, might be easier to cherry-pick again) TLDR: with the fix The 3 new commits:
Before: original unfused dense WMMA kernel from main at Settings: Falcon 1M × 1024, output degree 64, intermediate degree 128, 20 iterations, 16 OpenMP threads, CUDA 13.3.73. Timings are three-run means on A100 PCIe 40 GB, H100 PCIe 80 GB, B200, and RTX PRO 6000 Blackwell Server Edition 96 GB. Latency
Register usage / occupancy
|
|
Thanks @sherylll, and for the A100/H100/B200/RTX PRO 6000 numbers. I've cherry-picked all three commits from maxwbuckley#1 onto this branch: a6e32fc, c1aed5d and fdef40d. The tree is now identical to your 6627f8e. Review notes
Tests and SASS
RTX 5090 (sm_120), kernel ms, min of 3 rounds (a build was running, so these numbers are approximate). The graph hash is identical across main, the previous head and this head in every case.
One trade-off. Inputs whose rows aren't 8-byte aligned now take the SIMT kernel instead of WMMA with scalar loads. That covers odd fp32 dims, fp16 dims not divisible by 4, and offset pointers. It also covers host fp32 input with dim not divisible by 4, since that input is downcast to fp16, which includes GloVe-50.
Would a @divyegala, this now has measurements from four architectures. Could you take another look? @achirkin, could you 🤖 Generated with Claude Code |
|
Follow-up with clean sm_120 numbers. These replace the approximate table above, which was measured while a build was running. RTX 5090, kernel time in ms, median of 5 interleaved rounds. The graph hash is identical across main, the previous head (4d47c43) and this head in every row.
With these numbers, your three commits are 0.3–3% faster than the previous head everywhere on sm_120. The scalar fp16 loads cost about 2% on the SIMT kernel itself (dim 128: 19.6 → 19.9 ms), which matters only for L1 and for the new unaligned fallback. 🤖 Generated with Claude Code |
|
@maxwbuckley is there a regression now in unaligned datasets? |
|
@divyegala Are you concerned about the change here: fdef40d? Instead of checking aligned-ness in both SIMT/wmma kernel at runtime, I think it would be a better choice to use SIMT as an unaligned fallback, since we're keeping this path anyways. SIMT might see some regression because it doesn't have the runtime selection for vectorized load. But I guess 2% is not criminal for a path that we don't use that often (I suppose alignment is satisfied most of the time, and people are using new GPUs with tensor cores) Also mentioned in my previous comment: #2835 (comment) |
|
@sherylll We often encounter unaligned datasets during Machine Learning. I do agree that embeddings are always aligned, but the general use-case for NN-Descent is not just aligned datasets. I figured that previously the kernel was able to work with unaligned datasets by using scalar loads (instead of vectorized loads) along with |
|
I believe the 2% data is from Max's standalone test, not e2e evaluation of real datasets. |
|
@sherylll indeed, I prefer we keep regressions to a minimum even if at the expense of code size temporarily. We can do more comprehensive benchmarks as a follow-up and then if there are no regressions, remove the extra code :) |
|
/ok to test 816cd44 |
Add a Vectorized template parameter to local_join_kernel_wmma. Rows that are 8-byte aligned keep the vectorized loads; unaligned float/half input now runs the scalar-load WMMA variant instead of falling back to SIMT. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
TL;DR: @divyegala, e712426 keeps WMMA for unaligned datasets: a Details (optional)
|
Resolve the nn_descent.cuh conflict by keeping the fused new-x-new/new-x-old pass and adding the BitwiseJaccard skip from NVIDIA#2997 alongside BitwiseHamming. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Merged |
Part of #2837.
Problem
local_join_kernel_wmmacomputes new×new (phase 1) and new×old (phase 2) in two separate passes over the feature dimension, in 128-column tiles. For dim > 128, phase 2 re-gathers from global memory every new-vector tile that phase 1 already loaded. At dim 1024 that is 3 × 64 rows × 2 KB gathered per block where 2 × 64 would do.Change
Built on #2751 (per-warp MMA guards, and the per-k-step barrier already moved out of the k loop).
One pass over the features. Each tile step gathers the new rows and the old rows once. Within the step, new×new and new×old are two MMA loops, each behind its own Improvements on NND kernels: u8 MMA and warp guard #2751 warp guard, accumulating into
c_nnandc_no. After the pass,c_nngoes through phase 1's metric and insert unchanged, thenc_nothrough phase 2's.Two loops rather than one with a branch per accumulator. The branchy version compiled to 15 branches and about 2.6× the instructions per k loop, and was slower than
mainfor fp32 input. The split loops are straight-line and reloada_fraginstead (see the review thread for the comparison).One shared-memory arena. The new/old tiles and the distance block share one arena, since their lifetimes never overlap.
s_unique_countergets its own slot, so no extra barrier is needed for aliasing.Both products stored to shared memory (d5ac29d, from @sherylll). After the last tile,
c_nnandc_noare both written to the arena, which now holds two distance blocks (34,816 bytes, the same as the two tiles). Neither accumulator stays live through the epilogues. This replaces an earlier arch gate that kept the two-phase code on the__launch_bounds__(512, 4)arches. The fused kernel still spills more than base on sm_80/90/100 (sm_90 fp32 24/32 → 112/84 bytes). Even so, it measured 16.8% faster in the join on H100 (sm_90), with GNND build 9.7% faster (review comment). On sm_120 the extra store is timing-neutral. A100 (sm_80) and B200 (sm_100) have not been measured. The results below are from sm_120. Further commits from @sherylll (a6e32fc, c1aed5d, fdef40d) fuse the new/old staging loops, drop a redundant barrier, and vectorize the WMMA tile loads. Inputs whose rows are not 8-byte aligned stay on WMMA with scalar tile loads (e712426, aVectorizedtemplate parameter), so they produce the same graph asmainand run 1–9% faster in the standalone harness (comment). Her measurements on Falcon 1M × 1024 show the local join 18–27% faster for fp32 on A100, H100 and B200 (comment has the sm_120 checks).Results
Bit-identical: per-fragment accumulation order is unchanged. The kernel harness gives byte-identical output to
mainin all 42 cases, with 0 mismatched pairs.Tests on sm_120a: all 5,019 tests pass across these suites: NN-Descent 870, CAGRA float 1,456, half 1,114, int8 746, uint8 807, merge 26.
Registers on sm_120a (
main→ this PR): 54 → 53 for fp32 input, 62 → 63 for fp16 input. Occupancy is unchanged at 2 blocks/SM, limited by shared memory.End-to-end (interleaved, 95% CI on the speedup):
local_join_kernel_wmmaper iteration (nsys, CAGRA Elastic config, 1M × 1024): −7.9% in total with device fp32 input and −11.4% with host input. Iteration 1 has no old lists, so nothing is shared and it costs 1–3%. Every later iteration is faster, by up to 13.7%.As expected, there is no gain at dim ≤ 128, where there is only one tile. Recall is unchanged everywhere.
How this was measured
RTX PRO 6000 Blackwell Server Edition (sm_120a), CUDA 13.0, driver 580,
main@ a2ec5f2. CAGRA builds use NN-Descent. "Elastic config" is what Elasticsearch's GPU codec derives from the Lucene HNSW defaults:graph_degree12,intermediate_graph_degree22, 11 NN-Descent iterations, cosine. "cuVS defaults" is 64 / 128 / 20, L2. Device input is Elastic's flush path (CuVSMatrix.deviceBuilder); host input is their merge path.Each configuration ran 4–5 interleaved rounds, rotating the variant order between rounds to remove run-order bias. Each round is one warm-up build plus 2–3 timed builds, so each speedup compares 6–15 builds per side. Kernel times come from nsys.
NN-Descent is not run-to-run deterministic even on
main: the slot claim inadd_rev_edges_kerneldecides which reverse edges survive the 32-entry cap. Graph equality was therefore checked at the kernel level instead. A standalone harness launches the dense local-join kernels on fixed inputs (dims 64/128/130/768/1024 × L2/IP/cosine × WMMA-half/WMMA-float/SIMT, 20k rows) and compares the canonicalised output lists byte for byte. It also checks every stored (id, dist) pair against an exact recomputation.🤖 Generated with Claude Code