Skip to content

qwen38: keep the router in its BF16 words - #732

Merged
juliankang4 merged 5 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-decode-copy
Oct 23, 2026
Merged

juliankang4 merged 5 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-decode-copy

Conversation

@juliankang4

Copy link
Copy Markdown
Collaborator

Qwen3.8의 router와 shared gate를 load 때 F32로 넓히지 않고 checkpoint의 BF16 그대로 card에 두어, 토큰마다 읽는 양과 card 메모리를 각각 120.2 MiB 줄입니다.

Part of #565.

What and why

Qwen3.8's router (ffn_gate_inp, 512 x 2560) and its shared-expert gate (ffn_gate_inp_shexp, 1 x 2560) are stored as BF16 in both the NVFP4 and the FP4-Local checkpoints. Main widened them to F32 at load. They now stay in the checkpoint's BF16 words on the card, and the gated router widens each value as it reads it. Decode reads 126,074,880 fewer bytes per token (120.2 MiB), and the card holds 120.2 MiB less. Routing is bit for bit the F32 path.

On a GB10, C@1 decode with the draft off goes from 29.62 to 30.15 tok/s (+1.79%). MTP decode is unchanged (53.90 and 53.88 tok/s). Both head requests in the draft-off arm are faster than both main requests, but main's own two requests differ by 2.0%, so the gain is close to the run-to-run spread. Greedy text is identical in every arm.

Release notes: Changed: Qwen3.8 decode keeps the router and shared-expert gate in BF16 on the card and reads 120.2 MiB less per token.

How

  • crates/gpu/src/q8f32.rs: the one-warp row walk is generic over RowValues (an F32 slice or Bf16Words), so the F32 and BF16 forms share one body. A BF16 row loads every word of a chunk first and widens afterwards (RowValues::chunks8 and chunks32, overridden by Bf16Words). Widening each value right after its load put the widens between the loads, and the router kernel took 4998.2 µs per replay against 1603.8 µs for F32. Loading the chunk first gives 1311.8 µs.
  • crates/gpu/src/arch/qwen3moe/router.rs: two new entries, qwen35moe_router_fused_512_bf16 and qwen35moe_router_logits_512_bf16, call the existing fused and ubatch bodies. gated::RouterWeight is the weight a launch reads, either F32 or BF16 words. The prompt logits stage goes through the GEMM tile's existing gemm::TileRows. The 256-expert instance refuses a BF16 router by name.
  • Load: placement.rs keeps a Role::Router BF16 tensor raw where the model's reader reads words, including the 1-row shared gate, and the existing join_rows joins the two into 513 rows. The Qwen3.8 reader and role tables map both tensors as BF16. A GGUF that stores the router as F32 loads as before.
  • TP=2: the router is replicated on every rank, so each rank reads and holds 120.2 MiB less. Nothing in the change depends on the rank count.

Code shape

  • No second copy. The F32 and BF16 forms share one row walk, one routing body and one stage owner. f32_load_chunks is folded into RowValues::chunks8.
  • Model code holds only architecture facts. The Qwen3.8 files name the two tensors and their BF16 type. The common owners gained no model switch or flag.
  • Dead code is gone. f32_load_chunks has no remaining caller.
  • No silent failure. A router of any other type, and a BF16 router on the 256-expert instance, is a named error.
  • Comments state what is true now.
  • No relaxed gate. No band, tolerance or lint level moved. The unsafe ratchet and the PTX shape tables are re-pinned for the new entries.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count stayed at its ratchet.

Duplication found or removed (path:line): f32_load_chunks is removed in favor of crates/gpu/src/q8f32.rs:133.

What I ran

On an RTX 5090 (the gate also builds the kernels for sm_86):

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 |
just gate-gpu-qwen35moe-moe --case wide512,shape
wide512 bf16 fused m=1 vs the f32 weight widened: 1/1 tokens bit-identical tickets=0 PASS
wide512 bf16 fused m=5 vs the f32 weight widened: 5/5 tokens bit-identical tickets=0 PASS
wide512 bf16 fused m=8 vs the f32 weight widened: 8/8 tokens bit-identical tickets=0 PASS
wide512 bf16 ubatch n=70 vs the f32 weight widened: 70/70 bit-identical PASS
shape kernel=qwen35moe_router_fused_512_bf16 local_depot=false ld_local=0 st_local=0 PASS
shape kernel=qwen35moe_router_logits_512_bf16 local_depot=false ld_local=0 st_local=0 PASS
gate_qwen35moe_moe: PASS

The new wide512 bf16 case cuts LCG values to BF16 and compares the BF16 entries bit for bit with the F32 entries over the widened values, for logits, probabilities, ids, weights and the ticket count. It fails first: with the two halves of Bf16Words::widen swapped, the same case gives 0/1, 0/5, 0/8 and 0/70 and the gate exits 1. The head passes in the same run.

wide512 bf16 fused m=1 vs the f32 weight widened: 0/1 tokens bit-identical tickets=0 FAIL
wide512 bf16 ubatch n=70 vs the f32 weight widened: 0/70 bit-identical FAIL
mutant gate rc=1 (FAIL-first wants nonzero)

Unit tests on the head: cargo test -p bloomery-model --lib qwen35moe has 96 passed, and cargo test -p bloomery-model-hf has 18 passed. The workspace cargo check --workspace --all-targets with the gate features finished with rc 0, and cargo test -p bloomery-placement --lib has 175 passed. Those two ran on the build before the last rebase and the prompt-stage cleanup, and were not run again on the head.

Not run here: the Qwen3.8 eager and graph end-to-end gate, and the PTX comparison of the unchanged entries.

GB10 decode

Qwen3.8-Flash-Next-FP4-Local, 4096 prompt ids, 128 output ids, greedy, C@1, one server load per arm with two requests each. The arms ran in the order main draft off, head draft off, head MTP, main MTP. The GPU clock cap was lifted for each arm and restored afterwards. Columns are tok/s.

Arm Request 1 Request 2 Mean
main, draft off 29.912 29.322 29.617
head, draft off 30.202 30.093 30.148
main, MTP 53.747 54.052 53.899
head, MTP 53.935 53.818 53.876

Mean delta: draft off +1.79%, MTP -0.04%.

The decode profile of the head (a 1295-kernel graph replay) puts the router kernel at 1311.8 µs, 3.77% of the step. Main's router kernel took 1603.8 µs on another GB10 machine, so the two wall times are not directly comparable. The BF16 kernel now reads 126 MB in 1.31 ms, below the read bandwidth of the card, so it is bound by load latency and not by bytes.

The A/B ran on a build of this change before the last rebase onto main, the prompt-stage cleanup and the added documentation and tests. None of those touch the decode path (the fused router, chunks32 and the loads), so its numbers carry to head 9bc8db0bde140f37328c14f3dbca5a53f82f5079.

What I ran into

The following does not block this PR.

The BF16 router entry reads 126 MB per replay at about 96 GB/s, against a 235 GB/s read probe on the same card. Several rows per block and an earlier routing tail would use the rest, and either would keep the walk's sum order. This PR leaves the kernel's block shape as it is.

The prompt logits stage now loads BF16 with two 4-byte loads where the F32 stage copies 16 bytes asynchronously. TTFT p95 in the A/B above went from 3770.8 to 3590.8 ms for the first request, so the stage does not show up there, but a wider BF16 load in gemm::Bf16Rows would help every BF16 tile GEMM.

Hardware

DGX Spark (GB10), driver 595.84, CUDA 13.2. The GPU read probe measured 234.996 GB/s.

| NVIDIA-SMI 595.84                 Driver Version: 595.84         CUDA Version: 13.2     |
|   0  NVIDIA GB10                    On  |   0000000F:01:00.0 Off |                  N/A |

AI help

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

The Qwen3.8 checkpoints store the router and the shared expert's gate in
BF16. The load widened both to F32, so every decode step read the joined
513 x 2560 router of each layer at twice its stored bytes.

Keep the BF16 words on the card instead. The wide gated router gains BF16
entries for its fused and ubatch launches. They widen each value as they
read it and walk the same sums, so the logits, ids and weights are the F32
entries' over the widened values bit for bit. The narrow instance refuses
a BF16 weight by name. A GGUF that stores the router in F32 loads and runs
as before.
The row walks hoist their chunks' loads above the multiply-adds so that
the loads are in flight together. A BF16 row read value by value put each
widening right after its load, and the widening waits for that load's
word, so the next load issued only when the previous word had arrived.
The one-warp-a-row router walk then kept one load in flight.

RowValues gains the chunk loads the walks use, eight and thirty-two
chunks. A BF16 weight's words are loaded first and widened after, with
the half every chunk shares. Every other weight keeps its loads as they
were, and every value is the same, so the sums do not change.
@github-actions github-actions Bot added gpu The card engine: crates/gpu*, crates/app model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card placement Placement planning: crates/placement tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Oct 23, 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 reachable behavior defect or proven quality defect survived review.

Non-blocking

⚠ Complete final-head kernel verification: crates/gpu/src/q8f32.rs:133.
The chunk loaders also affect the existing bf16_gemv and bf16_gemv_ids dense/head kernels. The PR omits the unchanged-entry PTX comparison and Qwen3.8 eager/graph gate.
Provide the PTX comparison for entries claimed unchanged, the owning BF16 gates, and the eager/graph gate on this head. These distinguish router-local success from shared-kernel regressions before merge.

⚠ Identify the measured builds: crates/gpu/src/arch/qwen3moe/router.rs:3487.
The hardware reports lack both tested commit hashes. The decode A/B also lacks runner commands and raw output, and names an earlier head.
Attach the tested base/head hashes and complete runner output for the named model and card so the reported speed change can be checked.

Optimization headroom

  • C. More in flight: crates/gpu/src/arch/qwen3moe/router.rs:884. Use the block's eight warps for eight router rows while preserving each row's sum order. At 513 rows and one token per launch, ticket increments fall from 513 to 65 per layer per decoded token [derived].

Checked

Duplicates: 18 new definitions/implementations checked; no actionable duplication. Dryer reported zero pairs; GPU owners were searched manually.
Complexity: wide_bf16 (29), mixed_router_load (24), wide_load (23) are new setup/run/verify pipelines. classify 5→11 adds pair-format decisions; MtpInputs::from_parts 20→24 and planned_tensors 16→19 add format cases; wide_case 50→51 adds one check.
Silent failure: two format fallbacks followed through placement and joining; absent parts and unsupported types produce named errors. NaN/inf logits reach the Router fault.
Tests: static mutation audit covered swapped BF16 halves/chunk offsets, half-width inputs, forced raw mixed pairs, BF16→F32 mapping, dropped F32 preservation/router exemption, restored matrix-only guard, and reordered sums; bit/error/type/byte assertions reject them. The PR reports swapped-halves FAIL-first. Extracted chunk offsets and both parities also passed a local arithmetic check.
Gates: no tolerance relaxed; unsafe additions have a dated PIN; new PTX entries pin zero spills.
Adversarial: mixed pairs across layers, short inputs, BF16 NaN/inf, and BF16 on the narrow instance are blocked by conversion, bounds checks, faults, or named refusal.
Escape catalog: C1–C4 do not match.

Notes

Static review only; no build or GPU gate was run locally. GPU evidence is incomplete under CONTRIBUTING.md.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_qwen35moe_moe.rs, crates/gpu-gates/src/bin/gate_qwen4exp_mtp.rs, crates/gpu-gates/src/bin/gate_qwen4exp_nvfp4.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 cd93565 into midagedev:main Oct 23, 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 model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card placement Placement planning: crates/placement 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