Skip to content

gemm: speed up the routed NVFP4 expert GEMMs on long prompts - #760

Merged
juliankang4 merged 3 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-prompt-routed
Oct 24, 2026
Merged

juliankang4 merged 3 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-prompt-routed

Conversation

@juliankang4

@juliankang4 juliankang4 commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

Qwen3.8의 routed expert NVFP4 GEMM을 빠르게 만들어, W4A8 경로(sm_86, sm_121 build)에서 4K 프롬프트의 prefill 시간을 줄입니다.

Part of #565.

What and why

On a prompt, each Qwen3.8 MoE layer runs three NVFP4 routed GEMMs (gate, up and down) and a SwiGLU pass between them that quantizes its output for the down GEMM. In a profile of a 4,096-token prompt gemm_nvfp4p is the largest kernel, 28.5% of the kernel time on main. This PR has three commits: the two below and a third that recounts the unsafe-block pins on the rebased tree.

Which builds this reaches: gemm_nvfp4p and the fold run on the W4A8 path, which an sm_86 or sm_121 build takes for NVFP4 and FP4-Local routed weights, on a GB10 and on other cards. Since #758 a GB10 build selects sm_121a by default, and there the routed prompt GEMM takes the native FP4 path (gemm_nvfp4_mma), which this PR does not change. The measurements below were taken with sm_121 builds on both sides, before #758.

  1. gemm: copy the NVFP4 routed weights two steps ahead and decode them at the fragment read. gemm_nvfp4p (crates/gpu/src/gemm/gemm32.rs, kernels32.rs) used to move its weights through registers. Now cp.async copies the raw weights into three stages (NV_STAGES), two steps ahead of the compute, and each warp decodes its own rows' nibbles and sub-block scales when it reads the fragment (nv_copy, nv_frags). The weight load no longer sits in registers while the step computes.
  2. gemm: fold the routed SwiGLU quantization into the NVFP4 up GEMM. The new kernel gemm_nvfp4p_swiglu walks the up weights like gemm_nvfp4p and changes only the store. It does not write the up values. It reads the gate GEMM's row g, forms silu(g) * u in a staging tile, and each warp quantizes its columns with the same group rule as swiglu_quant32_sel (quant32_group), writing the down GEMM's activation plane directly. A 128-row slab holds four Q8 blocks, which is one quantizer group, so a group never crosses thread blocks and the order of operations matches the two-launch path. The host entry is Gemm32Kernels::enqueue_up_swiglu32 (gemm32.rs). Before the table walk, block 0 of the fused kernel reads the place of every slot and raises ExpertId for a place at or above the card count and below the host marker. The scan covers slots the route omits, so a bad place is refused whether or not a tile reaches it, as swiglu_quant32_sel does for the two-launch path. The store and refused-slot arms no longer raise ExpertId themselves; the refused-slot arm writes its block through quant32_group and raises QuantColumn once per block. For a weight type other than NVFP4, or the native FP4 path, it calls enqueue_gemm32 and then enqueue_swiglu_quant32_sel as before, so those paths keep their bits and faults. Its first caller is enqueue_gemm_batch in crates/gpu/src/arch/qwen3moe/wide38.rs, which now issues five launches per batch instead of six for NVFP4 weights. The grouped (K-quant) path is unchanged. quant_launch in act32.rs becomes pub(super) so the fold reuses the same plane check.

The fold requires rows == 32 * oblocks. The Qwen3.8 FF width of 640 meets it, and other widths get a named error from the host before launch.

tools/unsafe-ratchet.txt raises the gpu block count from 2273 to 2293 with three dated PINs: the weight stages, the fused kernel's store, and the place scan. The refused-slot arm calls the existing quantizer, quant32_group, with a NaN group, so the refused block format has one owner. Each new block has a SAFETY line that states its invariant in place and holds one memory operation.

The PTX spill tables pin both kernels with dated PIN lines, read on a GB10 (ptxas 13.3.73, driver 595.84): gemm_nvfp4p 48 spill bytes at sm_86 and 64 at sm_121 and sm_121a, and the new gemm_nvfp4p_swiglu 0 at sm_86 and 160 at sm_121 and sm_121a. Both use 128 registers, 33,328 shared bytes and 256 threads. The sm_86 rows of the base table record ptxas's stack frame as the local bytes; the cc 8.6 JIT was not measured.

Release notes: Changed: the routed NVFP4 expert GEMMs on Qwen3.8 prompts copy weights ahead of the compute and fold the SwiGLU quantization into the up GEMM, which shortens the routed GEMM time of a 4K prompt on the W4A8 path (sm_86 and sm_121 builds).

Code shape

  • No second copy. The fold reuses quant32_group for the quantizer, quant_launch for the plane check, Gemm32Launch::check for the launch check and silu_mul for SiLU. Its fallback calls the two existing host functions. The new kernel and gemm_nvfp4p share one gemm32_block! body and differ only in the store arm.
  • Model code holds only architecture facts. wide38.rs only calls the new host entry in place of two calls it already made. The common owner gained no per-model branch.
  • Dead code is gone. Nothing was made unused.
  • No silent failure. The host entry refuses a wrong K, column count, short g or sel and an out-of-range n_card with a named error before launch. A misaligned code plane is refused by Gemm32Launch::check, which reaches Nvfp4Stack::experts. The kernel raises a fault for a refused slot and for the bad place of any slot, including one the route omits. No new allocation.
  • Comments state what is true now. Each SAFETY comment names its own invariant and does not point at another comment.
  • No relaxed gate. No band or tolerance moves. The unsafe ratchet rises with dated PINs.
  • cargo fmt is clean on what I touched, and cargo clippy on the GPU crates reports 3 warnings, the same count as main.

Duplication found or removed (path:line): the scan flagged two pairs, none a copy. NV_STAGES (gemm32.rs:129) and STAGES (f32tile.rs:70) have equal values but size different pipelines. gemm_nvfp4p_swiglu (kernels32.rs:806) repeats the argument list of gemm_nvfp4p (:735) because device entries take flat arguments, while both bodies call the shared gemm32_block!. The NVFP4 code-plane alignment check has one owner, Gemm32Launch::check through Nvfp4Stack::experts; enqueue_gemm32 and enqueue_up_swiglu32 do not repeat it.

What I ran

Kernel bench

The bench replays 64 launches of one routed GEMM as a CUDA graph and reports the mean per launch. It uses synthetic inputs with the Qwen3.8 shapes: 640 and 2,560 rows, K of 2,560 and 640, 512 experts, top-10, 4,096 tokens, 40,960 slots. Main and head alternated for three rounds on one GB10, and the table shows the median round. The spread between the rounds of one arm was at most 0.7%. Main has no 4,096-token arms in its bench table, so I added the gate and down arms to main's copy for this measurement only. This PR adds them to the head's bench table.

Routed GEMM, 4,096 tokens (one GB10, microseconds per launch) main head change
gate 6,501.8 5,564.6 -14.4%
down 7,012.2 6,179.3 -11.9%

On the head, the fold replaces the up GEMM and the SwiGLU quantization:

Up GEMM plus SwiGLU quantization (head, microseconds per launch) two launches one folded launch change
up and SwiGLU 6,590.1 5,677.6 -13.8%

Both up arms write the same activation plane in every round (act_q_fnv=2944078e47be9d85, act_d_fnv=b478f440dfd5f8f3). Main's two-launch up path was not timed on its own.

Speed A/B

This is a 4,096-token prompt, one client, draft off, greedy, 128 generated tokens, three requests per arm. Each arm loads the server once, and main and head alternate in one session on one DGX Spark (GB10). Each checkpoint starts with a discarded warm load and the arm order is reversed between checkpoints. A read probe and the decode rate right before each arm serve as witnesses that the card state matched. The models are the Qwen3.8 NVFP4 checkpoint (revision fc694b54) and the Qwen3.8 FP4-Local checkpoint (revision b9ce18a6).

Qwen3.8 NVFP4, one GB10, 4,096-token prompt, C@1, draft off main head change
Median TTFT ms 3,192.9 3,007.6 -5.8%
Prefill tok/s 1,285.0 1,364.7 +6.2%

Delta (head against main): NVFP4 TTFT -5.8% (3,192.9 to 3,007.6 ms), prefill +6.2% (1,285.0 to 1,364.7 tok/s).

The witnesses matched on this checkpoint: decode 22.52 tok/s on main and 22.47 on head, read probe 235.1 and 235.7 GB/s.

The FP4-Local checkpoint shows no difference beyond noise in this session:

Qwen3.8 FP4-Local, one GB10, 4,096-token prompt, C@1, draft off main head change
Median TTFT ms 3,116.5 3,143.5 +0.9%
Prefill tok/s 1,316.8 1,305.0 -0.9%

The head arm of this checkpoint ran on a card whose witnesses were lower than the main arm's: read probe 223.8 against 230.7 GB/s and decode 29.97 against 30.66 tok/s. The changed kernels are not on the decode path, so I read that gap as card state. I did not repeat this arm, so I make no claim about the end-to-end effect on this checkpoint.

Each arm is one session of three requests, so these are single observations and I make no significance claim. Load time is outside the numbers.

Output is identical. Per window, the greedy 128-token output hash is the same on main and head: e137fcd8279a292c, 66645d7f0f23665e and 96bd4403a463e001 on FP4-Local, and e137fcd8279a292c, 135a9834806eb026 and 96bd4403a463e001 on NVFP4.

Kernel time of one real prompt

An nsys run on the FP4-Local checkpoint, one request with a 4,096-token prompt at window 16,384, shows the routed kernels:

Routed kernels of one prompt (FP4-Local, one GB10, ms) main head change
gemm_nvfp4p and swiglu_quant32_sel, or gemm_nvfp4p_swiglu 933.1 812.8 -12.9%
q38_card_sum_shared_add 99.3 99.4 same

On main the first row sums 144 gemm_nvfp4p launches (883.5 ms) and 48 swiglu_quant32_sel launches (49.6 ms). On the head it sums 96 gemm_nvfp4p launches (551.2 ms) and 48 gemm_nvfp4p_swiglu launches (261.6 ms). The gain on real routing is smaller than the synthetic bench, which uses uniform routing. The profiled request's TTFT is longer than its kernel total by more on the head than on main, so part of the kernel saving shows up as idle time instead of a shorter request. I did not analyze the timeline for the cause.

Gates

The fold has a new gate, g32_nvfp4_swiglu, with its case filter nvfp4_swiglu in crates/gpu-gates/src/bin/gate_gemm.rs. It builds 16 card experts (every third of 24 on host) with 640-row and 160-row stacks, K of 512, shared column top-4, and T of 1, 9, 64 and 448. For each T the fold's activation plane is bit-identical to the two-launch plane, with no fault. The fused run gets its own up scratch, filled with NaN before each run, so it cannot read the up rows the reference wrote; a launcher that quantizes without running the up GEMM fails 12 of the 21 cases, while the gate without this separation passed all 21. For T of 64 and up the exact-walk path runs too. Two fault inputs are kept apart. The NaN-gate input has a NaN gate value in a card column and must raise QuantColumn. The refused-slot input has a slot refused by the card place, a slot of an unowned place and a listed slot in [n_card, HOST), and must raise ExpertId and QuantColumn, so the refused-slot raise is required on its own. Both paths must give the same plane and the same faults. A third group uses a route with no tile: one expert, every slot on host, with 1 and with 257 slots, once with a valid last place and once with the last slot at n_card. The valid cases raise nothing. The invalid ones must raise ExpertId from the two-launch path, the fused eager launch and the graph replay, and 257 slots cover the second pass of the scan loop. Each run's fold is captured as a graph and replayed over a fresh seed, and the replay must equal eager. A wrong K, column count, short g and short sel must be refused before launch.

just gate-gpu-gemm was not run as a recipe, so I ran its gate step directly on each card. The existing cases for routed and dense NVFP4 bits (g32_nvfp4_routed, g32_nvfp4_dense) and for the quantizer (g32_quant) need a Qwen3 model file that the GB10 machines I used did not have, so they ran only on the RTX 5090.

bash tools/gpu-gate.sh gate_gemm --case nvfp4_swiglu

On the GB10 (sm_121), on the head with the place scan, all 21 g32_nvfp4_swiglu lines read PASS with no FAIL:

gpu-gate.sh: gate_gemm ran 13 s (exit 0)

On the RTX 5090 (sm_120), the existing cases ran on the head before the place scan was added:

GATE case=g32_nvfp4 rc=0 lines=56 pass=50 fail=0
GATE case=g32_quant rc=0 lines=41 pass=35 fail=0

The fold's activation fingerprint for T of 1 and 640 rows is 56b9a33321c11a4e on both cards. cargo check --workspace --all-targets with the GPU features finished with CHECK workspace all-targets rc=0 warnings=0 on the RTX 5090, also before the place scan.

FAIL first

Three planted defects, each shown to fail the gate:

  • Every slab took its quantizer group from slab 0, and the host's K refusal was removed. The gate then failed twelve checks, among them every plane comparison and the K refusal:
FAILFIRST mutant rc=1 pass=4 fail=12
  • The refused-row raise of QuantColumn was deleted. The refused-slot input then failed at both row counts, with only ExpertId raised, and the NaN-gate input still passed:
mutant rc=1 pass=15 fail=3
  • The place scan was absent (the head before it was added). The two invalid all-host inputs, with 1 and with 257 slots, failed: the two-launch path raised ExpertId and the fused eager launch and graph replay raised nothing. The valid all-host inputs and the earlier cases passed:
gate_gemm: FAILED: one or more checks above did not pass

With the real source the gate passes every case (above). Commit 1 changes no output bits, and the existing g32_nvfp4_routed and g32_nvfp4_dense cases cover it. I did not plant a defect for the graph-replay check, which would fail if the fold read state from outside the captured graph.

GPU evidence

The kernel bench, the GB10 gate run and the speed A/B ran on DGX Spark (GB10) machines, and the other gate run on an RTX 5090 machine. nvidia-smi lines from each:

| NVIDIA-SMI 595.84                 Driver Version: 595.84         CUDA Version: 13.3     |
|   0  NVIDIA GB10                    On  |   0000000F:01:00.0 Off |                  N/A |
NVIDIA GeForce RTX 5090, 595.99.02
| NVIDIA-SMI 595.99.02              Driver Version: 595.99.02      CUDA Version: 13.2     |

Tested head

The GB10 gate run above used the head's kernel code. The planted-defect runs, the RTX 5090 runs, the kernel bench, the speed A/B and the nsys run each ran on an earlier head. The bench, the A/B and the nsys run were taken before the place scan was added, so their numbers do not include it. The scan reads one u32 per slot once per launch, 163,840 bytes for 40,960 slots, and I did not time it. After those runs the branch was rebased onto newer main. Among this PR's files, main's new commits changed wide38.rs and gate_gemm.rs in other places, the PTX shape tables and the unsafe ratchet; gemm32.rs, kernels32.rs and act32.rs changed only in this PR. The third commit recounts the unsafe pins.

Not run: the other just gate-* recipes.

What I ran into

None of this blocks the PR.

  • The FP4-Local end-to-end A/B was not repeated, so its effect on that checkpoint is not established beyond the nsys kernel numbers.
  • The two-launch up and SwiGLU path on main was not timed on its own, so the table above compares the head's two paths with each other.
  • The time of the place scan in the fused kernel was not measured; the bench, A/B and nsys numbers above predate it.
  • Folding the card sum (q38_card_sum_shared_add) into the down GEMM's epilogue is not possible under the current bit contract, so it is not part of this change.

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 24, 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: CLEAN: No must-fix finding remains.

Non-blocking

⚠ Complete the measurement evidence for the final head: crates/gpu/src/gemm/kernels32.rs:839. The added scan reads 4 × n_slots bytes per fused launch: 163,840 bytes at 40,960 slots [derived]. The PR states that its bench, A/B and profile predate this scan. The AGENTS change class “fold a launch into a neighbour” requires a timed A/B. Attach final-head measurements with the tested base/head hashes, card and driver, exact model paths, commands and output before reusing the speed claim.

Checked

Duplicates: dryer reports 0 pairs in crates/gpu; gpu-gates was excluded. Both NVFP4 entries share gemm32_block!. The fold reuses the quantizer, SiLU and launch checks.

Complexity: diagnostics report new nvfp4_swiglu_case (96) and swiglu_sides (24), nvfp4_gemm_arm 25→39, and g32::run 17→18. The new gate covers fixtures, plane/fault comparisons, replay and host refusals.

Silent failure: the new clamp repeats the last live block for quantizer padding. Invalid places raise ExpertId; refused quantizer groups raise QuantColumn. The launcher rejects mismatched K and short gate/place buffers with shape errors.

Tests: the gate compares planes and faults across the reference, eager fold and graph replay, with separate poisoned up scratch. The PR reports FAIL-first runs for wrong-slab, missing-K-check, dropped refused-slot fault and omitted-scan mutants. CUDA gates were not rerun during validation.

Gates: changed spill and unsafe ratchets have dated PINs and reasons.

Escape catalog: C1–C4 do not match the changed Rust and table files.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_gemm.rs, crates/gpu/src/arch/qwen3moe/wide38.rs, crates/gpu/src/gemm/act32.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.

@juliankang4
juliankang4 merged commit 346bbd7 into midagedev:main Oct 24, 2026
8 checks passed
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