Skip to content

perf(gemma4): cut decode-path primitive count on CUDA (#680) - #682

Merged
inureyes merged 4 commits into
mainfrom
perf/680-gemma4-decode-op-count
Jul 7, 2026
Merged

inureyes merged 4 commits into
mainfrom
perf/680-gemma4-decode-op-count

Conversation

@inureyes

@inureyes inureyes commented Jul 7, 2026 •

Copy link
Copy Markdown
Member

Summary

The #680 profiling attributed the gemma-4-12b decode gap to a CPU-bound per-step MLX primitive count and asked for >=1.8x decode by cutting that count. Re-measuring the same nsys traces shows that attribution is wrong: gemma-4-12b-it-4bit decode is GPU-weight-bandwidth-bound (the GPU is ~93-95% busy streaming the checkpoint's 8-bit MLP weights), so cutting the primitive count cannot move throughput. This PR corrects the attribution with evidence and lands the one primitive-count reduction that is a genuine latent fix (compiling the 8-bit affine GeGLU MLP), gated so it does not regress prefill or peak. Honest bottom line: the 1.8x bar is not reachable in scope, for the reason documented below.

Corrected attribution (re: the #680 profiling comment)

The earlier pass summed only CUPTI_ACTIVITY_KIND_KERNEL for GPU time (8.66 ms across the whole gemma trace, 1.28 ms for the llama control) and concluded the GPU was idle and decode was CPU-bound on ~2383 primitives/step at ~28 us each. That table only holds kernels launched OUTSIDE a CUDA graph; on GB10 MLX captures each forward into CUDA graphs, so the real GPU work is in CUPTI_ACTIVITY_KIND_GRAPH_TRACE, which was never summed. Re-measured over a steady-state 20-decode-step window from the same sqlite exports: gemma-4-12b spends 1329 ms of GPU graph execution inside a 1422 ms wall = 93.5% GPU-busy at 71.1 ms/step; the llama-3.1-8b control's GRAPH_TRACE totals 2333 ms at ~21.4 ms/step, also GPU-bound. The attribution error was systematic, not gemma-specific, so the "GPU idle, ~28 us/primitive CPU cost" framing does not hold for either model.

gemma-4-12b-it-4bit is a mixed-precision checkpoint: attention q/k/v/o are 4-bit but every MLP gate/up/down is group_size=64 bits=8 (config.json quantization). Per-token active weight is ~10.1 GB (48 layers x ~200 MB: 23.6 MB 4-bit attention + 176.9 MB 8-bit MLP, plus a 4-bit lm_head), a ~37 ms/token floor at 273 GB/s; measured 71 ms/token is ~140 GB/s effective. The llama control streams ~4.5 GB/token at ~214 GB/s effective, so it is faster because it is smaller, pure 4-bit (half the MLP bytes), and its 4-bit qmm GEMV reaches higher bandwidth than the 8-bit path. The issue's "44 ms context-independent overhead" is exactly this weight streaming: bytes do not scale with k_len, which is why decode is flat from 512 to 32768.

What changed

compiled_gelu_approx_mlp_forward (src/lib/mlxcel-core/cpp/mlx_cxx_bridge.cpp) previously took its fused mx::compile path only for group_size=64/bits=4 affine MLPs, so the 8-bit MLP of every gemma-4 mixed-precision checkpoint fell through to the op-at-a-time fallback, where gelu_tanh_approx emits ~14 element-wise primitives per layer (7 Multiply + 4 Broadcast + 2 Add + 1 Tanh). The compiled path is now keyed on (group_size, bits, mode) so any affine quantization gets the fusion, collapsing those ops into one Compiled primitive. It is applied only to the single-token decode call (l == 1) for the newly covered non-4-bit cases; the original group_size=64/bits=4 path is preserved bit-for-bit (compiled on every shape). MLXCEL_COMPILED_QGELU_MLP=0 forces the op-at-a-time fallback (A/B + rollback; documented in docs/environment-variables.md).

Testing

compiled_gelu_approx_mlp_forward had no Rust FFI unit coverage before this PR. Three new tests in src/lib/mlxcel-core/src/ffi_tests.rs close that gap: one asserts the new group_size=64/bits=8 single-token decode path (the fusion this PR adds) matches an op-at-a-time quantized-matmul + tanh-GELU reference; one asserts a multi-token input on the same 8-bit weights correctly takes the fallback path and still matches that reference, proving the decode gate excludes prefill as intended; and one asserts the pre-existing group_size=64/bits=4 legacy always-compiled path still matches the reference on a multi-token input. cargo test -p mlxcel-core --lib compiled_qgelu_mlp_forward passes all three.

Per-lever measured deltas (GB10, release, mlxcel-bench-decode)

Lever (c) compile the MLP element-wise chain (the largest primitive reducer of the candidates): verified by nsys to cut per-step primitives Multiply 394->59 and total 2383->1853 (~530 removed; Tanh and the gelu Broadcasts gone, Compiled 1->97/step). Decode throughput moved under 1% because the GPU is already ~94% busy (bandwidth-bound). Compiling the 8-bit PREFILL GEMM regressed prefill 8-9% and +0.2-0.7 GB peak (the fused shapeless graph forces a decode-oriented qmm kernel onto the large prefill matmul), so it is gated OUT of prefill; decode-only keeps the primitive cut with no prefill/peak regression (see table). Levers (a) redundant view/copy elimination, (b) fold layer_scalar, (d) route full-attention decode to fused SDPA, and (e) port fused QK-norm each remove FEWER primitives than (c), so on a ~94%-GPU-busy decode each is bounded above by (c)'s sub-1% and none was pursued once (c) established the op-count ceiling.

Final A/B (MLXCEL_COMPILED_QGELU_MLP: 0 = op-at-a-time, 1 = decode-gated compiled, default)

model ctx decode tok/s 0 -> 1 prefill tok/s 0 -> 1 mlx peak GB 0 -> 1
gemma-4-12b-it-4bit 512 14.63 -> 14.72 1190.2 -> 1190.6 11.60 -> 11.60
gemma-4-12b-it-4bit 2048 14.39 -> 14.45 966.4 -> 956.8 13.00 -> 13.00
gemma-4-12b-it-4bit 8192 14.30 -> 14.38 815.3 -> 825.3 14.51 -> 14.51
llama-3.1-8b-4bit (control) 2048 47.62 -> 47.63 2762.7 -> 2777.7 7.08 -> 7.08
gemma-4-31b-it-4bit (family) 2048 8.72 -> 8.74 408.7 -> 430.4 21.67 -> 22.16

Decode is flat within run-to-run noise (+0.4 to +0.6% on the 12b); prefill and peak are unchanged (the earlier 8-9% prefill / +0.2-0.7 GB regression of the ungated prototype is gone). llama-3.1-8b is untouched (SwiGLU, 4-bit). gemma-4-31b is uniform 4-bit, so it already used the compiled path and is unaffected; its prefill/peak delta is single-run noise. Full data in benchmarks/cuda_gb10_gemma_decode_680_2026-07-07.csv.

Token identity

The compiled-decode path fuses the tanh-approx GELU, an FP-reassociating change (lever c), so near-tie greedy drift is expected and permitted (as in #681). The gemma-4-12b-it checkpoint greedy-collapses to EOS/pad within 1-2 tokens at temp 0 in this harness for essentially every prompt, and the op-at-a-time path (MLXCEL_COMPILED_QGELU_MLP=0, the unchanged main code) collapses the same way, so a clean long-form identity comparison is not available on this checkpoint. Where the two paths emit the same confident leading token(s) they match ("Write the numbers from 1 to 20" is identical on both paths); the only divergences are single tokens at the near-tied EOS boundary ("The user" vs "The"), the benign FP-reassociation near-tie drift documented for compile/fusion levers. The op-at-a-time path is byte-identical to main by construction (only a new compiled branch was added; the fallback is untouched).

Honest statement vs the 1.8x bar

Not met, and not reachable by reducing the decode-path primitive count: decode is GPU-weight-bandwidth-bound (~94% GPU-busy) on the checkpoint's 8-bit MLP, so removing cheap element-wise primitives is throughput-neutral (measured under 1% from a ~530-primitive/step cut, the largest cut of the candidate levers). The 1.8x acceptance criterion was set against the earlier CPU-bound attribution, which this PR corrects. Reaching it needs fewer bytes per token (requantizing the MLP to 4-bit, which changes the checkpoint and its output) or a faster MLX 8-bit qmm GEMV kernel (MLX overlay); both are out of scope here. This mirrors the #675 re-scope: a correct, non-regressing change plus honest measurement that the target is bounded by a different bottleneck. The landed change is still worthwhile: it removes ~530 CPU-dispatched primitives/step (real on op-count-bound backends), fixes a latent inefficiency for every 8-bit affine gemma checkpoint, and does not regress prefill, peak, or the op-at-a-time output on GB10.

Closes #680

inureyes added 2 commits July 7, 2026 12:27
The compiled `mx::compile` GeGLU MLP path only fired for group_size=64/bits=4 affine weights, so the group_size=64/bits=8 MLP of Gemma 4 mixed-precision checkpoints (gemma-4-12b-it-4bit and family) fell through to the op-at-a-time fallback, where `gelu_tanh_approx` emits ~14 element-wise MLX primitives per layer (7 Multiply + 4 Broadcast + 2 Add + 1 Tanh). Keying the compiled cache on (group_size, bits, mode) lets any affine quantization take the fused path, collapsing those ops into one `Compiled` primitive and cutting ~530 primitives/step at decode (nsys-verified: Multiply 394->59/step, total 2383->1853/step).

The fusion is applied only to the single-token decode call for the newly covered non-4-bit cases. Compiling the 8-bit prefill GEMM measured 8-9% slower and +0.2-0.7 GB peak on GB10 (the shapeless fused graph forces a decode-oriented qmm kernel onto the large prefill matmul), so prefill for these checkpoints stays on the op-at-a-time path; the original group_size=64/bits=4 case is preserved bit-for-bit on every shape.

Context for #680: re-measuring the nsys traces (summing CUPTI_ACTIVITY_KIND_GRAPH_TRACE, not just the non-graph KERNEL table the earlier attribution used) shows gemma-4-12b decode is ~93-95% GPU-busy streaming the 8-bit MLP weights (~10 GB/token), i.e. weight-bandwidth-bound, not CPU-primitive-bound. This primitive-count cut is therefore throughput-neutral on GB10 (measured under 1%); it still removes real CPU dispatch and helps op-count-bound backends, and fixes a latent inefficiency for every 8-bit affine gemma checkpoint. `MLXCEL_COMPILED_QGELU_MLP=0` forces the fallback.
Records the decode-gated compiled-MLP A/B (MLXCEL_COMPILED_QGELU_MLP 0 vs 1) at 512/2048/8192 for gemma-4-12b-it-4bit, plus a llama-3.1-8b-4bit non-gemma control and a gemma-4-31b-it-4bit family-scaling point. Confirms the fix is throughput-neutral at decode (within run-to-run noise) and non-regressing on prefill and peak, consistent with the corrected GPU-weight-bandwidth-bound attribution. The 31b checkpoint is uniform 4-bit so it already used the compiled path and is unaffected.
@inureyes inureyes added type:performance Performance improvements priority:high High priority area:inference Generation, sampling, decoding (incl. speculative, DRY) status:review Under review labels Jul 7, 2026
`compiled_gelu_approx_mlp_forward` had zero Rust FFI test coverage, including the decode-gated 8-bit affine path added for Gemma 4 mixed-precision checkpoints. Adds three tests in ffi_tests.rs comparing it against an op-at-a-time quantized_matmul + gelu_tanh_approx reference: group_size=64/bits=8 single-token decode (the new compiled branch), group_size=64/bits=8 multi-token (proves the fallback gate excludes prefill and still matches), and group_size=64/bits=4 multi-token (proves the pre-existing always-compiled legacy path is unaffected).

Also fixes two comment nits from the #680 fix: the `compiled_gelu_approx_mlp_forward` "Used by" list omitted Gemma (gemma.rs also calls it), and the compile-cache comment mislabeled MLX's CompilerCache as process-wide when it is `thread_local` per-thread (mlx/compile.cpp).
@inureyes inureyes added status:done Completed and removed status:review Under review labels Jul 7, 2026
The advisory published today fails cargo-deny on every PR; crossbeam-epoch is transitive via rayon/tokenizers and 0.9.20 is the patched semver-compatible release.
@inureyes
inureyes merged commit 6714a29 into main Jul 7, 2026
4 checks passed
@inureyes
inureyes deleted the perf/680-gemma4-decode-op-count branch July 7, 2026 04:16
@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#682)

* perf(gemma4): compile 8-bit affine GeGLU MLP at decode (lablup#680)

The compiled `mx::compile` GeGLU MLP path only fired for group_size=64/bits=4 affine weights, so the group_size=64/bits=8 MLP of Gemma 4 mixed-precision checkpoints (gemma-4-12b-it-4bit and family) fell through to the op-at-a-time fallback, where `gelu_tanh_approx` emits ~14 element-wise MLX primitives per layer (7 Multiply + 4 Broadcast + 2 Add + 1 Tanh). Keying the compiled cache on (group_size, bits, mode) lets any affine quantization take the fused path, collapsing those ops into one `Compiled` primitive and cutting ~530 primitives/step at decode (nsys-verified: Multiply 394->59/step, total 2383->1853/step).

The fusion is applied only to the single-token decode call for the newly covered non-4-bit cases. Compiling the 8-bit prefill GEMM measured 8-9% slower and +0.2-0.7 GB peak on GB10 (the shapeless fused graph forces a decode-oriented qmm kernel onto the large prefill matmul), so prefill for these checkpoints stays on the op-at-a-time path; the original group_size=64/bits=4 case is preserved bit-for-bit on every shape.

Context for lablup#680: re-measuring the nsys traces (summing CUPTI_ACTIVITY_KIND_GRAPH_TRACE, not just the non-graph KERNEL table the earlier attribution used) shows gemma-4-12b decode is ~93-95% GPU-busy streaming the 8-bit MLP weights (~10 GB/token), i.e. weight-bandwidth-bound, not CPU-primitive-bound. This primitive-count cut is therefore throughput-neutral on GB10 (measured under 1%); it still removes real CPU dispatch and helps op-count-bound backends, and fixes a latent inefficiency for every 8-bit affine gemma checkpoint. `MLXCEL_COMPILED_QGELU_MLP=0` forces the fallback.

* bench: gemma-4 decode op-count A/B on GB10 (lablup#680)

Records the decode-gated compiled-MLP A/B (MLXCEL_COMPILED_QGELU_MLP 0 vs 1) at 512/2048/8192 for gemma-4-12b-it-4bit, plus a llama-3.1-8b-4bit non-gemma control and a gemma-4-31b-it-4bit family-scaling point. Confirms the fix is throughput-neutral at decode (within run-to-run noise) and non-regressing on prefill and peak, consistent with the corrected GPU-weight-bandwidth-bound attribution. The 31b checkpoint is uniform 4-bit so it already used the compiled path and is unaffected.

* test(mlxcel-core): cover compiled qgelu MLP decode gate and paths (lablup#680)

`compiled_gelu_approx_mlp_forward` had zero Rust FFI test coverage, including the decode-gated 8-bit affine path added for Gemma 4 mixed-precision checkpoints. Adds three tests in ffi_tests.rs comparing it against an op-at-a-time quantized_matmul + gelu_tanh_approx reference: group_size=64/bits=8 single-token decode (the new compiled branch), group_size=64/bits=8 multi-token (proves the fallback gate excludes prefill and still matches), and group_size=64/bits=4 multi-token (proves the pre-existing always-compiled legacy path is unaffected).

Also fixes two comment nits from the lablup#680 fix: the `compiled_gelu_approx_mlp_forward` "Used by" list omitted Gemma (gemma.rs also calls it), and the compile-cache comment mislabeled MLX's CompilerCache as process-wide when it is `thread_local` per-thread (mlx/compile.cpp).

* deps: bump crossbeam-epoch to 0.9.20 for RUSTSEC-2026-0204

The advisory published today fails cargo-deny on every PR; crossbeam-epoch is transitive via rayon/tokenizers and 0.9.20 is the patched semver-compatible release.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) 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(gemma4/cuda): gemma-4 decode carries ~44 ms/token model-specific fixed overhead on GB10, independent of context length

1 participant