Skip to content

update(rocm): port fused_add_rms_norm and fused_rope_qk_append to HIP - #2107

Merged
inureyes merged 8 commits into
mainfrom
update/issue-2063-rocm-fused-norm-rope
Oct 5, 2026
Merged

inureyes merged 8 commits into
mainfrom
update/issue-2063-rocm-fused-norm-rope

Conversation

@inureyes

@inureyes inureyes commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

Summary

fused_add_rms_norm and fused_rope_qk_append now have HIP ports, so on ROCm MLXCEL_FUSED_ADD_RMSNORM=1 and MLXCEL_FUSED_ROPE_APPEND=1 run a kernel instead of silently keeping the graph. Each port is byte-identical to the ROCm graph it replaces, so turning a fusion on changes no logit. Decode does not clearly improve, so both defaults stay off on every backend.

Changes

  • HIP bodies in fused_norm_hip.h and fused_rope_append_hip.h, compiled by fast::hip_kernel from a .rocm entry in each port table; launches, template args and dtype keys are the CUDA ones (make verify-kernel-dtype-keys pin unchanged). .rocm = nullptr count goes from 10 to 8.
  • The ports follow ROCm's graph, not the Metal kernel: 256 threads per row and the row length read at run time as rms_norm_kernel does, the gain multiply in T (keeps -0), sincosf in rope.hip order, the FMA form of each of the graph's two RoPE kernels (batch-1 decode differs), and one f16 rounding of the fused RoPE result. Each detail came from a failing test, and each test fails with its fix reverted.
  • Both predicates also require the GPU as the default device; the Rust gates read the device per call and cache only a true port answer. tests/cpu_device_custom_kernel_gates.rs covers both.
  • Parity tests fail instead of skipping on a GPU backend whose predicate is false; new ROCm byte-identity tests, a sign-of-zero test and a RoPE dtype sweep. Tolerances unchanged.
  • The norm HIP body keeps the #error wave guard, which is inert on AMD clang 23 (it defines neither macro); the explicit __shfl_xor width of 32 is what keeps each fold in one 32-lane group. The RoPE body has no cross-lane operation, so it has no guard, as with the perf(rocm): port gumbel_max_sample and rejection_sample to HIP #2064 samplers.
  • Results page docs/benchmark_results/rocm-fused-norm-rope-gfx1151-2026-10-05.md, raw rows and traces under benchmarks/, env-var, installation, README and correctness-page updates.

Measured (gfx1151)

bench_decode.sh pp512/tg128, arms rotated per round, every run through rocm_gpu_guard.sh --idle-secs 60 (44 of 44 clean on the first attempt). Medians:

Model Off On Change
Llama-3.1-8B, norm only (5 rounds) 37.85 37.95 +0.3%, noise
Qwen2.5-7B, add / rope / both (7 rounds) 46.53 47.23 / 46.80 / 47.32 +1.5 / +0.6 / +1.7%
Qwen3-30B-A3B, calls neither (3 rounds) 62.21 62.42 +0.3%, control

Qwen2.5's on arms beat off in 6 of 7 rounds, but the gain's size drifted between runs as much as off's own spread, and both is not above add. Recommendation: keep the defaults off; flip on ROCm only after a longer interleaved run shows a consistent gain.

Traces (compare_logit_traces.py --decided 2.0): every on/off pair is byte-identical at w1, w8, w1ctx512; Llama w8 vs Metal M1U 0/230 decided mismatches, Qwen2.5 w8 vs Metal M5 0/274.

Verification (gfx1151)

  • make verify-rocm on 756d03d8: 147 suites, 11871 passed, 0 failed, 378 ignored. The one later commit (bea7d1ab, review fixes: gate caching, bf16 RoPE test budget, a docs sentence) re-ran the parity tests (21 passed), cpu_device_custom_kernel_gates, dead_doc_pointers, clippy on mlxcel-core lib and tests, and fmt, all passing; Qwen2.5-7B greedy 64-token output is identical with both fusions off and on.

  • make verify-versions verify-kernel-dtype-keys verify-kernel-port-dispatch verify-llama-compat verify-fmt: pass (9 in scope, pin unchanged).

  • Negative checks: a row-sized thread count, a compile-time row length, an f32 gain product, a single RoPE FMA form, f32 rounding of f16 RoPE results and a norm fold starting at 8 each make a parity test fail.

  • Orchestrator gate on the final head c6592780 (up to date with origin/main 33c4505): make verify-rocm passed every step, 11,873 tests passed, 0 failed, 378 ignored, smoke OK. That head adds host-side refusals for empty inputs (fused_add_rms_norm with an empty x or zero last dim, fused_rope_qk_append with a zero batch or window) and the matching Rust gate terms, so those shapes take the graph instead of launching a zero-size grid.

Not verified: Metal and CUDA (not available on this host). Their kernel sources and table entries are untouched; their predicates gained the GPU-device term, so MLXCEL_DEVICE=cpu now takes the graph path there instead of throwing, and their parity tests now fail rather than skip if the predicate is false. Gemma and IQuest Loop Coder also call the norm port but have no checkpoint here. Wave64 (CDNA) untested.

Closes #2063

Both kernels had Metal and CUDA ports only, so on ROCm `MLXCEL_FUSED_ADD_RMSNORM=1` and `MLXCEL_FUSED_ROPE_APPEND=1` silently kept the graph path. Each table now has a `.rocm` entry compiled through `fast::hip_kernel` from a HIP body in its own header; the launch stays in the existing file, so the dtype-key pin is unchanged.

Each port follows ROCm's own graph rather than the Metal kernel, so it is byte-identical to the path it replaces on gfx1151 in f32, f16 and bf16: the norm launches the overlay's 256-thread `rms_norm_kernel` block with 32-wide xor folds and `1.0f / sqrtf`; the RoPE body computes the angle in `rope.hip` order with `sincosf` and spells out the two rotation FMAs, because hipRTC contracted the second one differently from hipcc.

Both predicates now also require the GPU as the default device, so `MLXCEL_DEVICE=cpu` takes the graph path. The Rust gates cache only the port answer and read the device per call. The parity tests fail instead of skipping on a GPU backend whose predicate is false, gain ROCm byte-identity tests and a RoPE dtype sweep, and `cpu_device_custom_kernel_gates` covers both predicates. build.rs tracks the new headers.

Refs #2063
… bit

Decode traces with the fusions on differed from the graph path although the parity tests passed, because the tests missed three places where hipRTC and the hipcc-compiled overlay kernels round differently:

- RoPE, batch-1 decode: the graph runs `rope_single_1d` there and `rope` otherwise, and the two fuse the second rotation output differently. The HIP body now picks the matching `fmaf` form from the same condition, under `fp contract(off)`.
- RoPE, f16: the graph rounds each fused result to f16 once. The body forms it in double and converts once for `__half`; f32 and bf16 keep the `fmaf` value.
- RMSNorm at width 4096: with `Dim` as a compile-time constant about 1% of f32 rows came out a normalizer ulp off. The body reads the row length from `weight_shape[0]`, as the graph takes it at run time.

The byte-identity tests gain batch-1 single-token, long-window and spread-row-scale cases; each fails with the corresponding fix reverted. A 432-case RoPE stress run and a 4096-row norm stress run at four widths matched the graph in f32, f16 and bf16.

Refs #2063
With the previous fixes, Llama 3.1 decode traces with `MLXCEL_FUSED_ADD_RMSNORM=1` still differed from the graph at 5 of 128 positions. Instrumenting the join showed one element per affected call: the port wrote +0 where the graph writes -0, for a normalized element that underflows in f16 or a zero weight times a negative element.

The graph multiplies the gain in the activation dtype (`w * normalized`); the port multiplied in f32 and rounded once, which gives the same value but hipRTC's code for it dropped the sign of a zero product. The HIP body now multiplies in `T` as the graph does. With this, Llama 3.1 8B and Qwen2.5 7B teacher-forced traces (w1, w8 and w1ctx512) with the fusions on are byte-identical to the fusions off.

New test `fused_add_rms_norm_keeps_the_rocm_graph_sign_of_zero` covers underflowing elements and signed-zero weights in f32, f16 and bf16.

Refs #2063
Results page for #2063 with what each HIP port matches, the tests that pin it, teacher-forced traces and decode with the fusions off and on, plus the raw rows and traces under `benchmarks/`.

Decode on gfx1151, medians: Llama 3.1 8B 37.85 off and 37.95 tok/s with the norm port (five rounds); Qwen2.5 7B 46.53 off, 47.23 add, 46.80 rope and 47.32 tok/s both (seven rounds), with on above off in 6 of 7 rounds but a gain whose size drifted between runs as much as the off arm's spread; Qwen3-30B-A3B, which calls neither kernel, as a control at +0.3%. That is not a clear win, so `FUSED_ADD_RMSNORM_DEFAULT` and `FUSED_ROPE_APPEND_DEFAULT` stay false on every backend; their doc comments, `docs/environment-variables.md`, `docs/installation.md`, README and the correctness page say so and link the results.

Refs #2063
Review follow-ups for #2063:

- The fused add-RMSNorm and RoPE gates read the default device and then the C++ predicate, which reads it again. A device move between the two reads cached `false` for the rest of the process. `gpu_port_available` now caches only a `true` answer.
- `fused_rope_append_matches_graph_rope_every_dtype` held bf16 to the f16 budget, about one bf16 ulp on a 2-sigma element, which a single rounding flip on Metal or CUDA (where the two paths contract differently) would fail. bf16 now uses the norm tests' bf16 budget; f32 and f16 are unchanged.
- The results page says ROCm fixes the norm's `Threads` at 256.

Parity tests (21), `cpu_device_custom_kernel_gates`, `dead_doc_pointers`, clippy on mlxcel-core lib and tests, and fmt pass on gfx1151.

Refs #2063
@inureyes inureyes added type:performance Performance improvements priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:linux Linux (CUDA / packaging) specific status:review Under review labels Oct 5, 2026
Resolves the docs/installation.md ROCm status table: keeps this branch's fused norm and RoPE row and main's paged-attention row (#2103), and drops the "other fused kernels" row, since every kernel it named now has a HIP port.
Security-review follow-ups for #2063. An empty input reached the fused launchers with a zero-size grid, and a zero-width row made the norm launcher divide by zero; the Rust eligibility checks now require a non-empty input with a positive row width (norm) or a positive batch and window (RoPE), and the launchers throw on the same cases for a direct caller. These cases already existed on Metal and CUDA; there they now also take the graph.

Also: the wave-guard comment in the norm HIP body names HIP 7.15's AMD clang 23 and says a firing guard is an evaluation error, not a fallback; the results page states the Qwen2.5 round-by-round ranges as the CSVs give them.

Refs #2063
@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 5, 2026
@inureyes
inureyes merged commit 022067a into main Oct 5, 2026
25 checks passed
@inureyes
inureyes deleted the update/issue-2063-rocm-fused-norm-rope branch October 5, 2026 10:28
inureyes added a commit that referenced this pull request Oct 6, 2026
## Summary

The shuffle-based HIP ports have only run on 32-lane wavefronts, and their `#error` guards on `__AMDGCN_WAVEFRONT_SIZE` are inert because AMD clang 23 defines neither macro spelling (rechecked here with `hipcc -E -dM` for gfx1151, gfx942 and gfx90a). This PR holds those ports to 32-lane devices at port selection, so a wave64 (CDNA) device takes the graph fallbacks instead of running unvalidated kernels. Nothing changes on gfx1151.

## What changed

- `port_for` (`kernel_port.cpp`) returns a ROCm port only when `rocm_port_allowed(ports.rocm_any_wave_size, rocm_port_warp_size())`, so `has_kernel_port`, every `*_available()` predicate and `select_kernel_port` agree. The refusal message names the width; stderr notes a non-32 wavefront once per process.
- The width is the hardware value from a new overlay call, `mlx::core::rocm::device_warp_size()` (`hipDeviceAttributeWarpSize`, ignores `MLX_ROCM_FORCE_WARP_SIZE`, 0 on error), recorded as LOCAL_FIXES item 32 (new "Additions to the fork's API" section; #2164 took 31) and stubbed in `no_rocm.cpp`. It clears only an HIP error it raised itself.
- `KernelPorts::rocm_any_wave_size` (default false) is set on the five tables whose HIP body has no lane-level operation: RoPE append, paged merge, Gumbel, rejection, and xIELU. xIELU is not in the issue's list, but checking the current code shows its body is purely elementwise; its inert guard is dropped, as the sampler and RoPE bodies already have none. The other ten ROCm tables (bitlinear, ssm, mamba1_scan, moe_gateup, moe_down, moe_fc1_relu2, add3_layer_norm, fused_norm, paged_attention, paged_v2_partial) stay wave32-only. #2107's fused norm is wave32-only (shuffles) and its RoPE port is any-wave.
- `bitlinear_kernel_available` now reads its port table (it returned "any GPU backend" before), so BitNet is refused at load on wave64 rather than failing mid-request.
- `verify-kernel-port-dispatch`: rule 5 pins the any-wave tables with their HIP source, follows each table's `.rocm` getter to its holder and requires exactly that source (no header argument, one raw literal), and fails on lane intrinsics, AMDGCN lane builtins, wavefront macros or 32-lane index arithmetic in it; rule 6 keeps the test seam `set_rocm_port_warp_size_for_tests` out of non-test code, with an exact use count in its definition files. `scripts/ci/check_kernel_port_dispatch_test.sh` (run by the make target and CI job) proves each rule fails on a mutated copy (13 cases).
- `mamba1_selective_scan` is now `-> Result<()>`, since `select_kernel_port` can refuse there; Mamba, Jamba and its parity test `expect` the gated launch. BitLinear's refusal names the BitNet load-time refusal instead of a graph fallback it lacks.
- Parity tests that assert a ROCm port exists (fused MoE, relu2, SSM, fused norm, Mamba1, add3) skip on a wave64 device through `test_support::kernel_ports::skip_for_wave32_only_rocm_port` instead of failing.
- `build.rs` now tracks `kernel_port.*` and `gpu_backend.*`; edits to them did not rebuild the bridge before (found when a negative check passed on a stale library).
- Guard comments now name the host-side check as the protection; `docs/installation.md` gains a "Wave64 devices" row; CONTRIBUTING and the paged-test skip message mention the hold.

## Verification (gfx1151)

- `cargo test --features rocm -p mlxcel-core --lib kernel_port`: 2 passed (`rocm_port_allowed` truth table, runs on every backend).
- `tests/rocm_wave_size.rs`: `device_warp_size() == 32` on gfx1151; with `MLX_ROCM_FORCE_WARP_SIZE=64` in a child (the child's device log confirms the override applied) it still reads 32; all 16 port predicates are true.
- `tests/rocm_wave64_port_refusal.rs`, with the reported width forced to 64 through the test seam: all 11 wave32-only predicates false, the five any-wave ones true; `bitlinear_matmul`, `fused_add_rms_norm` and `fused_moe_expert_kernel` (moe_gateup) refuse naming the width; `layers::fused_add_rms_norm` (fusion on) and `residual_add3_layer_norm` return the graph pair's bytes. With the hold disabled in `port_for`, this test fails listing all 11 tables.
- Existing port tests (debug profile): fused norm, RoPE, MoE, relu2, SSM, Mamba1, Gumbel, rejection, fixed-key, paged v2, MLA, residual add3: 357 passed; 2 `cache::paged_detach` tests fail on a `debug_assert` in the dev profile only (the gate's `test-fast` profile has no debug assertions; unrelated to ports). Apertus, BitNet and Cohere2 tests in the mlxcel lib: 26 passed. `cpu_device_custom_kernel_gates`: passed.
- `make verify-versions verify-kernel-dtype-keys verify-kernel-port-dispatch verify-llama-compat verify-fmt verify-rocm-overlay`: pass.
- `make verify-rocm` on the final head (merged with origin/main 08e2269): OK, 151 test suites, 11969 passed, 0 failed, 381 ignored; clippy, smoke, overlay and script gates pass. The targeted tests above were re-run after the review fixes (29 mlxcel-core, 30 Mamba/Jamba, the three integration files): all pass.
- Meta-Llama-3.1-8B-Instruct-4bit, release binary under `scripts/rocm_gpu_guard.sh` (clean attempt): greedy 64 tokens with `MLXCEL_FUSED_ADD_RMSNORM=0` and `=1` give identical text (33.88 and 33.90 tok/s, single run, not a performance claim); `rocprofv3 --kernel-trace` of a sampled run shows `custom_kernel_mlxcel_fused_add_rms_norm` (wave32-only, 544 launches) and `custom_kernel_mlxcel_gumbel_max_sample` (any-wave) still selected, and no wavefront notice on stderr.

Not verified: no wave64 device is available, so the refusal is proven only through the test seam. Metal and CUDA are not available on this host; the change touches the shared `KernelPorts` struct and `port_for`, whose Metal and CUDA cases are unchanged, and `bitlinear_kernel_available`, which answers the same on Metal and CUDA (both tables have ports).

Closes #2147
inureyes added a commit that referenced this pull request Oct 7, 2026
…ROCm (#2189)

## Summary

Turns the fused add-RMSNorm and RoPE + KV-append kernels on by default in a ROCm build, as the maintainer decided after #2107. Metal and CUDA defaults are unchanged.

- `FUSED_ADD_RMSNORM_DEFAULT` and `FUSED_ROPE_APPEND_DEFAULT` in `src/lib/mlxcel-core/src/layers.rs` are now `cfg!(feature = "rocm")`, following the build-flag pattern PR #2098 used for the ROCm SGY default. There is no runtime backend comparison, so `verify-kernel-port-dispatch` passes. `fused_flag_enabled_from` keeps its behavior: `=0` disables and `=1` enables on every backend.
- The new `layers::fused_flag_explicit_value` returns the setting a value spells out, or none. The Llama 3.1 `rope_scaling` bypass notice (`fused_rope_launcher_requested` in `src/models/llama3.rs`) now uses it, so the notice fires only for an explicit truthy `MLXCEL_FUSED_ROPE_APPEND` and default ROCm runs stay quiet.
- Tests: `fused_905_defaults_are_on_for_rocm_builds_only` pins both defaults to `cfg!(feature = "rocm")` and checks the override in each direction. `fused_flag_explicit_value_separates_a_setting_from_the_default` covers the parser, and `the_rope_append_bypass_notice_needs_an_explicit_truthy_value` covers the unset case.
- `scripts/rocm_decode_profile.py` now reports the #2063 roles as reached with the shipped defaults on ROCm, and its test is updated to match. The README's ROCm bullet no longer calls these fusions opt-in.
- Docs: `environment-variables.md` (Default column now reads "off (Metal, CUDA) / on (ROCm)"), the ROCm row in `installation.md`, `benchmarks.md`, the correctness-page note, and a new Decision section with the re-measurement on `rocm-fused-norm-rope-gfx1151-2026-10-05.md`. Raw CSVs are in `benchmarks/rocm_strixhalo-gfx1151_2026-10-07_fused-default-{on,off}.csv`.

## Re-measurement (gfx1151, pp512/tg128, medians of 3, arms alternated)

| Model | Default (on) | `=0` (off) | Change |
|---|---|---|---|
| Llama-3.1-8B-Instruct-4bit | 38.09 | 38.15 | -0.2% (noise; paired +0.02 / -0.49 / -0.05) |
| Qwen2.5-7B-Instruct-4bit | 47.90 | 47.51 | +0.8% (paired +0.39 / +0.30 / -0.04) |

Both changes are within run-to-run noise, so neither is a speedup claim. Every run went through `scripts/rocm_gpu_guard.sh` with the host-wide lock from #2146 (main's copy after #2161 merged). All 12 runs were clean on the first attempt.

## Verification

All on gfx1151:

- `logit_trace` `w8` for both models, default vs both variables at `0`: the files are byte-identical (`cmp`).
- `rocprofv3` kernel trace with no variables set: Qwen2.5 dispatches `fused_add_rms_norm` and `fused_rope_qk_append` 252 times each and no graph RoPE kernel. Llama 3.1 dispatches the norm port 288 times and keeps its graph RoPE.
- Bypass notice: absent with the default on Llama 3.1, present with `MLXCEL_FUSED_ROPE_APPEND=1`, absent with `=0`.
- `cargo test --profile test-fast --features rocm -p mlxcel-core --lib -- --test-threads=1 layers::tests::fused fused_norm_parity_tests fused_rope_parity_tests`: 32 passed.
- `cargo test --profile test-fast --features rocm --lib -- --test-threads=1 models::llama3::`: 27 passed, including `greedy_decode_is_token_identical_to_the_unfused_baseline`. That greedy test also passes with both variables at `0`.
- `make verify-versions verify-kernel-dtype-keys verify-kernel-port-dispatch verify-llama-compat verify-fmt`: pass.
- `make verify-rocm` at `9874c3c4` (rebased on `fc21784f`): OK. Clippy and the ROCm smoke test passed, and the tests had 11996 passed, 0 failed and 383 ignored across 152 test binaries.
- `python3 -m unittest tests.test_rocm_decode_profile`: 26 passed.

Not verified: Metal and CUDA (not available on this host). On those builds both constants evaluate to `false` as before, and the notice change only narrows when it prints. Gemma and IQuest Loop Coder now take the norm port by default on ROCm, but no checkpoint for either is available here.

Closes #2145
@inureyes inureyes added this to the 0.8 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 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(rocm): port fused_add_rms_norm and fused_rope_qk_append to HIP

1 participant