Skip to content

fix(cuda): repack ModelOpt NVFP4 to native MLX layout - #692

Merged
inureyes merged 2 commits into
mainfrom
fix/issue-630-repair-nvfp4-cuda
Jul 8, 2026
Merged

inureyes merged 2 commits into
mainfrom
fix/issue-630-repair-nvfp4-cuda

Conversation

@inureyes

@inureyes inureyes commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

Refs #630.
Refs #693.
Refs #694.

Summary

  • Accept the narrow Gemma 4 NVIDIA ModelOpt NVFP4 metadata shape and keep rejecting other unsupported external quantization formats.
  • Repack ModelOpt {weight, weight_scale, weight_scale_2} groups at load time so CUDA no longer falls into the pathological dense fallback.
  • Use MLX native NVFP4 for CUDA builds, which improves long-prompt prefill substantially versus the earlier affine stopgap.
  • Keep non-CUDA builds on the affine fallback until direct ModelOpt transcode (perf(nvfp4): direct-transcode ModelOpt triplets to MLX native #693) and Apple Silicon validation (perf(metal): evaluate native NVFP4 path after direct transcode #694) are completed.
  • Add an MLX C++ bridge wrapper for explicit quantize modes and optional bias-less quantize results so block-float layouts can be materialized once.
  • Promote Gemma 4 root quantization_config into text quantization args, keep layout reconciliation for the non-CUDA affine fallback, and document GB10 benchmarks.

Validation

  • cargo fmt
  • cargo test --features cuda -p mlxcel load_and_sanitize_weights_repacks_nvfp4_gemma4_checkpoint
  • cargo test -p mlxcel load_and_sanitize_weights_repacks_nvfp4_gemma4_checkpoint
  • cargo test --features cuda -p mlxcel-core reconcile_
  • cargo build --release --features cuda --bin mlxcel --bin mlxcel-bench-decode
  • target/release/mlxcel-bench-decode -m models/gemma-4-31b-it-nvfp4 -p "Hello, how are you today?" -n 16 --warmup-tokens 4
  • nsys profile --force-overwrite=true --trace=cuda,nvtx,osrt -o /tmp/mlxcel_issue630_nvfp4_after target/release/mlxcel-bench-decode -m models/gemma-4-31b-it-nvfp4 -p "Hello, how are you today?" -n 8 --warmup-tokens 2 (earlier affine-stopgap profile)

Benchmarks

Run Prefill tok/s Decode tok/s
Gemma 4 31B NVFP4 before (benchmarks/cuda_gb10_2026-06-17.csv) 16.26 0.89
Gemma 4 31B NVFP4 affine stopgap, short prompt (benchmarks/cuda_gb10_issue630_nvfp4_short_gs64_2026-07-08.csv) 51.75 4.48
Gemma 4 31B NVFP4 native CUDA, short prompt (benchmarks/cuda_gb10_issue630_nvfp4_native_short_2026-07-08.csv) 75.36 5.24
Gemma 4 31B NVFP4 affine stopgap, 2048 prompt (benchmarks/cuda_gb10_issue630_nvfp4_prefill2048_2026-07-08.csv) 116.44 4.60
Gemma 4 31B NVFP4 native CUDA, 2048 prompt (benchmarks/cuda_gb10_issue630_nvfp4_native_prefill2048_2026-07-08.csv) 392.71 5.42
Gemma 4 31B IT 4-bit reference, same final build short prompt 78.97 8.84
Gemma 4 31B IT 4-bit reference, same final build 2048 prompt 431.82 8.84
GPT-OSS 20B MXFP4 control (benchmarks/cuda_gb10_issue630_gptoss_mxfp4_2026-07-08.csv) 95.86 70.23

The final smoke run on the native CUDA path reported 74.56 prefill tok/s, 5.62 decode tok/s, and 36.62 GB MLX peak memory for a 16-token generation. The earlier nsys affine-stopgap short profile generated /tmp/mlxcel_issue630_nvfp4_after.nsys-rep and reported 52.58 prefill tok/s, 5.11 decode tok/s, and 36.67 GB MLX peak memory.

Remaining gap

This PR repairs the broken CUDA execution path and moves the final CUDA repack target to MLX native NVFP4. It exceeds the 2048-token prefill target by a wide margin, but it intentionally does not close #630 because the requested 9 tok/s decode target is still not met. The local ModelOpt NVFP4 checkpoint is about 31 GB and keeps many non-MLP tensors dense; the fully affine Gemma 4 31B IT 4-bit reference checkout is about 18 GB and still measures 8.84 decode tok/s on the same final GB10 build. Cold-load optimization and exact source-scale preservation are tracked in #693, and Apple Silicon native-path enablement is split into #694 after direct transcode exists.

@inureyes inureyes added area:core mlxcel-core: MLX FFI, primitives, KV cache, layers priority:medium Medium priority status:in-progress Currently being worked on type:bug Bug fixes, error corrections, or issue resolutions labels Jul 8, 2026
Use MLX native NVFP4 for CUDA ModelOpt triplets after GB10 showed a large 2048-token prefill gain, while keeping non-CUDA builds on the affine fallback pending direct transcode and Apple Silicon validation.

The C++ bridge now accepts explicit quantize modes and optional bias-less quantize results so block-float weights can be materialized once. The Gemma 4 sanitizer selects native NVFP4 under the CUDA feature, keeps affine fallback behavior elsewhere, and updates the fixture to validate both layouts.

Validation: cargo fmt; cargo test --features cuda -p mlxcel load_and_sanitize_weights_repacks_nvfp4_gemma4_checkpoint; cargo test -p mlxcel load_and_sanitize_weights_repacks_nvfp4_gemma4_checkpoint; cargo test --features cuda -p mlxcel-core reconcile_; cargo build --release --features cuda --bin mlxcel --bin mlxcel-bench-decode; target/release/mlxcel-bench-decode -m models/gemma-4-31b-it-nvfp4 -p "Hello, how are you today?" -n 16 --warmup-tokens 4.

Refs #630.
Refs #693.
Refs #694.
@inureyes inureyes changed the title fix(cuda): repack ModelOpt NVFP4 weights for Gemma 4 fix(cuda): repack ModelOpt NVFP4 to native MLX layout Jul 8, 2026
@inureyes inureyes added status:review Under review and removed status:in-progress Currently being worked on labels Jul 8, 2026
@inureyes
inureyes merged commit f9f9f09 into main Jul 8, 2026
4 checks passed
@inureyes
inureyes deleted the fix/issue-630-repair-nvfp4-cuda branch July 8, 2026 11:29
@inureyes inureyes added status:done Completed and removed status:review Under review labels Jul 8, 2026
inureyes added a commit that referenced this pull request Jul 8, 2026
## 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

- [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 #693
@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
* fix(cuda): repack ModelOpt NVFP4 weights for Gemma 4

* fix(cuda): use native NVFP4 repack for ModelOpt Gemma 4

Use MLX native NVFP4 for CUDA ModelOpt triplets after GB10 showed a large 2048-token prefill gain, while keeping non-CUDA builds on the affine fallback pending direct transcode and Apple Silicon validation.

The C++ bridge now accepts explicit quantize modes and optional bias-less quantize results so block-float weights can be materialized once. The Gemma 4 sanitizer selects native NVFP4 under the CUDA feature, keeps affine fallback behavior elsewhere, and updates the fixture to validate both layouts.

Validation: cargo fmt; cargo test --features cuda -p mlxcel load_and_sanitize_weights_repacks_nvfp4_gemma4_checkpoint; cargo test -p mlxcel load_and_sanitize_weights_repacks_nvfp4_gemma4_checkpoint; cargo test --features cuda -p mlxcel-core reconcile_; cargo build --release --features cuda --bin mlxcel --bin mlxcel-bench-decode; target/release/mlxcel-bench-decode -m models/gemma-4-31b-it-nvfp4 -p "Hello, how are you today?" -n 16 --warmup-tokens 4.

Refs lablup#630.
Refs lablup#693.
Refs lablup#694.
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
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:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(cuda/quant): repair nvfp4 execution path on CUDA

1 participant