Skip to content

perf(cuda): recover fused add+RMSNorm kernel time with byte identity - #3534

Merged
inureyes merged 4 commits into
mainfrom
perf/issue-3518-fused-norm-kernel-time
Nov 28, 2026
Merged

inureyes merged 4 commits into
mainfrom
perf/issue-3518-fused-norm-kernel-time

Conversation

@inureyes

@inureyes inureyes commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

Summary

The byte-identical CUDA fused add+RMSNorm kernel of #3510 read one element at a time and read its residual sum back, which left it slower than the graph path's two kernels at every #2834 shape. This PR changes how both kernels move data and no value they compute, and closes the four hardening gaps listed in #3518.

  • Kernel time (item 1). The NVRTC kernel moves rows through MLX's load_vector / store_vector (run-time alignment test, element-wise fallback), keeps a thread's vectors of sums in registers on the small path, and requests the weight with the row when a thread owns one or two vectors. The cuda-oxide kernel moves whole vectors as 64-bit words and keeps two vectors in registers; its ABI and launch rule are unchanged, so Launch gained no field beyond item 3's.
  • Rows above 65535 (item 2). Rows are walked grid-stride on x from at most 65535 blocks, with the count in a 1-element int64 input, CUDA only.
  • compute_dtype (item 3) is part of Launch and checked against Lane::compute_under.
  • Dtype guard (item 4). The launcher refuses anything but f32, f16 and bf16 on every backend, and fused_add_rms_norm_eligible answers false first.
  • One promotion table (item 5). Lane::compute_under is the Rust source, n_reads_under derives from it, and lane_promotion_matches_mlx_promote_types pins it to MLX at run time.

Kernel time

#2834 M4 method, bf16, width 2048, µs, median of six captures (results):

Rows Before #3510 #3510 Now Graph path cuda-oxide, #3510 now
1 2.21 3.39 2.30 2.46 4.06 4.10
4 2.59 3.90 2.27 2.91 4.06 4.10
128 6.53 12.74 2.82 3.52 12.80 4.80
512 24.13 43.94 6.82 8.42 43.71 10.88
2048 139.68 185.50 140.11 143.82 182.83 141.71

The fused kernel is below the graph path at all five shapes, in each of the six captures, and at or below its time before #3510 at 4, 128 and 512 rows. FUSED_ADD_RMSNORM_DEFAULT is unchanged.

Host state. Two runs of the stage (six captures) had no CI job and no other gpu-lock holder, sampled once a second (host-state.csv); two earlier runs that a CI job overlapped were discarded. The CPUs were not idle: another project's test process held about 16 of the 20 cores (load average 20 to 21). The durations are GPU timestamps and the untouched graph kernels read as on 2026-11-28, but a run with idle CPUs was not obtained. At one row and at 2048 rows the kernel misses its time before #3510 (2.30 against 2.21, 140.1 against 139.7) and passes on the graph bar, by 6 % and 3 %.

Validation (GB10, sm_121)

  • fused_norm_parity_tests: 18 passed with MLXCEL_FUSED_ADD_RMSNORM unset, =0, =1. The feat(cuda): make the fused add+RMSNorm kernel byte-identical to MLX rms_norm and regenerate the cuda-oxide artifact #3510 byte-identity tests are unchanged; new: unaligned views (8 pairs, widths 2048 / 2049 / 8193, the view address asserted unaligned), 65535 / 65536 / 70000 rows at width 8, 70000 rows at 2048 and 66000 rows at 8200 (looped body), the dtype guard.
  • Opted-in build: 35 cuda_oxide tests, matrix cases=130 failed=0 bitwise_identical_to_fused_cuda=130; the layer-route integration test; spike build.sh, run.sh (130), compare.sh (130 bitwise, zero deviation from the graph), bench.sh, check-lint.sh, check-clean-build.sh.
  • Clippy on mlxcel-core in both build variants, cargo fmt --all -- --check, make verify-kernel-dtype-keys verify-kernel-port-dispatch, check_binary_assets.py.
  • Compute Sanitizer (2025.3.1) memcheck, racecheck and synccheck: 0 errors and 0 hazards on the oxide harness (130 cases, PTX loaded by the driver) and on the NVRTC kernel through cuda_byte_identity (graphs off, filtered to fused_add_rms_norm; memcheck also unfiltered), plus the grid-stride test alone under unfiltered racecheck.
  • Item 5 mutation check: with compute_under returning f32 for bf16 under f32, the test fails with Bf16 under a F32 weight: compute_under says F32, MLX promotes to dtype 12, and the committed artifact stops validating (8 of 15 artifact tests fail).
  • Not run: Metal parity (no Metal host; the Metal and ROCm bodies, geometry, template args and cache keys are untouched, the launcher's dtype refusal is the one shared change). The three tests the issue expects to fail on main (70000 rows, compute_dtype refusal, int32 guard) were not executed against main.

Changes during review

  • Review and security passes found nothing at CRITICAL or HIGH. A follow-up commit keys scripts/fused_norm_m4_summarize.py on (stage, label) so it reproduces the committed m4-summary.csv from the committed CSV (6 of 6 pairs), corrects the README's idle-wait wording to what host-state.csv recorded, documents the oxide packing limit (a vector is at most two 64-bit words) in a comment, and adds the wide and looped grid-stride test. Artifacts are unchanged (the PTX has no .loc or .file directives).

For review

  • The cuda-oxide kernel now does raw 64-bit reads and writes where every access was bounds-checked. They are taken only when the whole row is inside each slice and starts on a word boundary; anything else keeps indexed access.
  • The cubin grew from 92,000 to 123,464 bytes, so its ceiling in check_binary_assets.py goes from 100 KB to 128 KB and the total budget by the same 31,464 bytes. PTX SHA-256 fb873d30443256e61b5cdcabbb6a0b0189531c19a2d52968f0c16e4b2b795d0f.
  • The cuda-oxide kernel keeps two vectors, not the NVRTC kernel's eight: with eight ptxas reports 72 registers and a 1024-lane launch fails; with two, 41 to 48.

Closes #3518

The byte-identical kernel of #3510 read one element at a time and read `new_residual` back for its second pass, which made it 1.3 to 2 times slower than before and slower than the graph path's two kernels at all five #2834 shapes. Only data movement changes here: the summation order, the FMA, the two butterflies and every cast point are as they were.

- NVRTC kernel: rows move through MLX's `load_vector` / `store_vector` (run-time alignment test, element-wise fallback), a thread keeps its `Chunks` vectors of residual sums in registers on the small path, a thread with one or two chunks requests its weight vectors with the row's, and the looped path re-reads `new_residual` as MLX's looped `rms_norm` re-reads its input.
- Rows above 65535: rows are walked grid-stride on x from at most 65535 blocks, with the count in a 1-element int64 input, CUDA only. A launch past 65535 rows used to fail at evaluation.
- cuda-oxide kernel: the same split at run time, with whole vectors moved as 64-bit words and two vectors kept in registers (eight need 72 registers, over the 64 a 1024-lane block allows). Artifact regenerated; cubin 92,000 to 123,464 bytes, so the asset ceiling goes to 128 KB.
- Validator: `Launch` carries `compute_dtype` and it is checked against `Lane::compute_under`, now the one Rust statement of the promotion table, which a test pins to MLX's own `promote_types`.
- The launcher refuses any activation or weight dtype other than f32, f16 and bf16, and `fused_add_rms_norm_eligible` answers false for them first.

Validated on GB10 (sm_121): `fused_norm_parity_tests` 17 passed with `MLXCEL_FUSED_ADD_RMSNORM` unset, 0 and 1; 35 `cuda_oxide` tests with the adapter matrix at 130 of 130 bitwise; spike `run.sh` 130 cases and `compare.sh` 130 bitwise against the fused kernel and the graph; clippy on mlxcel-core in both build variants.

Refs #3518
Adds `docs/benchmark_results/cuda-fused-norm-kernel-time-gb10-2026-11-29/` with the #2834 M4 kernel rows, a per-shape summary against both bars of #3518, and the host state of each run of the stage. The fused kernel is below the graph path's two kernels at all five shapes (2.30 against 2.46 µs at one row, 140.5 against 145.8 at 2048 rows) and at or below its time before #3510 at 4, 128 and 512 rows.

Both runs of the stage overlapped a CI job on the host, which the README and the changelog state; the idle-host run the issue asks for is still owed.

Also updates the changelog, the `MLXCEL_FUSED_ADD_RMSNORM` entry, the three cuda-oxide evidence documents and the spike README for the new data movement and artifact digests, and re-records `compare-sm_121.json` against the implementation commit.

Refs #3518
The two runs of the M4 stage recorded in the previous commit each overlapped a CI job. Two later runs had no CI job and no other `gpu-lock` holder for their whole length, so the results directory now holds those six captures and the earlier ones are discarded. The medians moved by at most 4 %: 2.30, 2.27, 2.82, 6.82 and 140.1 µs for the fused kernel against 2.46, 2.91, 3.52, 8.42 and 143.8 for the graph path. The CPUs were busy with an unrelated process during the captures, which the README states.

`fused_norm_m4_summarize.py` writes LF line endings and adds a `paired` row per shape: the captures in which the fused kernel was below that capture's own graph pair (6 of 6 at every shape). The README marks the causes that were not isolated as likely.

Refs #3518
@inureyes inureyes added status:review Under review type:performance Performance improvements priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:linux Linux (CUDA / packaging) specific labels Nov 28, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Recover the CUDA fused add+RMSNorm kernel time while keeping #3510's byte identity, and close the four hardening gaps of #3518 (rows above 65535, validator compute_dtype, dtype guard, one promotion table).

Findings Addressed

None needed: no CRITICAL or HIGH finding.

Remaining Items

  • scripts/fused_norm_m4_summarize.py keys a capture by label only. Fed the committed m4-nsys-kernels.csv, where both stages reuse the labels mlx-graphs-off-rep1..3, the paired rows read 3 of 3 instead of 6 of 6. Split per stage, the output matches the committed m4-summary.csv byte for byte, so the data is right; keying on (stage, label) would make the committed CSV reproduce it directly. (LOW)
  • The results README says each stage ran after 45 idle seconds, but host-state.csv has s4 starting 5 s after s3 ended. Both stages show zero busy samples, so the captures stand; the sentence overstates the wait. (LOW)
  • The cuda-oxide row routine packs a vector into two 64-bit words and checks n is a multiple of per_word but not that n <= 2 * per_word. All five instantiated entries satisfy it (at most 128 bits per vector); an f32 activation with an 8-wide compute dtype would not. Latent, worth a debug_assert or comment when a sixth entry is added. (LOW)
  • The 65536 and 70000 row tests run at dim = 8, so only Chunks = 1 takes more than one grid-stride iteration. The loop carries no state across rows apart from the closing barrier, so the other bodies are covered by inspection. (LOW)
  • results/compare-sm_121.json records gpu_lock_kind: unspecified (was gpu-lock), because GPU_LOCK_KIND was not set; compare touches no GPU. (LOW)

Checked

  • NVRTC body: thread t still sums vectors t, t + block, ... ascending, element by element, same butterflies and casts. Padded lanes add +0 to a non-negative sum and store nothing (load_vector / store_vector bounds at the pin). The early weight load and the hoisted n_rows read change no value. blocks = min(rows, 65535) <= rows, so the do/while first row always exists; row and gridDim.x are block-uniform, so every barrier, the closing one included, is reached by the whole block.
  • Oxide body: word access only when the row lies inside all four slices and starts on a word boundary in each, and only for vectors that end inside the row; the weight has its own guard. Arithmetic order unchanged from the bit-identical feat(cuda): make the fused add+RMSNorm kernel byte-identical to MLX rms_norm and regenerate the cuda-oxide artifact #3510 port.
  • compute_dtype in Launch (schema comparison covers it), Lane::compute_under as the single source with n_reads_under derived, runtime pin to MLX promotion; launcher guard before promote_types and the oxide route, eligibility mirrors it.
  • Metal and ROCm keep fused_norm_input_names(), template args and z-grid; FUSED_ADD_RMSNORM_DEFAULT and both dated directories untouched; no oxide test loosened (the removed asserts were the self-referential ones the issue asked to replace).
  • PTX and cubin SHA-256 match all five manifests, the README and compare-sm_121.json (130 of 130 bitwise). Cubin 123,464 bytes under the 128 KB ceiling; the total budget rises by exactly 31,464 and check_binary_assets.py passes.
  • README states the CPU-load caveat plainly; the median table matches m4-summary.csv.

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (GPU and oxide suites not rerun in this review; results above are from the PR's own validation; CI clippy and CPU-only link still running)

@inureyes

Copy link
Copy Markdown
Member Author

Security and Performance Review

No CRITICAL or HIGH finding; nothing was changed on the branch.

Sanitizer runs (GB10, CUDA 13.0 compute-sanitizer 2025.3.1, under gpu-lock)

Target memcheck racecheck synccheck
cuda-oxide harness, run (130 of 130 cases, 5 rejects) 0 errors 0 hazards 0 errors
NVRTC kernel, cuda_byte_identity (5 tests, MLX_USE_CUDA_GRAPHS=0) 0 errors, unfiltered 0 hazards, filtered 0 errors, filtered

Filtered means --kernel-name kns=fused_add_rms_norm; MLX names the kernel custom_kernel_mlxcel_fused_add_rms_norm<hash>. Unfiltered racecheck is not usable on this binary: on the unaligned-views test it grows the process to about 115 GB RSS and the host OOM killer ends it, also with the fused kernel excluded, so the cost comes from instrumenting MLX's own kernels. The grid-stride test (65535, 65536, 70000 rows) ran alone under unfiltered racecheck: 0 hazards. dtype_guard passes (2 of 2).

Reviewed by reading

  • Oxide word path: wide requires the whole row inside all four slices and word alignment in each; whole adds first + n <= dim; reads start at j % per_word == 0, so every word ends at or before the vector's end. The weight has its own guard. small bounds the chunk index to 0 or 1. All five entries use at most two words per vector. The adapter passes a.size() of row-contiguous arrays as lengths and refuses rows past the grid limit before enqueue.
  • NVRTC loop: blocks = min(rows, 65535), the row and gridDim.x are block-uniform, and synccheck agrees that every barrier is reached by the whole block. As far as I can tell the closing __syncthreads() is not needed, because the next row's shared writes already sit behind that row's first two barriers. It costs one barrier per row and is cheap insurance; no action needed.
  • Default path: fused_add_rmsnorm_enabled() short-circuits before eligibility, and FUSED_ADD_RMSNORM_DEFAULT is unchanged, so the graph path does no new work.

Coverage limits (LOW, no fix requested)

  • The oxide harness has no 16-bit row above 8192, so the 1024-lane block runs only for f32-compute entries, and it never passes an offset view. The short-slice guards are checked only by reading, since the harness rejects bad lengths on the host.
  • The harness loads the PTX and the driver JITs it, so the sanitizer checked code from the committed PTX, not the cubin bytes.
  • MLX allocates 8-byte arrays from a small pool and reuses cached buffers, so memcheck cannot see an overrun into pooled slack on the NVRTC side.

The summarizer paired captures by label alone, so the two stages of the committed m4-nsys-kernels.csv, which reuse mlx-graphs-off-rep1..3, collapsed into 3 pairs; it now keys on (stage, label) and reproduces the committed m4-summary.csv byte for byte (6 of 6 pairs).

The results README now says what host-state.csv records: the first stage started after 45 idle seconds, the second 5 seconds after the first ended, both with zero busy samples. It also notes that the compare step does not use the GPU, which is why compare-sm_121.json has gpu_lock_kind unspecified.

A new test runs 70000 rows at width 2048 and 66000 rows at width 8200 (bf16/bf16) so the Chunks 2+ bodies and the looped body walk a second row per block; it passes byte-identical against the graph. A comment in the oxide kernel states the n <= 2 * per_word packing limit (comment only; the PTX has no .loc or .file directives and the manifests digest PTX and cubin, unchanged).

Validation:
- gpu-lock run fused_norm_parity_tests --test-threads=1: 18 passed
- cargo fmt --all --check, cargo clippy --release -p mlxcel-core --features cuda --lib --tests -D warnings, make verify-*, check_benchmark_raw_logs.py: pass

Refs #3518
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 28, 2026
@inureyes
inureyes merged commit 39846bf into main Nov 28, 2026
33 checks passed
@inureyes
inureyes deleted the perf/issue-3518-fused-norm-kernel-time branch November 30, 2026 14:01
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:linux Linux (CUDA / packaging) specific priority:medium Medium priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(cuda): recover fused add+RMSNorm kernel time with byte identity

1 participant