Skip to content

gpu: gemm_nvfp4p — the NVFP4 planes in the 32-value GEMM - #344

Closed
midagedev wants to merge 4 commits into
mainfrom
bolt-g5-nvfp4-gemm32-r3
Closed

midagedev wants to merge 4 commits into
mainfrom
bolt-g5-nvfp4-gemm32-r3

Conversation

@midagedev

Copy link
Copy Markdown
Owner

Supersedes #342: the first commit's WIP title ("WIP(G5, GLM round stopped mid-task)…") is
reworded; force-push was not available overnight, so the reworded history went to a new branch.

What

gemm_nvfp4p: the NVFP4 planes read as they are resident (mxfp4.rs's repack: qs u32 words
four a 32-value unit, e one word a 64-value block) in the 32-value GEMM, with the tensor's F32
scale folded once at the store — no Q8_0 twin derived beside them. One mma.m16n8k32 s8 per
16-value sub-block with the other half's A codes zero (the pinned cuda-oxide has no s8
m16n8k16), so the two sub-block sums are separate exact i32s, acc = fma(d_a, fma(d1, f32(i1), d0·f32(i0)), acc), K-only order (gemm32.rs module doc's NVFP4 contract; the host transcription
gpu-gates' dot32_nv).

Why: on the RTX 3090 (24 GB, no room for the twins) Bolt's NVFP4 projections (ssm_in 18560×4096,
ssm_out 4096×8192) ran as 8-column gemv past the gemv's row limit — 4.02 s of the 8.02 s
P=4096 prompt (nsys s1734); the GEMM's derived target is ~0.86 s. The A6000 keeps its room by
dropping the 4.7 GB of twins. The engine wires it into project_rows on the #328 branch.

Proof (add class, AGENTS.md table)

  • gate_gemm --case nvfp4 PASS on the 3090 — g32_nvfp4_dense at Bolt's two shapes and 128
    rows at both K for m ∈ {1, 9, 64, 448}: band γ(2K/32+4) worst 0.022, contract_bits_differ=0,
    rerun bit-identical, a captured table and GEMM replayed (nodes 2); g32_nvfp4_routed under
    uniform and same-top-k routings at 1..448 slots, an id past the stack refused and NaN with the
    rest the clean run's bits; g32_refuse gains K-not-64, a short qs, a short e, a NaN scale.
  • FAIL-first, tools/mutant-run.sh 4 killed / 0 survived, clean 4 green: d0/d1 swapped,
    low/high nibble swapped, the store without scale, one MMA over the whole unit with d0 for
    both halves (dense FAIL lines, band ~10⁵ over).
  • ptx-compare bf83ac8f4 gate_e2e --features gpu and generate_ds41 --features gpu,deepseek41: rc 0 added-only both — added 1: gemm_nvfp4p, removed none, changed none.
  • gate-ptx-spill red on exactly the two rows (measured spill 0, jit_local 0), pinned in
    ptx-shapes.tsv, rerun green: 333/266/16 entries, violations 0.
  • unsafe-ratchet: gpu 1869 → 1871 blocks (main's IQ2_XXS table pin + the nvfp4p relays).

GPU Evidence

  • Card: NVIDIA GeForce RTX 3090 (driver 615.71.09); the box's A6000 idle-checked by the queue.
  • Commits: base 29ca500fa (origin/main) → head 0097d4977 (bolt-g5-nvfp4-gemm32-r3). The GPU
    runs below were measured at 7f09e00db (then-main bf83ac8f4); every changed file in this
    branch is byte-identical to it (git diff empty, the diff vs main is the same 7 files,
    900 insertions / 45 deletions).
  • Commands and summary lines (box jobs, the 3090 lane):
    • just gate-gpu-gemm --case nvfp4 (job s1883, Compiling bloomery-gpu):
      PASSED: gate_gemm — e.g. g32_nvfp4_dense rows=18560 K=4096 m=1 … worst_err_over_band=0.017 band_off=0 contract_bits_differ=0 rerun_eq=true … PASS; id_past_stack … refused_slots_nan=true others_eq_clean=true refused_listed=[5, 9] PASS.
    • just gate-ptx-spill (Q_CARD=any): generate_ds41 333/333 … gate_e2e 266/266 … gate_qwen3vl_tower 16/16, violations 0 PASS.
    • tools/ptx-compare.sh bf83ac8f4 … both bins: added-only (rc 0).
  • Static: cargo check + clippy green (bloomery-gpu, bloomery-gpu-gates), fmt clean,
    check-comments / check-arch / check-unsafe / check-ptx-names green.

🤖 Generated with Claude Code

midagedev and others added 3 commits October 17, 2026 02:42
Gemm32Weight::Nvfp4Planes reads the NVFP4 planes as mxfp4.rs's repack
holds them (qs u32 words four a 32-value unit, e one word a 64-value
block) with the tensor's F32 scale: one mma.m16n8k32 s8 a 16-value
sub-block, the other half's A codes zero (the pinned cuda-oxide has no
s8 m16n8k16), so the two sub-block sums stay separate exact i32s,
acc = fma(d_a, fma(d1, f32(i1), d0·f32(i0)), acc), the store folding
scale once — no Q8_0 twin derived beside the planes. Started by the GLM
round bolt-g5-nvfp4 (engine spec 2026-10-16), stopped mid-task; verified
against the plane layouts and completed here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… refusals, the unsafe pin

The kernel entry landed one commit below (WIP finished on the Mac). This adds
its gate on the g32 family's model: g32_nvfp4_dense over Bolt's two NVFP4
projections' shapes (ssm_in 18560x4096, ssm_out 4096x8192) and 128 rows at
both K for 1, 9, 64 and 448 columns, and g32_nvfp4_routed under uniform and
same-expert routings with an id past the stack (refused slots NaN, the rest
the clean run's bits); every output inside gamma(2K/32 + 4) of the f64
reference (ggml's dequant_row x scale against the dequantized q8 column) and
bit for bit gemm32::dot32_nv, the new one-owner host transcription of the
module doc's contract; a rerun and a graph replay bit-identical. The
reference check generalizes to a dot closure (check's four call sites pass
row_dot; the band's rounding count moves to the caller). g32_refuse gains
the four NVFP4 refusals (K not a multiple of 64, a short qs, a short e, a
non-finite scale). unsafe-ratchet: gpu 1863 -> 1865 blocks, the nvfp4p relays
of w32! (each with its SAFETY line).

Clean run: gate_gemm --case nvfp4 PASS on the 3090 (all 29 case lines, band
worst 0.022, bits 0, refused [5, 9]).

Co-Authored-By: Claude Code <[email protected]>
The add-class proof's last piece: just gate-ptx-spill was red on exactly the
two unpinned rows (measured spill=0 jit_local=0 on both, the family's every
other entry all zeroes too) and is green over the pinned table on a rerun —
generate_ds41 333/333, gate_e2e 266/266, gate_qwen3vl_tower 16/16, violations 0.

Co-Authored-By: Claude Code <[email protected]>
@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 labels Oct 16, 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 refusal gate exits during setup, and the change adds two duplicates and an unnecessary macro.

Must fix

1. Construct short planes with matching upload lengths

crates/gpu-gates/src/bin/gate_gemm.rs:5301 uploads 1,536 words with a 1,504-word shape; the next upload has the same defect. DeviceTensor::upload rejects this, and ? exits g32_refuse before its assertions. The reported --case nvfp4 run skips this case.
Fixing the fixtures now makes the refusal checks executable. Replace both uploads and run just gate-gpu-gemm --case g32_refuse:

let nvq_short = DeviceTensor::<u32>::zeroed(stream, rows, 384 / 8 - 1)?;
let nve_short = DeviceTensor::<u32>::zeroed(stream, rows, 384 / 64 - 1)?;

2. Reuse the existing NVFP4 decoder (R14)

crates/gpu/src/gemm/gemm32.rs:405 repeats crates/gpu/src/mxfp4.rs:303: the same nibble ordering, parity and two scale bytes.
Reusing the existing inline owner removes a second place to maintain the resident layout. Replace the four table decodes and sh calculation with:

let ([l0, l1, h0, h1, l2, l3, h2, h3], d0, d1) =
    <crate::mxfp4::Nvfp4 as crate::mxfp4::Fp4>::decode(v, ew, $n);

Replace the two scale stores with:

*$dst.add(16 + $pj) = d0.to_bits();
*$dst.add(18 + $pj) = d1.to_bits();

Keep the existing code stores and SAFETY block. Restore E2M1's private visibility.

3. Share the GEMM gate runner (R14)

crates/gpu-gates/src/bin/gate_gemm.rs:3334 copies crates/gpu-gates/src/bin/gate_gemm.rs:3301: sentinel fill, launch, synchronization, readback and truncation. Only weight construction differs.
Sharing the existing runner removes one function before more layouts acquire copies. Delete gemm_nv and replace gemm with:

fn gemm(
    dev: &Dev<'_>,
    w: Gemm32Weight<'_>,
    rows: usize,
    act: &GemmAct32,
    route: &GemmRoute,
    input: GemmInput,
    y: &mut DeviceBuffer<f32>,
    n_slots: usize,
) -> Result<Vec<f32>, GateError> {
    let stream = dev.gpu.stream();
    y.copy_from_host(stream, &vec![SENT; y.len()])?;
    dev.g32.enqueue_gemm32(
        stream,
        Gemm32Args {
            w,
            rows_per_expert: rows,
            act,
            route,
            input,
            y,
        },
    )?;
    stream.synchronize()?;
    let mut out = y.to_host_vec(stream)?;
    out.truncate(n_slots * rows);
    Ok(out)
}

Pass res.weight(lay)? at existing calls. Replace NVFP4 calls with this runner, passing Gemm32Weight::Nvfp4Planes { qs: &qs, e: &e, scale: w.scale }.

4. Inline the epilogue used by one macro arm

crates/gpu/src/gemm/gemm32.rs:500 introduces epi32_nv! solely for the call at line 542. It adds a definition and seven parameters around a loop used once.
Removing it now leaves fewer elements without changing the kernel boundary. Delete epi32_nv, update its reference in mma_epi32's documentation, and replace its sole invocation inside mma_epi32 with:

let da: [u32; 2] = $da;
for i in 0..4usize {
    ::cuda_device::thread::__unroll_config::<0>();
    let tv = mul_rn_f32($d0[i / 2], i0[i] as f32);
    let tv = fma_rn_f32($d1[i / 2], i1[i] as f32, tv);
    $acc[4 * $nt + i] =
        fma_rn_f32(f32::from_bits(da[i & 1]), tv, $acc[4 * $nt + i]);
}

Checked

Duplicates: both cited copies confirmed; their fixes reuse existing owners and remove elements. epi32_nv! has one invocation.
Complexity: diagnostics report new dense/routed gates at 45/41, refusals 30→42, and launch validation 41→49. Complexity alone is not a finding.
Failure paths: the upload guard rejects the fixtures before refusal assertions. The unchanged reference-worker panic fallback and pass conditions support the separate issue candidate.
Tests: the PR reports four mutants killed; this validation did not rerun them.
Gates: the unsafe-ratchet increase has a dated PIN. Escape catalog C1–C4: no finding matches.

Notes

GPU gates were not run in this review. The fixture failure was verified against the upload length check.

Card check: gpu-evidence. This pull request changes crates/gpu-gates/src/bin/gate_gemm.rs, crates/gpu-gates/src/gemm32.rs, crates/gpu/src/gemm/gemm32.rs … and carries a gate run on the author's card, which counts as verified.

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

Filed outside this PR: #346

Comment thread crates/gpu-gates/src/bin/gate_gemm.rs Outdated
Comment on lines +5301 to +5302
let nvq_short = DeviceTensor::upload(stream, &pnv.qs, rows, 384 / 8 - 1)?;
let nve_short = DeviceTensor::upload(stream, &pnv.e, rows, 384 / 64 - 1)?;

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.

The full planes fail upload's length check with these shorter shapes. Allocate matching short tensors so setup reaches the refusal assertions.

Suggested change
let nvq_short = DeviceTensor::upload(stream, &pnv.qs, rows, 384 / 8 - 1)?;
let nve_short = DeviceTensor::upload(stream, &pnv.e, rows, 384 / 64 - 1)?;
let nvq_short = DeviceTensor::<u32>::zeroed(stream, rows, 384 / 8 - 1)?;
let nve_short = DeviceTensor::<u32>::zeroed(stream, rows, 384 / 64 - 1)?;

@github-actions github-actions Bot added gpu-evidence Verified on the author's card: the pull request carries the gate run and its output and removed needs-gpu Changes code a card must check, and carries no gate run on a card labels Oct 16, 2026
@Burntgogi

Copy link
Copy Markdown
Contributor

I am implementing the fail-closed reference-worker panic fix from #346 on current main. This overlaps check and its callers, including the NVFP4 callers in this PR. I will keep kernel changes out of the fix and provide an explicit adaptation for your current helper/callers; no changes to numeric bands.

@Burntgogi

Copy link
Copy Markdown
Contributor

The #346 correction is now #364 (main fix f11aaee). Exact integration for your 0097d49 head is published at Burntgogi/bloomery:support/gemm346-on344 (7eaf697): both NVFP4 consumers propagate errors and the generic dot/rounding formulas are preserved. A fresh isolated-target metadata check passes. Host execution of the actual reference owners returns 0 for complete work and 1 for partial/all-worker panic. NVIDIA gate/device-consumer mutants remain unrun here (AMD-only; default ws SSH name cannot resolve). Could the GPU lane run gate-gpu-gemm and the panic-mutant cases before landing?

… shared NVFP4 decode, one GEMM runner

g32_refuse's short NVFP4 planes were uploads of the full plane data into
shorter shapes, which DeviceTensor::upload rejects, so the case exited in
setup before its assertions. They are zeroed short tensors now, and the
case runs: all twenty-four refusals named (nvfp4_qs_short, nvfp4_e_short,
nvfp4_scale_nan among them), rc 0 — before the fix the log shows
`DeviceTensor::upload: data.len() 1536 != rows*cols = 32*47`.

gemm32's nvfp4p stage decode moves to the one owner every NVFP4 path
shares, mxfp4's Fp4::decode (E2M1 private again); the staged code words
and the two scale stores are the owner's. --case nvfp4 is green before
and after with all 30 y_fnv lines identical. gate_gemm's two GEMM runners
are one: gemm takes the Gemm32Weight directly, gemm_nv is gone (98 lines
out).

ptx-compare 0097d49..head: added none, removed none, changed 1
gemm_nvfp4p (md5 only; regs/spill/smem/blk unchanged), gate-ptx-spill
267/267 green. ptx-canon on the moved md5 differs (186 lines, not
reorder-only): the shared call compiles to a different body than the
four inline table loads, held equal by the case's bits, not its PTX.

Co-Authored-By: Claude Code <[email protected]>
@midagedev

Copy link
Copy Markdown
Owner Author

All three must-fix items are in 40e87b1. Bot-written reply (Claude Code, on the maintainer's instruction).

  1. The short planes are zeroed short tensors now. just gate-gpu-gemm --case g32_refuse runs: all twenty-four refusals named, rc 0 (nvfp4_qs_short=refused nvfp4_e_short=refused nvfp4_scale_nan=refused among them). Before the fix the same command ended in setup with DeviceTensor::upload: data.len() 1536 != rows*cols = 32*47.

  2. gemm32's nvfp4p stage now calls <Nvfp4 as Fp4>::decode; E2M1 is private again. --case nvfp4 is green before and after the move with all 30 y_fnv lines identical.

  3. gemm takes the Gemm32Weight directly and gemm_nv is gone (98 lines out).

Also run: ptx-compare 0097d497..head — added none, removed none, changed 1 gemm_nvfp4p (md5 only; regs/spill/smem/blk unchanged); gate-ptx-spill 267/267 green. ptx-canon on the moved md5 reports differs (186 lines, not reorder-only): the shared call compiles to a different body than the four inline table loads; the case's bits hold it equal, the PTX does not.

@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:

  • Earlier 1 fixed: short-plane fixtures now allocate their declared lengths.
  • Earlier 2 fixed: the GEMM uses the existing NVFP4 decoder; E2M1 is private again.
  • Earlier 3 fixed: all layouts use the shared GEMM gate runner.

Verdict: CLEAN: no must-fix findings remain in the incremental diff.

Non-blocking

⚠ Refresh verification for this revision: crates/gpu/src/gemm/gemm32.rs:403 changes the kernel's decoder call. The attached PTX comparison and GPU runs predate this change; --case nvfp4 also skips the repaired refusal fixtures.
Add the move-class proof with just canon-check 0097d4977138f1797dda20727e806a088ef1ab39, plus revised-head output from just gate-gpu-gemm --case g32_refuse and just gate-gpu-gemm --case nvfp4.

Checked

Duplicates: the decoder and gate-runner copies are removed; E2M1 is private. No new definitions in this update.
Complexity: diagnostics describe the full PR; this incremental update adds no branches.
Silent failure: 0 new fallback sites. The shared runner propagates launch, synchronization and readback errors.
Tests: refusal fixtures now allocate their declared shapes. The refusal case requires each call to return its expected named error. No mutations were executed during validation.
Gates: no thresholds or pins changed in this update.
Escape catalog: C1–C4 have no matches.

Notes

GPU gates and PTX scans were not run during validation. Dryer excluded gpu-gates; the changed runner and callers were checked against the diff and code.

Card check: gpu-evidence. This pull request changes crates/gpu-gates/src/bin/gate_gemm.rs, crates/gpu-gates/src/gemm32.rs, crates/gpu/src/gemm/gemm32.rs … and carries a gate run on the author's card, which counts as verified.

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

@midagedev

Copy link
Copy Markdown
Owner Author

Closing: this PR's work is already on main through the Bolt train, so nothing here is left to merge.

  • 2bf3a7d gpu-gates: the gemm_nvfp4p gate (dense and routed NVFP4-plane cases, refusals)
  • 1c69f89 gpu: Gemm32Weight::Nvfp4Planes and the nvfp4p entries
  • 4def256 tools: gemm_nvfp4p's ptx shapes pinned
  • 784470a the review items (short planes upload truncated, the quantizer fold case)
  • 02d1451 then moved the kernel to one s8 m16n8k16 mma a sub-block

Further NVFP4 GEMM work goes through #565. Thanks @Burntgogi for the #364 integration branch; #364 itself is on main.

Bot-written (Claude Code, on the maintainer's instruction).

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 gpu-evidence Verified on the author's card: the pull request carries the gate run and its output

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants