From a8ecbf01e2f9aac940ec933bb3298e520f0f264a Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:58:51 -0800 Subject: [PATCH 1/3] refactor(model): the Inkling forward pass is written once against an Ops trait; CpuOps is the reference implementation --- crates/dluth-model/src/inkling/mod.rs | 5 +- crates/dluth-model/src/inkling/model.rs | 495 ++++++++++++++++-------- 2 files changed, 341 insertions(+), 159 deletions(-) diff --git a/crates/dluth-model/src/inkling/mod.rs b/crates/dluth-model/src/inkling/mod.rs index 7ef4657..f68cef6 100644 --- a/crates/dluth-model/src/inkling/mod.rs +++ b/crates/dluth-model/src/inkling/mod.rs @@ -5,4 +5,7 @@ pub mod model; pub mod prompt; pub use config::{load_config, model_kind, validate_weights, Checked, ExpertFormat, InklingConfig, ModelKind}; -pub use model::{CpuProducts, ExpertLayer, ExpertMatrices, InklingCpu, Products}; +pub use model::{ + CpuBlend, CpuOps, CpuProducts, ExpertLayer, ExpertMatrices, Gate, Inkling, InklingCpu, KvConv, Layer, Ops, + PassState, Products, +}; diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index 2cd0054..306a8fc 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs @@ -216,7 +216,7 @@ impl Products for CpuProducts { } /// The convolution on a layer's keys or values. -enum KvConv<'w> { +pub enum KvConv<'w> { /// Local layers: fixed taps per channel. Fixed { taps: Vec }, /// Global layers: fixed taps plus taps computed from the token by `token_proj`. @@ -224,10 +224,10 @@ enum KvConv<'w> { } /// A gate that merges a message from the previous pass into a sublayer's input. -struct Gate<'w> { - down: &'w [u8], - forget: &'w [u8], - gain: &'w [u8], +pub struct Gate<'w> { + pub down: &'w [u8], + pub forget: &'w [u8], + pub gain: &'w [u8], } /// The four inputs of a looped layer that can receive a message. @@ -239,43 +239,235 @@ enum Port { Expert = 3, } -struct Layer<'w> { - local: bool, +/// One stored layer: its settings and where its weights are. Small weights are decoded +/// to floats; large matrices stay as the slices of the weight file they are stored in. +pub struct Layer<'w> { + pub local: bool, /// Whether this layer starts a block of the blends across depth. - starts_block: bool, + pub starts_block: bool, /// How far back the relative-position term reaches. - reach: usize, + pub reach: usize, /// Queries of the attention input blend: none in layer 0, one in a local layer, three /// (query, key, value) in a global layer. - attn_queries: Vec, - expert_query: Vec, + pub attn_queries: Vec, + pub expert_query: Vec, /// Norm weights for the query, key and value inputs. A local layer has one set, stored /// three times here so both kinds of layer read the same way. - input_norms: [Vec; 3], - wq: &'w [u8], - wk: &'w [u8], - wv: &'w [u8], - wo: &'w [u8], - out_gate: &'w [u8], - wr: &'w [u8], - sink: &'w [u8], - q_scale: Vec, - rel_scale: Vec, + pub input_norms: [Vec; 3], + pub wq: &'w [u8], + pub wk: &'w [u8], + pub wv: &'w [u8], + pub wo: &'w [u8], + pub out_gate: &'w [u8], + pub wr: &'w [u8], + pub sink: &'w [u8], + pub q_scale: Vec, + pub rel_scale: Vec, /// `[rel_dim][reach]`: learned curves over distance. - rel_table: Vec, - k_conv: KvConv<'w>, - v_conv: KvConv<'w>, - attn_taps: Vec, - expert_taps: Vec, - expert_norm: Vec, - router: &'w [u8], - router_bias: Vec, + pub rel_table: Vec, + pub k_conv: KvConv<'w>, + pub v_conv: KvConv<'w>, + pub attn_taps: Vec, + pub expert_taps: Vec, + pub expert_norm: Vec, + pub router: &'w [u8], + pub router_bias: Vec, /// Hidden state to alternating gate and up rows. - first: ExpertMatrices<'w>, + pub first: ExpertMatrices<'w>, /// Inner width back to the hidden state. - second: ExpertMatrices<'w>, + pub second: ExpertMatrices<'w>, /// Query, key, value and expert gates; only looped layers have them. - gates: Option<[Gate<'w>; 4]>, + pub gates: Option<[Gate<'w>; 4]>, +} + +/// The operations a forward pass is made of, on values that live wherever the +/// implementation keeps them. +/// +/// The forward pass in this file is written once, in terms of these operations. The CPU +/// implementation, `CpuOps`, is the reference: each of its operations is a few calls into +/// `dluth-kernels`. Another implementation may keep its values on a device and compute +/// there; it is correct if each of its operations gives what `CpuOps` gives, and the golden +/// checks against the reference implementation run with either. +/// +/// A value (`V`) is a vector of floats. A `Pass` is what one application of a layer +/// remembers between tokens: the keys and values of the tokens it can still see and the +/// recent inputs of its short convolutions. +pub trait Ops { + type V: Clone; + /// Candidates normalized for blending (see `normalize` and `mix`). + type Blend; + type Pass; + + /// Memory for one application of a layer, empty, with room for `max_seq` positions. + fn new_pass(&mut self, cfg: &InklingConfig, local: bool, max_seq: usize) -> Result; + /// Forgets every token. + fn reset_pass(&mut self, pass: &mut Self::Pass) -> Result<(), ModelError>; + + /// A token's row of the embedding table (BF16), normalized with the weights `norm`. + fn embed(&mut self, cfg: &InklingConfig, table: &[u8], norm: &[f32], token: u32) -> Result; + /// Normalizes each candidate (root-mean-square 1), ready to be blended. + fn normalize(&mut self, candidates: &[&Self::V]) -> Result; + /// The blend of normalized candidates that `query` asks for. + fn mix(&mut self, blend: &Self::Blend, query: &[f32]) -> Result; + /// Merges a message from the previous pass into a sublayer input through a gate. + fn merge( + &mut self, + cfg: &InklingConfig, + gate: &Gate, + x: &Self::V, + message: &Self::V, + ) -> Result; + /// Root-mean-square normalization with learned weights. + fn rmsnorm(&mut self, x: &Self::V, weights: &[f32], eps: f32) -> Result; + /// Attention for the token at `pos`: `inputs` are the normalized query, key and value + /// inputs. Remembers the token's key and value in `pass`. + fn attention( + &mut self, + cfg: &InklingConfig, + layer: &Layer, + pass: &mut Self::Pass, + inputs: [&Self::V; 3], + pos: usize, + ) -> Result; + /// The short convolution over the attention sublayer's recent outputs. + fn attn_conv(&mut self, layer: &Layer, pass: &mut Self::Pass, x: &Self::V) -> Result; + /// The short convolution over the expert sublayer's recent outputs. + fn expert_conv(&mut self, layer: &Layer, pass: &mut Self::Pass, x: &Self::V) -> Result; + /// `a + b`, element by element. + fn add(&mut self, a: &Self::V, b: &Self::V) -> Result; + /// The expert sublayer: choose a few experts for `x`, run each, add up their weighted outputs. + fn experts(&mut self, cfg: &InklingConfig, layer: &Layer, x: &Self::V) -> Result; + /// The score of every real token of the vocabulary for the final hidden state `x`, + /// soft-capped, as plain floats. + fn scores(&mut self, cfg: &InklingConfig, unembed: &[u8], x: &Self::V) -> Result, ModelError>; +} + +/// Candidates normalized on the CPU: one after another in `data`, `width` floats each. +pub struct CpuBlend { + data: Vec, + width: usize, +} + +/// The operations on the CPU, with the matrix products made by a `Products`. +pub struct CpuOps<'w> { + products: Box, +} + +impl<'w> CpuOps<'w> { + pub fn new(products: Box) -> Self { + CpuOps { products } + } +} + +impl Ops for CpuOps<'_> { + type V = Vec; + type Blend = CpuBlend; + type Pass = PassState; + + fn new_pass(&mut self, cfg: &InklingConfig, local: bool, max_seq: usize) -> Result { + let (h, kv_width, recent) = (cfg.hidden, cfg.kv_heads * cfg.head_dim, cfg.conv_taps - 1); + let window = local.then_some(cfg.window); + Ok(PassState { + keys: History::new(kv_width, window, max_seq)?, + values: History::new(kv_width, window, max_seq)?, + k_recent: vec![0.0; recent * kv_width], + v_recent: vec![0.0; recent * kv_width], + attn_recent: vec![0.0; recent * h], + expert_recent: vec![0.0; recent * h], + }) + } + + fn reset_pass(&mut self, pass: &mut PassState) -> Result<(), ModelError> { + pass.keys.len = 0; + pass.values.len = 0; + for recent in [&mut pass.k_recent, &mut pass.v_recent, &mut pass.attn_recent, &mut pass.expert_recent] { + recent.fill(0.0); + } + Ok(()) + } + + fn embed(&mut self, cfg: &InklingConfig, table: &[u8], norm: &[f32], token: u32) -> Result, ModelError> { + let h = cfg.hidden; + let row = &table[token as usize * h * 2..(token as usize + 1) * h * 2]; + let raw: Vec = row.as_chunks::<2>().0.iter().map(|c| bf16_to_f32(u16::from_le_bytes(*c))).collect(); + let mut x = vec![0.0f32; h]; + cpu::rmsnorm(&raw, norm, cfg.eps, &mut x); + Ok(x) + } + + fn normalize(&mut self, candidates: &[&Vec]) -> Result { + let slices: Vec<&[f32]> = candidates.iter().map(|c| c.as_slice()).collect(); + let width = slices.first().map_or(0, |c| c.len()); + Ok(CpuBlend { data: depthmix::normalize(&slices, BLEND_EPS), width }) + } + + fn mix(&mut self, blend: &CpuBlend, query: &[f32]) -> Result, ModelError> { + let mut out = vec![0.0f32; blend.width]; + depthmix::mix_normalized(query, &blend.data, blend.width, &mut out); + Ok(out) + } + + fn merge( + &mut self, + cfg: &InklingConfig, + gate: &Gate, + x: &Vec, + message: &Vec, + ) -> Result, ModelError> { + merge(cfg, self.products.as_mut(), gate, x, message) + } + + fn rmsnorm(&mut self, x: &Vec, weights: &[f32], eps: f32) -> Result, ModelError> { + let mut out = vec![0.0f32; x.len()]; + cpu::rmsnorm(x, weights, eps, &mut out); + Ok(out) + } + + fn attention( + &mut self, + cfg: &InklingConfig, + layer: &Layer, + pass: &mut PassState, + inputs: [&Vec; 3], + pos: usize, + ) -> Result, ModelError> { + attention(cfg, self.products.as_mut(), layer, pass, [inputs[0], inputs[1], inputs[2]], pos) + } + + fn attn_conv(&mut self, layer: &Layer, pass: &mut PassState, x: &Vec) -> Result, ModelError> { + let mut out = vec![0.0f32; x.len()]; + sconv::fixed(&pass.attn_recent, x, &layer.attn_taps, &mut out); + remember(&mut pass.attn_recent, x); + Ok(out) + } + + fn expert_conv(&mut self, layer: &Layer, pass: &mut PassState, x: &Vec) -> Result, ModelError> { + let mut out = vec![0.0f32; x.len()]; + sconv::fixed(&pass.expert_recent, x, &layer.expert_taps, &mut out); + remember(&mut pass.expert_recent, x); + Ok(out) + } + + fn add(&mut self, a: &Vec, b: &Vec) -> Result, ModelError> { + let mut out = a.clone(); + add_into(&mut out, b); + Ok(out) + } + + fn experts(&mut self, cfg: &InklingConfig, layer: &Layer, x: &Vec) -> Result, ModelError> { + experts(cfg, self.products.as_mut(), layer, x) + } + + fn scores(&mut self, cfg: &InklingConfig, unembed: &[u8], x: &Vec) -> Result, ModelError> { + let h = cfg.hidden; + // The output table is padded; only its first rows are tokens. + let mut logits = vec![0.0f32; cfg.vocab_out]; + self.products.bf16(&unembed[..cfg.vocab_out * h * 2], cfg.vocab_out, h, x, &mut logits)?; + for l in logits.iter_mut() { + *l = cpu::softcap(*l, cfg.logit_cap); + } + Ok(logits) + } } /// Keys or values of the tokens a layer pass can still see. @@ -321,9 +513,9 @@ impl History { } } -/// Everything one application of a layer remembers between tokens. A looped layer has one -/// of these per pass: passes share weights, not history. -struct PassState { +/// Everything one application of a layer remembers between tokens, on the CPU. A looped +/// layer has one of these per pass: passes share weights, not history. +pub struct PassState { keys: History, values: History, /// The last few inputs of each of the four convolutions, oldest first. @@ -362,7 +554,8 @@ fn schedule(cfg: &InklingConfig) -> Vec { steps } -pub struct InklingCpu<'w> { +/// The Inkling 2 looped model, one token at a time, computed by the operations `O`. +pub struct Inkling<'w, O: Ops> { pub cfg: InklingConfig, embed: &'w [u8], embed_norm: Vec, @@ -374,30 +567,40 @@ pub struct InklingCpu<'w> { layers: Vec>, steps: Vec, /// One per entry of `steps`. - states: Vec, + passes: Vec, max_seq: usize, /// How many tokens have been fed since the last reset. cached: usize, - /// The hidden state after the last layer, before the final blend. - last: Vec, - last_blocks: Vec>, - products: Box, + /// The hidden state after the last layer, before the final blend, and the finished + /// blocks at that point. None until a token has been fed. + last: Option<(O::V, Vec)>, + ops: O, } -impl<'w> InklingCpu<'w> { +/// The model on the CPU: the reference every faster path is compared with. +pub type InklingCpu<'w> = Inkling<'w, CpuOps<'w>>; + +impl<'w> Inkling<'w, CpuOps<'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. + /// As `new`, with the matrix products computed by `products` and everything else on the CPU. pub fn with_products( cfg: InklingConfig, w: &'w Weights, max_seq: usize, products: Box, ) -> Result { + Self::with_ops(cfg, w, max_seq, CpuOps::new(products)) + } +} + +impl<'w, O: Ops> Inkling<'w, O> { + /// As `InklingCpu::new`, with every operation of the forward pass computed by `ops`. + pub fn with_ops(cfg: InklingConfig, w: &'w Weights, max_seq: usize, mut ops: O) -> 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 {}", @@ -406,7 +609,6 @@ impl<'w> InklingCpu<'w> { } let checked = validate_weights(&cfg, w)?; let (h, inner) = (cfg.hidden, cfg.expert_width); - let kv_width = cfg.kv_heads * cfg.head_dim; let m = "model.llm"; let mut layers = Vec::with_capacity(cfg.layers); @@ -492,21 +694,12 @@ impl<'w> InklingCpu<'w> { } let steps = schedule(&cfg); - let recent = cfg.conv_taps - 1; - let mut states = Vec::with_capacity(steps.len()); + let mut passes = Vec::with_capacity(steps.len()); for step in &steps { - let window = cfg.is_local(step.layer).then_some(cfg.window); - states.push(PassState { - keys: History::new(kv_width, window, max_seq)?, - values: History::new(kv_width, window, max_seq)?, - k_recent: vec![0.0; recent * kv_width], - v_recent: vec![0.0; recent * kv_width], - attn_recent: vec![0.0; recent * h], - expert_recent: vec![0.0; recent * h], - }); + passes.push(ops.new_pass(&cfg, cfg.is_local(step.layer), max_seq)?); } - Ok(InklingCpu { + Ok(Inkling { embed: w.bytes(&format!("{m}.embed.weight"))?, embed_norm: bf16_values(w, &format!("{m}.embed_norm.weight"))?, final_norm: bf16_values(w, &format!("{m}.norm.weight"))?, @@ -515,34 +708,38 @@ impl<'w> InklingCpu<'w> { message_queries, layers, steps, - states, + passes, max_seq, cached: 0, - products, - last: vec![0.0; h], - last_blocks: Vec::new(), + last: None, + ops, cfg, }) } + /// The operations this model computes with. + pub fn ops(&self) -> &O { + &self.ops + } + /// Forgets every token fed so far. - fn reset(&mut self) { - for state in &mut self.states { - state.keys.len = 0; - state.values.len = 0; - for recent in [&mut state.k_recent, &mut state.v_recent, &mut state.attn_recent, &mut state.expert_recent] { - recent.fill(0.0); - } + fn reset(&mut self) -> Result<(), ModelError> { + for pass in &mut self.passes { + self.ops.reset_pass(pass)?; } self.cached = 0; + self.last = None; + Ok(()) } /// Runs one token through every layer application and leaves the last hidden state and /// block list for `logits`. fn advance(&mut self, token: u32, pos: usize) -> Result<(), ModelError> { - let cfg = &self.cfg; - if token as usize >= cfg.vocab { - return Err(ModelError::Capacity(format!("token id {token} is outside the vocabulary of {}", cfg.vocab))); + if token as usize >= self.cfg.vocab { + return Err(ModelError::Capacity(format!( + "token id {token} is outside the vocabulary of {}", + self.cfg.vocab + ))); } if pos >= self.max_seq { return Err(ModelError::Capacity(format!( @@ -551,28 +748,24 @@ impl<'w> InklingCpu<'w> { ))); } if pos == 0 { - self.reset(); + self.reset()?; } else if pos != self.cached { return Err(ModelError::Capacity(format!( "position {pos} is out of order: the next position is {}, and only position 0 starts over", self.cached ))); } - // Taken again: the reset above needed the whole model. - let cfg = &self.cfg; + let (cfg, ops) = (&self.cfg, &mut self.ops); let h = cfg.hidden; // Embedding: the token's row of the table, normalized. - let row = &self.embed[token as usize * h * 2..(token as usize + 1) * h * 2]; - let raw: Vec = row.as_chunks::<2>().0.iter().map(|c| bf16_to_f32(u16::from_le_bytes(*c))).collect(); - let mut x = vec![0.0f32; h]; - cpu::rmsnorm(&raw, &self.embed_norm, cfg.eps, &mut x); + let mut x = ops.embed(cfg, self.embed, &self.embed_norm, token)?; - let mut blocks: Vec> = Vec::new(); + let mut blocks: Vec = Vec::new(); // The state on entering the loop, which every pass starts from. - let mut before_loop: Option<(Vec, Vec>)> = None; + let mut before_loop: Option<(O::V, Vec)> = None; // The previous pass's results that messages are blended from, normalized. - let mut message_source: Option> = None; + let mut message_source: Option = None; for (index, step) in self.steps.iter().enumerate() { if step.layer == cfg.loop_start { @@ -584,10 +777,9 @@ impl<'w> InklingCpu<'w> { // this pass's messages. Then start again from the loop's entry. // The configuration check guarantees the loop starts on a block // boundary and is not empty, so that block exists. - let mut source: Vec<&[f32]> = - blocks[start_blocks.len() + 1..].iter().map(Vec::as_slice).collect(); + let mut source: Vec<&O::V> = blocks[start_blocks.len() + 1..].iter().collect(); source.push(&x); - message_source = Some(depthmix::normalize(&source, BLEND_EPS)); + message_source = Some(ops.normalize(&source)?); x = start_x.clone(); blocks = start_blocks.clone(); } @@ -597,43 +789,35 @@ impl<'w> InklingCpu<'w> { let messages = match (&message_source, cfg.is_looped(step.layer) && step.pass > 0) { (Some(source), true) => { let at = (step.layer - cfg.loop_start) * 4 * h; - let mut four = vec![0.0f32; 4 * h]; - for (port, out) in four.chunks_exact_mut(h).enumerate() { - let query = &self.message_queries[at + port * h..at + (port + 1) * h]; - depthmix::mix_normalized(query, source, h, out); + let mut four = Vec::with_capacity(4); + for port in 0..4 { + four.push(ops.mix(source, &self.message_queries[at + port * h..at + (port + 1) * h])?); } Some(four) } _ => None, }; - 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)?; + x = apply_layer(cfg, ops, layer, &mut self.passes[index], &x, &mut blocks, at)?; } - self.last = x; - self.last_blocks = blocks; + self.last = Some((x, blocks)); self.cached = pos + 1; Ok(()) } /// Scores every real token of the vocabulary from the state `advance` left. 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(); - candidates.push(&self.last); - let mut blended = vec![0.0f32; h]; - depthmix::mix(&self.final_query, &candidates, BLEND_EPS, &mut blended); - let mut normed = vec![0.0f32; h]; - 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]; - 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); - } - Ok(logits) + let Some((last, blocks)) = &self.last else { + return Err(ModelError::Capacity("no token has been fed yet".into())); + }; + let (cfg, ops) = (&self.cfg, &mut self.ops); + let mut candidates: Vec<&O::V> = blocks.iter().collect(); + candidates.push(last); + let blend = ops.normalize(&candidates)?; + let blended = ops.mix(&blend, &self.final_query)?; + let normed = ops.rmsnorm(&blended, &self.final_norm, cfg.eps)?; + ops.scores(cfg, self.unembed, &normed) } /// Feeds one token at position `pos` and returns the scores for the token after it. @@ -845,93 +1029,88 @@ fn experts(cfg: &InklingConfig, p: &mut dyn Products, layer: &Layer, input: &[f3 } /// What a layer application is given besides the layer itself. -struct Arrival<'a> { +struct Arrival<'a, V> { /// 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]>, + /// The four messages from the previous pass (query, key, value, expert), for a looped + /// layer from its second pass on. + messages: Option<&'a [V]>, } /// 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( +fn apply_layer( cfg: &InklingConfig, - p: &mut dyn Products, + ops: &mut O, layer: &Layer, - state: &mut PassState, - x: &[f32], - blocks: &mut Vec>, - at: Arrival, -) -> Result, ModelError> { + pass: &mut O::Pass, + x: &O::V, + blocks: &mut Vec, + at: Arrival, +) -> Result { 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 message = |port: Port| messages.map(|m| &m[port as usize]); let gate = |port: Port| layer.gates.as_ref().map(|g| &g[port as usize]); - 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), + let merged = |ops: &mut O, port: Port, input: O::V| match (gate(port), message(port)) { + (Some(g), Some(m)) => ops.merge(cfg, g, &input, m), _ => Ok(input), }; // 1. The attention inputs: the first layer reads the running sum; every other layer // blends the finished blocks and the running sum, once (local) or once each for // queries, keys and values (global). - let mut inputs: [Vec; 3] = if layer.attn_queries.is_empty() { - [x.to_vec(), x.to_vec(), x.to_vec()] + let inputs: [O::V; 3] = if layer.attn_queries.is_empty() { + [x.clone(), x.clone(), x.clone()] } else { - let mut candidates: Vec<&[f32]> = blocks.iter().map(Vec::as_slice).collect(); + let mut candidates: Vec<&O::V> = blocks.iter().collect(); candidates.push(x); - let normalized = depthmix::normalize(&candidates, BLEND_EPS); - let blend = |query: &[f32]| { - let mut out = vec![0.0f32; h]; - depthmix::mix_normalized(query, &normalized, h, &mut out); - out - }; + let blend = ops.normalize(&candidates)?; if layer.local { - let one = blend(&layer.attn_queries); + let one = ops.mix(&blend, &layer.attn_queries)?; [one.clone(), one.clone(), one] } else { - [blend(&layer.attn_queries[..h]), blend(&layer.attn_queries[h..2 * h]), blend(&layer.attn_queries[2 * h..])] + [ + ops.mix(&blend, &layer.attn_queries[..h])?, + ops.mix(&blend, &layer.attn_queries[h..2 * h])?, + ops.mix(&blend, &layer.attn_queries[2 * h..])?, + ] } }; // 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(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()) { - cpu::rmsnorm(input, weights, cfg.eps, out); + let [q, k, v] = inputs; + let mut normed = Vec::with_capacity(3); + for ((input, port), weights) in + [q, k, v].into_iter().zip([Port::Query, Port::Key, Port::Value]).zip(&layer.input_norms) + { + let input = merged(ops, port, input)?; + normed.push(ops.rmsnorm(&input, weights, cfg.eps)?); } // 3. Attention, then a short convolution over its recent outputs. - 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); + let attended = ops.attention(cfg, layer, pass, [&normed[0], &normed[1], &normed[2]], pos)?; + let a = ops.attn_conv(layer, pass, &attended)?; // 4. A layer that starts a block closes the previous one: the running sum joins the // list and a new sum starts from this layer's attention output. - let mut sum = a; - if layer.starts_block { - blocks.push(x.to_vec()); + let sum = if layer.starts_block { + blocks.push(x.clone()); + a } else { - add_into(&mut sum, x); - } + ops.add(&a, x)? + }; // 5. The experts read their own blend, with the block list as it is now. - let mut candidates: Vec<&[f32]> = blocks.iter().map(Vec::as_slice).collect(); + let mut candidates: Vec<&O::V> = blocks.iter().collect(); candidates.push(&sum); - let mut blended = vec![0.0f32; h]; - depthmix::mix(&layer.expert_query, &candidates, BLEND_EPS, &mut 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, 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); - Ok(sum) + let blend = ops.normalize(&candidates)?; + let blended = ops.mix(&blend, &layer.expert_query)?; + let blended = merged(ops, Port::Expert, blended)?; + let expert_in = ops.rmsnorm(&blended, &layer.expert_norm, cfg.eps)?; + let expert_out = ops.experts(cfg, layer, &expert_in)?; + let y = ops.expert_conv(layer, pass, &expert_out)?; + + ops.add(&sum, &y) } #[cfg(test)] From d10f7543a13ceb30e94dbfd192073acd1591cf68 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:12:04 -0800 Subject: [PATCH 2/3] test: planted bugs regenerated for the forward pass written against Ops --- tools/mutants/40-inkling-shared-history.patch | 12 +++++------ tools/mutants/41-inkling-value-message.patch | 18 ++++++++--------- tools/mutants/42-inkling-pass-restart.patch | 8 ++++---- tools/mutants/43-inkling-no-window.patch | 20 +++++++++---------- tools/mutants/48-inkling-message-source.patch | 12 +++++------ tools/mutants/49-inkling-block-boundary.patch | 17 ++++++++-------- tools/mutants/51-inkling-output-cap.patch | 6 +++--- 7 files changed, 47 insertions(+), 46 deletions(-) diff --git a/tools/mutants/40-inkling-shared-history.patch b/tools/mutants/40-inkling-shared-history.patch index f8bba05..c9e919f 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 8693fee..a6be3d7 100644 +index 306a8fc..dcaaf9f 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -569,7 +569,8 @@ impl<'w> InklingCpu<'w> { +@@ -798,7 +798,8 @@ impl<'w, O: Ops> Inkling<'w, O> { + _ => None, }; - 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)?; +- x = apply_layer(cfg, ops, layer, &mut self.passes[index], &x, &mut blocks, at)?; + let shared = self.steps.iter().position(|s| s.layer == step.layer).unwrap_or(index); -+ x = apply_layer(cfg, p, layer, &mut self.states[shared], &x, &mut blocks, at)?; ++ x = apply_layer(cfg, ops, layer, &mut self.passes[shared], &x, &mut blocks, at)?; } - self.last = x; + self.last = Some((x, blocks)); diff --git a/tools/mutants/41-inkling-value-message.patch b/tools/mutants/41-inkling-value-message.patch index 9a1d897..22578a9 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 8693fee..c856a7f 100644 +index 306a8fc..1ab29ae 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -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(p, port, std::mem::take(input))?; +@@ -1083,7 +1083,7 @@ fn apply_layer( + for ((input, port), weights) in + [q, k, v].into_iter().zip([Port::Query, Port::Key, Port::Value]).zip(&layer.input_norms) + { +- let input = merged(ops, port, input)?; ++ let input = if matches!(port, Port::Value) { input } else { merged(ops, port, input)? }; + normed.push(ops.rmsnorm(&input, weights, cfg.eps)?); } - let mut normed = [vec![0.0f32; h], vec![0.0f32; h], vec![0.0f32; h]]; + diff --git a/tools/mutants/42-inkling-pass-restart.patch b/tools/mutants/42-inkling-pass-restart.patch index 242f83d..6c78344 100644 --- a/tools/mutants/42-inkling-pass-restart.patch +++ b/tools/mutants/42-inkling-pass-restart.patch @@ -3,13 +3,13 @@ # weights-env: DLUTH_INKLING2_MINI # Bug: a later pass continues from the previous pass instead of starting again from the loop entry. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 899fc4b..b70fa48 100644 +index 306a8fc..1570241 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -464,7 +464,6 @@ impl<'w> InklingCpu<'w> { - blocks[start_blocks.len() + 1..].iter().map(Vec::as_slice).collect(); +@@ -780,7 +780,6 @@ impl<'w, O: Ops> Inkling<'w, O> { + let mut source: Vec<&O::V> = blocks[start_blocks.len() + 1..].iter().collect(); source.push(&x); - message_source = Some(depthmix::normalize(&source, BLEND_EPS)); + message_source = Some(ops.normalize(&source)?); - x = start_x.clone(); blocks = start_blocks.clone(); } diff --git a/tools/mutants/43-inkling-no-window.patch b/tools/mutants/43-inkling-no-window.patch index 8dd8688..b95ad99 100644 --- a/tools/mutants/43-inkling-no-window.patch +++ b/tools/mutants/43-inkling-no-window.patch @@ -1,15 +1,15 @@ # test: cargo test -p dluth-model --test tiny_inkling_golden # Bug: local layers see the whole sequence. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 899fc4b..4caa761 100644 +index 306a8fc..c4c9d7b 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -375,7 +375,7 @@ impl<'w> InklingCpu<'w> { - let recent = cfg.conv_taps - 1; - let mut states = Vec::with_capacity(steps.len()); - for step in &steps { -- let window = cfg.is_local(step.layer).then_some(cfg.window); -+ let window: Option = None; - states.push(PassState { - keys: History::new(kv_width, window, max_seq)?, - values: History::new(kv_width, window, max_seq)?, +@@ -366,7 +366,7 @@ impl Ops for CpuOps<'_> { + + fn new_pass(&mut self, cfg: &InklingConfig, local: bool, max_seq: usize) -> Result { + let (h, kv_width, recent) = (cfg.hidden, cfg.kv_heads * cfg.head_dim, cfg.conv_taps - 1); +- let window = local.then_some(cfg.window); ++ let window: Option = None.filter(|_: &usize| local); + Ok(PassState { + keys: History::new(kv_width, window, max_seq)?, + values: History::new(kv_width, window, max_seq)?, diff --git a/tools/mutants/48-inkling-message-source.patch b/tools/mutants/48-inkling-message-source.patch index 58d78c6..06beebc 100644 --- a/tools/mutants/48-inkling-message-source.patch +++ b/tools/mutants/48-inkling-message-source.patch @@ -3,15 +3,15 @@ # weights-env: DLUTH_INKLING2_MINI # Bug: messages are blended from the wrong blocks of the previous pass. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index deeb305..0a5621f 100644 +index 306a8fc..335010b 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -464,7 +464,7 @@ impl<'w> InklingCpu<'w> { +@@ -777,7 +777,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + // this pass's messages. Then start again from the loop's entry. // The configuration check guarantees the loop starts on a block // boundary and is not empty, so that block exists. - let mut source: Vec<&[f32]> = -- blocks[start_blocks.len() + 1..].iter().map(Vec::as_slice).collect(); -+ blocks[start_blocks.len()..].iter().map(Vec::as_slice).collect(); +- let mut source: Vec<&O::V> = blocks[start_blocks.len() + 1..].iter().collect(); ++ let mut source: Vec<&O::V> = blocks[start_blocks.len()..].iter().collect(); source.push(&x); - message_source = Some(depthmix::normalize(&source, BLEND_EPS)); + message_source = Some(ops.normalize(&source)?); x = start_x.clone(); diff --git a/tools/mutants/49-inkling-block-boundary.patch b/tools/mutants/49-inkling-block-boundary.patch index 9a593a0..8ec7478 100644 --- a/tools/mutants/49-inkling-block-boundary.patch +++ b/tools/mutants/49-inkling-block-boundary.patch @@ -3,14 +3,15 @@ # weights-env: DLUTH_INKLING2_MINI # Bug: a layer that starts a block still adds the previous running sum. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 899fc4b..96d6cce 100644 +index 306a8fc..6b94aec 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -770,6 +770,7 @@ fn apply_layer( - let mut sum = a; - if layer.starts_block { - blocks.push(x.to_vec()); -+ add_into(&mut sum, x); +@@ -1095,7 +1095,7 @@ fn apply_layer( + // list and a new sum starts from this layer's attention output. + let sum = if layer.starts_block { + blocks.push(x.clone()); +- a ++ ops.add(&a, x)? } else { - add_into(&mut sum, x); - } + ops.add(&a, x)? + }; diff --git a/tools/mutants/51-inkling-output-cap.patch b/tools/mutants/51-inkling-output-cap.patch index b88804b..26bb2ab 100644 --- a/tools/mutants/51-inkling-output-cap.patch +++ b/tools/mutants/51-inkling-output-cap.patch @@ -3,12 +3,12 @@ # 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 8693fee..0a783b0 100644 +index 306a8fc..cd48873 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -592,7 +592,7 @@ impl<'w> InklingCpu<'w> { +@@ -464,7 +464,7 @@ impl Ops for CpuOps<'_> { let mut logits = vec![0.0f32; cfg.vocab_out]; - self.products.bf16(&self.unembed[..cfg.vocab_out * h * 2], cfg.vocab_out, h, &normed, &mut logits)?; + self.products.bf16(&unembed[..cfg.vocab_out * h * 2], cfg.vocab_out, h, x, &mut logits)?; for l in logits.iter_mut() { - *l = cpu::softcap(*l, cfg.logit_cap); + *l = l.clamp(-1e30, 1e30); From 4c2f6e1bafb23ba4fa4b712c5cf1fd7f47f02fb3 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:51:49 -0800 Subject: [PATCH 3/3] docs(model): the Ops trait states what a second implementation must do, and the order the convolutions rely on; review fixes --- crates/dluth-model/src/inkling/model.rs | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index 306a8fc..816fdef 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs @@ -223,7 +223,8 @@ pub enum KvConv<'w> { Dynamic { fixed_taps: Vec, token_proj: &'w [u8] }, } -/// A gate that merges a message from the previous pass into a sublayer's input. +/// A gate that merges a message from the previous pass into a sublayer's input. Built by +/// the model from checked weights, like `Layer`. pub struct Gate<'w> { pub down: &'w [u8], pub forget: &'w [u8], @@ -241,6 +242,10 @@ enum Port { /// One stored layer: its settings and where its weights are. Small weights are decoded /// to floats; large matrices stay as the slices of the weight file they are stored in. +/// +/// The model builds these from weights it has checked against the configuration. They are +/// public so that an `Ops` implementation can read them, not to be built by hand: the +/// operations index into them by the configuration's sizes without checking again. pub struct Layer<'w> { pub local: bool, /// Whether this layer starts a block of the blends across depth. @@ -284,10 +289,11 @@ pub struct Layer<'w> { /// implementation keeps them. /// /// The forward pass in this file is written once, in terms of these operations. The CPU -/// implementation, `CpuOps`, is the reference: each of its operations is a few calls into -/// `dluth-kernels`. Another implementation may keep its values on a device and compute -/// there; it is correct if each of its operations gives what `CpuOps` gives, and the golden -/// checks against the reference implementation run with either. +/// implementation, `CpuOps`, is the reference: its operations are this file's CPU functions +/// over `dluth-kernels`. Another implementation may keep its values on a device and compute +/// there. It is correct if each of its operations gives what `CpuOps` gives, and it must +/// pass the same golden checks against the reference implementation that the CPU model +/// passes. /// /// A value (`V`) is a vector of floats. A `Pass` is what one application of a layer /// remembers between tokens: the keys and values of the tokens it can still see and the @@ -329,9 +335,12 @@ pub trait Ops { inputs: [&Self::V; 3], pos: usize, ) -> Result; - /// The short convolution over the attention sublayer's recent outputs. + /// The short convolution over the attention sublayer's recent outputs. It reads the + /// outputs of the tokens before this one as `pass` holds them, and only then adds `x` to + /// them: the convolution adds the current token itself. fn attn_conv(&mut self, layer: &Layer, pass: &mut Self::Pass, x: &Self::V) -> Result; - /// The short convolution over the expert sublayer's recent outputs. + /// The short convolution over the expert sublayer's recent outputs, in the same order: + /// read the earlier tokens' outputs from `pass`, then add `x` to them. fn expert_conv(&mut self, layer: &Layer, pass: &mut Self::Pass, x: &Self::V) -> Result; /// `a + b`, element by element. fn add(&mut self, a: &Self::V, b: &Self::V) -> Result;