Skip to content

gpu, gpu-gates: the Mamba-2 decode step on the card, one fused kernel per layer, gated against the host twin - #209

Merged
midagedev merged 7 commits into
mainfrom
nemo5
Oct 14, 2026
Merged

midagedev merged 7 commits into
mainfrom
nemo5

Conversation

@midagedev

@midagedev midagedev commented Oct 14, 2026 •

Copy link
Copy Markdown
Owner

Part of #156 (Nemotron 3 Nano 4B), step N5: the Mamba-2 decode step on the card.

What

bloomery_gpu::mamba2 runs one token of a Mamba-2 layer in one launch (mamba2_step, 480 blocks at the 4B widths). The kernel does these steps:

  1. The causal conv over the position-keyed ring, then its bias, then SiLU.
  2. The scan at state 128, with the state updated in place. Every product is rounded before its add, as the host twin does it.
  3. y + x·D, then silu(z)·y.
  4. The grouped RMSNorm (width d_inner / n_group), fused into the tail through one ticket per norm group.

The position is a device word, so one captured graph serves every step. A non-finite y raises FaultSite::Mamba2Scan. A state other than 128 is refused by name at enqueue, and nothing is launched. The in-proj and out-proj, the nemotron body and the prompt path are not here (N6/N7).

Prediction (derived, not timed: no engine caller yet). The step is HBM-bound:

  • The scan state is 3.93 MB per layer, read and written once per token: 165 MB per step over 21 layers.
  • About 8.35 MB per layer is about 12.8 µs at 650 GB/s.
  • Fusion makes 21 launches per step instead of 84 for a conv/scan/mix/norm split: about 18 µs of nodes instead of 72 µs at the measured c_node.
  • The achieved HBM fraction is the one term left to read at N7's step run.

공통화한 것 (Commonized)

  • Mamba-2 is a common module: crates/gpu/src/mamba2.rs names no model. The next Mamba-2 model calls enqueue_step with its widths.
  • The conv ring is GDN's position-keyed ring. linear::ring_input is now the one ring index both the delta conv (gdn_conv_prep, kda_conv_prep) and this step call. A --no-jit scan of gate_e2e shows all 234 existing entries md5-equal to the base, plus mamba2_step.
  • The grouped norm is fused into this kernel's tail, not added as a branch to gdn_norm_gate's contract. The ticket pattern, the fault sink, the launch contracts and the shared-module loader are the existing owners.
  • The gate's referee is the host twin model::mamba2::step_token (model: the shared host Mamba-2 step (Nemotron 3 Nano 4B, N2) #191), not a second reference.

Evidence

Run commit 863780ef (the review fold; parent c3a1dae2). The pushed head d9bfa9dc differs from it only in where GateRng sits in crates/gpu-gates/src/lib.rs (below verdict, so verdict keeps its doc comment); no line of code changed. Base origin/main 785d9334. Cards: GeForce RTX 3090 and RTX A6000, driver 615.71.09, CUDA 13.4.

just gate-gpu-mamba2 (job s431, re-read with boxq.py attach after a lost poll)

gpu-gate.sh: gate_mamba2 on the 3090 (asked 3090)
gpu-gate.sh: gate_mamba2 ran 1 s (exit 0)
exact gain: y differing values per token [0,0,0,0], state differing 0, ring exact true, window exact true PASS
exact no gain: y differing values per token [0,0,0,0], state differing 0, ring exact true, window exact true PASS
exact sequence start: y differing values per token [0,0,0,0], state differing 0, ring exact true, window exact true PASS
band: referee is step_token true; y outside the band 0 (largest |Δ|/band 0.022); state outside the band 0 (largest |Δ|/band 0.114); ring exact true PASS
refuse: state 96=PASS state 256=PASS groups 7=PASS conv 3=PASS short state=PASS eps inf=PASS; nothing launched (output keeps its poison) true PASS
fault base: the clean launch raised nothing PASS
fault NaN in x: raised layer 7 site mamba2_scan; sites raised in layer 7 (architecture unknown, so in code order, not step order): mamba2_scan, group 3 non-finite true, other groups unchanged true PASS
fault NaN in B: raised layer 7 site mamba2_scan; sites raised in layer 7 (architecture unknown, so in code order, not step order): mamba2_scan, group 3 non-finite true, other groups unchanged true PASS
fault inf in z: raised layer 7 site mamba2_scan; sites raised in layer 7 (architecture unknown, so in code order, not step order): mamba2_scan, group 5 non-finite true, other groups unchanged true PASS
fault -inf dt: raised layer 7 site mamba2_scan; sites raised in layer 7 (architecture unknown, so in code order, not step order): mamba2_scan, group 0 non-finite true, other groups unchanged true PASS
fault -inf A: raised layer 7 site mamba2_scan; sites raised in layer 7 (architecture unknown, so in code order, not step order): mamba2_scan, group 0 non-finite true, other groups unchanged true PASS
replay: nodes=1 y bit-identical to eager 3/3 ring true state true PASS
shape kernel=mamba2_step local_depot=false ld_local=0 st_local=0 PASS
PASSED: gate_mamba2 the fused Mamba-2 decode step equals the host twin bit for bit where the device library is not asked for a value libm gives differently (four tokens, with and without the gain, and from the sequence start; the ring exact) and within the derived band where it is; state 96 and 256, a conv of 3 taps, a group count that does not divide, a short buffer and a non-finite norm eps refused by name; a NaN in x or B, an infinity in z, a non-finite dt and a non-finite A raise mamba2_scan and leave their norm group non-finite and the other groups the clean bits; a captured graph is one node and replays three tokens bit for bit as eager; no local depot

just gate-gpu-cand (the other GateRng user)

gpu-gate.sh: gate_cand on the a6000 (asked a6000)
gpu-gate.sh: gate_cand ran 0 s (exit 0)
PASSED: gate_cand block keys the fold of the visible rows and kept lists the reference's selection over them (pin, ties to the lower block, ±0 tied, one block dropped) at 2048x8, 16x8, 64x1 and 8x32; nothing written at or below the bound; the compaction's slots, histogram and counts view and the remapped lists exact, alone and after the card's own selection; every refusal raises cand_mask at its layer; a captured replay equals eager; shapes refused by name; no local depot

just gate-ptx-spill

ptx-spill bin=generate_ds41 entries=302 pinned=302 nonzero=ds41_attn_seg_stage(spill=8,jit_local=8) violations=0 PASS
ptx-spill bin=gate_e2e entries=235 pinned=235 nonzero=none violations=0 PASS
ptx-spill bin=gate_qwen3vl_tower entries=16 pinned=16 nonzero=none violations=0 PASS

Mac static (tools/mac-remote.sh --tree … origin/main): rc 0.

Evidence (earlier head)

Run commit 3a8d67f4f518caa6916592fdd9c0dd4ec68cd6e4. Base 89d5ce011b11322fe01823ade1b796e85d64bb4d. No model file: the gate plants synthetic inputs at the 4B widths (state 128, conv 4).

nvidia-smi --query-gpu=name,driver_version --format=csv,noheader
NVIDIA GeForce RTX 3090, 615.71.09
NVIDIA RTX A6000, 615.71.09

just gate-gpu-mamba2 and just gate-ptx-spill below ran on the GeForce RTX 3090 (driver 615.71.09, JIT CUDA 13.4 in the scan banner). The A6000 line is the same machine's other card. This head was not gated on the A6000.

just gate-gpu-mamba2

Daemon rc 0. The gate's output:

gpu-gate.sh: gate_mamba2 on the 3090 (asked 3090)
gpu-gate.sh: gate_mamba2 ran 1 s (exit 0)
exact gain: y differing values per token [0,0,0,0], state differing 0, ring exact true, window exact true PASS
exact no gain: y differing values per token [0,0,0,0], state differing 0, ring exact true, window exact true PASS
exact sequence start: y differing values per token [0,0,0,0], state differing 0, ring exact true, window exact true PASS
band: referee is step_token true; y outside the band 0 (largest |Δ|/band 0.022); state outside the band 0 (largest |Δ|/band 0.114); ring exact true PASS
refuse: state 96=PASS state 256=PASS conv 3=PASS groups 7=PASS short state=PASS; nothing launched (output keeps its poison) true PASS
fault base: the clean launch raised nothing PASS
fault NaN in x: raised layer 7 mamba2_scan (want layer 7 mamba2_scan), group 3 non-finite true, other groups the clean bits true PASS
fault NaN in B: raised layer 7 mamba2_scan (want layer 7 mamba2_scan), group 3 non-finite true, other groups the clean bits true PASS
fault inf in z: raised layer 7 mamba2_scan (want layer 7 mamba2_scan), group 5 non-finite true, other groups the clean bits true PASS
replay: nodes=1 y bit-identical to eager 3/3 ring true state true PASS
shape kernel=mamba2_step local_depot=false ld_local=0 st_local=0 PASS
PASSED: gate_mamba2 the fused Mamba-2 decode step equals the host twin bit for bit where the device library is not asked for a value libm gives differently (four tokens, with and without the gain, and from the sequence start; the ring exact) and within the derived band where it is; state 96 and 256, a conv of 3 taps, a group count that does not divide and a short buffer refused by name; a NaN in x or B and an infinity in z raise mamba2_scan and leave their norm group non-finite and the other groups the clean bits; a captured graph replays three tokens bit for bit as eager; no local depot

just gate-ptx-spill

Daemon rc 0, same head, GeForce RTX 3090. tools/ref/ptx-shapes.tsv pins mamba2_step at spill 0, jit_local 0 under both generate_ds41 and gate_e2e. The scan pinned every entry it saw:

ptx-scan bin=target/release/generate_ds41 section=.oxart bytes=10635664 ptxas=/usr/local/cuda-13.3/bin/ptxas ptxas-version=13.3.73 arch=sm_86 modules=2 jit-card=NVIDIA_GeForce_RTX_3090 jit-cc=8.6 jit-cuda=13.4
ptx-spill bin=generate_ds41 table=tools/ref/ptx-shapes.tsv arch=sm_86 jit-cc=8.6
ptx-spill bin=generate_ds41 entries=302 pinned=302 nonzero=ds41_attn_seg_stage(spill=8,jit_local=8) violations=0 PASS
ptx-scan bin=target/release/gate_e2e section=.oxart bytes=8579520 ptxas=/usr/local/cuda-13.3/bin/ptxas ptxas-version=13.3.73 arch=sm_86 modules=1 jit-card=NVIDIA_GeForce_RTX_3090 jit-cc=8.6 jit-cuda=13.4
ptx-spill bin=gate_e2e table=tools/ref/ptx-shapes.tsv arch=sm_86 jit-cc=8.6
ptx-spill bin=gate_e2e entries=235 pinned=235 nonzero=none violations=0 PASS
ptx-scan bin=target/release/gate_qwen3vl_tower section=.oxart bytes=9150160 ptxas=/usr/local/cuda-13.3/bin/ptxas ptxas-version=13.3.73 arch=sm_86 modules=2 filter=vis_ jit-card=NVIDIA_GeForce_RTX_3090 jit-cc=8.6 jit-cuda=13.4
ptx-spill bin=gate_qwen3vl_tower table=tools/ref/ptx-shapes.tsv arch=sm_86 jit-cc=8.6
ptx-spill bin=gate_qwen3vl_tower entries=16 pinned=16 nonzero=none violations=0 PASS

Host static on this head

tools/mac-remote.sh against base 89d5ce011b11322fe01823ade1b796e85d64bb4d, remote rc 0, wall 150 s. Not a card gate.

mac-static: fmt-check rc 0 in 25 s — rustfmt diff blocks: 0
mac-static: lint rc 0 in 61 s — mac-check: lint ^warning: 41 = the ratchet 41 in tools/lint-ratchet.txt
mac-static: combos rc 0 in 56 s — mac-check: combos rc 0; 18 shapes run, 0 red, 31 skipped (scoped), in 56 s
mac-static: check-arch rc 0 in 40 s
mac-static: check-comments rc 0 in 40 s
mac-static: check-defaults rc 0 in 4 s
mac-static: check-levers rc 0 in 30 s
mac-static: check-loads rc 0 in 6 s
mac-static: check-ptx-names rc 0 in 0 s
mac-static: check-records rc 0 in 21 s
mac-static: check-recipes rc 0 in 78 s
mac-static: check-rustflags rc 0 in 0 s
mac-static: check-unsafe rc 0 in 9 s
mac-static: check-waits rc 0 in 0 s
mac-static: total 117 s, base 89d5ce011b11322fe01823ade1b796e85d64bb4d
mac-static: ok
mac-remote: wall 150 s (setup 25 s, run 122 s), remote rc 0

FAIL-first

Each mutant was run on its own, not on this head. F2–F6 went through tools/mutant-run.sh. F1 went through an equivalent loop before those files were tracked.

  • F1, decay 1: exact red in all three cases, and band red.
  • F2, a sequential lane sum: exact red. Band stays green (0.027), so the exact clause is the bit-equal claim's test.
  • F3, conv taps reversed: exact and band red.
  • F4, state 96 accepted: refuse: state 96=FAIL.
  • F5, no fault raise: the three fault lines raised none … FAIL.
  • F6, the position as a launch argument: replay … 0/3 … FAIL.

The 23a9fd3 head adds three rows. Each is red when its guard is removed (the review's static mutants; not re-run on this fold):

  • Scalar guard: quad_finite on dt, dt_bias, A and D, so a non-finite parameter becomes a non-finite sigma. The old sigma (σ of −∞ is 0, finite y) leaves fault -inf dt and fault -inf A without a fault and with a finite group (FAIL).
  • Epsilon refusal: enqueue_step returns norm eps must be finite and launches nothing. Removing that guard makes refuse: … eps inf=FAIL.
  • Node count: replay passes only when graph.node_count() == 1. An extra captured node makes replay: nodes=… … FAIL.

@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 14, 2026
@midagedev midagedev added the model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja label Oct 14, 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: non-finite parameters evade the fault contract, and the replay gate accepts extra nodes.

Must fix

1. Reject non-finite parameters before they become finite outputs

crates/gpu/src/mamba2.rs:277: kind A. Enqueue checks buffer lengths but accepts dt = -∞, which becomes σ=0, and A = -∞ with positive σ, which becomes decay=0. Finite remaining inputs and state then yield finite y, so the output-only fault checks stay clear. At line 418, norm with eps = +∞ similarly yields zero output without a fault. The fault/refusal clauses omit these inputs.
Close this before engine integration. Replace the sigma assignment:

let fin = crate::fault::quad_finite([dt_h, bias_h, a_h, d_h])
    & dtv.is_finite();
let sigma = if !fin {
    f32::NAN
} else if dtv <= 20.0 {
    dtv.exp().ln_1p()
} else {
    dtv
};

After shape.check(what)?, insert:

if norm.is_some() && !eps.is_finite() {
    return Err(GpuError::shape(what, "norm eps must be finite"));
}

Add fault/refusal plants that turn red without these checks.

2. Assert the one-node replay contract

crates/gpu-gates/src/bin/gate_mamba2.rs:932: kind B. The pass predicate ignores graph.node_count(). A captured no-op node leaves y, ring and state equal, so the gate can print nodes=2 and PASS despite the one-node contract.
Pin launch count now. Replace the pass assignment:

let pass = graph.node_count() == 1
    && same_y == toks.len() && same_ring && same_state && clean(cx, "replay")?;

3. Reuse the host state and division checks

crates/gpu/src/mamba2.rs:491 repeats crates/model/src/mamba2.rs:122's state and head/group division rules (kind B, R14). The host check also rejects overflow.
Prevent rule drift. Replace Mamba2Shape::check:

fn check(&self, what: &'static str) -> Result<(), GpuError> {
    model::mamba2::check(model::mamba2::Geom {
        d_inner: self.d_inner,
        n_heads: self.n_head,
        n_groups: self.n_group,
        d_state: self.d_state,
        d_conv: self.d_conv,
    }).map_err(|e| GpuError::shape(
        what, format!("d_state {}: {e}", self.d_state)
    ))?;
    if self.d_conv != CONV_TAPS {
        return Err(GpuError::shape(
            what, format!("d_conv {} is refused: need {CONV_TAPS}", self.d_conv)
        ));
    }
    Ok(())
}

Replace the repeated STATE declaration with:

pub use model::mamba2::STATE;

4. Share the repeated seeded generator

crates/gpu-gates/src/bin/gate_mamba2.rs:131 copies crates/gpu-gates/src/bin/gate_cand.rs:90's xorshift update and uniform mapping. gate_hc_gated:87 and gate_minicpmv_tower:93 also hold that update (kind B, R14).
In gpu-gates lib.rs, add this owner; replace all four local Rng definitions/impls with imports of bloomery_gpu_gates::Rng. This removes three types and repeated methods:

/// A fixed xorshift64 stream initialized with its seed.
pub struct Rng(pub u64);
impl Rng {
    /// Return the next word.
    pub fn next(&mut self) -> u64 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        self.0
    }
    /// Return an index below n.
    pub fn below(&mut self, n: usize) -> usize {
        (self.next() % n as u64) as usize
    }
    /// Return a value in [0, 1).
    pub fn unit(&mut self) -> f32 {
        (self.next() >> 40) as f32 / (1u64 << 24) as f32
    }
    /// Return a value in [lo, hi).
    pub fn uni(&mut self, lo: f32, hi: f32) -> f32 {
        lo + (hi - lo) * self.unit()
    }
}

5. Remove unused no-norm band paths

crates/gpu-gates/src/bin/gate_mamba2.rs:615 and trace_run at line 552 take norm, but both have one caller and it always passes true (lines 717 and 724). Their false branches have no user (kind B).
Delete both unused norm: bool parameters, unwrap their true branches, and delete bands' false branch. This removes unused cases now. Replace the calls:

let trace = trace_run(&w, &st, &toks)?;
let (y_bands, s_band) = bands(&w, &trace);

Optimization headroom

  • E, Less work: crates/gpu/src/mamba2.rs:407, compute total/scale once in thread 0 and broadcast through the existing LAST storage. Removes 60,960 lane f64 loads per layer/token [derived @ 96 heads, head_dim 80, 8 groups].

Checked

Duplicates: confirmed both owners; both fixes reduce elements.
Complexity: checked the cited kernel paths for correctness.
Silent failure: followed scalars through state, output and fault checks.
Tests: fault plants cover x, B and z; replay only prints node count. PR reports six FAIL-first mutants.
Gates: unsafe ratchet has a dated PIN/reason; no band relaxed.
Escape catalog: C1–C4 do not match these findings; no ledger lessons.

Notes

GPU runs reported in the PR were not rerun. They lack the required nvidia-smi output line.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_mamba2.rs, crates/gpu/src/fault.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 thread crates/gpu-gates/src/bin/gate_mamba2.rs Outdated
.count();
let same_ring = bits_equal(&ring, &eager.ring);
let same_state = bits_equal(&scan, &eager.scan);
let pass = same_y == toks.len() && same_ring && same_state && clean(cx, "replay")?;

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.

Assert the one-node contract; buffer equality alone accepts an extra no-op node.

Suggested change
let pass = same_y == toks.len() && same_ring && same_state && clean(cx, "replay")?;
let pass = graph.node_count() == 1
&& same_y == toks.len() && same_ring && same_state && clean(cx, "replay")?;

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

  • Fixed: non-finite scalars poison the scan; non-finite norm epsilon is refused.
  • Fixed: replay requires exactly one node.

Verdict: MUST_FIX: the new fault plant duplicates the existing checks and report.

Must fix

1. Check every fault plant with one owner

crates/gpu-gates/src/bin/gate_mamba2.rs:940 repeats crates/gpu-gates/src/bin/gate_mamba2.rs:912's fault, non-finite-group and unchanged-other-groups checks and report (kind B, R14).
Sharing these checks now prevents later plants from drifting. The replacement removes more code and bindings than it adds.

Insert before the plant loop:

let check = |label: &str, y: &[f32], g: usize| -> Result<bool, GateError> {
    let f = cx.gpu.take_fault()?;
    let all_bad = group(y, g).iter().all(|v| !v.is_finite());
    let others = (0..GROUPS).filter(|&o| o != g)
        .all(|o| bits_equal(group(y, o), group(&base.y[0], o)));
    let pass = f == want && all_bad && others;
    let shown = f.map_or("none".to_owned(), |f| f.to_string());
    println!(
        "fault {label}: raised {shown}, group {g} non-finite {all_bad}, other groups unchanged {others} {}",
        verdict(pass)
    );
    Ok(pass)
};

Replace the check/report block inside the plant loop (lines 912–932) with:

ok &= check(label, &got.y[0], g)?;

Replace the check/report block after restoring A (lines 940–960) with:

ok &= check("-inf A", &got.y[0], 0)?;

Non-blocking

⚠ Gate the revised head: crates/gpu/src/mamba2.rs:281, published card evidence names an earlier commit and omits the new dt/A and epsilon cases. Publish head gate/spill output and FAIL-first for the scalar guard, epsilon refusal and node-count assertion.

Checked

Duplicates: the new A plant repeats the existing fault checks and report.
Complexity: a scalar guard, fault plants and a node-count assertion were added; the kernel remains fused.
Silent failure: the new error-message default is test-only; a missing error makes the refusal check fail.
Tests (static mutants): old sigma defeats dt/A fault assertions; removing the epsilon guard defeats refusal; an extra captured node defeats replay.
Gates: no threshold/PIN changes.
Escape catalog: no matching pattern in these Rust changes.

Card check: gpu-evidence. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_mamba2.rs, crates/gpu/src/fault.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)

@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 14, 2026
github-actions[bot]
github-actions Bot previously approved these changes Oct 14, 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.

Since the last review:

Verdict: CLEAN: the duplication is removed, and the incremental refactor preserves the gate's failure checks.

Non-blocking

⚠ Gate the revised head: crates/gpu-gates/src/bin/gate_mamba2.rs:935, the published run names 3a8d67f4 and omits the later dt/A and epsilon cases.
Publish revised-head just gate-gpu-mamba2 and just gate-ptx-spill output, plus FAIL-first for the scalar guard, epsilon refusal and node-count assertion. This verifies the clauses added after that run.

Checked

Duplicates: 1 new local checker checked; no duplicate remains. Both dryer pairs are module-specific loaders using the existing shared-module owner; unchanged this increment.
Complexity: crapper's mamba2_step (32, kernel), check_replay (16), and FaultSite name/cause are unchanged this increment.
Silent failure: 1 display default followed; missing faults still fail equality. Driver errors propagate through ?, and false checks reach the gate's error exit.
Tests (static mutation): bypassing the scalar guard at mamba2.rs:281 makes the dt/A assertions fail; changing another group's output fails the retained bit comparison. Each plant reads and clears its fault.
Gates: no bands, thresholds, pins or assertions relaxed.
Escape catalog: no C1–C4 patterns match these Rust changes.

Notes

Static review only; CUDA gates were not rerun.

Card check: gpu-evidence. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_mamba2.rs, crates/gpu/src/fault.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 and others added 6 commits October 15, 2026 06:52
… per layer, gated against the host twin

bloomery_gpu::mamba2 runs one token of a Mamba-2 layer in one launch: the
conv over GDN's position-keyed ring (linear::ring_input, now the one ring
index both the delta conv and this step call; GDN's PTX is unchanged), the
bias, SiLU, the scan at state 128 with the state updated in place and every
product rounded before its add, y + x*D, silu(z)*y, and the grouped RMSNorm
fused through one ticket per norm group. The position is a device word, so
one captured graph serves every step. A non-finite y raises
FaultSite::Mamba2Scan; state 96 and 256 are refused by name at enqueue.

gate_mamba2 holds the card to model::mamba2::step_token at the 4B widths
with no model file: bit for bit where the device library is not asked for a
value libm gives differently, within a derived per-element band where it is;
plus the refusals, the fault, and eager = captured replay.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…and replay requires one node

A non-finite dt, bias, A or D, or a non-finite sum of dt and bias, becomes a
non-finite sigma, so the scan raises FaultSite::Mamba2Scan instead of a
finite y. A non-finite norm epsilon is refused by name at enqueue and
launches nothing. The gate plants those three and requires the captured
graph to be one node.
The -inf A plant repeated the plant loop's fault, group and other-group report.
Both plants call that closure, and the printed line is its line.
The device shape repeated the host geometry and its checks. Enqueue and
the scratch take Checked. A conv other than four taps stays a device
refusal; every other width is the host's error.
…ts NaN scale

The card's STATE was a second copy of the host's. A non-finite group
mean already makes every output NaN, which raises the scan fault; the
raise before that scale was the same signal.
The short-state and infinite-eps clauses repeated the launch's
argument list. They call the same step, with the short buffer swapped
in and with the epsilon they mean to refuse.

@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 new gate duplicates a generator and adds unused parameters and an unused export.

Must fix

1. Give the gate generator one owner (kind B, R14)

crates/gpu-gates/src/bin/gate_mamba2.rs:134 repeats crates/gpu-gates/src/bin/gate_cand.rs:90: the same xorshift transition and high-24-bit float mapping.
Sharing it removes repeated generator logic.
Add this to crates/gpu-gates/src/lib.rs; delete both local Rng types and implementations, and import use bloomery_gpu_gates::GateRng as Rng; in both gates. This removes more lines and declarations than it adds.

/// Seeded xorshift64 draws for gate inputs.
pub struct GateRng(pub u64);
impl GateRng {
    fn next(&mut self) -> u64 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        self.0
    }
    /// Draw in `[0, 1)`.
    pub fn unit(&mut self) -> f32 {
        (self.next() >> 40) as f32 / (1u64 << 24) as f32
    }
    /// Draw below positive `n`.
    pub fn below(&mut self, n: usize) -> usize {
        (self.next() % n as u64) as usize
    }
    /// Scale a unit draw with the supplied endpoints.
    pub fn uni(&mut self, lo: f32, hi: f32) -> f32 {
        lo + (hi - lo) * self.unit()
    }
}

2. Remove the unused norm switches (kind B)

crates/gpu-gates/src/bin/gate_mamba2.rs:561 and crates/gpu-gates/src/bin/gate_mamba2.rs:620 take norm, but their only calls, at lines 722 and 729, pass true. The false branch has no consumer.
Removing the switches now avoids maintaining an untested path. Apply this patch:

--- a/crates/gpu-gates/src/bin/gate_mamba2.rs
+++ b/crates/gpu-gates/src/bin/gate_mamba2.rs
@@ -560,3 +560,2 @@
         toks: &[TokenIn],
-        norm: bool,
     ) -> Result<Vec<Trace>, GateError> {
@@ -597,5 +596,3 @@
             qdot::swiglu(&t.z, &vec![1.0; INNER], &mut sz);
-            if norm {
-                mamba2::grouped_rms(&mut y, &w.norm, GROUPS, EPS)?;
-            }
+            mamba2::grouped_rms(&mut y, &w.norm, GROUPS, EPS)?;
             out.push(Trace {
@@ -619,3 +616,3 @@
     /// the bound on each final state element.
-    fn bands(w: &Weights, trace: &[Trace], norm: bool) -> (Vec<Vec<f64>>, Vec<f64>) {
+    fn bands(w: &Weights, trace: &[Trace]) -> (Vec<Vec<f64>>, Vec<f64>) {
         let mut e = vec![0.0f64; INNER * STATE];
@@ -659,3 +656,3 @@
             }
-            if norm {
+            {
                 for g in 0..GROUPS {
@@ -682,4 +679,2 @@
                 }
-            } else {
-                band.copy_from_slice(&d2);
             }
@@ -721,3 +716,3 @@
         let want = host_run(&w, &st, &toks, true)?;
-        let trace = trace_run(&w, &st, &toks, true)?;
+        let trace = trace_run(&w, &st, &toks)?;
         // The referee's composition is step_token.
@@ -728,3 +723,3 @@
         referee &= bits_equal(&trace[TOKENS - 1].s_after, &want.scan);
-        let (y_bands, s_band) = bands(&w, &trace, true);
+        let (y_bands, s_band) = bands(&w, &trace);
         let mut dev = Dev::new(cx, &w)?;

3. Keep the block-width constant private (kind B, R13)

crates/gpu/src/mamba2.rs:106 exports CH_PER_BLOCK, but every reference is inside this module.
Remove the unused API before callers acquire a dependency on kernel geometry. Replace the declaration:

const CH_PER_BLOCK: usize = WARPS * CH_PER_WARP;

Non-blocking

⚠ Refresh the card evidence: crates/gpu-gates/src/bin/gate_mamba2.rs:822, the attached run names 3a8d67f and omits the epsilon, negative-infinite dt and negative-infinite A cases now present. Run just gate-gpu-mamba2 and just gate-ptx-spill on this head and attach the output before engine integration.

Optimization headroom

  • E. Less work: crates/gpu/src/mamba2.rs:417, all 128 threads in each group's last block repeat its reduction. Compute the scale once and publish it through existing shared scratch. At the 4B widths this removes 8 × 127 × 60 = 60,960 f64 additions per layer per token [derived]; time it if profiling identifies the norm tail as a limit.

Checked

Duplicates: both generator implementations confirmed. Dryer loader pairs use distinct module bundles.
Complexity: diagnostics flags the new kernel (30), replay pipeline (17), buffer initialization (16), and added fault match arms.
Silent failure: refusal checks require named errors; non-finite scan and norm outputs raise faults.
Tests: inspected refusal, fault and replay assertions; PR evidence reports F1–F6 red.
Gates: unsafe ratchet has a dated PIN and reason; existing thresholds and cases remain.
Escape catalog: C1–C4 do not match the cited findings. No ledger lessons apply.

Notes

GPU gates were not executed during this review.

Card check: gpu-evidence. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_mamba2.rs, crates/gpu/src/fault.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)

Comment thread crates/gpu/src/mamba2.rs Outdated
/// Channels one warp walks.
const CH_PER_WARP: usize = 4;
/// Channels of one head a block takes.
pub const CH_PER_BLOCK: usize = WARPS * CH_PER_WARP;

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.

R13: Only this module uses the constant; keep its visibility private.

Suggested change
pub const CH_PER_BLOCK: usize = WARPS * CH_PER_WARP;
const CH_PER_BLOCK: usize = WARPS * CH_PER_WARP;

…ways on, the block width private

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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

Verdict: CLEAN: the earlier must-fix items are resolved, and the incremental changes preserve the active gate checks and device behavior.

Checked

Duplicates: 5 moved items checked. The two generators share one owner and retain their draw formulas. Both dryer pairs load distinct device bundles.
Complexity: the reported kernel (30), replay pipeline (17), buffer initialization (16), and fault match arms are unchanged in this increment. The oracle helpers each lose a branch.
Silent failure: 0 new fallback sites. Migrated below calls receive positive bounds, including nonempty chunk lengths.
Tests: no assertions removed. Static mutation check: changing the norm bypass at crates/gpu/src/mamba2.rs:367 to an unconditional return makes the exact-gain and band comparisons fail.
Gates: no thresholds, pins or executed cases changed. Both removed norm switches had only true callers.
Performance: kernel instructions and launch arguments are unchanged; the other edits affect gate helpers.
Escape catalog: C1–C4 do not match this increment.

Notes

GPU results are author-supplied. GPU gates were not executed during this review.

Card check: gpu-evidence. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_cand.rs, crates/gpu-gates/src/bin/gate_mamba2.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
midagedev merged commit b3153d7 into main Oct 14, 2026
7 checks passed
@midagedev
midagedev deleted the nemo5 branch October 14, 2026 23:56
@github-actions github-actions Bot mentioned this pull request Oct 18, 2026
1 task
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 model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja 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