Skip to content

gpu: speed up Qwen3.8 prompt prefill in the routed NVFP4 walk and the HC mix - #822

Merged
juliankang4 merged 5 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-lead-moe-prefill
Oct 26, 2026
Merged

juliankang4 merged 5 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-lead-moe-prefill

Conversation

@juliankang4

@juliankang4 juliankang4 commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

Qwen3.8 프롬프트 처리에서 NVFP4 expert 곱셈의 K 순회를 128값 단위로 바꾸고, HC mix가 다음 사이트의 입력 형식을 자기 epilogue에서 함께 쓰게 해 첫 토큰까지의 시간을 줄입니다.

What and why

Prompt prefill on Qwen3.8 runs the routed NVFP4 gate/up and down products on the card, and each layer's HC mix writes values that the next site then quantizes in a separate launch. This PR speeds up both without changing a value.

The native NVFP4 products (gate_up_nvfp4_mma and gemm_nvfp4_mma) waited, synchronized the block and issued their copies once per 64-value step. Four commits change that walk:

  • A step stages two 64-value halves and runs both halves' MMAs between one wait and one barrier, in the same K order. A K with an odd number of 64-value steps runs its last step on one half.
  • The copies run two steps ahead. Three stages fit in 41,472 bytes of shared memory, so two blocks still run per SM.
  • Each lane of the product epilogues reads all its column slots and input scales before its first store, instead of one column at a time.
  • Each row's 16-byte chunks are turned by chunk, so the cp.async copies and the LDS.128 and STS.128 of the nibble packing meet no bank twice, and one ldmatrix phase still meets none. A const block counts both access sets with swizzle::conflict_degree and holds every chunk aligned and inside its row.

The fifth commit changes the HC mix. The Qwen3.8 prompt walk quantized the mix's output for the next site with a separate launch that read the hidden rows back. up_mma_mix_body is now generic over OutForm. When the next site's readers take only the BF16 form or only the MXFP8 form from the scratch (site::only_form), the mix writes that form beside the mixed values, in hc_gated_up_mma_mix_4_bf16 or hc_gated_up_mma_mix_4_mxfp8. Those entries write the quantizer's bits and OR the column's refusal word. In every other case the split path runs and forgets the form, so a later reader never takes a stale one, and the walk's quantizers skip a form the scratch already holds. GemmAct32::out_planes and wrote own the room check, the refusal reset and the form marking for every epilogue that writes a form, the MXFP8 norm gate included. Gemm32Kernels::enqueue_form_cols is the quantizer of either form.

On a DGX Spark, FP4-Local TTFT p95 for a 4096-token prompt is 2.026% shorter than on main, and prefill is 2.062% faster. The NVFP4 checkpoint gains the same way, and greedy output is identical.

Release notes: Changed: Qwen3.8 prompt prefill is about 2% faster on the FP4-Local and NVFP4 checkpoints.

Code shape

The review reads these first. A box left unticked needs one line of why.

  • No second copy. chunk is the one owner of the stage layout that both native kernels' copies, packing and ldmatrix use. OutForm is the one epilogue interface for the BF16 form, the MXFP8 form and none, and up_mma_mix_body is one body for all three. GemmAct32::out_planes and wrote are the one owner of the room check, refusal reset and marking for every form-writing epilogue.
  • Model code holds only architecture facts. The Qwen3.8 file hands the readers' site names and the scratch to the common owners and skips a quantizer launch that the scratch already satisfies. The common owners gained a trait and arguments, not a per-model branch.
  • Dead code is gone. OutForm has one store generic over the block count (1 or 4, checked at compile time), so each form has the one store its callers use. Nothing this change made unused is left.
  • No silent failure. A form scratch of another K or without room is refused with a named error before the first launch, and an empty column is excluded by column_of(i) < len. The gate has a row for each.
  • Comments state what is true now.
  • No relaxed gate. No band or tolerance moved. The unsafe ratchet and the PTX shape table are raised for the new epilogue code and the new entries, each with a PIN line and its reason. The gate gains K = 448 cases.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up.

Duplication found or removed (path:line), or "none": the duplicate scan reports four candidates, all in the HC mix commit, and each differs. crates/gpu/src/gemm/nvfp4mma.rs:1617, crates/gpu/src/gemm/nvfp4mma.rs:1542, crates/gpu/src/hc_gated.rs:2023 and crates/gpu/src/hc_gated.rs:1978 are kernel entries that call one shared body (up_mma_mix_body or the norm gate body) with the flat arguments a kernel ABI needs, one entry per output form. crates/gpu/src/hc_gated.rs:2023 and crates/gpu/src/gemm/kernels32.rs:1164 call different bodies.

What I ran

On this head:

cargo check of the 38 workspace crates finished with rc 0 on this head, and so did the 11 crates built for sm_121a.

That run was before a one-line lint fix in the HC mix commit (lane.is_multiple_of(2)); the sm_121a PTX of the generated entries is byte-identical with and without that line.

cargo fmt --check passed on this head. cargo clippy --workspace --all-targets with the GPU features ran on a DGX Spark for the default target and for sm_121a; its only warning on either target is type_complexity at crates/gpu-gates/src/bin/shared/q38_combine.rs:111, a file this change does not touch.

GPU Evidence

Card conditions of the timed runs, the spill gate, the zgate cases and the HC mix gate, from nvidia-smi:

NVIDIA GB10, 595.84
| NVIDIA-SMI 595.84                 Driver Version: 595.84         CUDA Version: 13.3     |

Card conditions of the RTX 5090 run of the native cases:

| NVIDIA-SMI 595.99.02              Driver Version: 595.99.02      CUDA Version: 13.2     |
|   0  NVIDIA GeForce RTX 5090        Off |   00000000:01:00.0 Off |                  N/A |

The native cases of gate_gemm compare the native product with a host transcription of the W4A4 rule and the fused gate/up with the product. They use the four walk commits on an earlier base than this head, and the rebase left the commits unchanged. On the RTX 5090:

gemm32 case=nvfp4_gate_up rows=64 k=448 slots=46 refused=false poison=None q8_off=0 y_eq=true eager_graph_eq=true fault=None replay_fault_eq=true native=true PASS
gemm32 case=nvfp4_native rows=16 slots=14 k=448 input=Varied fused=false native=true q8_eq=true producer_eq=true wrong=0 guard=true eager_graph_eq=true hash=cbd6f69350018dfd PASS
gemm32 case=nvfp4_native rows=16 slots=14 k=448 input=Varied fused=true native=true q8_eq=true producer_eq=true wrong=0 guard=true eager_graph_eq=true hash=cbd6f69350018dfd PASS
gpu-gate.sh: gate_gemm ran 1 s (exit 0)

and on the GB10:

gemm32 case=nvfp4_gate_up rows=64 k=448 slots=46 refused=false poison=None q8_off=0 y_eq=true eager_graph_eq=true fault=None replay_fault_eq=true native=true PASS
gemm32 case=nvfp4_native rows=16 slots=14 k=448 input=Varied fused=false native=true q8_eq=true producer_eq=true wrong=0 guard=true eager_graph_eq=true hash=cbd6f69350018dfd PASS
gemm32 case=nvfp4_native rows=16 slots=14 k=448 input=Varied fused=true native=true q8_eq=true producer_eq=true wrong=0 guard=true eager_graph_eq=true hash=cbd6f69350018dfd PASS
gpu-gate.sh: gate_gemm ran 1 s (exit 0)

Every nvfp4_gate_up and nvfp4_native row passed on both cards. Both native kernels use 128 and 126 registers, 41,472 bytes of shared memory, two blocks per SM and no spill on sm_121a.

The HC mix gate and the PTX spill gate, on a GB10:

just gate-gpu-hc-gated
PASSED: gate_hc_gated the mix within its bands of the f64 rule at 4x2560 rank 320 (inject site and head)
just gate-ptx-spill
ptx-spill bin=gate_qwen3vl_tower entries=26 pinned=26 nonzero=none violations=0 PASS

The HC mix gate ran on the same HC mix commit before the last rebase. The two new HC entries spill 348 bytes each with 88 bytes of GB10 JIT local, pinned in tools/ref/ptx-shapes/sm_121a-cc12.1.tsv.

The gated-projection cases (zgate) of gate_gemm, which the MXFP8 norm gate shares with the new form owners, ran on this head on a GB10:

zgate PASS lines: 28

just gate-gpu-gemm not run as the full recipe: the nvfp4_gate_up, nvfp4_native and zgate cases above ran from the same gate_gemm binary, and a maintainer runs the recipe on the workstation.

Timed A/B

The timed A/B ran on a DGX Spark with main and with this change, three rounds per side in alternating order, medians below. Each request is a 4096-token prompt with 128 greedy tokens. The FP4-Local rows use the FP4-Local checkpoint without a draft and with the MTP draft (code and prose windows). The NVFP4 rows use the NVFP4 checkpoint without a draft.

Arm and metric Main Head Change
FP4-Local TTFT p95 (ms) 1935.49 1896.27 -2.026%
FP4-Local prefill (tok/s) 2123.24 2167.03 +2.062%
FP4-Local decode (tok/s) 30.1644 30.438 +0.907%
FP4-Local MTP code TTFT p95 (ms) 2024.83 1982.36 -2.097%
FP4-Local MTP code prefill (tok/s) 2029.59 2073.56 +2.167%
FP4-Local MTP code decode (tok/s) 60.5725 60.6978 +0.207%
FP4-Local MTP prose TTFT p95 (ms) 1997.99 1955.75 -2.114%
FP4-Local MTP prose prefill (tok/s) 2056.92 2101.01 +2.144%
FP4-Local MTP prose decode (tok/s) 42.4673 41.1396 -3.126%
NVFP4 TTFT p95 (ms) 2093.17 2042.47 -2.422%
NVFP4 prefill (tok/s) 1962.4 2012.79 +2.567%
NVFP4 decode (tok/s) 22.4975 22.6728 +0.779%

Greedy output was identical on main and on head in every part.

On FP4-Local the prefill, TTFT and decode ranges of the two sides are separate. With the MTP draft the prefill and TTFT ranges are separate in both windows, and the decode ranges overlap in both windows. On NVFP4 the prefill and TTFT ranges are separate and the decode ranges overlap.

The timed runs used a build that carried one further kernel entry, a BF16 variant of the norm gate, which neither measured checkpoint launches for these prompts. The five commits here are otherwise the same.

Reproduce one FP4-Local round, with base on main and head on this branch:

(cd base && cargo oxide build --arch "$(bash tools/arch.sh)" -- -p bloomery-gpu-gates --features glm5next,clef,vision,mimo2,solar2,minimaxm3,gemma-embedding2,hf,checkpoint --release --bin bloomery-serve)
env BLOOMERY_DRAFT=off BLOOMERY_HOST_ROOM=96G ./base/target/release/bloomery-serve -m "<folder>" --host 127.0.0.1 --port 18731 --parallel 1 --ctx-size 16896 & server_pid=$!
until curl -fsS http://127.0.0.1:18731/health; do sleep 1; done
kill "$server_pid"; wait "$server_pid"

The NVFP4 round uses the NVFP4 checkpoint. The MTP rounds add BLOOMERY_DRAFT=mtp BLOOMERY_MTP_DRAFT="<mtp-folder>" BLOOMERY_MTP_WIDTH=cost.

Hardware

DGX Spark (GB10), driver 595.84, CUDA 13.3, for the timed A/B, the spill gate, the HC mix gate, the zgate cases and the GB10 native cases. RTX 5090, driver 595.99.02, CUDA 13.2, for the RTX 5090 native cases.

AI help

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

The routed FP4 gate/up and product walks waited, synchronized the block
and issued their copies once per 64-value step, which is one MMA per
fragment. Each step now stages two 64-value halves in two shared stages
and runs both halves' MMAs between one wait and one barrier, in the same
K order. The fused gate/up's SwiGLU tile reuses the weight stages after
the walk, so both kernels keep two blocks per SM in 33,792 bytes of
shared memory. A K that is an odd number of 64-value steps runs its last
step on one half.
With 128-value steps the walk issues fewer barriers and address
instructions per MMA, and the time it saved moved into the wait for the
step's cp.async copies: one step of copies in flight per block no longer
covers their latency. Three stages copy each step two steps ahead and
wait for all but the newest group.

The rows drop their four words of pad and turn their 16-byte chunks by
bits 1 and 2 of the row index instead, so ldmatrix still reads eight
rows without a bank conflict and the three stages fit in 41,472 bytes
of static shared memory, two blocks per SM. A const check holds each
chunk aligned and inside its row and counts the banks of an ldmatrix
phase with swizzle::conflict_degree. The halves of a step run as an
unrolled loop over the constant half count.

The gate gains K = 448 cases, native against the host W4A4
transcription and fused against the product: seven halves end on one
half in a stage the walk reuses.
Each lane of the down product's epilogue read a column's slot, then its
input scale, then stored the column's two values, one column after the
other, so every column paid two global load latencies in a row. The lane
now reads all sixteen slots, then all sixteen input scales, and only then
stores, and the fused gate and up does the same for its eight columns.
Its Q8 loop reads each column's slot ahead of the quantization's
shuffles. The values and the order of the stores are unchanged.
… bank twice

Each thread copies and packs its own 16-byte chunks of a stage row, and
eight consecutive threads cover the two chunks of one half in four rows.
The chunks turned by bits 1 and 2 of the row index, which put rows 0 and
2 of every four on the same two chunks, so each cp.async into the stage
and each LDS.128 and STS.128 of the nibble packing took two passes
through the banks.

Bit 1 of the row index now turns bit 1 of the chunk number and bit 2
turns bit 0. The eight threads land on eight bank groups, and the eight
rows one ldmatrix phase reads still meet no bank twice; the const check
counts both access sets with swizzle::conflict_degree. Per full step a
thread's eight 128-bit shared accesses of the walk (six for the rows
past the activation's 64) go from two passes to one. Values, MMA order
and stores are unchanged.
The Qwen3.8 ubatch walk quantizes the HC mix's output for the next site:
the attention mixer's input and the shared expert's input, each a separate
cols launch that reads the hidden x rows f32 values back. The wide MMA
up/mix (up_mma_mix_body, now generic over the epilogue's OutForm) writes
that form beside the mixed values when it is all the next site's readers
take from the scratch (site::only_form): after the mix, each warp reads
one tile column's 32 hidden values back and writes their BF16 words
(hc_gated_up_mma_mix_4_bf16) or MXFP8 block (hc_gated_up_mma_mix_4_mxfp8),
bit for bit the quantizer's, and ORs the column's refusal word. The split
path forgets the form instead, so a later reader never takes a stale one,
and the walk's quantizers skip a form the scratch already holds for those
rows.

GemmAct32::out_planes and wrote own the room check, the refusal reset and
the form's marking for every epilogue that writes a form, the MXFP8 norm
gate included, and Gemm32Kernels::enqueue_form_cols the quantizer of either
form that the site and the gates choose by form.

check_wide_forms holds both forms of the wide mix to the mix without one
and to the quantizer's form under the next product, with a NaN column, a
column the form must refuse, graph replay and the split path's forgotten
form.
@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 26, 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: The remaining findings request evidence and do not establish a must-fix defect.

Non-blocking

⚠ Complete the hardware evidence: crates/gpu/src/gemm/nvfp4mma.rs:1183.
The occupancy and launch-fusion changes require identifiable gate and timed A/B runs. The PR reports earlier builds without their hashes and uses model-variable placeholders. Attach both tested build hashes, model filenames, and commands with output so the claimed gain can be reproduced.

⚠ Supply FAIL-first results: crates/gpu-gates/src/bin/gate_hc_gated.rs:1279.
The body reports passing runs but no failing runs for the added clauses. Attach failures with split-path form invalidation removed and the final odd K half skipped, then restore both. These mutations check stale-form rejection and the new K=192/448 reference cases.

Optimization headroom

  • E. Less work: crates/gpu/src/hc_gated.rs:1944. Evaluate staging mixed values in the existing shared allocation for form conversion. This would avoid 4 × hidden global-load bytes per token per fused mix [derived]; price the replacement shared-memory traffic and synchronization.

Checked

Duplicates: output-form entries share up_mma_mix_body; out_planes and wrote own form preparation and marking.
Complexity: enqueue_mix adds form dispatch; check_wide_forms checks eager outputs, stale forms and replay. No kernel split is requested.
Silent failure: absent forms fall back to quantization; form room checks return named errors.
Tests: static mutation review supports the two requested FAIL-first runs. Deleting hc_gated.rs:2678 leaves the stale form readable, contradicting gate_hc_gated.rs:1453. New K=192/448 cases exercise the final live half at nvfp4mma.rs:529.
Gates: no numeric band moved; new spill and unsafe entries have dated PIN reasons.
Escape catalog: C1–C4 do not match the cited changes.

Notes

Static review only; no builds or GPU gates were run here. GPU evidence is incomplete under CONTRIBUTING.md.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_gemm.rs, crates/gpu-gates/src/bin/gate_hc_gated.rs, crates/gpu/src/arch/qwen3moe/mtp38.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 60296d9 into midagedev:main Oct 26, 2026
7 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