Skip to content

perf(models): generalize fused QKV+RMSNorm+RoPE to standard RMSNorm - #341

Merged
inureyes merged 4 commits into
mainfrom
perf/326-generic-fused-qkv-rmsnorm-rope
Jun 17, 2026
Merged

inureyes merged 4 commits into
mainfrom
perf/326-generic-fused-qkv-rmsnorm-rope

Conversation

@inureyes

Copy link
Copy Markdown
Member

Summary

Generalize FusedQKVLinear::forward_split_norm_rope_quantized so models with a standard RMSNorm Q/K norm can use the fused projection + split + Q/K norm + RoPE kernel, not only Gemma's (1 + weight) RMSNorm, then wire it into the Qwen3 and Qwen3-MoE decode attention paths. This targets the per-layer "extra small ops" decode gap that the MoE decode-gap investigation attributes to QK-norm models (docs/benchmark_results/moe-decode-gap-investigation.md).

What changed

  • src/lib/mlxcel-core/src/layers.rs: new FusedQkNorm trait (raw weight for RMSNorm, pre-computed (1 + weight) for GemmaRMSNorm); forward_split_norm_rope_quantized is now generic over it. The C++ kernel already applies the plain x * weight * rsqrt(mean(x^2) + eps) form, so the Gemma-vs-standard distinction is just which weight the trait hands back, never a kernel branch. The // Used by: comment is updated to Gemma3 + Qwen3 + Qwen3-MoE.
  • src/lib/mlxcel-core/src/lib.rs: FFI doc comment for fused_qkv_project_split_norm_rope updated to the generalized usage.
  • src/models/qwen3.rs, src/models/qwen3_moe.rs: each (separate but identical) attention module dispatches the fused path on decode (l == 1) and keeps the existing graph sequence as the prefill and non-quantized fallback. The kernel norms after the head transpose while the fallback norms before it; RMSNorm reduces over head_dim, which the transpose leaves untouched, so the two orders match per element. Gemma3 keeps passing GemmaRMSNorm and stays byte-identical.

Test plan

  • cargo check -p mlxcel-core --lib --tests and cargo check -p mlxcel --lib
  • cargo clippy -p mlxcel-core --lib --tests -- -D warnings and cargo clippy -p mlxcel --lib -- -D warnings (clean)
  • cargo test --release -p mlxcel-core layers::tests::fused_qkv (4 passed: standard-RMSNorm match RMS < 5e-3, Gemma unchanged, variant selects (1 + weight), plus the existing fused-QKV bias test). Each comparison test asserts the projection is non-degenerate so it cannot pass on a zero projection.
  • cargo fmt --check
  • Real-model validation (orchestrator): RMS < 5e-3 vs graph + greedy temp-0 parity + mlxcel-bench-decode on qwen3-0.6b/8b/30b-a3b-4bit and Apertus-8B-2509-4bit, with a non-QK-norm dense (Llama) regression guard.

Closes #326

Generalize FusedQKVLinear::forward_split_norm_rope_quantized so models with a standard RMSNorm Q/K norm can use the fused projection + split + norm + RoPE kernel, not only Gemma's (1 + weight) RMSNorm, then wire it into the Qwen3 and Qwen3-MoE decode attention paths (#326).

The C++ kernel already applies the plain x * weight * rsqrt(mean(x^2) + eps) form, so the only Gemma-vs-standard difference is the weight fed to it. A new FusedQkNorm trait returns the raw weight for RMSNorm and the pre-computed (1 + weight) for GemmaRMSNorm; the primitive is now generic over that trait. Gemma3 keeps passing GemmaRMSNorm and stays byte-identical.

Qwen3 and Qwen3-MoE (separate but identical attention modules) each dispatch the fused path on decode (l == 1) and keep the existing graph sequence as the prefill and non-quantized fallback. The kernel norms after the head transpose while the fallback norms before it; RMSNorm reduces over head_dim, which the transpose leaves untouched, so the two orders match per element.

Tests: the fused primitive with a standard RMSNorm matches the graph sequence within RMS < 5e-3, the GemmaRMSNorm path is unchanged, and feeding the same raw weights as RMSNorm vs GemmaRMSNorm produces materially different output (guards against hardcoding or dropping the (1 + weight) offset). Each test asserts the projection is non-degenerate so none can pass on a zero projection.
@inureyes inureyes added type:performance Performance improvements priority:high High priority area:models Model architectures, weights, loading, metadata area:core mlxcel-core: MLX FFI, primitives, KV cache, layers status:review Under review labels Jun 17, 2026
inureyes added 2 commits June 18, 2026 03:10
Add a process-level OnceLock gate for the fused QKV+RMSNorm+RoPE decode
kernel (#326), following the same pattern as MLXCEL_FUSED_MOE in
switch_layers.rs. The env var is read once at first call via
fused_qk_norm_enabled_from() and cached; per-step env::var() lookups are
explicitly avoided to prevent regressing the decode hot path.

Gate is applied in Qwen3 and Qwen3-MoE attention forward: fused path
requires l==1 (decode) AND quantized weights AND kill-switch not disabled.
Setting MLXCEL_FUSED_QK_NORM=0 (also false/off/no, case-insensitive) forces
the graph fallback path for both models.

Also add a debug_assert_eq! in FusedQKVLinear::forward_split_norm_rope_quantized
documenting that the C++ primitive uses a single eps for both Q and K norms;
compiled out in release so there is no hot-path cost.

New test fused_qk_norm_enabled_defaults_on_and_respects_disable_values covers
the pure decision function; all 25 layers:: tests pass.
Add the new kill-switch next to the MLXCEL_FUSED_MOE family. Entry covers
what it gates (fused QKV+QK-norm+RoPE decode for Qwen3 / Qwen3-MoE),
default (on), how to disable (set to 0/false/off/no), and that it is a
safety valve for the jitter-class (RMS < 5e-3, not bit-exact) fused path.
@inureyes

Copy link
Copy Markdown
Member Author

PR finalization

Kill-switch: MLXCEL_FUSED_QK_NORM

Added fused_qk_norm_enabled() in mlxcel_core::layers, following the exact pattern of fused_moe_enabled() in switch_layers.rs:

  • Backed by a static OnceLock<bool>, read from MLXCEL_FUSED_QK_NORM at first call and cached for the process lifetime. Per-step env lookups are not possible.
  • fused_qk_norm_enabled_from(Option<&str>) is a pure, testable helper (same split as fused_moe_enabled_from).
  • Accepted disable values: 0, false, off, no (case-insensitive, trimmed). Unset or any other value keeps the kernel on.
  • Gate is applied in both qwen3.rs and qwen3_moe.rs: fused path requires l == 1 AND quantized weights AND kill-switch not disabled. MLXCEL_FUSED_QK_NORM=0 forces the graph fallback for both.

Defensive eps assertion

FusedQKVLinear::forward_split_norm_rope_quantized now has debug_assert_eq!(q_norm.rms_eps(), k_norm.rms_eps(), ...) immediately before the FFI call. Compiled out in release; zero hot-path cost.

Test

New fused_qk_norm_enabled_defaults_on_and_respects_disable_values test covers the pure helper. All 25 layers:: tests pass.

Docs

MLXCEL_FUSED_QK_NORM added to docs/environment-variables.md next to the MLXCEL_FUSED_MOE family. No Korean mirror of that file exists.

Commits

  • 75947da feat(layers): add MLXCEL_FUSED_QK_NORM kill-switch and eps assertion
  • 90f2e45 docs: document MLXCEL_FUSED_QK_NORM in environment-variables.md

Clippy and fmt clean on both crates. Ready for real-model validation with MLXCEL_FUSED_QK_NORM=0 for fused-vs-graph A/B.

Real-model warmup+measured benchmarks on M1 Ultra show the fused QKV+RMSNorm+RoPE decode path is about 1 to 3.4% slower than the graph path (qwen3-0.6b 275 vs 284, qwen3-8b 82.3 vs 83.2 tok/s), consistent across runs. The fused kernel reduces Rust/C++ FFI crossings rather than MLX op count, and on Apple Silicon's fast FFI that saving is net-negative. Decode output is byte-identical to the graph path on Qwen3 and Qwen3-MoE (the RMSNorm reduces over the transpose-invariant head_dim axis), so this is a pure throughput regression, not a correctness issue.

Flip MLXCEL_FUSED_QK_NORM to default off (opt-in via 1/true/on/yes). The generalized FusedQkNorm primitive still ships as the reusable foundation for the deferred QK-norm families, and the fused dispatch can be enabled on backends where it wins (for example CUDA, where op-dispatch and FFI cost differ and a per-backend re-bench is the follow-up). This mirrors the opt-in treatment of the performance-neutral MLXCEL_FUSED_MOE_RELU2 path. Default behavior is now the unchanged graph path, so no decode regression ships on by default.
@inureyes

Copy link
Copy Markdown
Member Author

Real-model validation + perf decision (orchestrator)

Validated on M1 Ultra (Metal). Branch built clean (metal,accelerate).

Correctness: PASS (byte-identical)

Within-binary A/B (fused default vs MLXCEL_FUSED_QK_NORM=0 graph path), greedy temp=0, --no-chat-template, n=64:

Model Attention path fused vs graph generated text
qwen3-0.6b-4bit dense (qwen3.rs) byte-identical
qwen3-8b-4bit dense (qwen3.rs) byte-identical
qwen3-30b-a3b-4bit MoE (qwen3_moe.rs) byte-identical

Both wired attention structs produce output identical to the graph path (the RMSNorm reduces over the transpose-invariant head_dim axis, so norm-before-transpose and norm-after-transpose commute exactly). The unit test already shows RMS < 5e-3 vs graph on synthetic quantized weights.

Performance: fused path is a small regression on M1 Ultra

Warmup (64) + measured (256) decode tok/s, 2 runs each, fused vs graph:

Model fused tok/s graph tok/s delta
qwen3-0.6b-4bit 275.5 / 273.8 284.1 / 284.3 about -3.4%
qwen3-8b-4bit 82.3 / 82.4 83.2 / 83.2 about -1.1%

Consistent across runs, so not noise. As the security review noted, the fused kernel cuts Rust/C++ FFI crossings rather than MLX op count; on Apple Silicon's fast FFI that saving is net-negative.

Decision: default the kill-switch OFF (opt-in)

Commit 5a5cb069d flips MLXCEL_FUSED_QK_NORM to default off (opt-in via 1/true/on/yes). The default decode path is now the unchanged graph path, so no regression ships on by default. The generalized FusedQkNorm primitive still ships as the reusable foundation for the deferred QK-norm families, and the fused dispatch can be enabled where it wins. This mirrors the opt-in treatment of the performance-neutral MLXCEL_FUSED_MOE_RELU2 path. A per-backend re-bench (notably CUDA, where op-dispatch and FFI cost differ) is the follow-up to decide where, if anywhere, to default it on.

Reviewer, security-checker, and finalizer: 0 CRITICAL/HIGH/MEDIUM. Acceptance criteria met: generalized primitive accepts standard RMSNorm, Qwen3 + Qwen3-MoE dispatch the fused path (now opt-in), RMS < 5e-3 + byte-identical greedy parity, // Used by: updated, kill-switch + docs added.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Jun 17, 2026
@inureyes
inureyes merged commit 015d126 into main Jun 17, 2026
4 checks passed
@inureyes
inureyes deleted the perf/326-generic-fused-qkv-rmsnorm-rope branch June 17, 2026 18:25
inureyes added a commit that referenced this pull request Jun 19, 2026
…#357)

Answer the open per-backend question left when the fused QKV+QK-norm+RoPE
decode primitive (#326, #341) merged default-OFF: whether CUDA, with its
different op-dispatch cost, is the per-backend win that would justify enabling
it. On GB10 (SM 12.1) it is not. The fused path is slower on every wired model
(qwen3-0.6b 0.96x, qwen3-8b ~1.0x, qwen3-30b-a3b 0.92x fused/graph), worst on
the 48-layer MoE where the per-layer norm/transpose reorder accumulates.

The primitive assembles the same MLX ops as the graph path in one C++ call, so
the GPU work is identical; it only cuts FFI crossings (about 14 to 1) and norms
after the head transpose. Decode is GPU/bandwidth-bound, so collapsing FFI calls
buys nothing and the reorder costs a little. Same direction as M1 Ultra
(1-3.4% slower) and consistent with M5 Max preferring the split decode path.

Correctness holds: RMS < 5e-3 (unit test); greedy temp-0 diverges only at a
near-tie argmax over long generation, and the graph path is itself
non-deterministic run-to-run on CUDA while the fused path is deterministic, so
the divergence stays inside the graph baseline's own envelope. Corrects the
stale "byte-identical" claim and the "pending a per-backend win (e.g. CUDA)"
note in the fused_qk_norm_enabled doc comment.

Add docs/benchmark_results/fused-qk-norm-decode-gb10.md with the full method,
on/off table, and determinism analysis. No code behavior change; the flag stays
default-OFF.
@inureyes inureyes added this to the 0.3 milestone Jun 21, 2026
inureyes added a commit that referenced this pull request Jun 25, 2026
CUDA (GB10/SM 12.1) was the last open backend question after the M1 Ultra regression (#326, #341). The GB10 benchmark (#357) found the fused path is also slower there (qwen3-0.6b 0.96x, qwen3-8b ~1.0x, qwen3-30b-a3b 0.92x fused/graph), so there is no per-backend win on any measured backend (M1 Ultra, M5 Max, GB10/CUDA). The default stays off on all backends; no code changes.

Two stale claims in the MLXCEL_FUSED_QK_NORM table row in docs/environment-variables.md are corrected:

1. The byte-identical overclaim is replaced with the canonical precision from the layers.rs doc comment: the fused path matches within RMS < 5e-3, but greedy temp-0 is not byte-identical over long generation. The determinism note is added: on CUDA the graph path is non-deterministic run-to-run from GPU FP-reduction order, while the fused path is deterministic, so its divergence from the graph stays inside the graph baseline's own envelope.

2. The CUDA-pending rationale is replaced with the settled verdict: GB10/CUDA was measured and is also slower, so the flag stays opt-in on every measured backend.

CHANGELOG.md gets a Docs entry under [Unreleased] recording the decision finalization.
@inureyes inureyes self-assigned this Aug 31, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…ablup#341)

* perf(models): generalize fused QKV+RMSNorm+RoPE to standard RMSNorm

Generalize FusedQKVLinear::forward_split_norm_rope_quantized so models with a standard RMSNorm Q/K norm can use the fused projection + split + norm + RoPE kernel, not only Gemma's (1 + weight) RMSNorm, then wire it into the Qwen3 and Qwen3-MoE decode attention paths (lablup#326).

The C++ kernel already applies the plain x * weight * rsqrt(mean(x^2) + eps) form, so the only Gemma-vs-standard difference is the weight fed to it. A new FusedQkNorm trait returns the raw weight for RMSNorm and the pre-computed (1 + weight) for GemmaRMSNorm; the primitive is now generic over that trait. Gemma3 keeps passing GemmaRMSNorm and stays byte-identical.

Qwen3 and Qwen3-MoE (separate but identical attention modules) each dispatch the fused path on decode (l == 1) and keep the existing graph sequence as the prefill and non-quantized fallback. The kernel norms after the head transpose while the fallback norms before it; RMSNorm reduces over head_dim, which the transpose leaves untouched, so the two orders match per element.

Tests: the fused primitive with a standard RMSNorm matches the graph sequence within RMS < 5e-3, the GemmaRMSNorm path is unchanged, and feeding the same raw weights as RMSNorm vs GemmaRMSNorm produces materially different output (guards against hardcoding or dropping the (1 + weight) offset). Each test asserts the projection is non-degenerate so none can pass on a zero projection.

* feat(layers): add MLXCEL_FUSED_QK_NORM kill-switch and eps assertion

Add a process-level OnceLock gate for the fused QKV+RMSNorm+RoPE decode
kernel (lablup#326), following the same pattern as MLXCEL_FUSED_MOE in
switch_layers.rs. The env var is read once at first call via
fused_qk_norm_enabled_from() and cached; per-step env::var() lookups are
explicitly avoided to prevent regressing the decode hot path.

Gate is applied in Qwen3 and Qwen3-MoE attention forward: fused path
requires l==1 (decode) AND quantized weights AND kill-switch not disabled.
Setting MLXCEL_FUSED_QK_NORM=0 (also false/off/no, case-insensitive) forces
the graph fallback path for both models.

Also add a debug_assert_eq! in FusedQKVLinear::forward_split_norm_rope_quantized
documenting that the C++ primitive uses a single eps for both Q and K norms;
compiled out in release so there is no hot-path cost.

New test fused_qk_norm_enabled_defaults_on_and_respects_disable_values covers
the pure decision function; all 25 layers:: tests pass.

* docs: document MLXCEL_FUSED_QK_NORM in environment-variables.md

Add the new kill-switch next to the MLXCEL_FUSED_MOE family. Entry covers
what it gates (fused QKV+QK-norm+RoPE decode for Qwen3 / Qwen3-MoE),
default (on), how to disable (set to 0/false/off/no), and that it is a
safety valve for the jitter-class (RMS < 5e-3, not bit-exact) fused path.

* perf(models): make fused QK-norm decode opt-in (M1 Ultra regression)

Real-model warmup+measured benchmarks on M1 Ultra show the fused QKV+RMSNorm+RoPE decode path is about 1 to 3.4% slower than the graph path (qwen3-0.6b 275 vs 284, qwen3-8b 82.3 vs 83.2 tok/s), consistent across runs. The fused kernel reduces Rust/C++ FFI crossings rather than MLX op count, and on Apple Silicon's fast FFI that saving is net-negative. Decode output is byte-identical to the graph path on Qwen3 and Qwen3-MoE (the RMSNorm reduces over the transpose-invariant head_dim axis), so this is a pure throughput regression, not a correctness issue.

Flip MLXCEL_FUSED_QK_NORM to default off (opt-in via 1/true/on/yes). The generalized FusedQkNorm primitive still ships as the reusable foundation for the deferred QK-norm families, and the fused dispatch can be enabled on backends where it wins (for example CUDA, where op-dispatch and FFI cost differ and a per-backend re-bench is the follow-up). This mirrors the opt-in treatment of the performance-neutral MLXCEL_FUSED_MOE_RELU2 path. Default behavior is now the unchanged graph path, so no decode regression ships on by default.
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…p#326) (lablup#357)

Answer the open per-backend question left when the fused QKV+QK-norm+RoPE
decode primitive (lablup#326, lablup#341) merged default-OFF: whether CUDA, with its
different op-dispatch cost, is the per-backend win that would justify enabling
it. On GB10 (SM 12.1) it is not. The fused path is slower on every wired model
(qwen3-0.6b 0.96x, qwen3-8b ~1.0x, qwen3-30b-a3b 0.92x fused/graph), worst on
the 48-layer MoE where the per-layer norm/transpose reorder accumulates.

The primitive assembles the same MLX ops as the graph path in one C++ call, so
the GPU work is identical; it only cuts FFI crossings (about 14 to 1) and norms
after the head transpose. Decode is GPU/bandwidth-bound, so collapsing FFI calls
buys nothing and the reorder costs a little. Same direction as M1 Ultra
(1-3.4% slower) and consistent with M5 Max preferring the split decode path.

Correctness holds: RMS < 5e-3 (unit test); greedy temp-0 diverges only at a
near-tie argmax over long generation, and the graph path is itself
non-deterministic run-to-run on CUDA while the fused path is deterministic, so
the divergence stays inside the graph baseline's own envelope. Corrects the
stale "byte-identical" claim and the "pending a per-backend win (e.g. CUDA)"
note in the fused_qk_norm_enabled doc comment.

Add docs/benchmark_results/fused-qk-norm-decode-gb10.md with the full method,
on/off table, and determinism analysis. No code behavior change; the flag stays
default-OFF.
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…lablup#444)

CUDA (GB10/SM 12.1) was the last open backend question after the M1 Ultra regression (lablup#326, lablup#341). The GB10 benchmark (lablup#357) found the fused path is also slower there (qwen3-0.6b 0.96x, qwen3-8b ~1.0x, qwen3-30b-a3b 0.92x fused/graph), so there is no per-backend win on any measured backend (M1 Ultra, M5 Max, GB10/CUDA). The default stays off on all backends; no code changes.

Two stale claims in the MLXCEL_FUSED_QK_NORM table row in docs/environment-variables.md are corrected:

1. The byte-identical overclaim is replaced with the canonical precision from the layers.rs doc comment: the fused path matches within RMS < 5e-3, but greedy temp-0 is not byte-identical over long generation. The determinism note is added: on CUDA the graph path is non-deterministic run-to-run from GPU FP-reduction order, while the fused path is deterministic, so its divergence from the graph stays inside the graph baseline's own envelope.

2. The CUDA-pending rationale is replaced with the settled verdict: GB10/CUDA was measured and is also slower, so the flag stays opt-in on every measured backend.

CHANGELOG.md gets a Docs entry under [Unreleased] recording the decision finalization.
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:models Model architectures, weights, loading, metadata priority:high High priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(models): generalize fused QKV+RMSNorm+RoPE to standard-RMSNorm QK-norm models

1 participant