Skip to content

perf(gemma4): fold NVFP4 global scales into fused MLP kernel - #701

Merged
inureyes merged 2 commits into
mainfrom
perf/698-nvfp4-fused-global-scale
Jul 9, 2026
Merged

inureyes merged 2 commits into
mainfrom
perf/698-nvfp4-fused-global-scale

Conversation

@inureyes

@inureyes inureyes commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

Summary

Folds the NVFP4 weight_scale_2 global_scale sidecar (from the direct ModelOpt transcode, #693/#697) back into the fused gemma-4 MLP and per-layer-input-gate kernels, at the mathematically correct points, so a sidecar-carrying MLP no longer bypasses the fused path and runs three op-at-a-time projections.

The GeGLU is nonlinear, so the gate scale is applied to the gate product BEFORE gelu_tanh_approx; the up scale is a linear factor on the up product; the down scale multiplies the fused output. Each fold reproduces apply_global_scale byte-for-byte (multiply by the f32 scalar, then astype back to the activation dtype), so the fused result is bit-close to the op-at-a-time path. A null scale means no multiply for that projection, so mixed sidecar sets stay exact for the unscaled projections.

What changed

  • src/lib/mlxcel-core/cpp/mlx_cxx_bridge.cpp / .h: new compiled_gelu_approx_mlp_forward_global_scale (compiles the scaled graph on the single-token decode call, keyed on group_size/bits/mode and the gate/up/down presence flags so the unscaled graph is unchanged and each sidecar pattern gets its own graph; folds eagerly on prefill, mirroring the decode-only compile gate of the unscaled path). compiled_per_layer_input_gate gains two optional scale operands folded into its eager fallback (NVFP4 and the affine compiled branch are mutually exclusive, so the compiled affine path is untouched). Shared apply_global_scale_eager helper mirrors QuantizedWeight::apply_global_scale.
  • src/lib/mlxcel-core/src/lib.rs: FFI declarations for the new function and the two extra scale operands.
  • src/lib/mlxcel-core/src/layers.rs: QuantizedWeight::global_scale_ptr() (null when absent), mirroring biases_ptr().
  • src/models/gemma4.rs: MLP::forward and the per-layer-input gate call the scaled fused path only for single-token inputs when any sidecar is present; MLXCEL_DISABLE_FUSED_GLOBAL_SCALE (read once) restores the op-at-a-time bypass; per_layer_input_gate_fused_path_eligible takes fused_scale_enabled and single_token flags, and the new dense_mlp_scaled_fused_path_eligible mirrors it for the dense MLP branch (review fix, see below).
  • docs/environment-variables.md: documents MLXCEL_DISABLE_FUSED_GLOBAL_SCALE.
  • benchmarks/cuda_gb10_issue698_nvfp4_fused_scale_2026-07-09.csv and docs/benchmark_results/nvfp4-direct-transcode-gb10-2026-07-08.md: the GB10 numbers below, including the post-fix re-measurement.

Review fixes

Review found that the initial fold gated only on sidecar presence and the MLXCEL_DISABLE_FUSED_GLOBAL_SCALE kill switch, with no check on query length. The C++ fused-scale function compiles the scaled graph only for single-token calls and falls back to an eager, uncompiled multiply(gelu_tanh_approx(gate), up) otherwise, so every multi-token prefill call silently downgraded from the compiled op-at-a-time activation to that eager fold. On the 2048-token prompt this regressed prefill from 449.90 tok/s (op-at-a-time) to 412.48 tok/s, an 8.3% loss, for no decode benefit; the 20-token short prompt showed no measurable change because a matmul that small is too cheap for the eager-versus-compiled cost to clear the noise floor.

The fix gates both fused call sites in src/models/gemma4.rs (MLP::forward's dense MLP branch and the per-layer-input gate) to single-token inputs (mlxcel_core::array_shape(x)[1] == 1), so a sidecar-carrying multi-token call now bypasses the fused path unconditionally, regardless of the kill switch, and takes the identical op-at-a-time projections plus compiled_geglu_approx_activation that non-sidecar prefill has always used. The C++ bridge itself is unchanged; its eager-fold branch remains correct and is still exercised by the multi-token FFI test, just no longer reached from gemma-4 prefill. Re-measured on the same host and release binary, 2048-token prefill recovers to 447.24 tok/s (within 0.6% of op-at-a-time) while decode stays fused at 5.05 tok/s, and greedy --temp 0 output is still byte-identical between the default and MLXCEL_DISABLE_FUSED_GLOBAL_SCALE=1 on the short prompt.

Review also flagged the benchmark doc's "no regression" and weight-layout-attribution claims. src/models/sanitize.rs shows the dense and direct-transcode routes produce identical MLX native NVFP4 layout (same mode, group_size, bits, weight dtype, and scale dtype), differing only in scale values (dense re-derives with about 10% drift, direct is bit-exact) plus a negligible f32 [1] sidecar, so the layout attribution was wrong. The doc now documents the prefill regression and fix honestly, and notes the residual dense-vs-direct decode gap is not conclusively isolated: the dense short run generated 42 tokens against 26 for direct, and the dense 2048 row is a cross-day carry-over rather than a same-run measurement.

dense_mlp_scaled_fused_path_eligible was extracted as a testable mirror of per_layer_input_gate_fused_path_eligible (now taking a single_token parameter) so both fused call sites have unit coverage without needing a full compiled forward pass. New guard tests pin: sidecar + single-token + fold enabled routes to the fused path; sidecar + multi-token bypasses the fused path regardless of the fold toggle; the existing kill-switch tests are preserved.

Parity outcome

Greedy --temp 0 decode is byte-identical between the fold (default) and the op-at-a-time bypass (MLXCEL_DISABLE_FUSED_GLOBAL_SCALE=1) on the 26-token short prompt Hello, how are you today?, both before and after the single-token gate fix.

On a 120-token generation (List five interesting facts about the planet Jupiter.) the two paths agree for the first ~68 tokens and then diverge at a near-tie fact selection. That divergence is baseline CUDA nondeterminism, not the fold: two runs of the unmodified default path diverge from each other as well (at ~115 tokens, so large that Earth could vs so large that it is), so the NVFP4 qmm FP-reduction order is not run-to-run reproducible on this backend for either path. The fused output stays inside that envelope rather than introducing divergence. This mirrors the documented behavior of MLXCEL_FUSED_QK_NORM on CUDA.

Synthetic compiled_qgelu_mlp_global_scale_* unit tests confirm the fold matches the op-at-a-time apply_global_scale reference to 1e-5 on the compiled single-token branch, the eager multi-token fallback, and a mixed (down-only) sidecar set, and that non-unit scales genuinely change the output (the sidecar is not silently dropped).

Benchmarks (GB10, gemma-4-31b-it-nvfp4, same release binary, 2026-07-09)

Run Scale path Prompt tokens Prefill tok/s Decode tok/s
short dense (folded into block scales) 20 78.55 5.25
short op-at-a-time bypass 20 74.62 4.86
short fused fold (this PR, default) 20 74.63 4.90
2048 dense (folded into block scales) 2048 395.20 5.38 (2026-07-08)
2048 op-at-a-time bypass 2048 449.90 5.01
2048 fused fold (initial, pre-fix) 2048 412.48 5.07
2048 fused fold (this PR, post-fix) 2048 447.24 5.05

The ~2% of dense throughput gate is NOT met: the fold is throughput-neutral on GB10 decode (+0.8% short, +0.8% at 2048 post-fix vs op-at-a-time) and stays 6.7% below dense short, 6.1% below dense at 2048 post-fix. GB10 gemma-4 decode is weight-bandwidth-bound (~94% GPU-busy streaming the NVFP4 MLP weights), so removing per-layer element-wise dispatches is throughput-neutral there, exactly as documented for the sibling MLXCEL_COMPILED_QGELU_MLP fusion. The fold rules out scale-op dispatch count as the cause of the residual dense-vs-direct gap (folding the scales into one compiled graph does not close it), but the gap itself is not conclusively isolated by this benchmark: the comparison is confounded by mismatched generation lengths (42 tokens dense-short vs 26 direct-short) and a cross-day dense-2048 row. The fold still removes three FFI crossings and three element-wise dispatches per MLP layer for single-token decode, which reduces CPU dispatch work and helps op-count-bound backends, so it ships default-on for decode with the kill switch retained; multi-token prefill takes the unaffected op-at-a-time path unconditionally. Full rationale in docs/benchmark_results/nvfp4-direct-transcode-gb10-2026-07-08.md.

Test plan

  • cargo test -p mlxcel-core --features cuda --lib global_scale (4 tests: compiled single-token, eager multi-token, mixed down-only, all-null == unscaled; all pass, fold matches reference to 1e-5)
  • cargo test -p mlxcel --features cuda --lib per_layer_input_gate (5 guard tests, including the new multi-token-bypass test; all pass)
  • cargo test -p mlxcel --features cuda --lib dense_mlp_scaled_fused_path_eligible (4 new guard tests for the dense MLP branch's single-token gating; all pass)
  • cargo clippy -p mlxcel-core --features cuda --lib --tests -- -D warnings (clean)
  • cargo clippy -p mlxcel --features cuda --lib --tests -- -D warnings (clean)
  • cargo fmt -p mlxcel -p mlxcel-core
  • Real-checkpoint greedy parity (fused default vs MLXCEL_DISABLE_FUSED_GLOBAL_SCALE=1) on gemma-4-31b-it-nvfp4, byte-identical on the short prompt; long-generation divergence attributed to baseline GPU nondeterminism (fused-vs-fused also diverges)
  • Decode benchmarks (short + 2048, pre-fix and post-fix) fused vs op-at-a-time vs dense, recorded in the CSV and doc

Closes #698

The direct ModelOpt NVFP4 transcode (#693/#697) keeps `weight_scale_2` as a per-linear f32 `global_scale` sidecar, applied by `UnifiedLinear::forward` as `astype(multiply(qmm_out, s), qmm_out.dtype())`. A sidecar-carrying gemma-4 MLP used to bypass the fused C++ path entirely and run three separate op-at-a-time projections, and the per-layer-input gate did the same, because the fused kernels had no parameter for the sidecar.

This folds the scales back into the fused kernels at the mathematically correct points. The GeGLU is nonlinear, so the gate scale is applied to the gate product before `gelu_tanh_approx`; the up scale is a linear factor on the up product; the down scale multiplies the fused output. Each fold reproduces `apply_global_scale` byte-for-byte (multiply by the f32 scalar, then astype back to the activation dtype), so the fused result is bit-close to the op-at-a-time path. A null scale means no multiply for that projection, so mixed sidecar sets stay exact for the unscaled projections.

New `compiled_gelu_approx_mlp_forward_global_scale` compiles the scaled graph on the single-token decode call (keyed on group_size/bits/mode and the gate/up/down presence flags, so the unscaled graph is unchanged and each sidecar pattern gets its own graph) and folds eagerly on prefill, mirroring the decode-only compile gate of the unscaled path. `compiled_per_layer_input_gate` gains two optional scale operands folded into its eager fallback (NVFP4 and the affine compiled branch are mutually exclusive). `MLXCEL_DISABLE_FUSED_GLOBAL_SCALE` restores the op-at-a-time bypass for A/B and rollback.

Validation on GB10 gemma-4-31b-it-nvfp4: greedy temp-0 decode is byte-identical between the fold and the op-at-a-time bypass on the 26-token short prompt; on a 120-token generation the two paths agree for ~68 tokens then diverge at a near-tie, but two runs of the unmodified default path diverge from each other as well (NVFP4 qmm FP-reduction order is not run-to-run reproducible on this backend), so the fold stays inside that envelope rather than introducing divergence. Synthetic `compiled_qgelu_mlp_global_scale_*` unit tests confirm the fold matches the op-at-a-time reference to 1e-5 on the compiled single-token branch, the eager multi-token fallback, and mixed sidecar sets.

Throughput is neutral on GB10 decode: fused vs op-at-a-time is 4.90 vs 4.86 tok/s (short) and 5.07 vs 5.01 tok/s (2048), and it does not recover to within 2% of the dense-repack baseline (5.25 short, 5.38 at 2048). GB10 gemma-4 decode is weight-bandwidth-bound (~94% GPU-busy), so removing per-layer element-wise dispatches is throughput-neutral there, exactly as documented for the sibling `MLXCEL_COMPILED_QGELU_MLP` fusion; the dense advantage comes from the native re-quantized NVFP4 weight layout, not the scale-op dispatch count. The fold still removes three FFI crossings and three element-wise dispatches per MLP layer with no regression, so it ships default-on with the kill switch retained. Raw numbers in `benchmarks/cuda_gb10_issue698_nvfp4_fused_scale_2026-07-09.csv` and `docs/benchmark_results/nvfp4-direct-transcode-gb10-2026-07-08.md`.

Refs #698
@inureyes inureyes added type:performance Performance improvements priority:low Low priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers status:review Under review labels Jul 8, 2026
The scaled fused GeGLU path (issue #698) checked only sidecar presence and the MLXCEL_DISABLE_FUSED_GLOBAL_SCALE kill switch before routing into the C++ fused-scale function, with no check on query length. That function compiles the scaled graph only for single-token calls and falls back to an eager, uncompiled multiply(gelu_tanh_approx(gate), up) otherwise, so every multi-token prefill call silently downgraded from the compiled op-at-a-time activation to that eager fold. On a 2048-token prompt this regressed prefill from 449.90 tok/s (op-at-a-time) to 412.48 tok/s, an 8.3% loss, for no decode benefit.

MLP::forward and the per-layer-input gate in src/models/gemma4.rs now gate both fused call sites to single-token inputs (mlxcel_core::array_shape(x)[1] == 1), so a sidecar-carrying multi-token call bypasses the fused path unconditionally, regardless of the kill switch, and falls through to the existing op-at-a-time path (UnifiedLinear::forward applies the scale, compiled_geglu_approx_activation handles the GeGLU). The C++ bridge is unchanged; its eager-fold branch stays correct and is still exercised by the multi-token FFI test, just no longer reached from gemma-4 prefill.

Extracted dense_mlp_scaled_fused_path_eligible as a testable mirror of the existing per_layer_input_gate_fused_path_eligible helper (now taking a single_token parameter), and extended the guard tests to pin: sidecar + single-token + fold enabled routes to the fused path; sidecar + multi-token bypasses regardless of the fold toggle; the kill-switch tests are preserved.

Re-measured on the same GB10 host and release binary: 2048-token prefill recovers to 447.24 tok/s (within 0.6% of op-at-a-time), decode stays fused at 5.05 tok/s, and greedy temp-0 output is byte-identical between the default fused path and MLXCEL_DISABLE_FUSED_GLOBAL_SCALE=1 on the 26-token short prompt. Corrects docs/benchmark_results/nvfp4-direct-transcode-gb10-2026-07-08.md, which had claimed no regression and attributed the residual dense-vs-direct decode gap to weight layout, a claim src/models/sanitize.rs contradicts (both routes produce identical MLX native NVFP4 layout, differing only in scale values and a negligible sidecar); the section now documents the prefill regression and fix honestly and notes the dense-vs-direct comparison is confounded by mismatched generation lengths and a cross-day carry-over row.

Refs #698
@inureyes

inureyes commented Jul 9, 2026

Copy link
Copy Markdown
Member Author

Applied review fixes in a39c8d6.

HIGH: unconditional fused-scale routing regressed prefill. Both fused call sites in src/models/gemma4.rs (MLP::forward's dense MLP branch and the per-layer-input gate) now gate on mlxcel_core::array_shape(x)[1] == 1 in addition to sidecar presence and the kill switch, so a sidecar-carrying multi-token (prefill) call bypasses the fused path unconditionally and falls through to the existing op-at-a-time projections plus the compiled GeGLU activation. The C++ bridge is unchanged; its eager-fold branch stays correct for the multi-token case and is exercised by the existing FFI test, it's just no longer reached from gemma-4 prefill. per_layer_input_gate_fused_path_eligible now takes a single_token parameter, and the new dense_mlp_scaled_fused_path_eligible mirrors it for the dense MLP branch so both call sites have unit coverage. New guard tests pin: sidecar + single-token + fold enabled routes to the fused path; sidecar + multi-token bypasses regardless of the fold toggle; the kill-switch tests are preserved.

MEDIUM: benchmark doc wording. Removed the "no regression" claim and the weight-layout attribution for the residual dense-vs-direct decode gap, which src/models/sanitize.rs contradicts (both routes produce identical MLX native NVFP4 layout, differing only in scale values and a negligible sidecar). The doc now documents the prefill regression and fix honestly, and notes the dense-vs-direct comparison is confounded by mismatched generation lengths and a cross-day carry-over row.

Post-fix re-measurement, same GB10 host, same release binary, minimal reload (3 loads total):

Run Scale path Prompt tokens Prefill tok/s Decode tok/s
2048 op-at-a-time bypass (reference) 2048 449.90 5.01
2048 fused fold (pre-fix, regressed) 2048 412.48 5.07
2048 fused fold (post-fix, default) 2048 447.24 5.05

Prefill recovers to within 0.6% of the op-at-a-time reference while decode stays on the fused path. Greedy --temp 0 output on the 26-token short prompt is byte-identical between the default and MLXCEL_DISABLE_FUSED_GLOBAL_SCALE=1.

Verification: cargo test -p mlxcel-core --features cuda --lib global_scale (4 pass), cargo test -p mlxcel --features cuda --lib per_layer_input_gate (5 pass) and dense_mlp_scaled_fused_path_eligible (4 new, pass), cargo clippy -p mlxcel -p mlxcel-core --features cuda --lib --tests -- -D warnings (clean), cargo fmt (clean). No CUDA errors during any of the three real-model loads.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Jul 9, 2026
@inureyes
inureyes merged commit d437bc7 into main Jul 9, 2026
4 checks passed
@inureyes
inureyes deleted the perf/698-nvfp4-fused-global-scale branch July 9, 2026 00:36
inureyes added a commit that referenced this pull request Jul 9, 2026
## Summary
- Make direct ModelOpt-triplet to MLX native NVFP4 the default on Metal/non-CUDA, matching the CUDA default while keeping `MLXCEL_NVFP4_DENSE_REPACK=1` as the dense-affine rollback path.
- Add a native-NVFP4 prefill-friendly Gemma 4 scaled MLP path: multi-token group_size=16/bits=4/mode=nvfp4 now uses a shape-specific compiled graph that folds the `weight_scale_2` sidecars and GeGLU activation without using the decode-oriented shapeless qmm graph.
- Add a sidecar-aware quantized linear C++ helper so standalone native-NVFP4 `UnifiedLinear` projections can preserve `apply_global_scale` semantics through one C++ boundary, with `MLXCEL_DISABLE_FUSED_GLOBAL_SCALE` still restoring the op-at-a-time rollback.
- Document the 512-16384 token M1 Ultra sweep and update the NVFP4 environment-variable semantics for the new native default.

## Validation scope

Issue #705 follows the #694 / #702 native-vs-affine Metal comparison on the local `models/gemma-4-31b-it-nvfp4` ModelOpt NVFP4 checkpoint. The earlier issue wording that named Llama 4 Scout has been corrected in the issue body; this PR's full sweep uses the same local Gemma 4 ModelOpt NVFP4 validation target rather than a reduced-size substitute.

## Benchmark summary
| Prompt tokens | Affine prefill tok/s | Native prefill tok/s | Native prefill gap | Native decode speedup | Peak memory delta | Load speedup |
|---:|---:|---:|---:|---:|---:|---:|
| 512 | 123.38 | 118.49 | -4.0% | 2.67x | -3.27 GB | 2.70x |
| 1024 | 126.71 | 117.46 | -7.3% | 2.68x | -4.44 GB | 2.68x |
| 2048 | 126.50 | 117.12 | -7.4% | 2.65x | -7.66 GB | 2.67x |
| 4096 | 118.07 | 112.88 | -4.4% | 2.75x | -10.15 GB | 2.66x |
| 8192 | 116.88 | 111.39 | -4.7% | 2.64x | -10.61 GB | 2.72x |
| 16384 | 115.86 | 108.10 | -6.7% | 2.51x | -12.32 GB | 2.71x |

The prefill gap is reduced on the mid-length cases that previously showed the largest regression, but it is not eliminated; native remains about 4-7% slower than affine for prefill on this M1 Ultra run. The default switch is based on the overall trade-off requested in #705: native load is about 2.7x faster, decode is 2.5-2.75x faster, and peak memory is 3.3-12.3 GB lower across the sweep. The dense-affine rollback remains available for prefill-sensitive A/B runs.

## Activation-path follow-up

Because native prefill still trails affine, this PR also rechecked the #701 path choice on the current Metal/MLX 0.32.1 baseline. At 2048 prompt tokens, the default shape-specific scaled MLP measured 116.10 tok/s, the op-at-a-time sidecar path with compiled GeGLU activation (`MLXCEL_DISABLE_FUSED_GLOBAL_SCALE=1`) measured 116.11 tok/s, and the C++ eager fold (`MLXCEL_COMPILED_QGELU_MLP=0`) measured 113.35 tok/s. At 8192 prompt tokens, the same paths measured 110.66, 109.99, and 108.10 tok/s respectively. This does not support switching native prefill back to the compiled-activation fallback; the #701 eager-fold warning still holds on this Metal baseline.

## Test plan
- [x] `cargo test --release -p mlxcel-core quantized_linear_forward_global_scale_matches_manual_sidecar_path -- --nocapture`
- [x] `cargo test --release -p mlxcel-core compiled_qgelu_mlp_global_scale -- --nocapture`
- [x] `cargo test --release -p mlxcel gemma4::quant_scheme_tests::dense_mlp_scaled_fused_path_eligible -- --nocapture`
- [x] `cargo test --release -p mlxcel sanitize::tests::nvfp4_repack_strategy_matrix -- --nocapture`
- [x] `cargo test --release -p mlxcel load_and_sanitize_weights_repacks_nvfp4_gemma4_checkpoint -- --nocapture`
- [x] `cargo test --release -p mlxcel load_and_sanitize_weights_dense_repack_env_keeps_non_cuda_affine_rollback -- --nocapture`
- [x] `cargo build --release --bin mlxcel-bench-decode`
- [x] `git diff --check`
- [x] `python3 scripts/ci/check_cross_repo_refs.py`
- [x] `mlxcel-bench-decode` native-default vs `MLXCEL_NVFP4_DENSE_REPACK=1` sweep at 512, 1024, 2048, 4096, 8192, and 16384 prompt tokens
- [x] `mlxcel-bench-decode` native default vs `MLXCEL_DISABLE_FUSED_GLOBAL_SCALE=1` vs `MLXCEL_COMPILED_QGELU_MLP=0` at 2048 and 8192 prompt tokens

Closes #705
@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
)

## Summary

Folds the NVFP4 `weight_scale_2` `global_scale` sidecar (from the direct ModelOpt transcode, lablup#693/lablup#697) back into the fused gemma-4 MLP and per-layer-input-gate kernels, at the mathematically correct points, so a sidecar-carrying MLP no longer bypasses the fused path and runs three op-at-a-time projections.

The GeGLU is nonlinear, so the gate scale is applied to the gate product BEFORE `gelu_tanh_approx`; the up scale is a linear factor on the up product; the down scale multiplies the fused output. Each fold reproduces `apply_global_scale` byte-for-byte (multiply by the f32 scalar, then astype back to the activation dtype), so the fused result is bit-close to the op-at-a-time path. A null scale means no multiply for that projection, so mixed sidecar sets stay exact for the unscaled projections.

## What changed

- `src/lib/mlxcel-core/cpp/mlx_cxx_bridge.cpp` / `.h`: new `compiled_gelu_approx_mlp_forward_global_scale` (compiles the scaled graph on the single-token decode call, keyed on group_size/bits/mode and the gate/up/down presence flags so the unscaled graph is unchanged and each sidecar pattern gets its own graph; folds eagerly on prefill, mirroring the decode-only compile gate of the unscaled path). `compiled_per_layer_input_gate` gains two optional scale operands folded into its eager fallback (NVFP4 and the affine compiled branch are mutually exclusive, so the compiled affine path is untouched). Shared `apply_global_scale_eager` helper mirrors `QuantizedWeight::apply_global_scale`.
- `src/lib/mlxcel-core/src/lib.rs`: FFI declarations for the new function and the two extra scale operands.
- `src/lib/mlxcel-core/src/layers.rs`: `QuantizedWeight::global_scale_ptr()` (null when absent), mirroring `biases_ptr()`.
- `src/models/gemma4.rs`: `MLP::forward` and the per-layer-input gate call the scaled fused path only for single-token inputs when any sidecar is present; `MLXCEL_DISABLE_FUSED_GLOBAL_SCALE` (read once) restores the op-at-a-time bypass; `per_layer_input_gate_fused_path_eligible` takes `fused_scale_enabled` and `single_token` flags, and the new `dense_mlp_scaled_fused_path_eligible` mirrors it for the dense MLP branch (review fix, see below).
- `docs/environment-variables.md`: documents `MLXCEL_DISABLE_FUSED_GLOBAL_SCALE`.
- `benchmarks/cuda_gb10_issue698_nvfp4_fused_scale_2026-07-09.csv` and `docs/benchmark_results/nvfp4-direct-transcode-gb10-2026-07-08.md`: the GB10 numbers below, including the post-fix re-measurement.

## Review fixes

Review found that the initial fold gated only on sidecar presence and the `MLXCEL_DISABLE_FUSED_GLOBAL_SCALE` kill switch, with no check on query length. The C++ fused-scale function compiles the scaled graph only for single-token calls and falls back to an eager, uncompiled `multiply(gelu_tanh_approx(gate), up)` otherwise, so every multi-token prefill call silently downgraded from the compiled op-at-a-time activation to that eager fold. On the 2048-token prompt this regressed prefill from 449.90 tok/s (op-at-a-time) to 412.48 tok/s, an 8.3% loss, for no decode benefit; the 20-token short prompt showed no measurable change because a matmul that small is too cheap for the eager-versus-compiled cost to clear the noise floor.

The fix gates both fused call sites in `src/models/gemma4.rs` (`MLP::forward`'s dense MLP branch and the per-layer-input gate) to single-token inputs (`mlxcel_core::array_shape(x)[1] == 1`), so a sidecar-carrying multi-token call now bypasses the fused path unconditionally, regardless of the kill switch, and takes the identical op-at-a-time projections plus `compiled_geglu_approx_activation` that non-sidecar prefill has always used. The C++ bridge itself is unchanged; its eager-fold branch remains correct and is still exercised by the multi-token FFI test, just no longer reached from gemma-4 prefill. Re-measured on the same host and release binary, 2048-token prefill recovers to 447.24 tok/s (within 0.6% of op-at-a-time) while decode stays fused at 5.05 tok/s, and greedy `--temp 0` output is still byte-identical between the default and `MLXCEL_DISABLE_FUSED_GLOBAL_SCALE=1` on the short prompt.

Review also flagged the benchmark doc's "no regression" and weight-layout-attribution claims. `src/models/sanitize.rs` shows the dense and direct-transcode routes produce identical MLX native NVFP4 layout (same mode, group_size, bits, weight dtype, and scale dtype), differing only in scale values (dense re-derives with about 10% drift, direct is bit-exact) plus a negligible f32 `[1]` sidecar, so the layout attribution was wrong. The doc now documents the prefill regression and fix honestly, and notes the residual dense-vs-direct decode gap is not conclusively isolated: the dense short run generated 42 tokens against 26 for direct, and the dense 2048 row is a cross-day carry-over rather than a same-run measurement.

`dense_mlp_scaled_fused_path_eligible` was extracted as a testable mirror of `per_layer_input_gate_fused_path_eligible` (now taking a `single_token` parameter) so both fused call sites have unit coverage without needing a full compiled forward pass. New guard tests pin: sidecar + single-token + fold enabled routes to the fused path; sidecar + multi-token bypasses the fused path regardless of the fold toggle; the existing kill-switch tests are preserved.

## Parity outcome

Greedy `--temp 0` decode is byte-identical between the fold (default) and the op-at-a-time bypass (`MLXCEL_DISABLE_FUSED_GLOBAL_SCALE=1`) on the 26-token short prompt `Hello, how are you today?`, both before and after the single-token gate fix.

On a 120-token generation (`List five interesting facts about the planet Jupiter.`) the two paths agree for the first ~68 tokens and then diverge at a near-tie fact selection. That divergence is baseline CUDA nondeterminism, not the fold: two runs of the unmodified default path diverge from each other as well (at ~115 tokens, `so large that Earth could` vs `so large that it is`), so the NVFP4 qmm FP-reduction order is not run-to-run reproducible on this backend for either path. The fused output stays inside that envelope rather than introducing divergence. This mirrors the documented behavior of `MLXCEL_FUSED_QK_NORM` on CUDA.

Synthetic `compiled_qgelu_mlp_global_scale_*` unit tests confirm the fold matches the op-at-a-time `apply_global_scale` reference to 1e-5 on the compiled single-token branch, the eager multi-token fallback, and a mixed (down-only) sidecar set, and that non-unit scales genuinely change the output (the sidecar is not silently dropped).

## Benchmarks (GB10, gemma-4-31b-it-nvfp4, same release binary, 2026-07-09)

| Run | Scale path | Prompt tokens | Prefill tok/s | Decode tok/s |
|-----|-----------|--------------:|--------------:|-------------:|
| short | dense (folded into block scales) | 20 | 78.55 | 5.25 |
| short | op-at-a-time bypass | 20 | 74.62 | 4.86 |
| short | fused fold (this PR, default) | 20 | 74.63 | 4.90 |
| 2048 | dense (folded into block scales) | 2048 | 395.20 | 5.38 (2026-07-08) |
| 2048 | op-at-a-time bypass | 2048 | 449.90 | 5.01 |
| 2048 | fused fold (initial, pre-fix) | 2048 | 412.48 | 5.07 |
| 2048 | fused fold (this PR, post-fix) | 2048 | 447.24 | 5.05 |

The `~2% of dense` throughput gate is NOT met: the fold is throughput-neutral on GB10 decode (+0.8% short, +0.8% at 2048 post-fix vs op-at-a-time) and stays 6.7% below dense short, 6.1% below dense at 2048 post-fix. GB10 gemma-4 decode is weight-bandwidth-bound (~94% GPU-busy streaming the NVFP4 MLP weights), so removing per-layer element-wise dispatches is throughput-neutral there, exactly as documented for the sibling `MLXCEL_COMPILED_QGELU_MLP` fusion. The fold rules out scale-op dispatch count as the cause of the residual dense-vs-direct gap (folding the scales into one compiled graph does not close it), but the gap itself is not conclusively isolated by this benchmark: the comparison is confounded by mismatched generation lengths (42 tokens dense-short vs 26 direct-short) and a cross-day dense-2048 row. The fold still removes three FFI crossings and three element-wise dispatches per MLP layer for single-token decode, which reduces CPU dispatch work and helps op-count-bound backends, so it ships default-on for decode with the kill switch retained; multi-token prefill takes the unaffected op-at-a-time path unconditionally. Full rationale in `docs/benchmark_results/nvfp4-direct-transcode-gb10-2026-07-08.md`.

## Test plan

- [x] `cargo test -p mlxcel-core --features cuda --lib global_scale` (4 tests: compiled single-token, eager multi-token, mixed down-only, all-null == unscaled; all pass, fold matches reference to 1e-5)
- [x] `cargo test -p mlxcel --features cuda --lib per_layer_input_gate` (5 guard tests, including the new multi-token-bypass test; all pass)
- [x] `cargo test -p mlxcel --features cuda --lib dense_mlp_scaled_fused_path_eligible` (4 new guard tests for the dense MLP branch's single-token gating; all pass)
- [x] `cargo clippy -p mlxcel-core --features cuda --lib --tests -- -D warnings` (clean)
- [x] `cargo clippy -p mlxcel --features cuda --lib --tests -- -D warnings` (clean)
- [x] `cargo fmt -p mlxcel -p mlxcel-core`
- [x] Real-checkpoint greedy parity (fused default vs `MLXCEL_DISABLE_FUSED_GLOBAL_SCALE=1`) on gemma-4-31b-it-nvfp4, byte-identical on the short prompt; long-generation divergence attributed to baseline GPU nondeterminism (fused-vs-fused also diverges)
- [x] Decode benchmarks (short + 2048, pre-fix and post-fix) fused vs op-at-a-time vs dense, recorded in the CSV and doc

Closes lablup#698
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
## Summary
- Make direct ModelOpt-triplet to MLX native NVFP4 the default on Metal/non-CUDA, matching the CUDA default while keeping `MLXCEL_NVFP4_DENSE_REPACK=1` as the dense-affine rollback path.
- Add a native-NVFP4 prefill-friendly Gemma 4 scaled MLP path: multi-token group_size=16/bits=4/mode=nvfp4 now uses a shape-specific compiled graph that folds the `weight_scale_2` sidecars and GeGLU activation without using the decode-oriented shapeless qmm graph.
- Add a sidecar-aware quantized linear C++ helper so standalone native-NVFP4 `UnifiedLinear` projections can preserve `apply_global_scale` semantics through one C++ boundary, with `MLXCEL_DISABLE_FUSED_GLOBAL_SCALE` still restoring the op-at-a-time rollback.
- Document the 512-16384 token M1 Ultra sweep and update the NVFP4 environment-variable semantics for the new native default.

## Validation scope

Issue lablup#705 follows the lablup#694 / lablup#702 native-vs-affine Metal comparison on the local `models/gemma-4-31b-it-nvfp4` ModelOpt NVFP4 checkpoint. The earlier issue wording that named Llama 4 Scout has been corrected in the issue body; this PR's full sweep uses the same local Gemma 4 ModelOpt NVFP4 validation target rather than a reduced-size substitute.

## Benchmark summary
| Prompt tokens | Affine prefill tok/s | Native prefill tok/s | Native prefill gap | Native decode speedup | Peak memory delta | Load speedup |
|---:|---:|---:|---:|---:|---:|---:|
| 512 | 123.38 | 118.49 | -4.0% | 2.67x | -3.27 GB | 2.70x |
| 1024 | 126.71 | 117.46 | -7.3% | 2.68x | -4.44 GB | 2.68x |
| 2048 | 126.50 | 117.12 | -7.4% | 2.65x | -7.66 GB | 2.67x |
| 4096 | 118.07 | 112.88 | -4.4% | 2.75x | -10.15 GB | 2.66x |
| 8192 | 116.88 | 111.39 | -4.7% | 2.64x | -10.61 GB | 2.72x |
| 16384 | 115.86 | 108.10 | -6.7% | 2.51x | -12.32 GB | 2.71x |

The prefill gap is reduced on the mid-length cases that previously showed the largest regression, but it is not eliminated; native remains about 4-7% slower than affine for prefill on this M1 Ultra run. The default switch is based on the overall trade-off requested in lablup#705: native load is about 2.7x faster, decode is 2.5-2.75x faster, and peak memory is 3.3-12.3 GB lower across the sweep. The dense-affine rollback remains available for prefill-sensitive A/B runs.

## Activation-path follow-up

Because native prefill still trails affine, this PR also rechecked the lablup#701 path choice on the current Metal/MLX 0.32.1 baseline. At 2048 prompt tokens, the default shape-specific scaled MLP measured 116.10 tok/s, the op-at-a-time sidecar path with compiled GeGLU activation (`MLXCEL_DISABLE_FUSED_GLOBAL_SCALE=1`) measured 116.11 tok/s, and the C++ eager fold (`MLXCEL_COMPILED_QGELU_MLP=0`) measured 113.35 tok/s. At 8192 prompt tokens, the same paths measured 110.66, 109.99, and 108.10 tok/s respectively. This does not support switching native prefill back to the compiled-activation fallback; the lablup#701 eager-fold warning still holds on this Metal baseline.

## Test plan
- [x] `cargo test --release -p mlxcel-core quantized_linear_forward_global_scale_matches_manual_sidecar_path -- --nocapture`
- [x] `cargo test --release -p mlxcel-core compiled_qgelu_mlp_global_scale -- --nocapture`
- [x] `cargo test --release -p mlxcel gemma4::quant_scheme_tests::dense_mlp_scaled_fused_path_eligible -- --nocapture`
- [x] `cargo test --release -p mlxcel sanitize::tests::nvfp4_repack_strategy_matrix -- --nocapture`
- [x] `cargo test --release -p mlxcel load_and_sanitize_weights_repacks_nvfp4_gemma4_checkpoint -- --nocapture`
- [x] `cargo test --release -p mlxcel load_and_sanitize_weights_dense_repack_env_keeps_non_cuda_affine_rollback -- --nocapture`
- [x] `cargo build --release --bin mlxcel-bench-decode`
- [x] `git diff --check`
- [x] `python3 scripts/ci/check_cross_repo_refs.py`
- [x] `mlxcel-bench-decode` native-default vs `MLXCEL_NVFP4_DENSE_REPACK=1` sweep at 512, 1024, 2048, 4096, 8192, and 16384 prompt tokens
- [x] `mlxcel-bench-decode` native default vs `MLXCEL_DISABLE_FUSED_GLOBAL_SCALE=1` vs `MLXCEL_COMPILED_QGELU_MLP=0` at 2048 and 8192 prompt tokens

Closes lablup#705
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 priority:low Low priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(gemma4): fold NVFP4 global scales into fused MLP kernel

1 participant