Skip to content

gpu: gemm_nvfp4p — the NVFP4 planes in the 32-value GEMM (Bolt prefill lever 3) - #342

Closed
midagedev wants to merge 3 commits into
mainfrom
bolt-g5-nvfp4-gemm32-r2
Closed

midagedev wants to merge 3 commits into
mainfrom
bolt-g5-nvfp4-gemm32-r2

Conversation

@midagedev

Copy link
Copy Markdown
Owner

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 bf83ac8f4 (origin/main) → head 7f09e00db (bolt-g5-nvfp4-gemm32-r2).
  • 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 01:20
…e nvfp4p entries

Partial edits of the GLM round bolt-g5-nvfp4 (spec: engine 2026-10-16), stopped for the move
to the Mac. cargo check was in progress; no gate run.

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 before its checks, and shared logic and redundant elements need consolidation.

Must fix

1. Construct valid short-plane fixtures

crates/gpu-gates/src/bin/gate_gemm.rs:5301 passes 1536 elements as a 32×47 tensor; the next line passes 192 as 32×5. DeviceTensor::upload rejects both shapes, and ? exits the gate before any refusal assertion. The attached --case nvfp4 run skips g32_refuse.
Fixing these now restores the full gate. Replace both lines and run just gate-gpu-gemm --case g32_refuse:

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

2. Reuse the NVFP4 decoder

crates/gpu/src/gemm/gemm32.rs:405 repeats the nibble order and scale-byte selection already owned by crates/gpu/src/mxfp4.rs:303 (R14).
Reusing that owner now prevents the GEMV and GEMM layouts from drifting. Replace the four decode bindings and sh 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 inside the existing unsafe block with:

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

Restore E2M1 to private visibility.

3. Reuse the existing gate launch helper

crates/gpu-gates/src/bin/gate_gemm.rs:3334 copies crates/gpu-gates/src/bin/gate_gemm.rs:3301: sentinel initialization, launch, synchronization, readback and truncation. Only weight construction differs (R14).
Consolidate now before another layout copies this pipeline. 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)
}

Existing callers replace res, lay with res.weight(lay)?. NVFP4 callers use gemm and replace &w, &qs, &e with Gemm32Weight::Nvfp4Planes { qs: &qs, e: &e, scale: w.scale }.

4. Derive the arithmetic family from the weight kind

crates/gpu/src/gemm/gemm32.rs:567 adds epi even though $kind already identifies NVFP4. The new epi32_nv macro at crates/gpu/src/gemm/gemm32.rs:500 has one caller, at line 542.
Remove the repeated family choice and one-use wrapper now. Delete epi32_nv, remove the epi: parameter and six entry arguments, and pass $kind instead of $epi at both arithmetic calls. Update the macro docs. Replace mma_epi32 with:

macro_rules! mma_epi32 {
    (nvfp4p, $mins:literal, $a:ident, [$($b:expr),+],
     $d0:ident, $d1:ident, $da:expr, $sa:expr, $acc:ident, $nt:expr) => {{
        // SAFETY: all warp lanes reach both MMAs with fragments in their layout.
        let (i0, i1) = unsafe {
            (
                mma_m16n8k32_s32_s8([0; 4], [$a[0], $a[1], 0, 0], [$($b),+]),
                mma_m16n8k32_s32_s8([0; 4], [0, 0, $a[2], $a[3]], [$($b),+]),
            )
        };
        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]);
        }
    }};
    ($kind:ident, $mins:literal, $a:ident, [$($b:expr),+],
     $dw:ident, $mw:ident, $da:expr, $sa:expr, $acc:ident, $nt:expr) => {{
        // SAFETY: all warp lanes reach this MMA with fragments in its layout.
        let i0 = unsafe { mma_m16n8k32_s32_s8([0; 4], $a, [$($b),+]) };
        epi32!($mins, i0, $dw, $mw, $da, $sa, $acc, $nt);
    }};
}

Verify the decoder and macro changes with PTX scans and the family gate.

Checked

Duplicates: decoder and gate-launch copies confirmed. The four dryer pairs are thin entries over the common block.
Complexity: diagnostics report new dense/routed cases at 45/41, refusals 30→42, and launch checks 41→49; complexity alone is not a finding.
Silent failure: fixture generation clamps random bytes to valid scales.
Tests: refusal setup returns a shape error before assertions; numeric gate results were not rerun here.
Gates: unsafe ratchet has a dated PIN; no existing numeric bands relaxed.
Escape catalog: no patterns matched.

Notes

The timing claim lacks the model file and timing commands/output. Attach these and the nvidia-smi line; the body gives card/driver prose.

Card check: needs-gpu. 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 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)

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.

Both uploads fail their own shape checks before the refusal gate reaches its 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::zeroed(stream, rows, 384 / 8 - 1)?;
let nve_short = DeviceTensor::zeroed(stream, rows, 384 / 64 - 1)?;

@midagedev

Copy link
Copy Markdown
Owner Author

Superseded by #344: the WIP commit title is reworded; force-push was not available overnight.

@midagedev midagedev closed this Oct 16, 2026
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant