Skip to content

gpu: run routed NVFP4 prompt GEMM on FP4 tensor cores - #687

Merged
juliankang4 merged 11 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-nvfp4-mma
Oct 23, 2026
Merged

juliankang4 merged 11 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-nvfp4-mma

Conversation

@juliankang4

Copy link
Copy Markdown
Collaborator

Qwen3.8 NVFP4 모델의 routed expert prompt GEMM을 GB10의 FP4 텐서 코어(block-scaled MMA)로 실행해 prefill과 첫 토큰까지의 시간을 줄입니다.

Part of #565.

What and why

On a GB10 the routed expert products of an NVFP4 model run on INT8 tensor cores in the prompt path: each NVFP4 weight is expanded to Q8 values and multiplied with Q8 activations. GB10 has FP4 tensor cores with block scaling, so the 4-bit weights can be multiplied directly.

This PR adds a native routed NVFP4 prompt kernel to the shared Gemm32Kernels owner in crates/gpu/src/gemm/nvfp4mma.rs.

  1. The kernel computes 128 output rows per tile over the existing 64 route slots. It stages tiles through shared memory with vector loads and double buffering, prefetches the next tile into registers, loads fragments with ldmatrix, and repacks weight nibble pairs with byte permutations. It reuses the existing route list and fault owner, so there is no second expert routing list.
  2. Activations are quantized to FP4 beside their Q8 form. A fused producer visits the live columns of the selected routes, skips HOST selections, and computes SiLU, Q8 and FP4 in one launch. It packs the Q8 values it just produced, so the fused and the plain producer share one rounding rule. GemmAct32::new_routed_for allocates the FP4 representation only when the resident routed format is NVFP4; other formats keep their Q8 storage.
  3. One scale owner, scaled_sum in crates/gpu/src/gemm/grouped.rs, applies the weight, activation and expert scales for every NVFP4 product. Ordinary inputs keep the F32 multiply and FMA rounding. When an intermediate product would overflow or underflow, it multiplies the original operands in F64 and narrows after the last scale, so a finite result stays finite. The native kernel's two output stores, the plain and fused Q8 reconstruction, the W4A8 path and the grouped epilogues all call it. The W4A8 NVFP4 accumulator is F64 because the expert scale is applied after the sum.
  4. crates/gpu/build.rs enables the kernel for explicit sm_120a/f and sm_121a/f builds. Other targets keep the existing path.

This is a W4A4 product: the activations round to FP4 where the existing path keeps Q8. The faster path is the default, and the existing oracle bands, which this PR does not change, still pass. KL against the oracle is reported below as a diagnostic.

Release notes: Changed: routed NVFP4 prompt products run on the FP4 tensor cores of a GB10, which speeds up prefill.

Code shape

  • No second copy. The kernel lives in the shared GEMM owner and reuses the existing route, Q8 quantization, activation and fault owners. The fused and the plain producer call one Q8-to-FP4 packer.
  • Model code holds only architecture facts. The dispatch keys on the resident routed format and the CUDA target, not on a model.
  • Dead code is gone. The new constructors have production callers.
  • No silent failure. Shape, route and fault checks stay in place; the grid size multiplication is checked. A decoded scale in the subnormal range is rescaled by exactly 2^24 before its reciprocal, so it cannot overflow.
  • Comments state what is true now. The shared-stage comments state the allocation and its bounds.
  • No relaxed gate. No band, tolerance or oracle pin moved. The unsafe ratchet row and its PIN explanation follow the added unsafe blocks, each with a SAFETY line.
  • cargo fmt and cargo clippy are clean on what I touched.

Duplication found or removed (path:line), or "none": none. packed_pair (crates/gpu/src/gemm/nvfp4mma.rs:251) permutes FP4 nibbles with integer register operations and the INT8 MMA helper (crates/gpu/src/gemm/gemm32.rs:222) multiplies INT8 fragments, so their PTX operations differ. The all-columns and the selected-columns entries (nvfp4mma.rs:297, nvfp4mma.rs:317) call the same fused_swiglu.

What I ran

The base of the comparison is main with the dense BF16 tensor-core prompt GEMM merged.

GPU Evidence

On an NVIDIA GB10:

| NVIDIA-SMI 595.84                 Driver Version: 595.84         CUDA Version: 13.3     |
|   0  NVIDIA GB10                    On  |   0000000F:01:00.0 Off |                  N/A |
just gate-gpu-gemm --case nvfp4_native

The native gate has 32 cases: plain and fused producers, one-hot weights with alternating signs, partial tiles, K=20480, tiny inputs, varied inputs, and six extreme-range classes (expert scales from 2^-120 to 2^120, inputs of plus and minus F32 MAX, subnormal scales, and a last multiply that overflows after a finite first one). The extreme classes run the native plain and fused producers and the W4A8 path against an independent F64 expectation. Every case checks sentinel guards and eager against graph replay. All 32 print PASS with wrong=0; four of them:

gemm32 case=nvfp4_native rows=16 slots=14 k=128 one_hot=false tiny=false varied=false range=None fused=false native=true q8_eq=true producer_eq=true wrong=0 guard=true eager_graph_eq=true hash=84a59ace36b2db65 PASS
gemm32 case=nvfp4_native rows=16 slots=14 k=20480 one_hot=false tiny=false varied=false range=None fused=true native=true q8_eq=true producer_eq=true wrong=0 guard=true eager_graph_eq=true hash=a402f9c5be47a425 PASS
gemm32 case=nvfp4_native rows=16 slots=14 k=64 one_hot=false tiny=false varied=true range=None fused=true native=true q8_eq=true producer_eq=true wrong=0 guard=true eager_graph_eq=true hash=9dd2d13aca566b5a PASS
gemm32 case=nvfp4_native rows=16 slots=1 k=64 one_hot=false tiny=false varied=false range=Some((1.329228e36, 7.888609e-31)) fused=false native=true q8_eq=true producer_eq=true wrong=0 guard=true eager_graph_eq=true hash=2fbefdf7963551c5 PASS

The output hashes of 12 ordinary-input cases are identical with and without the scale range handling, so ordinary inputs produce the same output as before.

A kernel that writes zeros fails the gate. A fused producer that packs unrounded SiLU values fails producer_eq:

gemm32 case=nvfp4_native rows=16 slots=14 k=128 fused=false q8_eq=true wrong=224 guard=true eager_graph_eq=true FAIL
gemm32 case=nvfp4_native rows=16 slots=14 k=128 one_hot=false tiny=false varied=false fused=true q8_eq=true producer_eq=false wrong=0 guard=true eager_graph_eq=true FAIL

The full-model NVFP4 oracle, with its bands unchanged:

gate_qwen4exp_nvfp4
(p) the batch set by one pass: last argmax ours=11751 oracle=11751 logits_rel=8.243e-2 kld=0.029813964 (printed) PASS
(g) the batch set by one ubatch: last argmax ours=11751 oracle=11751 logits_rel=1.471e-1 kld=0.030307662 (printed) PASS
(t) hf-qwen4exp-nvfp4/hf_qwen4exp_nvfp4_d3k_bf16: position 3000 after 3000 ids by ubatches (3.9 s, runtime value); argmax ours=423 oracle=423 (its runner-up 11222, margin 0.9281, our distance at the two 0.2434); logits_rel 1.313e-1; kld=0.029886880; worst l_out_rel 2.441e-1 (printed) PASS
ORACLE_RC arm=head rc=0

Prefill and decode

One server load per arm, base then head, two requests per load. The prompt is a 4096-token code window (corpus offset 20480), 8 tokens are generated at temperature 0 with top-k 1, with no draft, no RAM cache, one request at a time and --ctx-size 4224. Model nvidia/Qwen3.8-Flash-Next-NVFP4 at fc694b54fb0174e0913e6adf86691ef85a4ead47, on one GB10 with driver 595.84, CUDA 13.3 and release binaries built with cargo oxide build --arch sm_121a. The first request of each load includes first-use effects.

Measurement Base Head Change
First server prefill (tok/s) 767.148 784.439 +2.25%
Second server prefill (tok/s) 774.465 793.170 +2.42%
First client TTFT (ms) 5346.054 5228.437 -2.20%
First server decode (tok/s) 23.063 22.919 -0.63%

Prefill of the 4096-token prompt rose by 2.25% on the first request and 2.42% on the second, and the first request's time to first token fell by 2.20%.

Both arms generated the same eight greedy token ids on both requests.

A second pair of loads with the scale range handling in place, on the same prompt and settings, gives 777.588 tok/s against 777.944 tok/s for first-request prefill (+0.05%), with the same eight greedy token ids. The decode kernels are unchanged, and eight generated tokens are too few to separate the small decode differences from noise.

Oracle diagnostics, KL against the reference set (the BF16 rows are judged by the oracle, the Q8 row is recorded only):

Reference Base Head
BF16, one pass 0.029813964 0.029813964
BF16, one ubatch 0.015113573 0.030307662
BF16, position 3000 0.010078292 0.029886880
Q8, position 3000 0.019428296 0.085409650

What I ran into

This does not block the PR. KL against the oracle is higher on the head than on the base for the one-ubatch and position 3000 sets, as expected when activations round to FP4. The oracle's argmax and margin checks pass on every set. The timing is two requests per arm on one prompt, not a long benchmark.

Hardware

One NVIDIA DGX Spark (GB10), driver 595.84, CUDA 13.3, with CUDA 13.3.1 in the build image.

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot added gpu The card engine: crates/gpu*, crates/app needs-gpu Changes code a card must check, and carries no gate run on a card tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Oct 22, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: MUST_FIX: the native fused producer accepts buffers that violate its vector-load alignment.

Must fix

1. Check both input buffers before the vector loads

crates/gpu/src/gemm/nvfp4mma.rs:104 casts the gate input to F32x4; line 106 does the same for the up input. A safe Window::<f32>::of(&parent, 4, 64) over a parent of at least 65 floats passes the public launchers' length checks with n_cols=1, k=64. With native scratch, either window reaches a vector load at an address that is 4 modulo 16, violating its alignment and allowing a CUDA misaligned-address failure.
Checking the shared launcher now closes all three fused entry points before callers depend on this unchecked alignment invariant.

Insert these checks in Kernels::swiglu, before let k = act.k as u32;:

crate::tensor::check_alignment::<cuda_device::vector::F32x4, _>(
    "NVFP4 activation", "g", g,
)?;
crate::tensor::check_alignment::<cuda_device::vector::F32x4, _>(
    "NVFP4 activation", "u", u,
)?;

Add a native-scratch gate case using a byte-offset-4 window for each input. It must return the named alignment error before launching; removing either check must fail its assertion.

Non-blocking

⚠ Validate the existing GEMM paths: crates/gpu/src/gemm/gemm32.rs:683 also changes the Q8/Q5/IQ epilogues, while grouped.rs changes K-quants. A full 128×64 tile now executes 8192 range-checked epilogues per 32-value block [derived]. Attach their owning-gate outputs and a timed A/B for the precision change, with occupancy evidence for the changed kernels. The supplied NVFP4 run does not exercise those formats.

Optimization headroom

  • G. Per-launch and per-sync fixed cost: crates/gpu/src/gemm/act32.rs:228, fuse the plain Q8 and FP4 producers as the SwiGLU path already does. With native NVFP4 scratch, this removes one launch per plain quantization call on the routed prompt path.

Checked

Duplicates: the retained findings concern separate defects or opportunities.
Complexity: scaled_sum adds fast-path range checks and an F64 fallback inside existing GEMM epilogues.
Silent failure: the public fused launchers check lengths but not the alignment required by act_quad.
Tests: the native gate compares plain/fused outputs, Q8 bytes, guards and graph replay. It uses allocated input buffers and has no native input-alignment case. CUDA gates were not rerun during validation.
Gates: no existing accuracy band moved; target spill and unsafe rows have dated PIN reasons.
Escape catalog: C1–C4 do not apply to the retained findings. No ledger lessons are in force.

Notes

The GPU evidence omits the tested base/head commit hashes and the timing commands with output. gpu.json records evidence=false.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_gemm.rs, crates/gpu-gates/src/bin/gate_qwen4exp_nvfp4.rs, crates/gpu-gates/src/gemm32.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@juliankang4
juliankang4 force-pushed the dgx-spark-q38-nvfp4-mma branch from 4fd25d1 to 4b3bd63 Compare October 22, 2026 23:46
github-actions[bot]
github-actions Bot previously approved these changes Oct 22, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the last review:

Verdict: CLEAN: the alignment defect is closed, and no new must-fix survives review of the added commit.

Non-blocking

⚠ Validate the existing GEMM paths: crates/gpu/src/gemm/gemm32.rs:683 changes Q8/Q5/IQ epilogues; grouped.rs changes K-quants. A full 128×64 tile executes 8192 range-checked epilogues per 32-value block [derived]. Supply their owning-gate outputs and a timed A/B for the precision change, with occupancy evidence. The NVFP4 runs do not exercise those formats.

Optimization headroom

  • G. Per-launch and per-sync fixed cost: crates/gpu/src/gemm/act32.rs:228, fuse the plain Q8 and FP4 producers. With native NVFP4 scratch, this removes one launch per plain routed prompt quantization call.

Checked

Duplicates: 0 new definitions in the interdiff; existing alignment owner reused. Dryer reports 0 pairs. Grep found no duplicate of the added gate cases.
Complexity: nvfp4_native_case gains an alignment-case loop and error matching. Crapper's other six flags concern unchanged commits; no kernel body changed in this round.
Silent failure: 2 new alignment checks followed through all 3 public fused launchers; errors propagate before launch and before updating the filled count.
Tests: removing the check at nvfp4mma.rs:705 or :710 prevents the corresponding named refusal at gate_gemm.rs:6885; the gate fails. This is source inspection of the mutation, not an executed mutation test. CUDA gates were not rerun.
Bounds: native K is a multiple of 64; aligned bases keep every four-value load aligned, including later columns and the selected-column path.
Gates: no band, tolerance or pin changes in the added commit.
Escape catalog: C1–C4 do not match the added commit.

Notes

Dryer did not search crates/gpu-gates; the added gate lines were checked by Grep and Read.
The PR evidence omits the tested base/head commit hashes and timing commands with output. It also has no run output for the new alignment cases.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_gemm.rs, crates/gpu-gates/src/bin/gate_qwen4exp_nvfp4.rs, crates/gpu-gates/src/gemm32.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the last review:

Verdict: CLEAN: the interdiff only updates the dated unsafe pin to match the rebased source counts.

Non-blocking

⚠ Validate the existing GEMM paths: crates/gpu/src/gemm/gemm32.rs:683 changes Q8/Q5/IQ epilogues; crates/gpu/src/gemm/grouped.rs:504 changes K-quants. A full 128×64 tile executes 8192 range-checked epilogues per 32-value block [derived]. Supply their owning-gate outputs and a timed A/B for the precision change, with occupancy evidence. The supplied NVFP4 runs do not exercise those formats.

Checked

Duplicates: 0 new definitions in the interdiff. Dryer reports 0 pairs; none to read.
Complexity: all seven crapper flags concern unchanged implementation commits. No function changes in the interdiff.
Silent failure: 0 new sites; no runtime behavior changes.
Tests: no new or changed tests in the interdiff, so no test mutation applies. CUDA gates were not rerun.
Gates: independently recounted GPU unsafe lines using the base check's rules: base 2186/267/10, head 2231/268/10 (blocks/functions/impls). The entire increase is 45 blocks and one function in nvfp4mma.rs. The dated pin matches exactly and adds no unused allowance; numeric bands are unchanged.
Escape catalog: C1–C4 do not match the interdiff.

Notes

Dryer did not search crates/gpu-gates; this interdiff changes no gate source.
The PR evidence still omits the tested base/head commit hashes and timing commands with output.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_gemm.rs, crates/gpu-gates/src/bin/gate_qwen4exp_nvfp4.rs, crates/gpu-gates/src/gemm32.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gpu The card engine: crates/gpu*, crates/app needs-gpu Changes code a card must check, and carries no gate run on a card tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant