Skip to content

Fuse the two WMMA local-join phases in NN-Descent - #2835

Open
maxwbuckley wants to merge 13 commits into
NVIDIA:release/26.12from
maxwbuckley:nn-descent/fused-wmma-join
Open

maxwbuckley wants to merge 13 commits into
NVIDIA:release/26.12from
maxwbuckley:nn-descent/fused-wmma-join

Conversation

@maxwbuckley

@maxwbuckley maxwbuckley commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Part of #2837.

Problem

local_join_kernel_wmma computes 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_nn and c_no. After the pass, c_nn goes through phase 1's metric and insert unchanged, then c_no through 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 main for fp32 input. The split loops are straight-line and reload a_frag instead (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_counter gets 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_nn and c_no are 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, a Vectorized template parameter), so they produce the same graph as main and 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 main in 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):

Workload Speedup 95% CI
CAGRA, Elastic config, 1M × 1024, device +4.5% +3.6 … +5.3
CAGRA, Elastic config, 1M × 1024, host +5.8% +4.6 … +7.0
CAGRA, Elastic config, 4M × 1024, device +4.5% +1.6 … +7.4
CAGRA, Elastic config, wiki_all 1M × 768, device +1.8% +0.6 … +3.0
CAGRA, Elastic config, wiki_all 1M × 768, host +2.5% +1.1 … +3.9
NN-Descent, 1M × 1024 (degree 22 / 33, 11 iterations, cosine) +3.6% +2.1 … +5.1
CAGRA, cuVS defaults, wiki_all 1M × 768, host +3.0% +1.9 … +4.0
CAGRA, cuVS defaults, 1M × 1024, device +0.5% (ns) −1.6 … +2.6
CAGRA, Elastic config, SIFT 1M × 128, device +0.5% (ns) −1.1 … +2.0

local_join_kernel_wmma per 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_degree 12, intermediate_graph_degree 22, 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 in add_rev_edges_kernel decides 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

…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>
@copy-pr-bot

copy-pr-bot Bot commented Oct 11, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Explain Change →

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Performance
    • GPU neighbor-search processing uses a fused computation on supported architectures, which may improve processing efficiency. Other architectures retain their existing computation path.
    • Neighbor-search calculations now handle new-to-new and new-to-existing comparisons in a single feature pass, while keeping their distance results separate.
  • Compatibility
    • No changes to public interfaces or user-facing options.

The WMMA local-join kernel now uses shared memory for separate new×new and new×old distance blocks. It stages both neighbor tiles during one feature-dimension pass, accumulates the two products separately, and uses the old-distance block for cross-list minimum searches.

Changes: WMMA Local Join

Layer / File(s) Summary
Fused WMMA computation
cpp/src/neighbors/detail/nn_descent.cuh
The kernel allocates separate distance blocks and accumulators for new×new and new×old products. It stages old-neighbor tiles during the feature-dimension loop, computes both products in that pass, and uses the old-distance block for cross-list minimum searches. When the old list is empty, the kernel skips old-list handling.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Suggested reviewers: lowener, robertmaynard

Merge Risk: Minimal · previous review d5ac2

This change fuses two distance computations in the NN-Descent GPU local-join kernel to improve build performance. No concrete correctness or stability risk was found, and the reported validation is reasonable for the scope, so it looks ready to merge.

Architecture risk: Low · up to d5ac2

The change affects 1 system.

Changed systems: cpp

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — cpp (service) was modified; 1 changed file maps to changed impact.

Before / after behavior

  • observed — Modified behavior in cpp/src/neighbors/detail/nn_descent.cuh: Adds <algorithm>, used by the shared-memory arena sizing expression.
  • observed — Modified behavior in cpp/src/neighbors/detail/nn_descent.cuh: Replaces separate shared vector arrays and the single distance-buffer alias with an aligned arena sized to the larger of the tile storage and two distance blocks. The arena holds new and old vector tiles, separate new×new and new×old distance blocks, and dedicated unique counters; the former buffer-size assertion is removed.
  • observed — Modified behavior in cpp/src/neighbors/detail/nn_descent.cuh: Replaces one accumulator and one activity flag with separate accumulators and guards for new×new and new×old work. The old-list presence is captured for later control flow, and both accumulators are initialized for non-Hamming metrics.
  • observed — Modified behavior in cpp/src/neighbors/detail/nn_descent.cuh: Stages old-neighbor vector tiles during the existing feature-dimension loop, alongside the new-neighbor tiles, replacing the later separate pass’s old-vector staging.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "Fuse the two WMMA local-join phases in NN-Descent" matches the main change: the new×new and new×old computations are merged into one pass over the feature dimension in local_join_kernel_wmm…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description states the PR fuses the new×new and new×old WMMA local-join phases in NN-Descent into one feature-dimension pass, which matches the raw summary of changes to cpp/src/neighbors/detail/n…
Full details: Title check

Explanation

The title "Fuse the two WMMA local-join phases in NN-Descent" matches the main change: the new×new and new×old computations are merged into one pass over the feature dimension in local_join_kernel_wmma. It is short, specific, and states the primary change. The PR objectives refer to a different PR number and describe a stale architecture-gate history, but the title itself still matches the changeset.

Full details: Description check

Explanation

The description states the PR fuses the new×new and new×old WMMA local-join phases in NN-Descent into one feature-dimension pass, which matches the raw summary of changes to cpp/src/neighbors/detail/nn_descent.cuh (shared-memory arena, separate c_nn and c_no accumulators, early return when the old list is empty). It also gives problem context, the design rationale, and test and benchmark results. The description is clearly related to the changeset.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 3d36a99 and d5ac29d.

Files selected for processing: 1

  • cpp/src/neighbors/detail/nn_descent.cuh

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

@sherylll sherylll left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread cpp/src/neighbors/detail/nn_descent.cuh Outdated
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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread cpp/src/neighbors/detail/nn_descent.cuh Outdated
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, done: since 4f8ab07 the new/old tiles and the distance blocks share one s_arena, and s_unique_counter has its own slot, so the extra aliasing barrier is gone. Your d5ac29d then put both distance blocks in that arena.

maxwbuckley and others added 2 commits October 13, 2026 17:28
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>
@maxwbuckley

Copy link
Copy Markdown
Contributor Author

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 main + one commit (4f8ab07); the description has the updated numbers.

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 s_unique_counter in its own slot, so the extra barrier the aliasing needed is gone.

How the variants compare. Everything below is rebased on main @ a2ec5f2, which includes #2751, and checked byte-identical to main on the kernel harness (42 cases, 0 mismatched pairs). Kernel time is relative to main, at dim 1024, for 100k rows with every row at the given (new, old) list sizes:

new, old input conditional in loop (as posted) unconditional MMA second MMA loop
64, 0 fp16 +4.6% +13.0% +2.3%
64, 16 fp16 −15.9% −17.8% −17.6%
32, 32 fp16 −8.8% −16.8% −15.9%
8, 64 fp16 −1.9% −11.2% −10.8%
64, 0 fp32 +6.0% +8.6% +0.1%
64, 16 fp32 −4.2% −4.8% −12.3%
32, 32 fp32 +6.1% +3.5% −3.2%
8, 64 fp32 +6.9% +4.3% −1.2%
  • Conditional in the loop: you were right that it costs. After Improvements on NND kernels: u8 MMA and warp guard #2751 there is a guard per accumulator, and the fused k loop compiles to 15 branches and about 2.6× the instructions of a straight-line loop (272 vs 107 for fp16 input). For fp32 input it ends up slower than main.
  • Unconditional MMA: good for fp16 input when both lists are long. It costs up to 13% (fp16) and 8.6% (fp32) when there is no old list, which is every block in the first iteration. It also gives up Improvements on NND kernels: u8 MMA and warp guard #2751's skip when the old list is short.
  • Second MMA loop: it reloads a_frag, but each loop is straight-line code under a hoisted guard. It is fastest or close to fastest everywhere, and it is what the PR now does.
  • Arena: performance-neutral in every case measured (within 0.4% of the split loop on its own).

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 local_join_kernel_wmma time from nsys, for a CAGRA build on 1M × 1024 with Elastic's config (11 iterations):

iteration 1 2 3 4–8 9 10 11 total
device fp32 input +1.1% −0.2% −13.7% −10.4…−12.0% −7.0% −4.2% −2.9% −7.9%
host input (fp16 kernel) +2.6% −9.5% −13.1% −11.9…−13.3% −12.7% −11.8% −11.5% −11.4%

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 main the difference is small:

main this PR
fp32 input 54 53
fp16 input 62 63

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.

@achirkin
achirkin changed the base branch from main to release/26.12 November 12, 2026 05:39
@achirkin achirkin added improvement Improves an existing functionality non-breaking Introduces a non-breaking change labels Nov 12, 2026
@achirkin

Copy link
Copy Markdown
Contributor

/ok to test 979efec

@sherylll

sherylll commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

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 local_join_kernel_wmma for FP32 input before and after the fusion, using CUDA 13.3.73, -O3, and the existing architecture-specific launch bounds. Compared release parent 485ffcfd2a30a8b66b71eabf744cd124113eab47 against branch head 979efeca732dce63ebd64db6366b2d107b88bc49.

Target Registers/thread before → after Spill stores/loads before → after (bytes)
B100 (sm_100) 32 → 32 0/0 → 68/68
H100 (sm_90) 32 → 32 24/32 → 148/104
A100 (sm_80) 32 → 32 8/4 → 108/88
RTX PRO 6000 Blackwell (sm_120) 52 → 53 0/0 → 0/0

The fusion increases spills on all three targets using __launch_bounds__(512, 4). The sm_120 path uses __launch_bounds__(512) without the four-block minimum and remains spill-free. Both versions' emitted PTX were checked for these launch-bound directives.

These are static ptxas spill reports from isolated cross-compilation, not measured runtime traffic or performance. The metric and data dimension remain runtime arguments; the probe uses raft::identity_op and int internal graph indices.

@divyegala divyegala left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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>
@maxwbuckley

Copy link
Copy Markdown
Contributor Author

Thanks @sherylll for the spill report, and @divyegala for the review.

Reproducing the spills. I compiled only local_join_kernel_wmma (nvcc 13.2, -O3, current launch bounds). Spill stores/loads in bytes, base → previous head:

arch fp32 input fp16 input
sm_80 8/4 → 108/88 0/0 → 100/72
sm_90 24/32 → 148/104 0/0 → 164/240
sm_100 0/0 → 68/68 0/0 → 36/36

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 __launch_bounds__(512, 4). Two 16x16 fp32 accumulators plus the A/B fragments don't fit, so ptxas spills one accumulator around each k-loop on every feature tile, and keeps the new×old accumulator in local memory through the whole new×new epilogue.

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.

  • The arches built with (512, 4) launch bounds (sm_70/80/90/100) compile the original two-phase code.
  • The arch test is factored into one macro, CUVS_NN_DESCENT_MIN_BLOCKS_4, which both the launch bounds and the code path use, so they can't drift apart.
  • Shared memory is static in both paths, so the host launch is unchanged.
  • I compared the full cuobjdump -sass output for both input types. sm_80/90/100 are instruction-for-instruction identical to release/26.12, and sm_75/86/89/103/120 identical to the fused version.
  • -Xptxas -warn-double-usage is clean on every arch.

Timing on an RTX 5090 (sm_120), kernel ms, base → this PR:

case fp32 fp16
dim 128, full lists 98.9 → 97.8 93.2 → 92.4
dim 128, mixed lists 57.8 → 57.1 54.8 → 54.1
dim 960, full lists 79.0 → 60.1 48.4 → 41.2
dim 960, mixed lists 30.0 → 27.9 26.2 → 23.2

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 /ok to test 3d36a998a0846d8fa5f677c347308e14b205ef53?

🤖 Generated with Claude Code

@sherylll

sherylll commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

We could enlarge SMEM usage to store distances earlier: sherylll@4d47c43 . This is safe because occupancy is not SMEM-bound.
I checked on H100 chip (same cc as H200) and the version with loop bound + fused new/old loop (this PR) + larger SMEM wins.
Feel free to drop the arch guards and cherry pick this one, if it works on your GPUs and datasets.

maxwbuckley and others added 2 commits November 16, 2026 15:52
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.
@maxwbuckley

Copy link
Copy Markdown
Contributor Author

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 local_join_kernel_wmma (stores/loads in bytes, fp32 / fp16 input). No other arch spills.

arch release/26.12 this PR
sm_80 8/4 / 0/0 48/32 / 48/32
sm_90 24/32 / 0/0 112/84 / 124/320
sm_100 0/0 / 0/0 68/68 / 36/36

Your sm_90 fp32 numbers reproduce. Your H100 timings show the spills cost less than the fusion saves there.

-Xptxas -warn-double-usage is clean on every arch.

RTX 5090 (sm_120), kernel ms, three interleaved rounds, base → previous head → this commit:

case fp32 fp16
dim 128, full lists 99.6 → 98.7 → 98.7 93.8 → 92.8 → 92.9
dim 128, mixed lists 57.8 → 57.1 → 57.1 54.8 → 54.1 → 54.1
dim 960, full lists 79.3 → 60.2 → 60.1 48.9 → 41.7 → 41.9
dim 960, mixed lists 30.0 → 27.9 → 27.9 26.2 → 23.2 → 23.2

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 /ok to test d5ac29d6e6d74c6432ccd282b8c2e4b8c5e21fad?

🤖 Generated with Claude Code

@sherylll

sherylll commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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 local_join performs better across several representative architectures on the Falcon-1M dataset.

The 3 new commits:

  • fuse load loops and remove unroll pragma (leave it to compiler's judgement)
  • remove a redundant syncthreads
  • refactor load_vec functions: wmma kernel only accepts 8B-aligned data; if not aligned choose the SIMT kernel. This removes run-time check of alignment, which happens now before kernel launch

Before: original unfused dense WMMA kernel from main at 7a3f538c7.
After: fused feature loop + shared arena + merged staging loops + redundant phase-barrier removal + unified vectorized WMMA loader, at 6627f8eb0 on nn-descent/fused-wmma-arena.

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

GPU Input Local-join time: main → after Build time: main → after
H100 PCIe FP32 5.404 → 3.951 s (-26.9%) 9.471 → 8.015 s (-15.4%)
H100 PCIe FP16 3.506 → 3.094 s (-11.8%) 7.540 → 7.122 s (-5.5%)
A100 PCIe FP32 6.582 → 5.369 s (-18.4%) 11.747 → 10.544 s (-10.2%)
A100 PCIe FP16 4.696 → 4.673 s (-0.5%) 9.856 → 9.803 s (-0.5%)
B200 FP32 2.792 → 2.263 s (-18.9%) 5.181 → 4.617 s (-10.9%)
B200 FP16 2.383 → 2.036 s (-14.6%) 4.759 → 4.632 s (-2.7%)
RTX PRO 6000 Blackwell FP32 3.774 → 3.681 s (-2.5%) 6.106 → 6.019 s (-1.4%)
RTX PRO 6000 Blackwell FP16 2.607 → 2.355 s (-9.7%) 4.939 → 4.726 s (-4.3%)

Register usage / occupancy

GPU Input Launch bounds Registers/thread: main → after Spill stores/loads (B): main → after Max resident blocks/SM: main → after
H100 (sm_90) FP32 (512, 4) 32 → 32 24/32 → 76/84 4 → 4
H100 (sm_90) FP16 (512, 4) 32 → 32 0/0 → 72/108 4 → 4
B200 (sm_100) FP32 (512, 4) 32 → 32 0/0 → 60/96 4 → 4
B200 (sm_100) FP16 (512, 4) 32 → 32 0/0 → 40/40 4 → 4
A100 (sm_80) FP32 (512, 4) 32 → 32 8/4 → 76/212 4 → 4
A100 (sm_80) FP16 (512, 4) 32 → 32 0/0 → 60/216 4 → 4
L40S (sm_89) FP32 (512) 62 → 56 0/0 → 0/0 2 → 2
L40S (sm_89) FP16 (512) 63 → 54 0/0 → 0/0 2 → 2
RTX PRO 6000 Blackwell (sm_120) FP32 (512) 52 → 55 0/0 → 0/0 2 → 2
RTX PRO 6000 Blackwell (sm_120) FP16 (512) 53 → 57 0/0 → 0/0 2 → 2

@maxwbuckley

Copy link
Copy Markdown
Contributor Author

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

  • Alignment dispatch looks right. It checks the actual data pointer, including any user offset, and the ndim * sizeof(T) row stride. Together these also guarantee the last partial tile is a whole number of float2/half loads. The check is required: without it, the new WMMA kernel faults with "misaligned address" on unaligned input. I tried it with odd dims and offset pointers.
  • The removed __syncthreads is redundant. Phase-1 insertion only reads s_list and s_distances, and phase-2 calculate_metric writes only s_distances_old, which doesn't overlap.

Tests and SASS

  • NN-Descent gtests on sm_120: 870 passed, 0 failed. The 48 skips are the suite's built-in skips for BitwiseHamming with float input. The float cases use dim 31, so they also cover the new SIMT fallback with host and device input.
  • -Xptxas -warn-double-usage reports no fp64 in the NN-Descent kernels. pre-commit is clean.
  • Spills in bytes (stores/loads): sm_90 fp32 goes from 112/84 to 76/84 and fp16 from 124/320 to 72/108. sm_80 goes the other way, to 76/212 (fp32) and 60/216 (fp16), but your A100 timings show it's still a win there.

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.

case main prev head this head
fp32 dim 128, full lists 100.3 100.7 94.3
fp16 dim 128, full lists 86.0 88.7 86.9
fp32 dim 960, full lists 82.9 62.7 62.6
fp16 dim 960, full lists 47.4 39.2 38.0

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.

  • On the 5090 that's 2.0–2.3× slower for dims like 129/130 or a +1 offset, 20% slower for fp32 dim 25, and 40% slower for fp16 dim 50.
  • Results stay correct, and SIMT is slightly more accurate.

Would a Vectorized template parameter on the WMMA kernel be worth the extra instantiation? Unaligned launches would use wmma<false>. I'm happy to add it here or leave it for a follow-up.

@divyegala, this now has measurements from four architectures. Could you take another look? @achirkin, could you /ok to test fdef40df002efbf87d6956e401679032006b50ba?

🤖 Generated with Claude Code

@maxwbuckley

Copy link
Copy Markdown
Contributor Author

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.

case main previous head this head
fp32 dim 128, full lists 92.7 92.0 90.7
fp16 dim 128, full lists 86.2 85.5 83.9
fp32 dim 128, mixed lists 53.4 52.8 51.8
fp16 dim 128, mixed lists 50.1 49.6 48.7
fp32 dim 960, full lists 79.0 59.9 59.6
fp16 dim 960, full lists 46.5 40.3 39.1
fp32 dim 960, mixed lists 28.8 27.1 27.0
fp16 dim 960, mixed lists 24.1 21.4 20.8

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

@divyegala

Copy link
Copy Markdown
Contributor

@maxwbuckley is there a regression now in unaligned datasets?

@sherylll

Copy link
Copy Markdown
Contributor

@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)

@divyegala

Copy link
Copy Markdown
Contributor

@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 wmma? Seems like after this PR that won't be the case. Do we have enough data to confirm that SIMT unaligned fallback will always have no greater than 2% regression?

@sherylll

sherylll commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

I believe the 2% data is from Max's standalone test, not e2e evaluation of real datasets.
If we still want unaligned access + wmma path we could sacrifice code size with one more template instantiation. The motivation for the refactor was to make things easier for the compiler

@divyegala

Copy link
Copy Markdown
Contributor

@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 :)

@achirkin

Copy link
Copy Markdown
Contributor

/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>
@maxwbuckley

Copy link
Copy Markdown
Contributor Author

TL;DR: @divyegala, e712426 keeps WMMA for unaligned datasets: a Vectorized template parameter, and unaligned float/half rows now use scalar loads instead of the SIMT fallback. Unaligned inputs now produce the same graph as main, 1–9% faster, and aligned inputs compile to identical SASS. @achirkin could you /ok to test e7124268e?

Details (optional)
  • Aligned path: for float and half, the SASS of local_join_kernel_wmma<true> and of the SIMT kernel is identical to the previous head (816cd44), so aligned performance is unchanged.
  • Unaligned path: RTX 5090 (sm_120), kernel ms, median of 3 interleaved rounds, n = 200k. The graph hash for wmma<false> matches main in every case.
case main (WMMA) previous head (SIMT fallback) this head (wmma<false>)
fp32 dim 129 20.1 55.3 18.8
fp32 dim 129, mixed list sizes 11.2 23.5 10.4
fp32 dim 25 14.9 19.6 14.7
fp32 dim 128, pointer +1 16.7 52.2 16.5
fp16 dim 130 18.6 52.3 17.2
fp16 dim 130, mixed list sizes 10.6 21.6 9.8
fp16 dim 50 14.9 26.8 14.7
fp16 dim 128, pointer +1 15.4 49.2 15.1
  • Cost: one extra instantiation each for float and half. Byte types keep a single instantiation, since they load one element per lane either way. No spills on sm_120.
  • Tests and checks: NN-Descent gtests pass on sm_120 (870 passed, plus the suite's 48 built-in skips). -Xptxas -warn-double-usage is clean, and so is pre-commit.

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>
@maxwbuckley

Copy link
Copy Markdown
Contributor Author

Merged release/26.12 to resolve the nn_descent.cuh conflict with #2997. The fused loop now skips BitwiseJaccard alongside BitwiseHamming, and the NN-Descent gtests pass locally. Could a maintainer /ok to test 3d67402e0594a6792f40731bcd530b65dd9ce750? Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

improvement Improves an existing functionality non-breaking Introduces a non-breaking change

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

4 participants