diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs index 79df46f..dec93f7 100644 --- a/crates/dluth-cuda/src/ops.rs +++ b/crates/dluth-cuda/src/ops.rs @@ -539,7 +539,33 @@ impl<'m> Ops for CudaOps<'m> { Ok(()) } - fn embed(&mut self, cfg: &InklingConfig, table: &[u8], norm: &[f32], token: u32) -> Result { + fn count(&self, _x: &DeviceVec) -> usize { + // One position at a time for now: see `embed`. + 1 + } + + fn row(&mut self, x: &DeviceVec, index: usize) -> Result { + if index != 0 { + return Err(ModelError::Capacity(format!("position {index} of a batch of 1"))); + } + Ok(x.clone()) + } + + fn embed( + &mut self, + cfg: &InklingConfig, + table: &[u8], + norm: &[f32], + tokens: &[u32], + ) -> Result { + // The device operations do not take batches yet. Refused here, where a batch enters + // the forward pass, before anything is computed. + let &[token] = tokens else { + return Err(ModelError::Capacity(format!( + "a batch of {} tokens: the device operations take one position at a time so far", + tokens.len() + ))); + }; // One row of the table, normalized on the host: 2,304 floats, once per token. let h = cfg.hidden; let row = &table[token as usize * h * 2..(token as usize + 1) * h * 2]; @@ -834,8 +860,20 @@ impl<'m> Ops for TimedOps<'m> { fn reset_pass(&mut self, pass: &mut DevicePass) -> Result<(), ModelError> { self.inner.reset_pass(pass) } - fn embed(&mut self, cfg: &InklingConfig, table: &[u8], norm: &[f32], token: u32) -> Result { - self.timed("embedding", |o| o.embed(cfg, table, norm, token)) + fn count(&self, x: &DeviceVec) -> usize { + self.inner.count(x) + } + fn row(&mut self, x: &DeviceVec, index: usize) -> Result { + self.inner.row(x, index) + } + fn embed( + &mut self, + cfg: &InklingConfig, + table: &[u8], + norm: &[f32], + tokens: &[u32], + ) -> Result { + self.timed("embedding", |o| o.embed(cfg, table, norm, tokens)) } fn normalize(&mut self, candidates: &[&DeviceVec]) -> Result { self.timed("blend: normalize", |o| o.normalize(candidates)) diff --git a/crates/dluth-cuda/tests/inkling_golden_cuda.rs b/crates/dluth-cuda/tests/inkling_golden_cuda.rs index f65de89..323d550 100644 --- a/crates/dluth-cuda/tests/inkling_golden_cuda.rs +++ b/crates/dluth-cuda/tests/inkling_golden_cuda.rs @@ -185,6 +185,27 @@ mod on_the_device { assert_eq!(dev.live_buffers(), before); } + /// Until the device operations take batches, a batch is refused before anything is + /// computed, and the model goes on as if it had not been asked. + #[test] + fn a_batch_is_refused_and_changes_nothing() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/tiny-inkling"); + let weights = Weights::open_dir(&dir).unwrap(); + let dev = CudaDevice::open(0).expect("GPU"); + let module = Module::load_embedded(&dev).unwrap(); + let ops = CudaOps::new(&dev, &module).unwrap(); + let mut gpu = Inkling::with_ops(load_config(&dir).unwrap(), &weights, 64, ops).unwrap(); + let ops = CudaOps::new(&dev, &module).unwrap(); + let mut fresh = Inkling::with_ops(load_config(&dir).unwrap(), &weights, 64, ops).unwrap(); + assert_eq!(gpu.forward_token(7, 0).unwrap(), fresh.forward_token(7, 0).unwrap()); + let e = gpu.forward_tokens(&[8, 9], 1).unwrap_err(); + assert!( + matches!(e, dluth_model::ModelError::Capacity(_)) && e.to_string().contains("one position at a time"), + "{e}" + ); + assert_eq!(gpu.forward_token(8, 1).unwrap(), fresh.forward_token(8, 1).unwrap()); + } + #[test] fn the_real_model_matches_the_reference() { let Ok(dir) = std::env::var("DLUTH_INKLING2_MINI") else { diff --git a/crates/dluth-model/src/inkling/mod.rs b/crates/dluth-model/src/inkling/mod.rs index 531caab..9e6d08a 100644 --- a/crates/dluth-model/src/inkling/mod.rs +++ b/crates/dluth-model/src/inkling/mod.rs @@ -6,6 +6,6 @@ pub mod prompt; pub use config::{load_config, model_kind, validate_weights, Checked, ExpertFormat, InklingConfig, ModelKind}; pub use model::{ - CpuBlend, CpuOps, CpuProducts, ExpertLayer, ExpertMatrices, Gate, Inkling, InklingCpu, KvConv, Layer, Ops, + CpuBlend, CpuOps, CpuProducts, CpuVecs, ExpertLayer, ExpertMatrices, Gate, Inkling, InklingCpu, KvConv, Layer, Ops, PassState, Products, BLEND_EPS, }; diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index 07445e5..061f305 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs @@ -295,9 +295,15 @@ pub struct Layer<'w> { /// 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 -/// recent inputs of its short convolutions. +/// A value (`V`) is a batch: one vector of floats for each of a few consecutive positions +/// of the sequence, in order. A token at a time is a batch of one. Every operation works on +/// each position of the batch; the ones that remember (`attention` and the two +/// convolutions) take the positions in order, so that a later position of the batch sees +/// the earlier ones exactly as it would if they had been fed before it. Feeding a +/// sequence in batches therefore computes what feeding it token by token computes. +/// +/// 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`). @@ -309,9 +315,16 @@ pub trait Ops { /// 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. + /// How many positions a value holds. + fn count(&self, x: &Self::V) -> usize; + /// The one position `index` of a batch, as a batch of one. + fn row(&mut self, x: &Self::V, index: usize) -> Result; + + /// Each token's row of the embedding table (BF16), normalized with the weights `norm`. + fn embed(&mut self, cfg: &InklingConfig, table: &[u8], norm: &[f32], tokens: &[u32]) + -> Result; + /// Normalizes each candidate (root-mean-square 1, position by position), ready to be + /// blended. All candidates hold the same positions. A list of no candidates is refused. 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; @@ -325,8 +338,9 @@ pub trait Ops { ) -> 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`. + /// Attention for the batch whose first token is at `pos`: `inputs` are the normalized + /// query, key and value inputs. Remembers each token's key and value in `pass`; a token + /// sees the tokens before it, those of its own batch included, and itself. fn attention( &mut self, cfg: &InklingConfig, @@ -346,8 +360,8 @@ pub trait Ops { 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. + /// The score of every real token of the vocabulary for each final hidden state in `x`, + /// soft-capped, as plain floats: one run of scores per position, one after another. fn scores(&mut self, cfg: &InklingConfig, unembed: &[u8], x: &Self::V) -> Result, ModelError>; } @@ -368,9 +382,29 @@ impl<'w> CpuOps<'w> { } } +/// A batch on the CPU: one vector per position. +#[derive(Clone)] +pub struct CpuVecs(Vec>); + +impl CpuVecs { + /// The vectors, one per position. + pub fn rows(&self) -> &[Vec] { + &self.0 + } +} + +/// Refuses two values of one operation that do not hold the same positions. +fn same_count(what: &str, a: &CpuVecs, b: &CpuVecs) -> Result<(), ModelError> { + if a.0.len() == b.0.len() { + Ok(()) + } else { + Err(ModelError::Capacity(format!("{what}: batches of {} and {} positions", a.0.len(), b.0.len()))) + } +} + impl Ops for CpuOps<'_> { - type V = Vec; - type Blend = CpuBlend; + type V = CpuVecs; + type Blend = Vec; type Pass = PassState; fn new_pass(&mut self, cfg: &InklingConfig, local: bool, max_seq: usize) -> Result { @@ -395,41 +429,85 @@ impl Ops for CpuOps<'_> { Ok(()) } - fn embed(&mut self, cfg: &InklingConfig, table: &[u8], norm: &[f32], token: u32) -> Result, ModelError> { + fn count(&self, x: &CpuVecs) -> usize { + x.0.len() + } + + fn row(&mut self, x: &CpuVecs, index: usize) -> Result { + match x.0.get(index) { + Some(row) => Ok(CpuVecs(vec![row.clone()])), + None => Err(ModelError::Capacity(format!("position {index} of a batch of {}", x.0.len()))), + } + } + + fn embed( + &mut self, + cfg: &InklingConfig, + table: &[u8], + norm: &[f32], + tokens: &[u32], + ) -> Result { 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) + let mut rows = Vec::with_capacity(tokens.len()); + for &token in tokens { + 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); + rows.push(x); + } + Ok(CpuVecs(rows)) } - 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 normalize(&mut self, candidates: &[&CpuVecs]) -> Result, ModelError> { + let Some(first) = candidates.first() else { + return Err(ModelError::Capacity("a blend of no candidates".into())); + }; + for candidate in candidates { + same_count("normalize", first, candidate)?; + } + let mut blends = Vec::with_capacity(first.0.len()); + for i in 0..first.0.len() { + let slices: Vec<&[f32]> = candidates.iter().map(|c| c.0[i].as_slice()).collect(); + let width = slices[0].len(); + blends.push(CpuBlend { data: depthmix::normalize(&slices, BLEND_EPS), width }); + } + Ok(blends) } - 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 mix(&mut self, blend: &Vec, query: &[f32]) -> Result { + let mut rows = Vec::with_capacity(blend.len()); + for one in blend { + let mut out = vec![0.0f32; one.width]; + depthmix::mix_normalized(query, &one.data, one.width, &mut out); + rows.push(out); + } + Ok(CpuVecs(rows)) } fn merge( &mut self, cfg: &InklingConfig, gate: &Gate, - x: &Vec, - message: &Vec, - ) -> Result, ModelError> { - merge(cfg, self.products.as_mut(), gate, x, message) + x: &CpuVecs, + message: &CpuVecs, + ) -> Result { + same_count("merge", x, message)?; + let mut rows = Vec::with_capacity(x.0.len()); + for (x, message) in x.0.iter().zip(&message.0) { + rows.push(merge(cfg, self.products.as_mut(), gate, x, message)?); + } + Ok(CpuVecs(rows)) } - 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 rmsnorm(&mut self, x: &CpuVecs, weights: &[f32], eps: f32) -> Result { + let mut rows = Vec::with_capacity(x.0.len()); + for x in &x.0 { + let mut out = vec![0.0f32; x.len()]; + cpu::rmsnorm(x, weights, eps, &mut out); + rows.push(out); + } + Ok(CpuVecs(rows)) } fn attention( @@ -437,45 +515,70 @@ impl Ops for CpuOps<'_> { cfg: &InklingConfig, layer: &Layer, pass: &mut PassState, - inputs: [&Vec; 3], + inputs: [&CpuVecs; 3], pos: usize, - ) -> Result, ModelError> { - attention(cfg, self.products.as_mut(), layer, pass, [inputs[0], inputs[1], inputs[2]], pos) + ) -> Result { + let [q, k, v] = inputs; + same_count("attention", q, k)?; + same_count("attention", q, v)?; + // In order: each token's key and value are remembered before the next token looks. + let mut rows = Vec::with_capacity(q.0.len()); + for i in 0..q.0.len() { + rows.push(attention(cfg, self.products.as_mut(), layer, pass, [&q.0[i], &k.0[i], &v.0[i]], pos + i)?); + } + Ok(CpuVecs(rows)) } - 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 attn_conv(&mut self, layer: &Layer, pass: &mut PassState, x: &CpuVecs) -> Result { + let mut rows = Vec::with_capacity(x.0.len()); + for x in &x.0 { + 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); + rows.push(out); + } + Ok(CpuVecs(rows)) } - 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 expert_conv(&mut self, layer: &Layer, pass: &mut PassState, x: &CpuVecs) -> Result { + let mut rows = Vec::with_capacity(x.0.len()); + for x in &x.0 { + 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); + rows.push(out); + } + Ok(CpuVecs(rows)) } - fn add(&mut self, a: &Vec, b: &Vec) -> Result, ModelError> { - let mut out = a.clone(); - add_into(&mut out, b); - Ok(out) + fn add(&mut self, a: &CpuVecs, b: &CpuVecs) -> Result { + same_count("add", a, b)?; + let mut rows = a.0.clone(); + for (row, b) in rows.iter_mut().zip(&b.0) { + add_into(row, b); + } + Ok(CpuVecs(rows)) } - fn experts(&mut self, cfg: &InklingConfig, layer: &Layer, x: &Vec) -> Result, ModelError> { - experts(cfg, self.products.as_mut(), layer, x) + fn experts(&mut self, cfg: &InklingConfig, layer: &Layer, x: &CpuVecs) -> Result { + let mut rows = Vec::with_capacity(x.0.len()); + for x in &x.0 { + rows.push(experts(cfg, self.products.as_mut(), layer, x)?); + } + Ok(CpuVecs(rows)) } - fn scores(&mut self, cfg: &InklingConfig, unembed: &[u8], x: &Vec) -> Result, ModelError> { + fn scores(&mut self, cfg: &InklingConfig, unembed: &[u8], x: &CpuVecs) -> 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); + let mut all = vec![0.0f32; x.0.len() * cfg.vocab_out]; + for (x, logits) in x.0.iter().zip(all.chunks_exact_mut(cfg.vocab_out)) { + self.products.bf16(&unembed[..cfg.vocab_out * h * 2], cfg.vocab_out, h, x, logits)?; + for l in logits.iter_mut() { + *l = cpu::softcap(*l, cfg.logit_cap); + } } - Ok(logits) + Ok(all) } } @@ -580,6 +683,8 @@ pub struct Inkling<'w, O: Ops> { max_seq: usize, /// How many tokens have been fed since the last reset. cached: usize, + /// How many tokens of a prompt `generate_greedy` feeds at once. + prompt_batch: usize, /// 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)>, @@ -720,6 +825,7 @@ impl<'w, O: Ops> Inkling<'w, O> { passes, max_seq, cached: 0, + prompt_batch: 1, last: None, ops, cfg, @@ -741,18 +847,23 @@ impl<'w, O: Ops> Inkling<'w, O> { 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> { - if token as usize >= self.cfg.vocab { + /// Runs a batch of consecutive tokens, the first at position `pos`, through every layer + /// application and leaves the last hidden states and block list for `logits`. + fn advance(&mut self, tokens: &[u32], pos: usize) -> Result<(), ModelError> { + if tokens.is_empty() { + return Err(ModelError::Capacity("an empty batch of tokens".into())); + } + if let Some(token) = tokens.iter().find(|t| **t 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 { + // The batch's last position must fit, checked before anything is computed. + if pos >= self.max_seq || tokens.len() > self.max_seq - pos { return Err(ModelError::Capacity(format!( - "position {pos} is outside the history of {} positions", + "position {} is outside the history of {} positions", + pos + tokens.len() - 1, self.max_seq ))); } @@ -767,8 +878,8 @@ impl<'w, O: Ops> Inkling<'w, O> { let (cfg, ops) = (&self.cfg, &mut self.ops); let h = cfg.hidden; - // Embedding: the token's row of the table, normalized. - let mut x = ops.embed(cfg, self.embed, &self.embed_norm, token)?; + // Embedding: each token's row of the table, normalized. + let mut x = ops.embed(cfg, self.embed, &self.embed_norm, tokens)?; let mut blocks: Vec = Vec::new(); // The state on entering the loop, which every pass starts from. @@ -811,29 +922,78 @@ impl<'w, O: Ops> Inkling<'w, O> { } self.last = Some((x, blocks)); - self.cached = pos + 1; + self.cached = pos + tokens.len(); Ok(()) } - /// Scores every real token of the vocabulary from the state `advance` left. - fn logits(&mut self) -> Result, ModelError> { + /// Scores every real token of the vocabulary from the state `advance` left: for every + /// position of the last batch, or only for its last position. + fn logits(&mut self, only_last: bool) -> Result, ModelError> { 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 count = ops.count(last); + let picked: Vec; + let mut candidates: Vec<&O::V> = if only_last && count > 1 { + // The output table is the largest matrix of the model; scoring positions nobody + // will read would cost a sweep of it each. + let mut rows = Vec::with_capacity(blocks.len() + 1); + for v in blocks.iter().chain(std::iter::once(last)) { + rows.push(ops.row(v, count - 1)?); + } + picked = rows; + picked.iter().collect() + } else { + blocks.iter().collect() + }; + if !(only_last && count > 1) { + 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) } + /// How many tokens of a prompt `generate_greedy` feeds at once (1 unless set). With + /// operations that take batches the result is the same for any value, and what changes + /// is how often the weights are read. An implementation of the operations may refuse + /// batches; generation then fails with that refusal for any value above 1. + pub fn set_prompt_batch(&mut self, tokens: usize) -> Result<(), ModelError> { + if tokens == 0 { + return Err(ModelError::Capacity("a prompt batch of no tokens".into())); + } + self.prompt_batch = tokens; + Ok(()) + } + + /// Feeds a batch of consecutive tokens, the first at position `pos`, and returns the + /// scores for the token after each of them: one run of scores per token, one after + /// another. Positions must be fed in order. Position 0 starts a new sequence. + /// + /// That is a vocabulary's worth of floats per token. For a long prompt, where only the + /// scores after its last token matter, use `feed` and then `next_scores`. + pub fn forward_tokens(&mut self, tokens: &[u32], pos: usize) -> Result, ModelError> { + self.advance(tokens, pos)?; + self.logits(false) + } + + /// Feeds a batch of consecutive tokens without scoring anything. + pub fn feed(&mut self, tokens: &[u32], pos: usize) -> Result<(), ModelError> { + self.advance(tokens, pos) + } + + /// The scores for the token after the last one fed. + pub fn next_scores(&mut self) -> Result, ModelError> { + self.logits(true) + } + /// 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)?; - self.logits() + self.advance(&[token], pos)?; + self.logits(false) } /// Greedy generation: feed the prompt, then repeatedly take the highest-scoring token. @@ -862,19 +1022,19 @@ impl<'w, O: Ops> Inkling<'w, O> { ))); } let mut pos = 0; - for &token in prompt_ids { - self.advance(token, pos)?; - pos += 1; + for batch in prompt_ids.chunks(self.prompt_batch) { + self.advance(batch, pos)?; + pos += batch.len(); } let mut generated = Vec::with_capacity(max_new); while generated.len() < max_new { - let next = argmax(&self.logits()?); + let next = argmax(&self.logits(true)?); generated.push(next); on_token(next); if next == eos || generated.len() == max_new { break; } - self.advance(next, pos)?; + self.advance(&[next], pos)?; pos += 1; } Ok(generated) diff --git a/crates/dluth-model/tests/inkling_batch.rs b/crates/dluth-model/tests/inkling_batch.rs new file mode 100644 index 0000000..a5ffcac --- /dev/null +++ b/crates/dluth-model/tests/inkling_batch.rs @@ -0,0 +1,138 @@ +//! Feeding a sequence in batches computes what feeding it token by token computes. +//! +//! On the CPU the two are the same arithmetic in the same order, so the scores must be +//! equal bit for bit. That equality is what "a batch" means for every other implementation +//! of the operations, which is held to it within its own rounding. + +use dluth_model::inkling::{load_config, InklingCpu}; +use dluth_model::weights::Weights; +use dluth_model::ModelError; +use std::path::{Path, PathBuf}; + +fn tiny() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/tiny-inkling") +} + +/// 40 tokens: longer than the tiny model's window (8), reach (12) and the position where +/// queries start to be scaled (16), and several times its loop. +fn tokens() -> Vec { + (0..40).map(|i| ((i * 37 + 11) % 256) as u32).collect() +} + +/// The scores after each token, fed one at a time. +fn one_at_a_time(model: &mut InklingCpu, tokens: &[u32]) -> Vec> { + tokens.iter().enumerate().map(|(pos, &t)| model.forward_token(t, pos).unwrap()).collect() +} + +#[test] +fn any_split_into_batches_gives_the_same_scores_bit_for_bit() { + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let cfg = load_config(&dir).unwrap(); + let vocab = cfg.vocab_out; + let tokens = tokens(); + let mut model = InklingCpu::new(cfg, &weights, 64).unwrap(); + let want = one_at_a_time(&mut model, &tokens); + + // The whole sequence at once; a first token alone; batches that end exactly on the + // window, straddle it, and are longer than it; many small ones. + let splits: [&[usize]; 6] = [&[40], &[1, 39], &[8, 8, 8, 8, 8], &[7, 2, 11, 20], &[3; 14], &[16, 1, 1, 22]]; + for split in splits { + let mut pos = 0; + for &n in split { + let n = n.min(tokens.len() - pos); + if n == 0 { + break; + } + let got = model.forward_tokens(&tokens[pos..pos + n], pos).unwrap(); + assert_eq!(got.len(), n * vocab); + for (i, scores) in got.chunks_exact(vocab).enumerate() { + assert!(scores == want[pos + i].as_slice(), "split {split:?}: position {} differs", pos + i); + } + pos += n; + } + assert_eq!(pos, tokens.len(), "split {split:?} covers the sequence"); + } +} + +#[test] +fn feeding_without_scoring_then_asking_gives_the_last_positions_scores() { + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let tokens = tokens(); + let mut model = InklingCpu::new(load_config(&dir).unwrap(), &weights, 64).unwrap(); + let want = one_at_a_time(&mut model, &tokens); + model.feed(&tokens[..9], 0).unwrap(); + assert!(model.next_scores().unwrap() == want[8]); + model.feed(&tokens[9..40], 9).unwrap(); + assert!(model.next_scores().unwrap() == want[39]); + // A batch of one is the old way of feeding. + model.feed(&tokens[..1], 0).unwrap(); + assert!(model.next_scores().unwrap() == want[0]); +} + +#[test] +fn generation_is_the_same_however_the_prompt_is_batched() { + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let prompt = &tokens()[..23]; + let mut model = InklingCpu::new(load_config(&dir).unwrap(), &weights, 64).unwrap(); + let want = model.generate_greedy(prompt, 12, u32::MAX).unwrap(); + for batch in [2, 5, 23, 100] { + model.set_prompt_batch(batch).unwrap(); + assert_eq!(model.generate_greedy(prompt, 12, u32::MAX).unwrap(), want, "prompt batch {batch}"); + } + assert!(matches!(model.set_prompt_batch(0), Err(ModelError::Capacity(_)))); +} + +#[test] +fn a_refused_batch_changes_nothing() { + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let tokens = tokens(); + let mut model = InklingCpu::new(load_config(&dir).unwrap(), &weights, 16).unwrap(); + let mut fresh = InklingCpu::new(load_config(&dir).unwrap(), &weights, 16).unwrap(); + let want = one_at_a_time(&mut fresh, &tokens[..16]); + + model.feed(&tokens[..10], 0).unwrap(); + let refused = |r: Result<(), ModelError>, what: &str| { + let e = r.unwrap_err(); + assert!(matches!(e, ModelError::Capacity(_)) && e.to_string().contains(what), "{e}"); + }; + // No tokens; a batch whose last position does not fit (its first would); a token that is + // not in the vocabulary, in the middle of a batch; a batch that does not follow on. + refused(model.feed(&[], 10), "empty"); + refused(model.feed(&tokens[10..17], 10), "outside the history"); + refused(model.feed(&[tokens[10], 9_999, tokens[12]], 10), "vocabulary"); + refused(model.feed(&tokens[11..13], 11), "out of order"); + // A refused batch at position 0, which would start a new sequence if it were accepted, + // must not forget the tokens fed so far. + refused(model.feed(&[tokens[0], 9_999], 0), "vocabulary"); + refused(model.feed(&tokens[..17], 0), "outside the history"); + // After all that, the sequence continues as if nothing had been asked. + let got = model.forward_tokens(&tokens[10..16], 10).unwrap(); + for (i, scores) in got.chunks_exact(want[0].len()).enumerate() { + assert!(scores == want[10 + i].as_slice(), "position {}", 10 + i); + } +} + +#[test] +fn the_real_model_scores_the_same_after_a_prompt_fed_at_once() { + let Ok(dir) = std::env::var("DLUTH_INKLING2_MINI") else { + eprintln!("skip: DLUTH_INKLING2_MINI not set"); + return; + }; + let dir = PathBuf::from(dir); + let golden: serde_json::Value = + serde_json::from_str(include_str!("../../../tests/fixtures/inkling2-mini-greedy.json")).unwrap(); + let prompt: Vec = serde_json::from_value(golden["cases"][0]["prompt_ids"].clone()).unwrap(); + let weights = Weights::open_dir(&dir).unwrap(); + let mut model = InklingCpu::new(load_config(&dir).unwrap(), &weights, 64).unwrap(); + let want = one_at_a_time(&mut model, &prompt).pop().unwrap(); + model.feed(&prompt, 0).unwrap(); + assert!(model.next_scores().unwrap() == want); + // And in two uneven batches. + model.feed(&prompt[..5], 0).unwrap(); + model.feed(&prompt[5..], 5).unwrap(); + assert!(model.next_scores().unwrap() == want); +} diff --git a/tools/mutants/51-inkling-output-cap.patch b/tools/mutants/51-inkling-output-cap.patch index 26bb2ab..8673dad 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 306a8fc..cd48873 100644 +index 149e860..3bef118 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -464,7 +464,7 @@ impl Ops for CpuOps<'_> { - 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); -+ *l = l.clamp(-1e30, 1e30); +@@ -575,7 +575,7 @@ impl Ops for CpuOps<'_> { + for (x, logits) in x.0.iter().zip(all.chunks_exact_mut(cfg.vocab_out)) { + self.products.bf16(&unembed[..cfg.vocab_out * h * 2], cfg.vocab_out, h, x, logits)?; + for l in logits.iter_mut() { +- *l = cpu::softcap(*l, cfg.logit_cap); ++ *l = l.clamp(-1e30, 1e30); + } } - Ok(logits) - } + Ok(all) diff --git a/tools/mutants/94-batch-one-position-for-all.patch b/tools/mutants/94-batch-one-position-for-all.patch new file mode 100644 index 0000000..ae13eae --- /dev/null +++ b/tools/mutants/94-batch-one-position-for-all.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-model --test inkling_batch any_split +# Bug: every token of a batch is given the position of the batch's first token in attention. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index 149e860..7535cfd 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -524,7 +524,7 @@ impl Ops for CpuOps<'_> { + // In order: each token's key and value are remembered before the next token looks. + let mut rows = Vec::with_capacity(q.0.len()); + for i in 0..q.0.len() { +- rows.push(attention(cfg, self.products.as_mut(), layer, pass, [&q.0[i], &k.0[i], &v.0[i]], pos + i)?); ++ rows.push(attention(cfg, self.products.as_mut(), layer, pass, [&q.0[i], &k.0[i], &v.0[i]], pos)?); + } + Ok(CpuVecs(rows)) + } diff --git a/tools/mutants/95-batch-scores-of-first.patch b/tools/mutants/95-batch-scores-of-first.patch new file mode 100644 index 0000000..bb2a722 --- /dev/null +++ b/tools/mutants/95-batch-scores-of-first.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-model --test inkling_batch feeding_without_scoring +# Bug: asked for the scores after the last token of a batch, the model scores its first. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index 149e860..dfca664 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -940,7 +940,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + // will read would cost a sweep of it each. + let mut rows = Vec::with_capacity(blocks.len() + 1); + for v in blocks.iter().chain(std::iter::once(last)) { +- rows.push(ops.row(v, count - 1)?); ++ rows.push(ops.row(v, 0)?); + } + picked = rows; + picked.iter().collect() diff --git a/tools/mutants/96-batch-counts-one-token.patch b/tools/mutants/96-batch-counts-one-token.patch new file mode 100644 index 0000000..3eff103 --- /dev/null +++ b/tools/mutants/96-batch-counts-one-token.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-model --test inkling_batch any_split +# Bug: after a batch the model believes only one token was fed. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index 149e860..003b686 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -922,7 +922,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + } + + self.last = Some((x, blocks)); +- self.cached = pos + tokens.len(); ++ self.cached = pos + 1; + Ok(()) + } + diff --git a/tools/mutants/97-batch-end-not-checked.patch b/tools/mutants/97-batch-end-not-checked.patch new file mode 100644 index 0000000..19e1efc --- /dev/null +++ b/tools/mutants/97-batch-end-not-checked.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-model --test inkling_batch a_refused_batch +# Bug: only the first position of a batch is checked against the room for the sequence. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index 149e860..e6e9493 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -860,7 +860,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + ))); + } + // The batch's last position must fit, checked before anything is computed. +- if pos >= self.max_seq || tokens.len() > self.max_seq - pos { ++ if pos >= self.max_seq { + return Err(ModelError::Capacity(format!( + "position {} is outside the history of {} positions", + pos + tokens.len() - 1,