Repository navigation
perf(gemma4): cut decode-path primitive count on CUDA (#680) - #682
Merged
Merged
Conversation
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.
5 tasks
`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).
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.
This was referenced Jul 7, 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_KERNELfor 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 inCUPTI_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 fusedmx::compilepath 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, wheregelu_tanh_approxemits ~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 oneCompiledprimitive. 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=0forces the op-at-a-time fallback (A/B + rollback; documented in docs/environment-variables.md).Testing
compiled_gelu_approx_mlp_forwardhad no Rust FFI unit coverage before this PR. Three new tests insrc/lib/mlxcel-core/src/ffi_tests.rsclose 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_forwardpasses 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)
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