Skip to content

model: the shared host Mamba-2 step (Nemotron 3 Nano 4B, N2) - #191

Merged
midagedev merged 6 commits into
mainfrom
nemo2
Oct 14, 2026
Merged

midagedev merged 6 commits into
mainfrom
nemo2

Conversation

@midagedev

@midagedev midagedev commented Oct 14, 2026 •

Copy link
Copy Markdown
Owner

Part of #156 (Nemotron 3 Nano 4B), step N2: the host Mamba-2 step, the twin the card's scan (N5) is gated against.

What

crates/model/src/mamba2.rs runs one Mamba-2 token on the host at state 128:

  • the causal depthwise conv (tap 0 is the oldest sample), then its bias, then SiLU;
  • the selective scan as the reference's group kernel (softplus with the dt > 20 identity arm, dA = exp(dt·A), s = s·dA + B·x·dt, y = Σ s·C, group = head / (n_head / n_group));
  • y + x·D, silu(z)·y, and the grouped RMSNorm.

The y sum follows the reference's lane order: four products per lane, then the 32-wide xor reduction of runtime::hc_gated::card::butterfly. That order is the gate the card's scan keeps. A state other than 128 is refused by name (Mamba2Error::State(n)), and nothing is written. The out projection is not this module.

공통화한 것 (Commonized)

  • Mamba-2 is a shared module beside ffn, moe and kv (crates/model/src/mamba2.rs), not a nemotron file. The next Mamba-2 model (Falcon-H1, Puzzle, a hybrid MoE) calls check, conv_tokens and step_token. It adds only its widths, or a new STATE if its state differs.
  • The 32-lane xor sum is runtime's one host owner (hc_gated::card::butterfly), not a second copy.
  • The runtime's conv-window and recurrent-state store arm is already shared with the delta rule (model, models: nemotron_h's header reader (Nemotron 3 Nano 4B, N0) #179).
  • No unsafe: the scan uses std's f32::exp and f32::ln_1p. The unsafe ratchet is unchanged.

Gates

FAIL-first (host, cargo test -p bloomery-model --lib mamba2, each mutant alone, restored by md5)

  • group = h % groups instead of h / per: group_offset_divides_heads_per_group_first red.
  • conv taps reversed (w[base + d_conv - 1 - tap]): conv_tap_0_is_the_oldest_sample and conv_slides_across_two_tokens red.
  • accept state 96: state_96_and_256_are_refused_by_name red.
  • conv bias before the dot: conv_adds_bias_after_the_dot red.
  • decay 1 instead of exp(dt·A): a_negative_a_decays_the_state red.
  • sequential lane sum instead of the butterfly: y_sums_the_lanes_in_xor_order red.
  • dt without its bias: a_composed_token_wires_every_stage red. With gate_z skipped, the same test is red.
  • softplus dt <= 20 → dt < 20: stays green. At dt = 20, log1p(exp(20)) rounds to exactly 20.0 in f32, so the two arms give the same bits and this mutant is equivalent.

🤖 Generated with Claude Code

@github-actions github-actions Bot 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: convolution adds bias in the wrong order, and the warp reduction duplicates an existing owner.

Must fix

1. Add the convolution bias after the dot product

crates/model/src/mamba2.rs:337 starts the sum with bias, although line 304 specifies convolution followed by bias. With four taps, state [16777216, -16777216, 0], input [0], weights [1; 4] and bias [1], the length guards accept the call. Binary32 rounding loses the bias and returns 0 instead of 1. In step_token, this output feeds SiLU and the scan at lines 427–433.
Fix this before the host reference becomes the oracle for the card kernel. Replace the inner channel loop with:

for channel in 0..channels {
    let mut sum = 0.0f32;
    let base = channel * d_conv;
    for tap in 0..d_conv {
        sum += conv_sample(state, x_new, channel, channels, ages, tok + tap)
            * w[base + tap];
    }
    y[channel + tok * channels] = sum + bias[channel];
}

Add this regression inside the existing test module. Both current conv tests use zero bias and pass when the bias add is removed.

#[test]
fn conv_adds_bias_after_the_dot() {
    let mut state = [16777216.0, -16777216.0, 0.0];
    let mut y = [0.0];
    conv_tokens(4, &mut state, &[0.0], &[1.0; 4], &[1.0], &mut y).unwrap();
    assert_eq!(y, [1.0]);
}

2. Reuse the existing host butterfly

crates/model/src/mamba2.rs:165 repeats crates/runtime/src/hc_gated.rs:380: the same 32 lanes, snapshot before each addition, and offsets 16, 8, 4, 2, 1. This is the same numeric contract, not just the same loop shape (R14).
The model crate already depends on runtime, and card::butterfly is public without a feature gate. Reuse that owner before the references diverge. Delete the local warp_sum and its comment; add this import and replace its production and test calls:

use runtime::hc_gated::card::butterfly;
y[h * head_dim + ch] = butterfly(&lane);
assert_eq!(y[0], butterfly(&lane));

This removes a function without adding an owner.

Non-blocking

⚠ Make the scan tests distinguish its numeric rules: crates/model/src/mamba2.rs:510. Every scan test uses A = 0; replacing decay with 1.0 passes. Sequentially summing the lane products also passes.
Use nonzero negative A and cancellation across lanes with independent expected results. Lane values [16777216, -16777216, 1, 0, …] give XOR sum 0 and sequential sum 1.

⚠ Test the composed token step: crates/model/src/mamba2.rs:387 has no test caller. The 11 tests do not exercise its dt-bias add, SiLU, z gate or norm wiring.
Add one small composed-step case with nonzero biases, a nontrivial z gate and norm gain to catch errors in how the stages connect.

Checked

Duplicates: confirmed the two butterfly implementations have the same numeric contract; the existing runtime dependency permits reuse.
Complexity: step_token delegates computation to conv, scan and mix functions; validation and optional norm account for its branches.
Silent failure: both optional-norm branches implement the documented omission; checked positive tap count makes saturating_sub(1) safe.
Tests: confirmed 11 unit tests, all scan cases use A = 0, and no test calls step_token. Binary32 arithmetic confirms both cancellation examples above.
Gates: the diff removes no existing pin, threshold or test.
Escape catalog: C1–C4 do not match. No ledger lessons are in force.

Notes

Cargo and GPU gates were not run during validation. Findings were checked against source and explicit binary32 rounding.

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

Comment thread crates/model/src/mamba2.rs Outdated
len("conv y", y.len(), n_tok * channels)?;
for tok in 0..n_tok {
for channel in 0..channels {
let mut sum = bias[channel];

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.

Accumulate the dot from zero; also apply the suggestion at line 343 to add bias after the dot.

Suggested change
let mut sum = bias[channel];
let mut sum = 0.0f32;

Comment thread crates/model/src/mamba2.rs Outdated
sum +=
conv_sample(state, x_new, channel, channels, ages, tok + tap) * w[base + tap];
}
y[channel + tok * channels] = sum;

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.

Add bias after the dot; also apply the suggestion at line 337 to avoid adding bias twice.

Suggested change
y[channel + tok * channels] = sum;
y[channel + tok * channels] = sum + bias[channel];

@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: remove a duplicate boundary test and an unused public accessor.

Must fix

1. Remove the second pin of the dt=20 boundary

crates/model/src/mamba2.rs:655 repeats the boundary asserted at crates/model/src/mamba2.rs:622. At 20, softplus and identity have identical f32 bits; this test cannot distinguish the arms. Its uniform state and sum assertions repeat uniform_row_at_the_4b_widths:635.
Removing it now keeps one test owner per contract. This is a kind B duplication finding.
Delete the complete dt_20_uses_the_log1p_arm definition, including #[test] (lines 654–690). No replacement is needed. Record the dated deletion reason: the boundary and uniform recurrence remain covered by the existing tests.

2. Remove the unused geometry accessor

crates/model/src/mamba2.rs:118 Checked::geom has no caller in the tree, including tests. It adds an unused public API (R13), a kind B unneeded element.
Removing it now avoids making later callers depend on an unnecessary method.
Replace the impl Checked block with:

impl Checked {
    /// Head width, `d_inner / n_head`.
    #[must_use]
    pub fn head_dim(self) -> usize {
        self.head_dim
    }

    /// Conv channels: `d_inner + 2 * n_group * d_state`.
    #[must_use]
    pub fn conv_dim(self) -> usize {
        self.conv_dim
    }
}

Non-blocking

⚠ Pin recurrence rounding: crates/model/src/mamba2.rs:208, the current scan tests use zero recurrence addends or exact products, so they do not distinguish the last separate product and add from mul_add.
Add a case with state=-21, A=0, dt=21, x=1-f32::EPSILON, B=1+f32::EPSILON, C=1. Assert every updated state element is zero; the fused mutant produces a nonzero value. This pins host rounding for the planned CUDA twin (R29).

Checked

  • Duplicates: the repeated boundary test and unused accessor are confirmed above. Dryer reported 0 pairs. SiLU, RMSNorm and butterfly call existing owners.
  • Complexity: crapper flagged new step_token at 20; it validates buffers and calls separate stage functions.
  • Silent failure: geometry rejects zero conv taps before saturating_sub; both optional-norm branches follow the documented absence contract.
  • Tests: 15 definitions inspected. The dt=20 threshold mutant is equivalent. Existing scan fixtures do not distinguish recurrence FMA; the proposed fixture does by f32 arithmetic.
  • Gates: no existing pin, tolerance or case moved. The PR reports FAIL-first runs for the main scan and conv clauses.
  • Escape catalog: C1–C4 do not match the Rust-only diff.
  • Runtime: this host reference has no engine caller; no existing decode cost changes.

Notes

Rust tests and gates were not rerun. No card run with the required evidence list is supplied.

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

midagedev and others added 5 commits October 15, 2026 00:32
The scan's libm calls are three new unsafe blocks, pinned 119 to 122. Divisibility uses is_multiple_of, and the lane and head loops index through iterators. The recurrence and the warp reduction are unchanged.
…te width once, and refuses any other by one variant

f32::exp and f32::ln_1p lower to the same libm expf and log1pf on
linux-gnu, so the unsafe extern block and the ratchet raise go. STATE holds
the 128 the scan runs; Mamba2Error::State(n) refuses every other length by
name (96 and 256 were two variants of the same refusal). warp_sum says its
order is the gate the card's scan keeps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n sums lanes through runtime's butterfly

The conv's bias joins after the four taps, as the reference's ssm_conv then
add; the bias-first order lost it to rounding next to a large tap. The lane
sum calls runtime::hc_gated::card::butterfly, the one host owner of the
32-lane xor order, instead of a second copy. New tests pin the bias order,
a negative A's decay, the xor lane order against a sequential sum, and one
composed token through every stage at two heads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… accessor, and the recurrence's product-then-add rounding pinned

dt_20_uses_the_log1p_arm repeated the boundary dt_21_is_identity... owns
(the two softplus arms give the same f32 bits at 20); it goes, with its dated
reason. Checked::geom had no caller. A new case (state -21, A 0, dt 21,
x = 1 - eps, B = 1 + eps) cancels the state to 0 only when B * (x * dt) is
rounded before the add, so a fused multiply-add on either side is red.

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.

Verdict: MUST_FIX: unchecked dimension products bypass buffer validation and reach an out-of-bounds read.

Must fix

1. Reject dimension overflow before accepting buffers

crates/model/src/mamba2.rs:316 With d_conv = usize::MAX / 2 + 2 and two channels, release arithmetic makes the required state length 0 and weight length 2. Empty state, two weights, two inputs, two biases and two outputs pass validation; the first convolution sample then reads state[0] and panics. Debug builds panic on multiplication instead of returning the named error.
crates/model/src/mamba2.rs:146 also wraps derived dimensions when constructing Checked.
Checking these products now closes the boundary before more callers rely on Checked.

Add this variant to Mamba2Error:

    /// A buffer size that cannot be represented.
    #[error("mamba2: {0} size overflows usize")]
    Size(&'static str),

Replace the final Ok(Checked { ... }) in check with:

    let bc_n = g.n_groups.checked_mul(STATE)
        .ok_or(Mamba2Error::Size("B/C"))?;
    let conv_dim = bc_n.checked_mul(2)
        .and_then(|n| g.d_inner.checked_add(n))
        .ok_or(Mamba2Error::Size("conv channels"))?;
    g.d_inner.checked_mul(STATE)
        .ok_or(Mamba2Error::Size("scan state"))?;
    g.d_conv.checked_mul(conv_dim)
        .ok_or(Mamba2Error::Size("conv weight"))?;
    Ok(Checked {
        geom: g,
        head_dim: g.d_inner / g.n_heads,
        conv_dim,
    })

Replace the convolution state and weight length checks with:

    let state_n = ages.checked_mul(channels)
        .ok_or(Mamba2Error::Size("conv state"))?;
    let weight_n = d_conv.checked_mul(channels)
        .ok_or(Mamba2Error::Size("conv weight"))?;
    len("conv state", state.len(), state_n)?;
    len("conv weight", w.len(), weight_n)?;

Add this regression test inside tests:

    #[test]
    fn overflowing_conv_size_is_refused() {
        assert_eq!(
            conv_tokens(usize::MAX / 2 + 2, &mut [], &[1.0; 2],
                &[1.0; 2], &[0.0; 2], &mut [0.0; 2]),
            Err(Mamba2Error::Size("conv state"))
        );
        assert_eq!(
            check(Geom {
                d_inner: usize::MAX - 255,
                n_heads: 1, n_groups: 1, d_state: STATE, d_conv: 4,
            }),
            Err(Mamba2Error::Size("conv channels"))
        );
    }

Non-blocking

⚠ Cover fusion of the decay product: crates/model/src/mamba2.rs:569. Changing line 202 to state[s_base + n].mul_add(d_a, b[b_base + n] * x_dt) passes the current scan tests: an active addition has zero initial state or unit decay. Pin both products before this oracle defines the device gate. Replace this test's body with:

        let g = one_channel();
        for (initial, a, b) in [
            (-21.0, 0.0, 1.0 + f32::EPSILON),
            (21.0, -f32::EPSILON / 21.0, -1.0),
        ] {
            let mut state = vec![initial; STATE];
            let mut y = [0.0];
            scan_token(
                &g, &mut state, &[1.0 - f32::EPSILON], &[21.0],
                &[a], &[b; STATE], &[1.0; STATE], &mut y,
            ).unwrap();
            assert!(state.iter().all(|&v| v == 0.0));
        }

Checked

Duplicates: dryer reported 0 qualifying pairs; no duplicate finding was submitted.
Complexity: crapper flagged new step_token at 20; it validates buffers and composes stages.
Silent failure: zero conv taps and invalid geometry return named errors; size products remain unchecked.
Tests: current scan inputs do not distinguish decay-product fusion. The proposed second case does; both proposed cases return zero with separate products.
Gates: no existing pin moved; the softplus test includes a dated removal reason.
Escapes: no C1–C4 pattern appears in the changed Rust code.

Notes

Rust tests were not run. Validation used source inspection and arithmetic checks. The PR reports gate-ops results for earlier commits, without command output for the current head.

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

…oducts overflow usize, by name

check and conv_tokens multiplied widths unchecked, so a huge d_conv wrapped
the required state length to 0 and let an empty buffer through to an
out-of-range read. Each product is now checked_mul/checked_add and refuses
with Mamba2Error::Size naming the buffer. The rounding pin also covers the
decay product: state * dA must round before the add.

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: both earlier items are fixed; no must-fix finding remains in the new commits.

Checked

Duplicates: 2 new items checked (the error variant and overflow test); no duplicate owner found.
Complexity: the new checks return errors before processing; step_token's buffer checks and stage composition are unchanged.
Silent failure: 6 new error-conversion sites followed; each propagates Mamba2Error::Size before state or output writes.
Tests: replacing checked sizing at lines 150 or 333 with unchecked arithmetic breaks the overflow assertions. Fusing either product at line 219 gives a nonzero residual in its matching rounding case.
Bounds: private Checked fields preserve the size proofs; the checked convolution-weight product also bounds the smaller state product. One-tap and zero-token convolutions remain defined.
Gates: no gate or tolerance relaxed in this increment; production float order is unchanged.
Escapes: no C1–C4 pattern matched.

Notes

Rust tests were not run here. Verification used source inspection and an in-memory f32 arithmetic probe.
The PR body reports gate results for earlier commits without command output for this head. It contains no complete card gate evidence record.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant