From 5374a197e75d9c1b6f517934c0c3e3f31a6c085a Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:57:39 -0800 Subject: [PATCH 1/4] refactor(model): the Inkling forward pass makes its matrix products through a Products trait, with the CPU as the default --- crates/dluth-model/src/error.rs | 3 + crates/dluth-model/src/inkling/mod.rs | 2 +- crates/dluth-model/src/inkling/model.rs | 281 +++++++++++++----- .../dluth-model/tests/tiny_inkling_golden.rs | 53 ++++ 4 files changed, 256 insertions(+), 83 deletions(-) diff --git a/crates/dluth-model/src/error.rs b/crates/dluth-model/src/error.rs index 97092a4..e3403ae 100644 --- a/crates/dluth-model/src/error.rs +++ b/crates/dluth-model/src/error.rs @@ -17,6 +17,8 @@ pub enum ModelError { Unsupported(String), /// A request does not fit the limits the model was opened with. Capacity(String), + /// The device computing part of the model failed. The text is the device's own. + Device(String), } impl ModelError { @@ -36,6 +38,7 @@ impl fmt::Display for ModelError { } ModelError::Unsupported(m) => write!(f, "unsupported: {m}"), ModelError::Capacity(m) => write!(f, "over capacity: {m}"), + ModelError::Device(m) => write!(f, "device failure: {m}"), } } } diff --git a/crates/dluth-model/src/inkling/mod.rs b/crates/dluth-model/src/inkling/mod.rs index 3a386dc..1757423 100644 --- a/crates/dluth-model/src/inkling/mod.rs +++ b/crates/dluth-model/src/inkling/mod.rs @@ -5,4 +5,4 @@ pub mod model; pub mod prompt; pub use config::{load_config, model_kind, validate_weights, Checked, ExpertFormat, InklingConfig, ModelKind}; -pub use model::InklingCpu; +pub use model::{CpuProducts, ExpertMatrices, InklingCpu, Products}; diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index deeb305..171fa1a 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs @@ -52,13 +52,15 @@ enum Stored<'w> { Mxfp8 { values: &'w [u8], scales: &'w [u8] }, } -struct Projection<'w> { +/// One of an expert layer's two projections: the same shape of matrix for every expert of +/// the layer, in the form the weight file stores them. +pub struct ExpertMatrices<'w> { rows: usize, cols: usize, stored: Stored<'w>, } -impl<'w> Projection<'w> { +impl<'w> ExpertMatrices<'w> { fn load(w: &'w Weights, name: &str, format: ExpertFormat, rows: usize, cols: usize) -> Result { let stored = match format { ExpertFormat::Nvfp4 => { @@ -72,38 +74,99 @@ impl<'w> Projection<'w> { } ExpertFormat::Mxfp8 => Stored::Mxfp8 { values: w.bytes(name)?, scales: w.bytes(&format!("{name}_scale"))? }, }; - Ok(Projection { rows, cols, stored }) + Ok(ExpertMatrices { rows, cols, stored }) } - /// Applies one expert's matrix to `x`. - fn apply(&self, expert: usize, x: &[f32], out: &mut [f32]) { - let (rows, cols) = (self.rows, self.cols); + /// Rows and columns of each expert's matrix. + pub fn shape(&self) -> (usize, usize) { + (self.rows, self.cols) + } + + pub fn format(&self) -> ExpertFormat { + match self.stored { + Stored::Nvfp4 { .. } => ExpertFormat::Nvfp4, + Stored::Mxfp8 { .. } => ExpertFormat::Mxfp8, + } + } + + /// The stored values of all experts, one expert after another: 4-bit codes or 8-bit floats. + pub fn values(&self) -> &'w [u8] { + match self.stored { + Stored::Nvfp4 { codes, .. } => codes, + Stored::Mxfp8 { values, .. } => values, + } + } + + /// The block scales of all experts, one expert after another. + pub fn scales(&self) -> &'w [u8] { + match self.stored { + Stored::Nvfp4 { scales, .. } | Stored::Mxfp8 { scales, .. } => scales, + } + } + + /// Bytes of values and bytes of scales that one expert takes. + pub fn bytes_per_expert(&self) -> (usize, usize) { + let weights = self.rows * self.cols; + match self.stored { + Stored::Nvfp4 { .. } => (weights / 2, weights / blockfloat::NVFP4_BLOCK), + Stored::Mxfp8 { .. } => (weights, weights / blockfloat::MXFP8_BLOCK), + } + } + + /// What an expert's products are multiplied by: stored per expert for 4-bit weights, 1 otherwise. + pub fn factor(&self, expert: usize) -> f32 { match &self.stored { - Stored::Nvfp4 { codes, scales, factors } => { - let (per_codes, per_scales) = (rows * cols / 2, rows * cols / blockfloat::NVFP4_BLOCK); - blockfloat::matvec_nvfp4( - &codes[expert * per_codes..(expert + 1) * per_codes], - &scales[expert * per_scales..(expert + 1) * per_scales], - factors[expert], - rows, - cols, - x, - out, - ); - } - Stored::Mxfp8 { values, scales } => { - let (per_values, per_scales) = (rows * cols, rows * cols / blockfloat::MXFP8_BLOCK); - blockfloat::matvec_mxfp8( - &values[expert * per_values..(expert + 1) * per_values], - &scales[expert * per_scales..(expert + 1) * per_scales], - rows, - cols, - x, - out, - ); - } + Stored::Nvfp4 { factors, .. } => factors[expert], + Stored::Mxfp8 { .. } => 1.0, } } + + /// Applies one expert's matrix to `x` on the CPU. + pub fn apply(&self, expert: usize, x: &[f32], out: &mut [f32]) { + let (rows, cols) = (self.rows, self.cols); + let (per_values, per_scales) = self.bytes_per_expert(); + let values = &self.values()[expert * per_values..(expert + 1) * per_values]; + let scales = &self.scales()[expert * per_scales..(expert + 1) * per_scales]; + match self.stored { + Stored::Nvfp4 { .. } => blockfloat::matvec_nvfp4(values, scales, self.factor(expert), rows, cols, x, out), + Stored::Mxfp8 { .. } => blockfloat::matvec_mxfp8(values, scales, rows, cols, x, out), + } + } +} + +/// Where a forward pass's matrix products are computed. +/// +/// Almost every byte a token reads is a weight matrix being multiplied by a vector, so +/// these products are what a faster device takes over first. Everything else in the model +/// is written once, here, and calls through this trait. The matrices are handed over as +/// the slices of the weight file they are stored in; an implementation that keeps its own +/// copy of the weights recognises a matrix by where its slice starts. +pub trait Products { + /// `out[r] = sum_c w[r][c] * x[c]` for a BF16 matrix of `rows` by `cols`. + fn bf16(&mut self, w: &[u8], rows: usize, cols: usize, x: &[f32], out: &mut [f32]) -> Result<(), ModelError>; + + /// One product per job: job `j` is (which expert, its input vector), and its result, + /// the expert's matrix times the vector times the expert's factor, goes to the `rows` + /// floats of `out` starting at `j * rows`. + fn experts(&mut self, m: &ExpertMatrices, jobs: &[(usize, &[f32])], out: &mut [f32]) -> Result<(), ModelError>; +} + +/// The products on the CPU: the reference every other implementation is compared with. +pub struct CpuProducts; + +impl Products for CpuProducts { + fn bf16(&mut self, w: &[u8], rows: usize, cols: usize, x: &[f32], out: &mut [f32]) -> Result<(), ModelError> { + cpu::matvec_bf16(w, rows, cols, x, out); + Ok(()) + } + + fn experts(&mut self, m: &ExpertMatrices, jobs: &[(usize, &[f32])], out: &mut [f32]) -> Result<(), ModelError> { + let rows = m.shape().0; + for (&(expert, x), out) in jobs.iter().zip(out.chunks_exact_mut(rows)) { + m.apply(expert, x, out); + } + Ok(()) + } } /// The convolution on a layer's keys or values. @@ -162,9 +225,9 @@ struct Layer<'w> { router: &'w [u8], router_bias: Vec, /// Hidden state to alternating gate and up rows. - first: Projection<'w>, + first: ExpertMatrices<'w>, /// Inner width back to the hidden state. - second: Projection<'w>, + second: ExpertMatrices<'w>, /// Query, key, value and expert gates; only looped layers have them. gates: Option<[Gate<'w>; 4]>, } @@ -272,12 +335,23 @@ pub struct InklingCpu<'w> { /// The hidden state after the last layer, before the final blend. last: Vec, last_blocks: Vec>, + products: Box, } impl<'w> InklingCpu<'w> { /// Checks the weights against the configuration and reserves attention history for /// `max_seq` positions. pub fn new(cfg: InklingConfig, w: &'w Weights, max_seq: usize) -> Result { + Self::with_products(cfg, w, max_seq, Box::new(CpuProducts)) + } + + /// As `new`, with the matrix products computed by `products` and everything else here. + pub fn with_products( + cfg: InklingConfig, + w: &'w Weights, + max_seq: usize, + products: Box, + ) -> Result { if max_seq == 0 || max_seq > cfg.max_positions { return Err(ModelError::Capacity(format!( "max_seq {max_seq} must be between 1 and the model's limit of {}", @@ -354,8 +428,8 @@ impl<'w> InklingCpu<'w> { expert_norm: bf16_values(w, &format!("{p}.mlp_norm.weight"))?, router: w.bytes(&format!("{p}.mlp.gate.weight"))?, router_bias: f32_values(w, &format!("{p}.mlp.gate.bias"))?, - first: Projection::load(w, &format!("{experts}.w13_weight"), checked.formats[i], 2 * inner, h)?, - second: Projection::load(w, &format!("{experts}.w2_weight"), checked.formats[i], h, inner)?, + first: ExpertMatrices::load(w, &format!("{experts}.w13_weight"), checked.formats[i], 2 * inner, h)?, + second: ExpertMatrices::load(w, &format!("{experts}.w2_weight"), checked.formats[i], h, inner)?, gates, }); } @@ -398,6 +472,7 @@ impl<'w> InklingCpu<'w> { states, max_seq, cached: 0, + products, last: vec![0.0; h], last_blocks: Vec::new(), cfg, @@ -485,7 +560,9 @@ impl<'w> InklingCpu<'w> { } _ => None, }; - x = apply_layer(cfg, layer, &mut self.states[index], &x, &mut blocks, messages.as_deref(), pos); + let p = self.products.as_mut(); + let at = Arrival { pos, messages: messages.as_deref() }; + x = apply_layer(cfg, p, layer, &mut self.states[index], &x, &mut blocks, at)?; } self.last = x; @@ -495,7 +572,7 @@ impl<'w> InklingCpu<'w> { } /// Scores every real token of the vocabulary from the state `advance` left. - fn logits(&self) -> Vec { + fn logits(&mut self) -> Result, ModelError> { let cfg = &self.cfg; let h = cfg.hidden; let mut candidates: Vec<&[f32]> = self.last_blocks.iter().map(Vec::as_slice).collect(); @@ -506,18 +583,18 @@ impl<'w> InklingCpu<'w> { cpu::rmsnorm(&blended, &self.final_norm, cfg.eps, &mut normed); // The output table is padded; only its first rows are tokens. let mut logits = vec![0.0f32; cfg.vocab_out]; - cpu::matvec_bf16(&self.unembed[..cfg.vocab_out * h * 2], cfg.vocab_out, h, &normed, &mut logits); + self.products.bf16(&self.unembed[..cfg.vocab_out * h * 2], cfg.vocab_out, h, &normed, &mut logits)?; for l in logits.iter_mut() { *l = cpu::softcap(*l, cfg.logit_cap); } - logits + Ok(logits) } /// Feeds one token at position `pos` and returns the scores for the token after it. /// Positions must be fed in order. Position 0 starts a new sequence. pub fn forward_token(&mut self, token: u32, pos: usize) -> Result, ModelError> { self.advance(token, pos)?; - Ok(self.logits()) + self.logits() } /// Greedy generation: feed the prompt, then repeatedly take the highest-scoring token. @@ -552,7 +629,7 @@ impl<'w> InklingCpu<'w> { } let mut generated = Vec::with_capacity(max_new); while generated.len() < max_new { - let next = argmax(&self.logits()); + let next = argmax(&self.logits()?); generated.push(next); on_token(next); if next == eos || generated.len() == max_new { @@ -567,44 +644,65 @@ impl<'w> InklingCpu<'w> { /// Merges a message into a sublayer input: `(1 - forget) * x + gain * message`, where /// forget and gain come from a small network that looks at both. -fn merge(cfg: &InklingConfig, gate: &Gate, x: &[f32], message: &[f32]) -> Vec { +fn merge( + cfg: &InklingConfig, + p: &mut dyn Products, + gate: &Gate, + x: &[f32], + message: &[f32], +) -> Result, ModelError> { let h = cfg.hidden; let mut both = vec![0.0f32; 2 * h]; cpu::rmsnorm_plain(x, cfg.eps, &mut both[..h]); cpu::rmsnorm_plain(message, cfg.eps, &mut both[h..]); let mut inner = vec![0.0f32; cfg.gate_rank]; - cpu::matvec_bf16(gate.down, cfg.gate_rank, 2 * h, &both, &mut inner); + p.bf16(gate.down, cfg.gate_rank, 2 * h, &both, &mut inner)?; let (mut forget, mut gain) = (vec![0.0f32; h], vec![0.0f32; h]); - cpu::matvec_bf16(gate.forget, h, cfg.gate_rank, &inner, &mut forget); - cpu::matvec_bf16(gate.gain, h, cfg.gate_rank, &inner, &mut gain); - x.iter() + p.bf16(gate.forget, h, cfg.gate_rank, &inner, &mut forget)?; + p.bf16(gate.gain, h, cfg.gate_rank, &inner, &mut gain)?; + Ok(x.iter() .zip(message) .zip(forget.iter().zip(&gain)) .map(|((&x, &m), (&f, &g))| (1.0 - f.tanh()) * x + g.tanh() * m) - .collect() + .collect()) } /// The keys or values of one token: project, convolve over the last few tokens, and /// remember the projection for the next tokens' convolutions. -fn project_kv(cfg: &InklingConfig, matrix: &[u8], conv: &KvConv, recent: &mut [f32], input: &[f32]) -> Vec { +fn project_kv( + cfg: &InklingConfig, + p: &mut dyn Products, + matrix: &[u8], + conv: &KvConv, + recent: &mut [f32], + input: &[f32], +) -> Result, ModelError> { let width = cfg.kv_heads * cfg.head_dim; let mut projected = vec![0.0f32; width]; - cpu::matvec_bf16(matrix, width, cfg.hidden, input, &mut projected); + p.bf16(matrix, width, cfg.hidden, input, &mut projected)?; let mut out = vec![0.0f32; width]; match conv { KvConv::Fixed { taps } => sconv::fixed(recent, &projected, taps, &mut out), KvConv::Dynamic { fixed_taps, token_proj } => { let mut token_taps = vec![0.0f32; cfg.kv_heads * cfg.conv_taps]; - cpu::matvec_bf16(token_proj, token_taps.len(), cfg.hidden, input, &mut token_taps); + let taps = token_taps.len(); + p.bf16(token_proj, taps, cfg.hidden, input, &mut token_taps)?; sconv::dynamic(recent, &projected, fixed_taps, &token_taps, cfg.kv_heads, &mut out); } } remember(recent, &projected); - out + Ok(out) } /// Attention for one token. `inputs` are the normalized query, key and value inputs. -fn attention(cfg: &InklingConfig, layer: &Layer, state: &mut PassState, inputs: [&[f32]; 3], pos: usize) -> Vec { +fn attention( + cfg: &InklingConfig, + p: &mut dyn Products, + layer: &Layer, + state: &mut PassState, + inputs: [&[f32]; 3], + pos: usize, +) -> Result, ModelError> { let (h, d) = (cfg.hidden, cfg.head_dim); let q_width = cfg.heads * d; let [q_in, k_in, v_in] = inputs; @@ -613,7 +711,7 @@ fn attention(cfg: &InklingConfig, layer: &Layer, state: &mut PassState, inputs: // Queries: learned scale per element, length limit per head. let mut q = vec![0.0f32; q_width]; - cpu::matvec_bf16(layer.wq, q_width, h, q_in, &mut q); + p.bf16(layer.wq, q_width, h, q_in, &mut q)?; for (v, s) in q.iter_mut().zip(&layer.q_scale) { *v *= s; } @@ -623,11 +721,11 @@ fn attention(cfg: &InklingConfig, layer: &Layer, state: &mut PassState, inputs: } // Keys: length limit per head. Values: normalized per head. - let mut keys = project_kv(cfg, layer.wk, &layer.k_conv, &mut state.k_recent, k_in); + let mut keys = project_kv(cfg, p, layer.wk, &layer.k_conv, &mut state.k_recent, k_in)?; for head in keys.chunks_exact_mut(d) { cpu::l2_clip_inplace(head, cfg.qk_clip); } - let unnormed = project_kv(cfg, layer.wv, &layer.v_conv, &mut state.v_recent, v_in); + let unnormed = project_kv(cfg, p, layer.wv, &layer.v_conv, &mut state.v_recent, v_in)?; let mut values = vec![0.0f32; unnormed.len()]; for (out, head) in values.chunks_exact_mut(d).zip(unnormed.chunks_exact(d)) { cpu::rmsnorm_plain(head, cfg.eps, out); @@ -639,7 +737,8 @@ fn attention(cfg: &InklingConfig, layer: &Layer, state: &mut PassState, inputs: // Relative position: each head turns a small vector into a preference per distance. let mut rel = vec![0.0f32; cfg.heads * cfg.rel_dim]; - cpu::matvec_bf16(layer.wr, rel.len(), h, q_in, &mut rel); + let rel_width = rel.len(); + p.bf16(layer.wr, rel_width, h, q_in, &mut rel)?; for (v, s) in rel.iter_mut().zip(&layer.rel_scale) { *v *= s; } @@ -657,7 +756,7 @@ fn attention(cfg: &InklingConfig, layer: &Layer, state: &mut PassState, inputs: } let mut sinks = vec![0.0f32; cfg.heads]; - cpu::matvec_bf16(layer.sink, cfg.heads, h, q_in, &mut sinks); + p.bf16(layer.sink, cfg.heads, h, q_in, &mut sinks)?; let mut attended = vec![0.0f32; q_width]; sinkattn::attend( @@ -677,59 +776,77 @@ fn attention(cfg: &InklingConfig, layer: &Layer, state: &mut PassState, inputs: // The output is gated element by element, by a function of the query input. let mut gate = vec![0.0f32; q_width]; - cpu::matvec_bf16(layer.out_gate, q_width, h, q_in, &mut gate); + p.bf16(layer.out_gate, q_width, h, q_in, &mut gate)?; for (a, g) in attended.iter_mut().zip(&gate) { *a *= cpu::sigmoid(*g); } let mut out = vec![0.0f32; h]; - cpu::matvec_bf16(layer.wo, h, q_width, &attended, &mut out); - out + p.bf16(layer.wo, h, q_width, &attended, &mut out)?; + Ok(out) } /// The experts for one token: choose a few, run each, add up their weighted outputs. -fn experts(cfg: &InklingConfig, layer: &Layer, input: &[f32]) -> Vec { +fn experts(cfg: &InklingConfig, p: &mut dyn Products, layer: &Layer, input: &[f32]) -> Result, ModelError> { let (h, inner) = (cfg.hidden, cfg.expert_width); let mut scores = vec![0.0f32; cfg.experts]; - cpu::matvec_bf16(layer.router, cfg.experts, h, input, &mut scores); + p.bf16(layer.router, cfg.experts, h, input, &mut scores)?; let chosen = router::choose(&scores, &layer.router_bias, cfg.experts_per_token, cfg.route_scale); - let mut total = vec![0.0f32; h]; - let mut both = vec![0.0f32; 2 * inner]; - let (mut gate, mut up, mut act) = (vec![0.0f32; inner], vec![0.0f32; inner], vec![0.0f32; inner]); - let mut out = vec![0.0f32; h]; - for (expert, weight) in chosen { - layer.first.apply(expert, input, &mut both); - // Gate and up values alternate. + // Every chosen expert's first matrix reads the same input. + let jobs: Vec<(usize, &[f32])> = chosen.iter().map(|&(expert, _)| (expert, input)).collect(); + let mut both = vec![0.0f32; chosen.len() * 2 * inner]; + p.experts(&layer.first, &jobs, &mut both)?; + + // Gate and up values alternate. Each expert's second matrix reads its own result. + let mut acts = vec![0.0f32; chosen.len() * inner]; + let (mut gate, mut up) = (vec![0.0f32; inner], vec![0.0f32; inner]); + for (both, act) in both.chunks_exact(2 * inner).zip(acts.chunks_exact_mut(inner)) { for (i, pair) in both.as_chunks::<2>().0.iter().enumerate() { gate[i] = pair[0]; up[i] = pair[1]; } - cpu::capped_gate_mul(&gate, &up, cfg.gate_cap, cfg.up_cap, &mut act); - layer.second.apply(expert, &act, &mut out); - for (t, o) in total.iter_mut().zip(&out) { + cpu::capped_gate_mul(&gate, &up, cfg.gate_cap, cfg.up_cap, act); + } + let jobs: Vec<(usize, &[f32])> = + chosen.iter().zip(acts.chunks_exact(inner)).map(|(&(e, _), act)| (e, act)).collect(); + let mut outs = vec![0.0f32; chosen.len() * h]; + p.experts(&layer.second, &jobs, &mut outs)?; + + let mut total = vec![0.0f32; h]; + for (&(_, weight), out) in chosen.iter().zip(outs.chunks_exact(h)) { + for (t, o) in total.iter_mut().zip(out) { *t += weight * o; } } - total + Ok(total) +} + +/// What a layer application is given besides the layer itself. +struct Arrival<'a> { + /// The token's position in the sequence. + pos: usize, + /// The four messages from the previous pass, for a looped layer from its second pass on. + messages: Option<&'a [f32]>, } /// One application of a layer. `x` is the running sum of the current block; `blocks` holds /// the embedding and the finished blocks. Returns the new running sum. fn apply_layer( cfg: &InklingConfig, + p: &mut dyn Products, layer: &Layer, state: &mut PassState, x: &[f32], blocks: &mut Vec>, - messages: Option<&[f32]>, - pos: usize, -) -> Vec { + at: Arrival, +) -> Result, ModelError> { + let Arrival { pos, messages } = at; let h = cfg.hidden; let message = |port: Port| messages.map(|m| &m[port as usize * h..(port as usize + 1) * h]); let gate = |port: Port| layer.gates.as_ref().map(|g| &g[port as usize]); - let merged = |port: Port, input: Vec| match (gate(port), message(port)) { - (Some(g), Some(m)) => merge(cfg, g, &input, m), - _ => input, + let merged = |p: &mut dyn Products, port: Port, input: Vec| match (gate(port), message(port)) { + (Some(g), Some(m)) => merge(cfg, p, g, &input, m), + _ => Ok(input), }; // 1. The attention inputs: the first layer reads the running sum; every other layer @@ -755,7 +872,7 @@ fn apply_layer( }; // 2. From the second pass on, merge in the previous pass's messages, then normalize. for (input, port) in inputs.iter_mut().zip([Port::Query, Port::Key, Port::Value]) { - *input = merged(port, std::mem::take(input)); + *input = merged(p, port, std::mem::take(input))?; } let mut normed = [vec![0.0f32; h], vec![0.0f32; h], vec![0.0f32; h]]; for ((input, weights), out) in inputs.iter().zip(&layer.input_norms).zip(normed.iter_mut()) { @@ -763,7 +880,7 @@ fn apply_layer( } // 3. Attention, then a short convolution over its recent outputs. - let attended = attention(cfg, layer, state, [&normed[0], &normed[1], &normed[2]], pos); + let attended = attention(cfg, p, layer, state, [&normed[0], &normed[1], &normed[2]], pos)?; let mut a = vec![0.0f32; h]; sconv::fixed(&state.attn_recent, &attended, &layer.attn_taps, &mut a); remember(&mut state.attn_recent, &attended); @@ -782,16 +899,16 @@ fn apply_layer( candidates.push(&sum); let mut blended = vec![0.0f32; h]; depthmix::mix(&layer.expert_query, &candidates, BLEND_EPS, &mut blended); - let blended = merged(Port::Expert, blended); + let blended = merged(p, Port::Expert, blended)?; let mut expert_in = vec![0.0f32; h]; cpu::rmsnorm(&blended, &layer.expert_norm, cfg.eps, &mut expert_in); - let expert_out = experts(cfg, layer, &expert_in); + let expert_out = experts(cfg, p, layer, &expert_in)?; let mut y = vec![0.0f32; h]; sconv::fixed(&state.expert_recent, &expert_out, &layer.expert_taps, &mut y); remember(&mut state.expert_recent, &expert_out); add_into(&mut sum, &y); - sum + Ok(sum) } #[cfg(test)] diff --git a/crates/dluth-model/tests/tiny_inkling_golden.rs b/crates/dluth-model/tests/tiny_inkling_golden.rs index 289dbbf..de57532 100644 --- a/crates/dluth-model/tests/tiny_inkling_golden.rs +++ b/crates/dluth-model/tests/tiny_inkling_golden.rs @@ -33,3 +33,56 @@ fn tiny_inkling_matches_reference_greedy_and_logprobs() { assert_eq!(report.tie_at, None); } } + +/// Counts the products it is asked for and passes them on to the CPU. +struct Counting { + inner: dluth_model::inkling::CpuProducts, + bf16: std::rc::Rc>, + expert_jobs: std::rc::Rc>, +} + +impl dluth_model::inkling::Products for Counting { + fn bf16( + &mut self, + w: &[u8], + rows: usize, + cols: usize, + x: &[f32], + out: &mut [f32], + ) -> Result<(), dluth_model::error::ModelError> { + self.bf16.set(self.bf16.get() + 1); + self.inner.bf16(w, rows, cols, x, out) + } + + fn experts( + &mut self, + m: &dluth_model::inkling::ExpertMatrices, + jobs: &[(usize, &[f32])], + out: &mut [f32], + ) -> Result<(), dluth_model::error::ModelError> { + self.expert_jobs.set(self.expert_jobs.get() + jobs.len()); + self.inner.experts(m, jobs, out) + } +} + +#[test] +fn every_matrix_product_goes_through_the_products_given_to_the_model() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/tiny-inkling"); + let weights = Weights::open_dir(&dir).unwrap(); + let cfg = load_config(&dir).unwrap(); + let (bf16, expert_jobs) = (std::rc::Rc::new(std::cell::Cell::new(0)), std::rc::Rc::new(std::cell::Cell::new(0))); + let counting = + Counting { inner: dluth_model::inkling::CpuProducts, bf16: bf16.clone(), expert_jobs: expert_jobs.clone() }; + let passes = cfg.layer_passes(); + let per_token = cfg.experts_per_token; + let mut plain = InklingCpu::new(cfg.clone(), &weights, 16).unwrap(); + let mut counted = InklingCpu::with_products(cfg, &weights, 16, Box::new(counting)).unwrap(); + for (pos, token) in [5u32, 9, 2].into_iter().enumerate() { + assert_eq!(plain.forward_token(token, pos).unwrap(), counted.forward_token(token, pos).unwrap()); + } + // Two expert matrices per chosen expert per layer pass per token, and nothing else. + assert_eq!(expert_jobs.get(), 3 * passes * per_token * 2); + // Eight BF16 products in every layer pass at the least (query, key, value, relative + // position, sink, output gate, output, router), and the output table once per token. + assert!(bf16.get() >= 3 * (passes * 8 + 1), "{} BF16 products", bf16.get()); +} From 7eae7106926b737bd46eed1efcfc32e13867b843 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:18:48 -0800 Subject: [PATCH 2/4] test(model): exact count of the products that go through the trait; review fixes --- crates/dluth-model/src/error.rs | 4 +++- crates/dluth-model/src/inkling/model.rs | 7 +++++++ .../dluth-model/tests/tiny_inkling_golden.rs | 18 +++++++++++++++--- 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/crates/dluth-model/src/error.rs b/crates/dluth-model/src/error.rs index e3403ae..6dc12d8 100644 --- a/crates/dluth-model/src/error.rs +++ b/crates/dluth-model/src/error.rs @@ -17,7 +17,9 @@ pub enum ModelError { Unsupported(String), /// A request does not fit the limits the model was opened with. Capacity(String), - /// The device computing part of the model failed. The text is the device's own. + /// The device computing part of the model failed. The text is the device's own. The + /// token being computed was left half done: a model that returned this must be given + /// position 0 (a new sequence) before it is used again. Device(String), } diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index 171fa1a..8693fee 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs @@ -82,6 +82,7 @@ impl<'w> ExpertMatrices<'w> { (self.rows, self.cols) } + /// Which stored format the matrices are in. pub fn format(&self) -> ExpertFormat { match self.stored { Stored::Nvfp4 { .. } => ExpertFormat::Nvfp4, @@ -162,6 +163,12 @@ impl Products for CpuProducts { fn experts(&mut self, m: &ExpertMatrices, jobs: &[(usize, &[f32])], out: &mut [f32]) -> Result<(), ModelError> { let rows = m.shape().0; + assert!( + out.len() == jobs.len() * rows, + "experts: {} outputs for {} jobs of {rows} rows", + out.len(), + jobs.len() + ); for (&(expert, x), out) in jobs.iter().zip(out.chunks_exact_mut(rows)) { m.apply(expert, x, out); } diff --git a/crates/dluth-model/tests/tiny_inkling_golden.rs b/crates/dluth-model/tests/tiny_inkling_golden.rs index de57532..004b3f6 100644 --- a/crates/dluth-model/tests/tiny_inkling_golden.rs +++ b/crates/dluth-model/tests/tiny_inkling_golden.rs @@ -75,6 +75,19 @@ fn every_matrix_product_goes_through_the_products_given_to_the_model() { Counting { inner: dluth_model::inkling::CpuProducts, bf16: bf16.clone(), expert_jobs: expert_jobs.clone() }; let passes = cfg.layer_passes(); let per_token = cfg.experts_per_token; + // BF16 products of one token, from the configuration. Every layer pass: query, key, + // value, relative position, sink, output gate, output and router. A global layer also + // computes taps for its key and value convolutions. A looped layer, from its second pass + // on, merges four messages with three products each. And the output table, once. + let mut bf16_per_token = 1; + for layer in 0..cfg.layers { + let times = if cfg.is_looped(layer) { cfg.passes } else { 1 }; + bf16_per_token += times * (8 + if cfg.is_local(layer) { 0 } else { 2 }); + if cfg.is_looped(layer) { + bf16_per_token += (cfg.passes - 1) * 4 * 3; + } + } + assert!(cfg.passes > 1 && cfg.layers > cfg.local_layers.len(), "the fixture must loop and have global layers"); let mut plain = InklingCpu::new(cfg.clone(), &weights, 16).unwrap(); let mut counted = InklingCpu::with_products(cfg, &weights, 16, Box::new(counting)).unwrap(); for (pos, token) in [5u32, 9, 2].into_iter().enumerate() { @@ -82,7 +95,6 @@ fn every_matrix_product_goes_through_the_products_given_to_the_model() { } // Two expert matrices per chosen expert per layer pass per token, and nothing else. assert_eq!(expert_jobs.get(), 3 * passes * per_token * 2); - // Eight BF16 products in every layer pass at the least (query, key, value, relative - // position, sink, output gate, output, router), and the output table once per token. - assert!(bf16.get() >= 3 * (passes * 8 + 1), "{} BF16 products", bf16.get()); + // Exactly the BF16 products counted above: one made directly, past the trait, would be missing. + assert_eq!(bf16.get(), 3 * bf16_per_token); } From 7f774c8e0e5f75d1b05a8bb59d8835925b8f8cc8 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:18:48 -0800 Subject: [PATCH 3/4] test: planted bug for a product made past the trait --- .../71-inkling-product-past-the-trait.patch | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 tools/mutants/71-inkling-product-past-the-trait.patch diff --git a/tools/mutants/71-inkling-product-past-the-trait.patch b/tools/mutants/71-inkling-product-past-the-trait.patch new file mode 100644 index 0000000..c2fbbf9 --- /dev/null +++ b/tools/mutants/71-inkling-product-past-the-trait.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-model --test tiny_inkling_golden every_matrix_product +# Bug: one product (the attention sink) is computed directly on the CPU, past the Products trait. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index 8693fee..0874f4d 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -763,7 +763,7 @@ fn attention( + } + + let mut sinks = vec![0.0f32; cfg.heads]; +- p.bf16(layer.sink, cfg.heads, h, q_in, &mut sinks)?; ++ cpu::matvec_bf16(layer.sink, cfg.heads, h, q_in, &mut sinks); + + let mut attended = vec![0.0f32; q_width]; + sinkattn::attend( From f5a0b23e2b2a42f5a0103003087c6bd496b4b055 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:50:08 -0800 Subject: [PATCH 4/4] test: planted bugs regenerated for the forward pass after the products seam --- tools/mutants/38-inkling-no-sink.patch | 6 +++--- tools/mutants/40-inkling-shared-history.patch | 12 ++++++------ tools/mutants/41-inkling-value-message.patch | 6 +++--- tools/mutants/45-inkling-router-bias.patch | 10 +++++----- tools/mutants/47-inkling-gate-up-swapped.patch | 12 ++++++------ tools/mutants/50-inkling-value-norm.patch | 6 +++--- tools/mutants/51-inkling-output-cap.patch | 8 ++++---- 7 files changed, 30 insertions(+), 30 deletions(-) diff --git a/tools/mutants/38-inkling-no-sink.patch b/tools/mutants/38-inkling-no-sink.patch index e464cd6..903f818 100644 --- a/tools/mutants/38-inkling-no-sink.patch +++ b/tools/mutants/38-inkling-no-sink.patch @@ -3,14 +3,14 @@ # weights-env: DLUTH_INKLING2_MINI # Bug: the model's attention gives the sink no say. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 899fc4b..93d4d61 100644 +index 8693fee..24ea6da 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -654,7 +654,7 @@ fn attention(cfg: &InklingConfig, layer: &Layer, state: &mut PassState, inputs: +@@ -763,7 +763,7 @@ fn attention( } let mut sinks = vec![0.0f32; cfg.heads]; -- cpu::matvec_bf16(layer.sink, cfg.heads, h, q_in, &mut sinks); +- p.bf16(layer.sink, cfg.heads, h, q_in, &mut sinks)?; + sinks.fill(-1e30); let mut attended = vec![0.0f32; q_width]; diff --git a/tools/mutants/40-inkling-shared-history.patch b/tools/mutants/40-inkling-shared-history.patch index 624102b..f8bba05 100644 --- a/tools/mutants/40-inkling-shared-history.patch +++ b/tools/mutants/40-inkling-shared-history.patch @@ -3,16 +3,16 @@ # weights-env: DLUTH_INKLING2_MINI # Bug: every pass of a looped layer shares one attention history. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 899fc4b..dfd589c 100644 +index 8693fee..a6be3d7 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -482,7 +482,8 @@ impl<'w> InklingCpu<'w> { - } - _ => None, +@@ -569,7 +569,8 @@ impl<'w> InklingCpu<'w> { }; -- x = apply_layer(cfg, layer, &mut self.states[index], &x, &mut blocks, messages.as_deref(), pos); + let p = self.products.as_mut(); + let at = Arrival { pos, messages: messages.as_deref() }; +- x = apply_layer(cfg, p, layer, &mut self.states[index], &x, &mut blocks, at)?; + let shared = self.steps.iter().position(|s| s.layer == step.layer).unwrap_or(index); -+ x = apply_layer(cfg, layer, &mut self.states[shared], &x, &mut blocks, messages.as_deref(), pos); ++ x = apply_layer(cfg, p, layer, &mut self.states[shared], &x, &mut blocks, at)?; } self.last = x; diff --git a/tools/mutants/41-inkling-value-message.patch b/tools/mutants/41-inkling-value-message.patch index 8f64752..9a1d897 100644 --- a/tools/mutants/41-inkling-value-message.patch +++ b/tools/mutants/41-inkling-value-message.patch @@ -3,15 +3,15 @@ # weights-env: DLUTH_INKLING2_MINI # Bug: the message for the value input is dropped. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 899fc4b..0d4404f 100644 +index 8693fee..c856a7f 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -751,7 +751,7 @@ fn apply_layer( +@@ -878,7 +878,7 @@ fn apply_layer( } }; // 2. From the second pass on, merge in the previous pass's messages, then normalize. - for (input, port) in inputs.iter_mut().zip([Port::Query, Port::Key, Port::Value]) { + for (input, port) in inputs.iter_mut().zip([Port::Query, Port::Key]) { - *input = merged(port, std::mem::take(input)); + *input = merged(p, port, std::mem::take(input))?; } let mut normed = [vec![0.0f32; h], vec![0.0f32; h], vec![0.0f32; h]]; diff --git a/tools/mutants/45-inkling-router-bias.patch b/tools/mutants/45-inkling-router-bias.patch index ed482cc..9d51879 100644 --- a/tools/mutants/45-inkling-router-bias.patch +++ b/tools/mutants/45-inkling-router-bias.patch @@ -3,15 +3,15 @@ # weights-env: DLUTH_INKLING2_MINI # Bug: experts are chosen without the routing bias. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 899fc4b..149a2e3 100644 +index 8693fee..3caca5c 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -688,7 +688,7 @@ fn experts(cfg: &InklingConfig, layer: &Layer, input: &[f32]) -> Vec { +@@ -797,7 +797,7 @@ fn experts(cfg: &InklingConfig, p: &mut dyn Products, layer: &Layer, input: &[f3 let (h, inner) = (cfg.hidden, cfg.expert_width); let mut scores = vec![0.0f32; cfg.experts]; - cpu::matvec_bf16(layer.router, cfg.experts, h, input, &mut scores); + p.bf16(layer.router, cfg.experts, h, input, &mut scores)?; - let chosen = router::choose(&scores, &layer.router_bias, cfg.experts_per_token, cfg.route_scale); + let chosen = router::choose(&scores, &vec![0.0; cfg.experts], cfg.experts_per_token, cfg.route_scale); - let mut total = vec![0.0f32; h]; - let mut both = vec![0.0f32; 2 * inner]; + // Every chosen expert's first matrix reads the same input. + let jobs: Vec<(usize, &[f32])> = chosen.iter().map(|&(expert, _)| (expert, input)).collect(); diff --git a/tools/mutants/47-inkling-gate-up-swapped.patch b/tools/mutants/47-inkling-gate-up-swapped.patch index 5fedfab..21a8f3a 100644 --- a/tools/mutants/47-inkling-gate-up-swapped.patch +++ b/tools/mutants/47-inkling-gate-up-swapped.patch @@ -3,17 +3,17 @@ # weights-env: DLUTH_INKLING2_MINI # Bug: an expert reads its gate and up rows the wrong way round. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 899fc4b..78b6ce7 100644 +index 8693fee..4c08d29 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -698,8 +698,8 @@ fn experts(cfg: &InklingConfig, layer: &Layer, input: &[f32]) -> Vec { - layer.first.apply(expert, input, &mut both); - // Gate and up values alternate. +@@ -809,8 +809,8 @@ fn experts(cfg: &InklingConfig, p: &mut dyn Products, layer: &Layer, input: &[f3 + let (mut gate, mut up) = (vec![0.0f32; inner], vec![0.0f32; inner]); + for (both, act) in both.chunks_exact(2 * inner).zip(acts.chunks_exact_mut(inner)) { for (i, pair) in both.as_chunks::<2>().0.iter().enumerate() { - gate[i] = pair[0]; - up[i] = pair[1]; + gate[i] = pair[1]; + up[i] = pair[0]; } - cpu::capped_gate_mul(&gate, &up, cfg.gate_cap, cfg.up_cap, &mut act); - layer.second.apply(expert, &act, &mut out); + cpu::capped_gate_mul(&gate, &up, cfg.gate_cap, cfg.up_cap, act); + } diff --git a/tools/mutants/50-inkling-value-norm.patch b/tools/mutants/50-inkling-value-norm.patch index 17ad51e..673e6bd 100644 --- a/tools/mutants/50-inkling-value-norm.patch +++ b/tools/mutants/50-inkling-value-norm.patch @@ -3,11 +3,11 @@ # weights-env: DLUTH_INKLING2_MINI # Bug: values are not normalized per head. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 899fc4b..db58585 100644 +index 8693fee..bb13568 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -627,7 +627,7 @@ fn attention(cfg: &InklingConfig, layer: &Layer, state: &mut PassState, inputs: - let unnormed = project_kv(cfg, layer.wv, &layer.v_conv, &mut state.v_recent, v_in); +@@ -735,7 +735,7 @@ fn attention( + let unnormed = project_kv(cfg, p, layer.wv, &layer.v_conv, &mut state.v_recent, v_in)?; let mut values = vec![0.0f32; unnormed.len()]; for (out, head) in values.chunks_exact_mut(d).zip(unnormed.chunks_exact(d)) { - cpu::rmsnorm_plain(head, cfg.eps, out); diff --git a/tools/mutants/51-inkling-output-cap.patch b/tools/mutants/51-inkling-output-cap.patch index 0eebb70..b88804b 100644 --- a/tools/mutants/51-inkling-output-cap.patch +++ b/tools/mutants/51-inkling-output-cap.patch @@ -3,15 +3,15 @@ # weights-env: DLUTH_INKLING2_MINI # Bug: the output scores are not capped. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 899fc4b..eb59bef 100644 +index 8693fee..0a783b0 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -505,7 +505,7 @@ impl<'w> InklingCpu<'w> { +@@ -592,7 +592,7 @@ impl<'w> InklingCpu<'w> { let mut logits = vec![0.0f32; cfg.vocab_out]; - cpu::matvec_bf16(&self.unembed[..cfg.vocab_out * h * 2], cfg.vocab_out, h, &normed, &mut logits); + self.products.bf16(&self.unembed[..cfg.vocab_out * h * 2], cfg.vocab_out, h, &normed, &mut logits)?; for l in logits.iter_mut() { - *l = cpu::softcap(*l, cfg.logit_cap); + *l = l.clamp(-1e30, 1e30); } - logits + Ok(logits) }