Skip to content

perf(nvfp4): direct-transcode ModelOpt triplets to MLX native - #697

Merged
inureyes merged 2 commits into
mainfrom
perf/693-nvfp4-direct-transcode
Jul 8, 2026
Merged

inureyes merged 2 commits into
mainfrom
perf/693-nvfp4-direct-transcode

Conversation

@inureyes

@inureyes inureyes commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

Summary

Replaces the conservative dense repack for CUDA ModelOpt NVFP4 (introduced in PR #692) with a direct triplet transcode that never materializes a dense f16 matrix per linear weight. The packed FP4 U8 bytes reinterpret straight into MLX native NVFP4 U32 words, the per-block E4M3 scales are preserved verbatim, and weight_scale_2 is kept as a per-linear global-scale sidecar applied as an exact scalar multiply on the matmul output. The transcode is bit-exact to the checkpoint, so it is both faster to load and more faithful than the dense path (which re-derives block scales and drifts).

Why the global scale is applied on the output, not folded into the block scales

MLX native NVFP4 already stores per-block E4M3 scales, but its quantize/dequantize global_scale parameter uses a different convention than ModelOpt: MLX re-derives the block scales from global_scale during quantize, so handing the checkpoint's E4M3 scales plus weight_scale_2 as MLX global_scale produces wrong values (verified empirically). Because weight_scale_2 is a single per-tensor f32 scalar, applying it on the matmul output is mathematically exact: y = x @ (W * s2)^T = (x @ W^T) * s2. Folding it into every E4M3 block scale is rejected by the issue for overflow/underflow drift (many block_scale * weight_scale_2 products underflow E4M3), and was independently confirmed lossy here.

What changed

  • src/models/sanitize.rs: add f32_to_f8_e4m3 (round-to-nearest-even inverse of the existing f8_e4m3_to_f32, exhaustively round-trip tested); add the direct transcode branch (default under CUDA) and the MLXCEL_NVFP4_DENSE_REPACK=1 escape hatch that forces the old dense f16 -> MLX quantize(mode="nvfp4") path; emit a {prefix}.global_scale sidecar.
  • src/lib/mlxcel-core/src/layers.rs: QuantizedWeight gains an optional global_scale sidecar and apply_global_scale; UnifiedLinear::from_weights_with_mode loads the sidecar; UnifiedLinear::forward runs the qmm without a fused bias, applies the scalar, then adds the bias separately so a (rare) linear bias is never scaled.
  • src/models/gemma4.rs: MLP::forward falls through to the op-at-a-time path when any projection carries a global scale, so each UnifiedLinear::forward applies its own scalar; the activation gelu_tanh_approx(gate) * up is byte-identical to the fused NVFP4 fallback.
  • src/bin/bench_decode.rs: report cold-load wall time and MLX peak memory for the load phase.
  • Tests: exhaustive E4M3 round-trip, a fixture comparing direct-transcode dequant against the dense path with a documented FP8/FP4 tolerance, and the checkpoint fixture now asserts the global-scale sidecar and raw E4M3 U8 scales.

Validation

The direct transcode dequantizes bit-exactly to the ModelOpt reference (fp4 * e4m3_decode(weight_scale) * weight_scale_2); the dense fallback drifts by one E4M3 block-scale plus one FP4 rounding step. Nibble order and scale re-encode were verified against the real gemma-4-31b-it-nvfp4 checkpoint before trusting the reinterpret.

Test plan

  • cargo test -p mlxcel --features cuda --lib f32_to_f8 (E4M3 round-trip + specials)
  • cargo test -p mlxcel --features cuda --lib nvfp4 (direct-vs-dense fixture + checkpoint fixture)
  • cargo clippy -p mlxcel-core --features cuda --lib --tests -- -D warnings
  • cargo build --release --features cuda --bin mlxcel --bin mlxcel-bench-decode
  • GB10 load + throughput benchmark, direct vs dense (table below)
  • Greedy continuation parity, direct vs dense, on the real checkpoint

Benchmark (GB10, gemma-4-31b-it-nvfp4, release, same binary)

Run Repack Cold-load wall (s) Load peak (GB) Prefill tok/s Decode tok/s
short (20 tok) direct 58.77 36.60 76.13 4.84
short (20 tok) dense 190.72 36.60 79.51 5.26
2048-token direct 58.87 36.60 443.85 5.01
2048-token dense 190.69 36.60 395.20 5.38

Cold-load wall time drops 69.2% (190.72 s -> 58.77 s), so the >=20% acceptance gate passes on load time. Peak load memory is identical (36.60 GB): the dense f16 transients are freed between weight groups and never raise the high-water mark. Prefill at 2048 tokens is 12% faster on the direct path; decode is about 7% slower because the global scale forces the Gemma 4 dense MLP onto the op-at-a-time path plus a per-linear scalar multiply while Gemma 4 decode runs with CUDA graphs disabled. Folding the three scales into the fused compiled_gelu_approx_mlp_forward kernel would recover that and is a reasonable follow-up. Raw CSV: benchmarks/cuda_gb10_issue693_nvfp4_direct_vs_dense_2026-07-08.csv; summary: docs/benchmark_results/nvfp4-direct-transcode-gb10-2026-07-08.md.

Parity

Greedy (--temp 0) continuation on the real checkpoint, 48 tokens, prompt "Explain in a few sentences why the sky appears blue during the day.". Both paths produce coherent, semantically identical explanations of Rayleigh scattering. Direct: "The sky appears blue due to a phenomenon called Rayleigh scattering. As sunlight enters Earth's atmosphere, it collides with gas molecules and scatters in all directions. Because blue light travels in shorter, smaller waves, it is scattered". Dense: "The sky appears blue because of a phenomenon called Rayleigh scattering. As sunlight reaches Earth's atmosphere, it is scattered in all directions by the gases and particles in the air. Because blue light travels in shorter, smaller waves, it". The token streams diverge early ("due to" vs "because of", "enters" vs "reaches") because the dense fallback re-quantizes and drifts about 10% mean relative weight error while the direct transcode is bit-exact to the checkpoint. Token-identical output between the two paths is therefore not expected; the bit-exactness that matters is direct-vs-checkpoint, covered by the nvfp4_direct_transcode_is_exact_and_bounds_dense_drift fixture.

Review fixes

Post-review hardening in a356fe3 addressed one MEDIUM and three LOW findings from the security review of the direct transcode.

  • src/models/gemma4.rs: the compiled per-layer-input-gate fused path now checks for a global_scale sidecar on both the gate and projection weights (mirroring MLP::forward) before taking the fused C++ path, so a per-layer-input ModelOpt-NVFP4 checkpoint no longer silently drops weight_scale_2. Three new tests cover the no-sidecar case and both sidecar-present cases.
  • src/models/sanitize.rs: MLXCEL_NVFP4_DENSE_REPACK now matches its truthy values case-insensitively; weight_scale_2 is validated as a single-element scalar before being read, with malformed triplets falling back like the other malformed-shape guards; the direct-transcode weight repack checks 4-byte alignment before reinterpreting packed bytes as u32, falling back to an aligned from_slice_u32 decode when the allocation is misaligned.
  • docs/environment-variables.md: documents MLXCEL_NVFP4_DENSE_REPACK alongside the other Gemma 4 rollback flags.

Validated with cargo test -p mlxcel --features cuda --lib nvfp4 and cargo test -p mlxcel --features cuda --lib per_layer_input_gate, both green, and cargo clippy -p mlxcel --features cuda --lib --tests -- -D warnings clean.

Closes #693

Replace the dense f16 requantize repack (PR #692) with a direct ModelOpt NVFP4 triplet transcode as the default CUDA path. The packed FP4 U8 bytes reinterpret straight into MLX native NVFP4 U32 words (a little-endian byte view matches MLX's eight-nibbles-per-u32 order), the per-block E4M3 scales are re-encoded losslessly from the load-time f16 decode, and weight_scale_2 is preserved as a per-linear global-scale sidecar. This never materializes a dense f16 matrix, so cold load drops from 190.7 s to 58.8 s on GB10 for gemma-4-31b-it-nvfp4 (69%), and the transcode is bit-exact to the checkpoint (the dense fallback re-derives block scales and drifts about 10% mean relative weight error).

MLX native NVFP4 kernels have no parameter matching ModelOpt's weight_scale_2 convention (MLX's own global_scale re-derives the block scales during quantize), so weight_scale_2 is applied as a scalar multiply on the matmul output, exact for a per-tensor scalar: y = x @ (W * s2)^T = (x @ W^T) * s2. Folding it into every E4M3 block scale is rejected for overflow/underflow drift.

QuantizedWeight gains an optional global_scale sidecar plus apply_global_scale; UnifiedLinear::forward runs the qmm without a fused bias, applies the scalar, then adds the linear bias separately. Gemma 4 MLP::forward falls through to the op-at-a-time path when a global scale is present so each projection applies its own scalar, and the activation gelu_tanh_approx(gate) * up is byte-identical to the fused NVFP4 fallback. MLXCEL_NVFP4_DENSE_REPACK=1 forces the old dense path for A/B comparison. bench_decode now reports cold-load wall time and MLX peak.

Validation: exhaustive E4M3 round-trip test, a fixture comparing direct-transcode dequant against the dense path with a documented FP8/FP4 tolerance, the checkpoint fixture now asserts the global-scale sidecar and raw E4M3 U8 scales, plus a GB10 load/throughput benchmark and greedy parity on the real checkpoint.

Closes #693
@inureyes inureyes added type:performance Performance improvements priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers status:review Under review labels Jul 8, 2026
Address a security review of PR #697's direct ModelOpt NVFP4 transcode (issue #693): one MEDIUM finding and three LOW findings.

MEDIUM: the compiled per-layer-input-gate fused path in gemma4.rs took the fused compiled_per_layer_input_gate C++ path whenever both the gate and projection weights were quantized, without checking for a native-NVFP4 global_scale sidecar the way MLP::forward already does. A per-layer-input ModelOpt-NVFP4 checkpoint would silently drop weight_scale_2 and compute wrong outputs. The guard now mirrors MLP::forward: a new per_layer_input_gate_fused_path_eligible helper requires global_scale.is_none() on both projections before taking the fused path, falling through to the op-at-a-time UnifiedLinear::forward calls (which already apply the sidecar) otherwise. Added three unit tests in gemma4::quant_scheme_tests covering the no-sidecar case and both sidecar-on-gate and sidecar-on-projection cases.

LOW fixes in sanitize.rs: MLXCEL_NVFP4_DENSE_REPACK now matches its truthy values case-insensitively so TRUE/On/YES work the same as the documented lowercase forms. weight_scale_2 is now validated to be a single-element scalar before item_f32 reads it; a malformed multi-element or wrong-shape tensor is skipped with a warning and the triplet falls back like the other malformed-shape guards instead of throwing across the FFI boundary. The direct-transcode weight repack now checks 4-byte alignment before reinterpreting the packed U8 buffer as U32 via from_bytes, falling back to a from_slice_u32 decode through a properly aligned Vec<u32> on the rare misaligned allocation.

Documented MLXCEL_NVFP4_DENSE_REPACK in docs/environment-variables.md alongside the other Gemma 4 compiled-path rollback flags.

Also fixed a pre-existing clippy nit uncovered while validating (needless_range_loop in the unrelated direct-transcode drift-bound test), so cargo clippy -p mlxcel --features cuda --lib --tests -- -D warnings is clean.

Validated with cargo test -p mlxcel --features cuda --lib nvfp4 and cargo test -p mlxcel --features cuda --lib per_layer_input_gate, both green.
@inureyes

inureyes commented Jul 8, 2026

Copy link
Copy Markdown
Member Author

Applied fixes from the security review (commit a356fe3).

MEDIUM: the compiled per-layer-input-gate fused path in gemma4.rs did not check for a native-NVFP4 global_scale sidecar the way MLP::forward already does, so a per-layer-input ModelOpt-NVFP4 checkpoint would silently drop weight_scale_2 and compute wrong outputs. Added a per_layer_input_gate_fused_path_eligible guard requiring global_scale.is_none() on both projections before taking the fused path, with three new unit tests in gemma4::quant_scheme_tests.

LOW fixes in sanitize.rs: MLXCEL_NVFP4_DENSE_REPACK now matches its truthy values case-insensitively (with a new test); weight_scale_2 is validated as a single-element scalar before item_f32 reads it, with the triplet skipped and a warning logged on a malformed shape (new test); the direct-transcode weight repack now checks 4-byte alignment before reinterpreting the packed U8 buffer as U32, falling back to a properly aligned from_slice_u32 decode on the rare misaligned allocation.

Docs: added MLXCEL_NVFP4_DENSE_REPACK to docs/environment-variables.md.

Validated with cargo test -p mlxcel --features cuda --lib nvfp4, cargo test -p mlxcel --features cuda --lib per_layer_input_gate, and cargo clippy -p mlxcel --features cuda --lib --tests -- -D warnings, all clean.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Jul 8, 2026
@inureyes
inureyes merged commit 21db6fe into main Jul 8, 2026
4 checks passed
@inureyes
inureyes deleted the perf/693-nvfp4-direct-transcode branch July 8, 2026 14:23
inureyes added a commit that referenced this pull request Jul 9, 2026
## 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

- [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 #698
@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
…#697)

## Summary

Replaces the conservative dense repack for CUDA ModelOpt NVFP4 (introduced in PR lablup#692) with a direct triplet transcode that never materializes a dense f16 matrix per linear weight. The packed FP4 U8 bytes reinterpret straight into MLX native NVFP4 U32 words, the per-block E4M3 scales are preserved verbatim, and `weight_scale_2` is kept as a per-linear global-scale sidecar applied as an exact scalar multiply on the matmul output. The transcode is bit-exact to the checkpoint, so it is both faster to load and more faithful than the dense path (which re-derives block scales and drifts).

## Why the global scale is applied on the output, not folded into the block scales

MLX native NVFP4 already stores per-block E4M3 scales, but its `quantize`/`dequantize` `global_scale` parameter uses a different convention than ModelOpt: MLX re-derives the block scales from `global_scale` during quantize, so handing the checkpoint's E4M3 scales plus `weight_scale_2` as MLX `global_scale` produces wrong values (verified empirically). Because `weight_scale_2` is a single per-tensor f32 scalar, applying it on the matmul output is mathematically exact: `y = x @ (W * s2)^T = (x @ W^T) * s2`. Folding it into every E4M3 block scale is rejected by the issue for overflow/underflow drift (many `block_scale * weight_scale_2` products underflow E4M3), and was independently confirmed lossy here.

## What changed

- `src/models/sanitize.rs`: add `f32_to_f8_e4m3` (round-to-nearest-even inverse of the existing `f8_e4m3_to_f32`, exhaustively round-trip tested); add the direct transcode branch (default under CUDA) and the `MLXCEL_NVFP4_DENSE_REPACK=1` escape hatch that forces the old dense f16 -> MLX `quantize(mode="nvfp4")` path; emit a `{prefix}.global_scale` sidecar.
- `src/lib/mlxcel-core/src/layers.rs`: `QuantizedWeight` gains an optional `global_scale` sidecar and `apply_global_scale`; `UnifiedLinear::from_weights_with_mode` loads the sidecar; `UnifiedLinear::forward` runs the qmm without a fused bias, applies the scalar, then adds the bias separately so a (rare) linear bias is never scaled.
- `src/models/gemma4.rs`: `MLP::forward` falls through to the op-at-a-time path when any projection carries a global scale, so each `UnifiedLinear::forward` applies its own scalar; the activation `gelu_tanh_approx(gate) * up` is byte-identical to the fused NVFP4 fallback.
- `src/bin/bench_decode.rs`: report cold-load wall time and MLX peak memory for the load phase.
- Tests: exhaustive E4M3 round-trip, a fixture comparing direct-transcode dequant against the dense path with a documented FP8/FP4 tolerance, and the checkpoint fixture now asserts the global-scale sidecar and raw E4M3 U8 scales.

## Validation

The direct transcode dequantizes bit-exactly to the ModelOpt reference (`fp4 * e4m3_decode(weight_scale) * weight_scale_2`); the dense fallback drifts by one E4M3 block-scale plus one FP4 rounding step. Nibble order and scale re-encode were verified against the real `gemma-4-31b-it-nvfp4` checkpoint before trusting the reinterpret.

## Test plan

- [x] `cargo test -p mlxcel --features cuda --lib f32_to_f8` (E4M3 round-trip + specials)
- [x] `cargo test -p mlxcel --features cuda --lib nvfp4` (direct-vs-dense fixture + checkpoint fixture)
- [x] `cargo clippy -p mlxcel-core --features cuda --lib --tests -- -D warnings`
- [x] `cargo build --release --features cuda --bin mlxcel --bin mlxcel-bench-decode`
- [x] GB10 load + throughput benchmark, direct vs dense (table below)
- [x] Greedy continuation parity, direct vs dense, on the real checkpoint

## Benchmark (GB10, `gemma-4-31b-it-nvfp4`, release, same binary)

| Run | Repack | Cold-load wall (s) | Load peak (GB) | Prefill tok/s | Decode tok/s |
|-----|--------|-------------------:|---------------:|--------------:|-------------:|
| short (20 tok) | direct | 58.77 | 36.60 | 76.13 | 4.84 |
| short (20 tok) | dense | 190.72 | 36.60 | 79.51 | 5.26 |
| 2048-token | direct | 58.87 | 36.60 | 443.85 | 5.01 |
| 2048-token | dense | 190.69 | 36.60 | 395.20 | 5.38 |

Cold-load wall time drops 69.2% (190.72 s -> 58.77 s), so the >=20% acceptance gate passes on load time. Peak load memory is identical (36.60 GB): the dense f16 transients are freed between weight groups and never raise the high-water mark. Prefill at 2048 tokens is 12% faster on the direct path; decode is about 7% slower because the global scale forces the Gemma 4 dense MLP onto the op-at-a-time path plus a per-linear scalar multiply while Gemma 4 decode runs with CUDA graphs disabled. Folding the three scales into the fused `compiled_gelu_approx_mlp_forward` kernel would recover that and is a reasonable follow-up. Raw CSV: `benchmarks/cuda_gb10_issue693_nvfp4_direct_vs_dense_2026-07-08.csv`; summary: `docs/benchmark_results/nvfp4-direct-transcode-gb10-2026-07-08.md`.

## Parity

Greedy (`--temp 0`) continuation on the real checkpoint, 48 tokens, prompt "Explain in a few sentences why the sky appears blue during the day.". Both paths produce coherent, semantically identical explanations of Rayleigh scattering. Direct: "The sky appears blue due to a phenomenon called Rayleigh scattering. As sunlight enters Earth's atmosphere, it collides with gas molecules and scatters in all directions. Because blue light travels in shorter, smaller waves, it is scattered". Dense: "The sky appears blue because of a phenomenon called Rayleigh scattering. As sunlight reaches Earth's atmosphere, it is scattered in all directions by the gases and particles in the air. Because blue light travels in shorter, smaller waves, it". The token streams diverge early ("due to" vs "because of", "enters" vs "reaches") because the dense fallback re-quantizes and drifts about 10% mean relative weight error while the direct transcode is bit-exact to the checkpoint. Token-identical output between the two paths is therefore not expected; the bit-exactness that matters is direct-vs-checkpoint, covered by the `nvfp4_direct_transcode_is_exact_and_bounds_dense_drift` fixture.

## Review fixes

Post-review hardening in a356fe3 addressed one MEDIUM and three LOW findings from the security review of the direct transcode.

- `src/models/gemma4.rs`: the compiled per-layer-input-gate fused path now checks for a `global_scale` sidecar on both the gate and projection weights (mirroring `MLP::forward`) before taking the fused C++ path, so a per-layer-input ModelOpt-NVFP4 checkpoint no longer silently drops `weight_scale_2`. Three new tests cover the no-sidecar case and both sidecar-present cases.
- `src/models/sanitize.rs`: `MLXCEL_NVFP4_DENSE_REPACK` now matches its truthy values case-insensitively; `weight_scale_2` is validated as a single-element scalar before being read, with malformed triplets falling back like the other malformed-shape guards; the direct-transcode weight repack checks 4-byte alignment before reinterpreting packed bytes as `u32`, falling back to an aligned `from_slice_u32` decode when the allocation is misaligned.
- `docs/environment-variables.md`: documents `MLXCEL_NVFP4_DENSE_REPACK` alongside the other Gemma 4 rollback flags.

Validated with `cargo test -p mlxcel --features cuda --lib nvfp4` and `cargo test -p mlxcel --features cuda --lib per_layer_input_gate`, both green, and `cargo clippy -p mlxcel --features cuda --lib --tests -- -D warnings` clean.

Closes lablup#693
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
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:medium Medium priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(nvfp4): direct-transcode ModelOpt triplets to MLX native

1 participant