Skip to content

gemm: copy the BF16 prompt sites' activations rounded once - #761

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

juliankang4 merged 3 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-dense-k64

Conversation

@juliankang4

Copy link
Copy Markdown
Collaborator

Qwen3.8 prefill의 BF16 dense 행렬곱에서 activation을 한 번만 BF16으로 반올림해 두고, 각 곱셈이 weight처럼 그 값을 복사해 쓰게 해서 NVFP4 체크포인트의 prefill을 빠르게 하는 작업입니다.

Part of #565.

What and why

On a GB10, the BF16 dense prompt GEMMs of Qwen3.8 run through one MMA tile. Until now the tile loaded its F32 activation pieces into registers, checked them, rounded them to BF16 and stored them into the stage again in every row block of every product. A bench of tile variants located the cost there. Staging K 64 wide on F32 activations ran slower on the large shapes, and reading activations rounded beforehand at the current K width ran faster.

This PR rounds a model-width input once into a BF16 form (kernel bf16_cols, which also writes a refusal word per column) and lets the tile copy those words with cp.async, the way it already copies the weight (kernel bf16_mma_cols_gemm). A column the range check refuses is still replayed on the exact path from the F32 rows, so every output keeps its bits.

  • The tile takes its activation source through a new trait, MmaCols. F32Cols is the existing behaviour and stays on bf16_mma_gemm, the E4M3 entries and the HC up and down kernels. Bf16Cols copies the rounded words.
  • GemmAct32 can hold a Bf16Form (the words, the refusal words and which x and how many columns they were rounded from). site::resident_quantize writes it when a site reading those rows is BF16 on the MMA tile and marks it stale otherwise. Every quantizer launch goes through GemmAct32::fill, which marks the form stale, and the filled field is private to act32.rs, so a new quantizer cannot skip that.
  • A GEMM reads the form only for the same x and no more columns than were rounded. Anything else takes the old path with the same output.
  • The Qwen3.8 walk keeps the form only for the model-width rows (K = 2,560), which several sites read per micro-batch. machine_for_experts reserves the bytes (5,124 B per token of the micro-batch) on a unified-memory card's stage, and bf16_form_bytes reads that row and refuses a missing or doubled one. A discrete card has no such reserve, so its plan does not move.
  • tools/ref/ptx-shapes*.tsv gets rows for the two new entries. The second commit corrects the spill pin of gqa_flash_fold_mma_256_p12_sel at cc 12.1: the table said 0/0, but ptxas reports a 16-byte spill at sm_121 and sm_121a and the driver JIT 8 local bytes at every arch, so ptx-spill-check.sh was already red on main. The entry's PTX is not changed by this PR.

Release notes: Changed: on GB10, the BF16 dense prompt matrix multiply copies activations that were rounded once instead of rounding them in every tile, which cuts its kernel time and raises NVFP4 prefill speed; outputs are bit-identical.

Code shape

  • No second copy. The activation load, check and rounding that lived inside the tile is now F32Cols, and bf16_cols_body calls the tile's own land_values and mma_fits, so the rounding and refusal rule has one owner. HC down's inject read goes through the same F32Cols::fetch. The gate compares against the F32 path's output, so no rule is copied into it.
  • Model code holds only architecture facts. The Qwen3.8 files only list which sites read the model-width rows (input_sites, shared_inputs, hidden_sites); the common GEMM owner gained no per-model branch.
  • Dead code is gone. The eight direct writes of act.filled (and the one in enqueue_up_swiglu32) became fill.
  • No silent failure. A form for another x, or too few columns, is not read and takes the old path. A misaligned x is refused in enqueue_bf16_cols, and a stale form handed to enqueue_bf16_mma_cols is a State error.
  • Comments state what is true now. tools/check-comments.sh is ok.
  • No relaxed gate. No band or tolerance moved. The only changed pin is the gqa_flash_fold_mma_256_p12_sel row above, which was wrong on main, and it carries PIN(2026-10-24) and its reason. The unsafe ratchet rises with the new code under a PIN line.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up. The lint count stays at the ratchet's 3 warnings, all in q38_combine.rs. nvfp4mma.rs builds only for native FP4 targets. Under CUDA_OXIDE_TARGET=sm_121a ./tools/mac-check.sh lint it no longer reports the misplaced SAFETY comment: this PR moves the comment onto the unsafe line and gives the file's kernel entries the too_many_arguments allows the other kernel entries carry. Its two host launchers still report too_many_arguments, as on main.

Duplication found or removed (path:line): the duplicate scan flagged crates/gpu/src/gemm/f32tile.rs:693 against crates/gpu/src/hc_gated.rs:1729, f32tile.rs:1335 against crates/gpu/src/q8f32.rs:2896, and two kernels32.rs:1324 pairs. They differ in what they read (activation columns against weight rows, a form check and a different launch, separate kernel entries that call the shared body). An earlier flagged pair, Bf16Cols::fetch and Bf16Rows::fetch, is now one: Bf16Cols::fetch calls Bf16Rows(self.words).fetch.

What I ran

Output is unchanged

In the production-entry micro, the F32 path and the BF16-form path produce the same output digest at every shape. In the gate, every new dense_mma bf16_cols row compares both the eager output and the graph-replayed output with the F32 path's output.

Greedy decoding of 128 tokens gives the same token hashes for main and head on both checkpoints in all three windows, and the 2-token profiled request matches too (PARITY ... True for four pairs).

GPU evidence

DGX Spark (GB10). nvidia-smi output on the gate run:

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

Build: cargo oxide build --arch sm_121a -- --locked -p bloomery-gpu-gates --features glm5next,clef,vision,mimo2,solar2,minimaxm3,gemma-embedding2,hf,checkpoint --release --bin gate_gemm --bin gate_hc_gated --bin gate_bf16 --bin gate_mxfp8, with BLOOMERY_BOX_LOCAL=1 BLOOMERY_BOX_CARD=local BLOOMERY_GATE_CARD=any.

just gate-gpu-gemm, just gate-gpu-bf16, just gate-gpu-mxfp8 and just gate-gpu-hc-gated were not run as recipes: the node run built each gate binary with cargo oxide build and ran it through bash tools/gpu-gate.sh, the last step of each recipe.

The gates below ran two commits before the head that goes up. On the head that goes up, gate_gemm (dense_mma, nvfp4_native, nvfp4_swiglu) and gate_hc_gated ran again with the same counts. The last commit does not touch the code that gate_bf16 and gate_mxfp8 cover:

GATE bash tools/gpu-gate.sh gate_gemm --case dense_mma rc=0 pass=89 fail=0
GATE bash tools/gpu-gate.sh gate_gemm --case nvfp4_native rc=0 pass=37 fail=0
GATE bash tools/gpu-gate.sh gate_gemm --case nvfp4_swiglu rc=0 pass=21 fail=0
GATE bash tools/gpu-gate.sh gate_bf16 rc=0 pass=309 fail=0
GATE bash tools/gpu-gate.sh gate_mxfp8 rc=0 pass=343 fail=0
GATE bash tools/gpu-gate.sh gate_hc_gated rc=0 pass=128 fail=0

FAIL-first

  • Gate: with Bf16Cols::refused forced to false, gate_gemm --case dense_mma exits 1, and the only FAIL lines are the two cells rows with a refused column (bf16_cols_bits=false). Every other row passes.
  • Stale form: the dense_mma bf16_cols stale_refused row checks that a fresh form is read (fresh_read) and that the same read is refused after a quantizer reuses the activation buffer (after_quantize). With the invalidation removed from GemmAct32::fill, dense_mma exits 1 with 88 passed and 1 failed, the only FAIL being after_quantize=false.
  • Placement test: a_unified_stage_reserves_the_bf16_form passes on the head and fails on each of three mutants (reserve on every card, b >= want turned into b == want, the refusal removed). The tree was clean after the mutants.

Speed

Server A/B on one DGX Spark with the default sm_121a build of both trees (main at 100c224fc): Qwen3.8 NVFP4 and FP4-Local, C = 1, draft off, three 4096-id code windows with 128 greedy tokens each, median of three requests, then one profiled 2-token request per arm for kernel times. Each checkpoint started with a discarded warm load, the clock cap was lifted only around each arm's requests and restored after, and NVFP4 ran head, main, head, main. Reproduce with bloomery-serve -m <model dir> --parallel 4 --ctx-size 16896 with BLOOMERY_DRAFT=off BLOOMERY_HOST_ROOM=96G, requests on /completion at temperature 0, seed 1.

Metric (one GB10, C@1, draft off) main head change
NVFP4 prefill tok/s, pair 1, median of three 4096-id prompts 1527.3 1581.4 +3.5%
NVFP4 prefill tok/s, pair 2, median of three 4096-id prompts 1572.5 1631.8 +3.8%
NVFP4 time to first token ms, pair 1, median 2688.2 2595.3 -93 ms
NVFP4 time to first token ms, pair 2, median 2609.2 2517.7 -92 ms
NVFP4 BF16 dense kernels, ms in one 4096-id prompt 503.9 418.7 -16.9%
NVFP4 all GPU kernels, ms in one 4096-id prompt 2601.1 2533.3 -2.6%
FP4-Local prefill tok/s, median of three 4096-id prompts 1456.3 1521.7 +4.5%
FP4-Local all GPU kernels, ms in one 4096-id prompt 2670.7 2666.3 -4.4 ms

Delta (head against main): NVFP4 prefill +3.5% and +3.8% in two alternated pairs (1527.3 to 1581.4 and 1572.5 to 1631.8 tok/s) with 67.8 ms less GPU kernel time in the profiled request; FP4-Local, whose dense sites are MXFP8, moves 4.4 ms of kernel time and its +4.5% prefill comes from one slow main request; one sitting on one machine, so a single observation.

Where the NVFP4 time went, from the profiled request: bf16_mma_gemm went from 327 launches and 503.9 ms to 97 launches and 145.6 ms, plus 230 launches of bf16_mma_cols_gemm at 245.2 ms and 97 launches of bf16_cols at 27.9 ms. The TTFT drop (92 to 93 ms) is close to the 85.2 ms drop in BF16 dense kernel time. Head was ahead of the neighbouring main in both pairs, and both arms got faster over the sitting, which order alone does not explain.

FP4-Local's dense sites are MXFP8, so this change barely touches it: its kernel time moves by 4.4 ms. Its +4.5% prefill comes from one slow third request of main (1320.8 tok/s), which the kernels do not explain. I count it as noise and make no FP4-Local speed claim.

Production-entry micro on one DGX Spark (4,096 columns, synthetic inputs, three orders alternated, median): the BF16-form entry takes 0.287 to 0.791 of the F32 entry's time at the TP=1 shapes and 0.690 to 0.790 at the split shapes for 2 and 4 ranks. For one 4K prompt's BF16 launches, 523.2 ms becomes 447.6 ms with the 96 roundings included (-75.7 ms, -14.5%). This micro ran on the commit that introduced the entries, whose dense device code is the same as the head's (the same ptx-compare md5 for each of these entries).

Compiler and PTX

  • Across the one-line Bf16Cols::fetch change: ptx-compare reports identical PTX, 402 entries on each side.
  • Against main: two entries added (bf16_cols, bf16_mma_cols_gemm), none removed. Five existing entries (bf16_mma_gemm, fp8_b128_mma_gemm, mxfp8_mma_gemm, hc_gated_up_mma_mix_4, hc_gated_down_mma_4) changed only in their PTX text hash, with the same registers, shared memory, spills and instruction counts, because the tile now reads its activations through F32Cols.
  • Driver JIT: bf16_mma_cols_gemm 122 registers, 48 KiB static shared, no local memory; bf16_cols 28 registers; bf16_mma_gemm 128.
  • ptx-spill-check.sh reports violations=0 PASS at sm_121, sm_121a and sm_86 on the dense device code, also on the head that goes up, where hc_gated_down_mma_4 and gemm_nvfp4_mma stay at their pinned 0 spill bytes. The ptx-compare lines above were taken one commit before HC down's inject read moved to F32Cols::fetch.
  • Other checks: tools/check-unsafe.sh is ok (gpu 2302 to 2314 unsafe blocks, 285 to 295 unsafe fn, each new block with a SAFETY comment).

Measured head against the head that goes up

The server A/B ran on an earlier head over main 100c224fc. The head that goes up was rebased onto a newer main afterwards, so the rebase is not pure: it carries three new upstream commits, and this PR gained a few host lines (the new SwiGLU quantizer now calls act.fill, nvfp4mma.rs reads act.filled(), filled is private to act32.rs, and Bf16Cols::fetch calls Bf16Rows::fetch). The device code of the dense entries did not change, which the identical ptx-compare above shows against the gate head. I did not rerun the timed A/B on the final head.

Hardware

DGX Spark (GB10), driver 595.84, CUDA 13.3 (Build cuda_13.3.r13.3/compiler.38244171_0). Models: Qwen3.8 NVFP4 and Qwen3.8 FP4-Local. The nvidia-smi lines are under GPU evidence above.

What I ran into

None of this blocks the PR.

  • qwen4exp_mtp_reserve::a_drafted_plan_on_one_pool_counts_the_draft_once fails on main with the same message ("a pool one byte under the need: Ok(3583999)"); this branch does not touch that file or machine.
  • The HC up kernel (hc_gated_up_mma_mix_4) read 1.2% to 1.9% slower at the median of nine launches in two micro runs, with the whole mix step unchanged within 0.4%. Its PTX hash moved and its resources did not. I could not tell noise from a small real cost with nine launches.
  • Not run on the final head: the timed A/B (see above), a line-by-line PTX diff of the five existing entries whose hash moved, a timing of fp8_b128_mma_gemm (its dense gate row passes, and neither checkpoint uses it), and a FAIL-first for the new 0/0 spill pins.
  • The BF16 form is only used for the model-width rows. Attention-output and SwiGLU inputs have one reader each, so rounding them separately would not pay back, and MXFP8 dense sites still take the F32 path.

AI help

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

On GB10 a BF16 dense site's MMA tile loaded its F32 activation pieces
into registers, checked and rounded them, and stored them into the stage
after the current products, in every row block of the product. The walk
now rounds a model-width input once into a BF16 form beside its q8
scratch (GemmAct32::with_bf16 and bf16_cols: the words and a refusal
word a column), and the tile copies those words with cp.async as it
copies the weight's (Bf16Cols). A refused column still replays on the
exact owner from the f32 rows, so every output keeps its bits.

The tile takes its activations through MmaCols: F32Cols for the existing
entries (bf16_mma_gemm, the E4M3 entries and the HC up and down),
Bf16Cols for bf16_mma_cols_gemm. site::resident_quantize writes the form
when a site reading the rows is BF16 on the MMA tile and marks it stale
otherwise; a quantizer launch marks it stale as well, and a GEMM reads
it only for the rows and columns it was rounded from.

The qwen38 walk holds the form for its model-width rows (the mixers',
the shared expert's and the PLE site's input) on a load with such a
site whose stage card reserves it. machine_for_experts reserves 5,124 B
a position on a unified card (GB10's) and place::bf16_form_bytes reads
the row back for the load; a discrete card's plan is unchanged, and its
load keeps rounding in the tile.
gqa_flash_fold_mma_256_p12_sel's rows in the three cc 12.1 tables read
0 0, but ptxas 13.3.73 spills 16 bytes of it at sm_121 and sm_121a and
the GB10 JIT (driver 595.84) gives it 8 local bytes at every arch, so
`ptx-spill-check.sh ... generate_ds41:mma` failed on upstream/main
already. The rows now hold the measured values; the entry's PTX is the
same with and without the dense MMA tile's activation source
(ptx-compare: unchanged). The cc 8.6 rows in tools/ref/ptx-shapes.tsv
stay as they are.
nvfp4mma.rs builds only with bloomery_nvfp4_mma (sm_120a and sm_121a), so
the default lint never saw it. The SAFETY comment of the module load moves
onto the unsafe line, the flat-argument kernel entries and the SwiGLU
device core carry the tree's too_many_arguments allowances for kernel ABIs
(the core sits in its own module, since the device macro's same-name
wrapper repeats its arguments), and the scale packer's range loop keeps
the unroller's form. The two host launchers still take flat arguments.
@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 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: Both findings are non-blocking; neither establishes a must-fix defect.

Non-blocking

⚠ Complete final-head measurements: crates/gpu/src/site.rs:1184. Preparation adds one launch per eligible input group. Its logical traffic is 15,364 B/token at K=2,560 [derived: 4K F32 reads + 2K BF16 writes + one 4-byte refusal word].
The PR reports final-head gate reruns, but its timed A/B predates that head and omits the measured head hash. Supply a final-head A/B with both measured commit hashes, concrete model paths, commands and output to verify the final dispatch cost.

⚠ Overwrite the BF16 form before graph replay: crates/gpu-gates/src/bin/gate_gemm.rs:7394. The eager run leaves the same input and rounded words in place.
Omitting only the captured bf16_cols launch leaves those words valid, so graph_bits still passes. After capture, round a separate zero input into act, then launch the graph and compare with eager. This makes a missing preparation node observable.

Checked

Duplicates: the activation readers reuse land_values and Bf16Rows::fetch. Dryer reported zero model pairs and did not scan GPU crates.

Complexity: dense_mma_case 76→108 adds gate cases; fused_swiglu 17 is a moved body, unchanged apart from a qualified callee. site::gemm 34→38 adds cache dispatch; Wide38::new 13→16 adds optional storage; Body38::load_placed 69→71 adds load-time reserve checks.

Silent failure: cached reads check the source address and column count; fill invalidates the form. Missing optional storage uses the F32 path; malformed reserves and stale direct reads return named errors.

Tests: static mutation analysis confirms the capture-only preparation omission above. Changing reserve >= to == fails the smaller-ubatch assertion. The stale-form case asserts rejection after quantizer reuse.

Gates: unsafe and existing spill-pin changes carry dated PIN reasons; no numeric tolerance moved. New spill-pin FAIL-first evidence is absent and disclosed.

Escape catalog: no C1–C4 pattern matched.

Notes

GPU gates were not rerun during validation. The submitted measurements lack the measured head hash; gpu.json remains evidence: false.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_gemm.rs, crates/gpu/src/arch/qwen3moe/body38.rs, crates/gpu/src/arch/qwen3moe/plan38.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 169826b into midagedev:main Oct 24, 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 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