From 6f8a952563f8d4b00898039aeb36e76ef8a87128 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:32:45 -0800 Subject: [PATCH 1/9] feat(model): the model's draft head on the CPU, as a drafter that reads the model's intermediate values --- crates/dluth-cuda/examples/generate.rs | 2 +- .../dluth-cuda/tests/inkling_golden_cuda.rs | 2 +- crates/dluth-model/src/inkling/draft.rs | 39 +- crates/dluth-model/src/inkling/mod.rs | 1 + crates/dluth-model/src/inkling/model.rs | 46 +- crates/dluth-model/src/inkling/mtp.rs | 444 ++++++++++++++++++ crates/dluth-model/tests/inkling_draft.rs | 7 +- crates/dluth-model/tests/inkling_mtp.rs | 260 ++++++++++ crates/dluth-serve/src/engine.rs | 2 +- 9 files changed, 790 insertions(+), 13 deletions(-) create mode 100644 crates/dluth-model/src/inkling/mtp.rs create mode 100644 crates/dluth-model/tests/inkling_mtp.rs diff --git a/crates/dluth-cuda/examples/generate.rs b/crates/dluth-cuda/examples/generate.rs index 2026aaa..88ecc6e 100644 --- a/crates/dluth-cuda/examples/generate.rs +++ b/crates/dluth-cuda/examples/generate.rs @@ -82,7 +82,7 @@ fn main() { let ops = CudaOps::new(&dev, &module).expect("the kernels"); let mut model = Inkling::with_ops(cfg, &weights, ids.len() + max_new, ops).expect("the model"); model.set_prompt_batch(16).expect("a prompt batch"); - let mut timed = |drafter: &mut dyn dluth_model::inkling::Drafter, most: usize| { + let mut timed = |drafter: &mut dyn dluth_model::inkling::Drafter, most: usize| { let mut first = None; let (tokens, stats) = model .generate_greedy_drafted(&ids, max_new, eos, drafter, most, |_| { diff --git a/crates/dluth-cuda/tests/inkling_golden_cuda.rs b/crates/dluth-cuda/tests/inkling_golden_cuda.rs index dd44fde..366313e 100644 --- a/crates/dluth-cuda/tests/inkling_golden_cuda.rs +++ b/crates/dluth-cuda/tests/inkling_golden_cuda.rs @@ -329,7 +329,7 @@ mod on_the_device { fn generation_with_guesses_gives_the_same_tokens_on_the_device() { use dluth_model::inkling::{Drafter, LookupDrafter}; struct Scripted(Vec, usize, usize); - impl Drafter for Scripted { + impl Drafter for Scripted { fn draft(&mut self, tokens: &[u32], most: usize) -> Vec { let done = tokens.len() - self.1; let wrong_every = self.2; diff --git a/crates/dluth-model/src/inkling/draft.rs b/crates/dluth-model/src/inkling/draft.rs index e952fe1..0a8c69c 100644 --- a/crates/dluth-model/src/inkling/draft.rs +++ b/crates/dluth-model/src/inkling/draft.rs @@ -8,17 +8,36 @@ //! produces; only the number of sweeps changes. A right guess is a token for a fraction of //! a sweep; a wrong guess costs the part of the sweep that was spent on it. -/// Something that guesses how a text goes on. -pub trait Drafter { +use crate::error::ModelError; + +/// Something that guesses how a text goes on. `V` is the type of the model's values (see +/// `Ops`), for a drafter that looks at what the model computed; one that only looks at the +/// text works with any. +pub trait Drafter { /// Up to `most` tokens that might follow `tokens` (the prompt and everything generated /// so far), most likely continuation first to last. No guess is an empty list. fn draft(&mut self, tokens: &[u32], most: usize) -> Vec; + + /// Which of the model's intermediate values the drafter wants to see: the running sum + /// after this many layer applications, for each number listed, in ascending order. + /// None by default. + fn wants(&self) -> Vec { + Vec::new() + } + + /// Called after every batch the model is fed, with the wanted values of that batch (one + /// per number in `wants`, each holding every position of the batch). `first` is the + /// position of the batch's first token (0 starts a new text) and `kept` how many of + /// its positions stay fed; the rest are guesses that were wrong and have been taken back. + fn fed(&mut self, _first: usize, _kept: usize, _states: &[V]) -> Result<(), ModelError> { + Ok(()) + } } /// Never guesses. pub struct NoDraft; -impl Drafter for NoDraft { +impl Drafter for NoDraft { fn draft(&mut self, _tokens: &[u32], _most: usize) -> Vec { Vec::new() } @@ -45,7 +64,7 @@ impl LookupDrafter { } } -impl Drafter for LookupDrafter { +impl Drafter for LookupDrafter { fn draft(&mut self, tokens: &[u32], most: usize) -> Vec { if most == 0 { return Vec::new(); @@ -82,10 +101,19 @@ pub struct DraftStats { mod tests { use super::*; + /// A drafter used for the text alone: no model values. + struct Text<'a, D: Drafter<()>>(&'a mut D); + impl> Text<'_, D> { + fn draft(&mut self, tokens: &[u32], most: usize) -> Vec { + self.0.draft(tokens, most) + } + } + #[test] fn lookup_proposes_what_followed_the_most_recent_longest_match() { let mut d = LookupDrafter::new(3, 1); // "1 2 3" appeared before, followed by 4 5. + let mut d = Text(&mut d); assert_eq!(d.draft(&[1, 2, 3, 4, 5, 9, 1, 2, 3], 2), [4, 5]); // The proposal stops at the end of the text, and is cut to `most`. assert_eq!(d.draft(&[1, 2, 3, 4, 5, 9, 1, 2, 3], 10), [4, 5, 9, 1, 2, 3]); @@ -101,12 +129,13 @@ mod tests { #[test] fn lookup_proposes_nothing_without_a_match_or_room() { let mut d = LookupDrafter::new(3, 2); + let mut d = Text(&mut d); assert!(d.draft(&[1, 2, 3, 4, 5], 4).is_empty()); // One matching token is below the shortest run asked for. assert!(d.draft(&[5, 1, 2, 5], 4).is_empty()); assert!(d.draft(&[1, 2, 9, 1, 2], 0).is_empty()); assert!(d.draft(&[], 4).is_empty()); assert!(d.draft(&[1], 4).is_empty()); - assert!(NoDraft.draft(&[1, 2, 1, 2], 4).is_empty()); + assert!(Text(&mut NoDraft).draft(&[1, 2, 1, 2], 4).is_empty()); } } diff --git a/crates/dluth-model/src/inkling/mod.rs b/crates/dluth-model/src/inkling/mod.rs index c3d3ee9..26a45f4 100644 --- a/crates/dluth-model/src/inkling/mod.rs +++ b/crates/dluth-model/src/inkling/mod.rs @@ -3,6 +3,7 @@ pub mod config; pub mod draft; pub mod model; +pub mod mtp; pub mod prompt; pub mod sample; diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index c2a194e..a5af02c 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs @@ -801,6 +801,10 @@ pub struct Inkling<'w, O: Ops> { prompt_batch: usize, /// How many positions of the last batch are still fed: all of them, or fewer after `undo`. kept: usize, + /// After how many layer applications the running sum is kept for a drafter, ascending. + taps: Vec, + /// The last batch's running sums at those points. + tapped: Vec, /// 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)>, @@ -943,6 +947,8 @@ impl<'w, O: Ops> Inkling<'w, O> { cached: 0, prompt_batch: 1, kept: 0, + taps: Vec::new(), + tapped: Vec::new(), last: None, ops, cfg, @@ -998,6 +1004,10 @@ impl<'w, O: Ops> Inkling<'w, O> { // Embedding: each token's row of the table, normalized. let mut x = ops.embed(cfg, self.embed, &self.embed_norm, tokens)?; + self.tapped.clear(); + if self.taps.first() == Some(&0) { + self.tapped.push(x.clone()); + } let mut blocks: Vec = Vec::new(); // The state on entering the loop, which every pass starts from. @@ -1035,6 +1045,9 @@ impl<'w, O: Ops> Inkling<'w, O> { }; let at = Arrival { pos, messages: messages.as_deref() }; x = apply_layer(cfg, ops, layer, &mut self.passes[index], &x, &mut blocks, at)?; + if self.taps.contains(&(index + 1)) { + self.tapped.push(x.clone()); + } } self.last = Some((x, blocks)); @@ -1134,6 +1147,28 @@ impl<'w, O: Ops> Inkling<'w, O> { Ok(()) } + /// Asks for the running sum after each of these numbers of layer applications to be + /// kept for every batch (see `tapped`), for a drafter that reads them. The numbers must + /// ascend and be at most the model's number of layer applications; an empty list keeps + /// nothing. + pub fn tap(&mut self, after: &[usize]) -> Result<(), ModelError> { + if after.windows(2).any(|w| w[0] >= w[1]) || after.last().is_some_and(|l| *l > self.steps.len()) { + return Err(ModelError::Capacity(format!( + "values after {after:?} layer applications were asked for; the numbers must ascend and the model has {}", + self.steps.len() + ))); + } + self.taps = after.to_vec(); + self.tapped.clear(); + Ok(()) + } + + /// The last batch's running sums at the points asked for with `tap`, in that order. + /// Each holds every position of the batch, those since undone too. + pub fn tapped(&self) -> &[O::V] { + &self.tapped + } + /// The position the next token fed must have. pub fn next_position(&self) -> usize { self.cached @@ -1217,7 +1252,7 @@ impl<'w, O: Ops> Inkling<'w, O> { prompt_ids: &[u32], max_new: usize, eos: u32, - drafter: &mut dyn Drafter, + drafter: &mut dyn Drafter, most: usize, mut on_token: impl FnMut(u32), ) -> Result<(Vec, DraftStats), ModelError> { @@ -1233,8 +1268,10 @@ impl<'w, O: Ops> Inkling<'w, O> { } let mut pos = 0; if max_new > 0 { + self.tap(&drafter.wants())?; for batch in prompt_ids.chunks(self.prompt_batch) { self.advance(batch, pos)?; + drafter.fed(pos, batch.len(), &self.tapped)?; pos += batch.len(); } } @@ -1257,6 +1294,10 @@ impl<'w, O: Ops> Inkling<'w, O> { /// given each token the moment it is chosen and returns false to stop there. Generation /// also stops after `eos` (which is reported and appended). /// + /// The drafter is told of every batch fed here. If it wants values of the model (see + /// `Drafter::wants`), the caller must have asked for them with `tap` and told it of the + /// batches fed before, or it will have nothing to guess from. + /// /// On return the model has been fed all of `text` except its last token, unless nothing /// was generated. #[allow(clippy::too_many_arguments)] @@ -1265,7 +1306,7 @@ impl<'w, O: Ops> Inkling<'w, O> { text: &mut Vec, max_new: usize, eos: u32, - drafter: &mut dyn Drafter, + drafter: &mut dyn Drafter, most: usize, pick: &mut dyn FnMut(&[f32]) -> u32, on_token: &mut dyn FnMut(u32) -> bool, @@ -1332,6 +1373,7 @@ impl<'w, O: Ops> Inkling<'w, O> { return Err(ModelError::Device("a sweep returned no scores".into())); } stats.accepted += kept - 1; + drafter.fed(pos, kept, &self.tapped)?; self.undo(batch.len() - kept)?; pos += kept; } diff --git a/crates/dluth-model/src/inkling/mtp.rs b/crates/dluth-model/src/inkling/mtp.rs new file mode 100644 index 0000000..cc5303f --- /dev/null +++ b/crates/dluth-model/src/inkling/mtp.rs @@ -0,0 +1,444 @@ +//! The draft head that ships with Inkling 2 (`mtp.safetensors`), on the CPU: a small +//! network beside the model that guesses the next few tokens, for the model to check in +//! one sweep (see `draft`). +//! +//! What it computes was worked out from the two public papers its design follows (DFlare, +//! arXiv 2606.02091; DSpark, arXiv 2607.05147) and, where they leave this checkpoint's +//! details open, by measurement: of the possible readings, the one whose guesses the model +//! accepts. A wrong reading could only guess badly; every guess is checked by the model. +//! +//! In short. The model has read the text up to position t - 1 and chosen the token for +//! position t (the anchor). The head is given a block: the anchor's embedding, then +//! placeholders for the positions after it. Three layers of attention and feed-forward +//! refine the block; in attention, the block's positions also look at every earlier +//! position of the text, through a mix of four of the model's own intermediate values +//! there. That gives every placeholder a hidden state, all at once. Then a small recurrent +//! step goes left to right: from its state, the token just guessed and the placeholder's +//! hidden state it makes a correction to that hidden state, and the next token is the +//! best-scoring one for the corrected state under the model's own output table. + +use super::draft::Drafter; +use super::model::CpuVecs; +use crate::error::ModelError; +use crate::safetensors::SafetensorsFile; +use dluth_core::bf16_to_f32; +use dluth_kernels::cpu; +use std::path::Path; + +/// The head's shape, from `mtp_config` in the model's `config.json`. +#[derive(Clone, Debug, PartialEq)] +pub struct MtpConfig { + pub hidden: usize, + pub layers: usize, + pub heads: usize, + pub kv_heads: usize, + pub head_dim: usize, + pub inner: usize, + /// The base of the rotary position encoding. + pub theta: f32, + pub eps: f32, + /// Positions in a block: the anchor and the placeholders after it. + pub block: usize, + /// The width of the recurrent step's state and of a token's vector in it. + pub rank: usize, + /// After how many of the model's layer applications each of the mixed values is taken. + pub targets: Vec, +} + +/// Reads `mtp_config`. None if the model has no draft head. +pub fn load_mtp_config(dir: &Path) -> Result, ModelError> { + let path = dir.join("config.json"); + let text = std::fs::read_to_string(&path).map_err(|e| ModelError::io(&path, e))?; + let root: serde_json::Value = + serde_json::from_str(&text).map_err(|e| ModelError::Format(format!("{}: {e}", path.display())))?; + let Some(c) = root.get("mtp_config").filter(|c| c.is_object()) else { + return Ok(None); + }; + let count = |name: &str| -> Result { + c.get(name) + .and_then(serde_json::Value::as_u64) + .and_then(|n| usize::try_from(n).ok()) + .filter(|n| *n > 0) + .ok_or_else(|| ModelError::Format(format!("mtp_config.{name} is missing or not a positive number"))) + }; + let real = |name: &str| -> Result { + c.get(name) + .and_then(serde_json::Value::as_f64) + .map(|f| f as f32) + .filter(|f| f.is_finite() && *f > 0.0) + .ok_or_else(|| ModelError::Format(format!("mtp_config.{name} is missing or not a positive number"))) + }; + let kind = c.get("markov_head_type").and_then(serde_json::Value::as_str).unwrap_or(""); + if kind != "rnn_hidden" { + return Err(ModelError::Unsupported(format!("a draft head whose sequential step is of type {kind:?}"))); + } + let targets: Vec = c + .get("target_layer_ids") + .and_then(serde_json::Value::as_array) + .map(|ids| ids.iter().filter_map(|v| v.as_u64().map(|n| n as usize)).collect()) + .unwrap_or_default(); + let cfg = MtpConfig { + hidden: count("hidden_size")?, + layers: count("num_hidden_layers")?, + heads: count("num_attention_heads")?, + kv_heads: count("num_key_value_heads")?, + head_dim: count("head_dim")?, + inner: count("intermediate_size")?, + theta: real("rope_theta")?, + eps: real("rms_norm_eps")?, + block: count("block_size")?, + rank: count("markov_rank")?, + targets, + }; + if cfg.targets.is_empty() || cfg.targets.windows(2).any(|w| w[0] >= w[1]) { + return Err(ModelError::Format(format!("mtp_config.target_layer_ids {:?} must ascend", cfg.targets))); + } + if !cfg.heads.is_multiple_of(cfg.kv_heads) || !cfg.head_dim.is_multiple_of(2) || cfg.block < 2 { + return Err(ModelError::Format("mtp_config: heads, head size or block size do not fit together".into())); + } + Ok(Some(cfg)) +} + +fn floats(bytes: &[u8]) -> Vec { + bytes.as_chunks::<2>().0.iter().map(|c| bf16_to_f32(u16::from_le_bytes(*c))).collect() +} + +/// `w` (rows by cols, row after row) times `x`. +fn matvec(w: &[f32], rows: usize, cols: usize, x: &[f32]) -> Vec { + debug_assert_eq!((w.len(), x.len()), (rows * cols, cols)); + w.chunks_exact(cols).map(|row| row.iter().zip(x).map(|(a, b)| a * b).sum()).collect() +} + +fn rms(x: &[f32], w: &[f32], eps: f32) -> Vec { + let mut out = vec![0.0; x.len()]; + cpu::rmsnorm(x, w, eps, &mut out); + out +} + +struct Layer { + input_norm: Vec, + post_norm: Vec, + /// Normalizes this layer's mix of the model's values. + context_norm: Vec, + q: Vec, + k: Vec, + v: Vec, + o: Vec, + /// Keys and values of the context have projections of their own. + k_context: Vec, + v_context: Vec, + q_norm: Vec, + k_norm: Vec, + k_norm_context: Vec, + gate: Vec, + up: Vec, + down: Vec, +} + +/// The head's weights, as 32-bit floats. +pub struct MtpHead { + cfg: MtpConfig, + /// For each layer and for the recurrent step: how much of each target value goes into + /// its mix (a softmax over a row of the stored weights). + mixes: Vec>, + mask: Vec, + layers: Vec, + norm: Vec, + /// One vector of `rank` per token, BF16 as stored. + token_vectors: Vec, + step: Vec, + step_bias: Vec, + step_out: Vec, + step_out_bias: Vec, + step_norm: Vec, +} + +impl MtpHead { + /// Loads `mtp.safetensors` from a model directory and checks every shape against `cfg`. + pub fn load(dir: &Path, cfg: MtpConfig) -> Result { + let file = SafetensorsFile::open(&dir.join("mtp.safetensors"))?; + let (h, kv, q, inner, d, r) = + (cfg.hidden, cfg.kv_heads * cfg.head_dim, cfg.heads * cfg.head_dim, cfg.inner, cfg.head_dim, cfg.rank); + let get = |name: &str, len: usize| -> Result, ModelError> { + let bytes = file.bytes(name)?; + if bytes.len() != len * 2 { + return Err(ModelError::Format(format!( + "draft head: {name} holds {} values where {len} are expected", + bytes.len() / 2 + ))); + } + Ok(floats(bytes)) + }; + let rows = cfg.layers + 1; + let stored = get("fuse_weight", rows * cfg.targets.len())?; + let mixes = stored + .chunks_exact(cfg.targets.len()) + .map(|row| { + let mut weights = row.to_vec(); + cpu::softmax_inplace(&mut weights); + weights + }) + .collect(); + let mut layers = Vec::with_capacity(cfg.layers); + for i in 0..cfg.layers { + let p = format!("layers.{i}"); + layers.push(Layer { + input_norm: get(&format!("{p}.input_layernorm.weight"), h)?, + post_norm: get(&format!("{p}.post_attention_layernorm.weight"), h)?, + context_norm: get(&format!("{p}.dflare_norm.weight"), h)?, + q: get(&format!("{p}.self_attn.q_proj.weight"), q * h)?, + k: get(&format!("{p}.self_attn.k_proj.weight"), kv * h)?, + v: get(&format!("{p}.self_attn.v_proj.weight"), kv * h)?, + o: get(&format!("{p}.self_attn.o_proj.weight"), h * q)?, + k_context: get(&format!("{p}.self_attn.k_proj_ctx.weight"), kv * h)?, + v_context: get(&format!("{p}.self_attn.v_proj_ctx.weight"), kv * h)?, + q_norm: get(&format!("{p}.self_attn.q_norm.weight"), d)?, + k_norm: get(&format!("{p}.self_attn.k_norm.weight"), d)?, + k_norm_context: get(&format!("{p}.self_attn.k_norm_ctx.weight"), d)?, + gate: get(&format!("{p}.mlp.gate_proj.weight"), inner * h)?, + up: get(&format!("{p}.mlp.up_proj.weight"), inner * h)?, + down: get(&format!("{p}.mlp.down_proj.weight"), h * inner)?, + }); + } + let token_vectors = file.bytes("markov_head.markov_w1.weight")?.to_vec(); + if token_vectors.is_empty() || !token_vectors.len().is_multiple_of(r * 2) { + return Err(ModelError::Format("draft head: the token vectors are not whole rows".into())); + } + Ok(MtpHead { + mixes, + mask: get("mask_embed", h)?, + layers, + norm: get("norm.weight", h)?, + token_vectors, + step: get("markov_head.rnn_proj.weight", 3 * r * (2 * r + 2 * h))?, + step_bias: get("markov_head.rnn_proj.bias", 3 * r)?, + step_out: get("markov_head.hidden_out.weight", h * r)?, + step_out_bias: get("markov_head.hidden_out.bias", h)?, + step_norm: get("markov_head.dflare_norm.weight", h)?, + cfg, + }) + } + + pub fn config(&self) -> &MtpConfig { + &self.cfg + } + + /// Per-head normalization with learned weights, then rotation by position. + fn head_norm_rope(&self, x: &mut [f32], heads: usize, w: &[f32], pos: usize) { + for head in x.chunks_exact_mut(self.cfg.head_dim) { + let normed = rms(head, w, self.cfg.eps); + head.copy_from_slice(&normed); + } + cpu::rope_inplace(x, heads, self.cfg.head_dim, pos, self.cfg.theta); + } + + /// The mix of the target values at one position for `row` (a layer, or the recurrent + /// step as the last row), normalized with `norm`. + fn mixed(&self, row: usize, norm: &[f32], targets: &[&[f32]]) -> Vec { + let mut mixed = vec![0.0f32; self.cfg.hidden]; + for (weight, value) in self.mixes[row].iter().zip(targets) { + for (m, v) in mixed.iter_mut().zip(*value) { + *m += weight * v; + } + } + rms(&mixed, norm, self.cfg.eps) + } +} + +/// What the head keeps of the text read so far: for each layer, a key and a value per +/// position; and the recurrent step's mix per position. +#[derive(Default)] +struct Context { + keys: Vec>, + values: Vec>, + step: Vec, + positions: usize, +} + +/// The head as a drafter for the CPU model. +pub struct MtpDrafter<'a> { + head: &'a MtpHead, + /// The model's embedding table (BF16) and the weights of its embedding norm. + embed: &'a [u8], + embed_norm: Vec, + /// The model's output table (BF16), its real tokens only. + unembed: &'a [u8], + vocab_out: usize, + context: Context, +} + +impl<'a> MtpDrafter<'a> { + /// `embed` and `unembed` are the model's tables as stored; `embed_norm` the weights of + /// its embedding norm; `vocab_out` how many rows of the output table are tokens. + pub fn new( + head: &'a MtpHead, + embed: &'a [u8], + embed_norm: Vec, + unembed: &'a [u8], + vocab_out: usize, + ) -> Result { + let h = head.cfg.hidden; + if embed_norm.len() != h || unembed.len() < vocab_out * h * 2 || !embed.len().is_multiple_of(h * 2) { + return Err(ModelError::Format("draft head: the model's tables do not have the head's width".into())); + } + let layers = head.cfg.layers; + let context = + Context { keys: vec![Vec::new(); layers], values: vec![Vec::new(); layers], ..Context::default() }; + Ok(MtpDrafter { head, embed, embed_norm, unembed: &unembed[..vocab_out * h * 2], vocab_out, context }) + } + + /// The hidden state of each block position after the head's layers and final norm, for + /// the anchor `token` at position `t`, with the text before it as context. + fn block(&self, token: u32, t: usize, positions: usize) -> Vec> { + let (head, cfg) = (self.head, &self.head.cfg); + let (h, d, heads, kv) = (cfg.hidden, cfg.head_dim, cfg.heads, cfg.kv_heads); + let width = kv * d; + let row = &self.embed[token as usize * h * 2..(token as usize + 1) * h * 2]; + let anchor = rms(&floats(row), &self.embed_norm, cfg.eps); + let mut z: Vec> = + (0..positions).map(|k| if k == 0 { anchor.clone() } else { head.mask.clone() }).collect(); + let scale = 1.0 / (d as f32).sqrt(); + for (index, layer) in head.layers.iter().enumerate() { + let (context_keys, context_values) = (&self.context.keys[index], &self.context.values[index]); + let normed: Vec> = z.iter().map(|x| rms(x, &layer.input_norm, cfg.eps)).collect(); + let (mut queries, mut keys, mut values) = (Vec::new(), Vec::new(), Vec::new()); + for (k, x) in normed.iter().enumerate() { + let mut q = matvec(&layer.q, heads * d, h, x); + head.head_norm_rope(&mut q, heads, &layer.q_norm, t + k); + let mut key = matvec(&layer.k, width, h, x); + head.head_norm_rope(&mut key, kv, &layer.k_norm, t + k); + queries.push(q); + keys.push(key); + values.push(matvec(&layer.v, width, h, x)); + } + for k in 0..positions { + let mut attended = vec![0.0f32; heads * d]; + for head_index in 0..heads { + let group = head_index / (heads / kv); + let q = &queries[k][head_index * d..(head_index + 1) * d]; + let dot = |key: &[f32]| q.iter().zip(key).map(|(a, b)| a * b).sum::() * scale; + // Every position of the text before the anchor, then the whole block: + // a placeholder sees the placeholders after it too. + let mut scores: Vec = context_keys + .chunks_exact(width) + .take(t) + .map(|key| dot(&key[group * d..(group + 1) * d])) + .collect(); + scores.extend(keys.iter().map(|key| dot(&key[group * d..(group + 1) * d]))); + cpu::softmax_inplace(&mut scores); + let out = &mut attended[head_index * d..(head_index + 1) * d]; + let all_values = context_values.chunks_exact(width).take(t).chain(values.iter().map(Vec::as_slice)); + for (weight, value) in scores.iter().zip(all_values) { + for (o, v) in out.iter_mut().zip(&value[group * d..(group + 1) * d]) { + *o += weight * v; + } + } + } + let a = matvec(&layer.o, h, heads * d, &attended); + z[k].iter_mut().zip(&a).for_each(|(x, a)| *x += a); + } + for x in z.iter_mut() { + let m = rms(x, &layer.post_norm, cfg.eps); + let (gate, up) = (matvec(&layer.gate, cfg.inner, h, &m), matvec(&layer.up, cfg.inner, h, &m)); + let mut act = vec![0.0f32; cfg.inner]; + cpu::silu_mul(&gate, &up, &mut act); + let y = matvec(&layer.down, h, cfg.inner, &act); + x.iter_mut().zip(&y).for_each(|(x, y)| *x += y); + } + } + z.iter().map(|x| rms(x, &head.norm, cfg.eps)).collect() + } +} + +impl Drafter for MtpDrafter<'_> { + fn wants(&self) -> Vec { + self.head.cfg.targets.clone() + } + + fn fed(&mut self, first: usize, kept: usize, states: &[CpuVecs]) -> Result<(), ModelError> { + let (head, cfg) = (self.head, &self.head.cfg); + if first == 0 { + let layers = cfg.layers; + self.context = + Context { keys: vec![Vec::new(); layers], values: vec![Vec::new(); layers], ..Context::default() }; + } + if states.len() != cfg.targets.len() || first != self.context.positions { + return Err(ModelError::Capacity(format!( + "draft head: told of position {first} with {} values; it has read {} positions and wants {} values", + states.len(), + self.context.positions, + cfg.targets.len() + ))); + } + let (h, d, kv) = (cfg.hidden, cfg.head_dim, cfg.kv_heads); + for b in 0..kept { + let targets: Vec<&[f32]> = states.iter().map(|s| &s.rows()[b][..]).collect(); + if targets.iter().any(|t| t.len() != h) { + return Err(ModelError::Capacity("draft head: the model's values do not have its width".into())); + } + let pos = self.context.positions; + for (index, layer) in head.layers.iter().enumerate() { + let mixed = head.mixed(index, &layer.context_norm, &targets); + let mut key = matvec(&layer.k_context, kv * d, h, &mixed); + head.head_norm_rope(&mut key, kv, &layer.k_norm_context, pos); + self.context.keys[index].extend(key); + self.context.values[index].extend(matvec(&layer.v_context, kv * d, h, &mixed)); + } + self.context.step.extend(head.mixed(cfg.layers, &head.step_norm, &targets)); + self.context.positions += 1; + } + Ok(()) + } + + fn draft(&mut self, tokens: &[u32], most: usize) -> Vec { + let (head, cfg) = (self.head, &self.head.cfg); + let (h, r) = (cfg.hidden, cfg.rank); + // The anchor is the last token, which the model has chosen and not read yet: the + // head must have been told of exactly the positions before it, and at least one. + let Some((&anchor, before)) = tokens.split_last() else { + return Vec::new(); + }; + let t = before.len(); + let room = most.min(cfg.block - 1); + let known = head.token_vectors.len() / (r * 2); + if room == 0 || t == 0 || t != self.context.positions || (anchor as usize + 1) * h * 2 > self.embed.len() { + return Vec::new(); + } + let hidden = self.block(anchor, t, room + 1); + let other = &self.context.step[(t - 1) * h..t * h]; + let mut state = vec![0.0f32; r]; + let mut previous = anchor as usize; + let mut guesses = Vec::with_capacity(room); + let mut scores = vec![0.0f32; self.vocab_out]; + for at in hidden.iter().skip(1) { + if previous >= known { + break; + } + let vector = floats(&head.token_vectors[previous * r * 2..(previous + 1) * r * 2]); + let input: Vec = state.iter().chain(&vector).chain(at).chain(other).copied().collect(); + let mut out = matvec(&head.step, 3 * r, 2 * r + 2 * h, &input); + out.iter_mut().zip(&head.step_bias).for_each(|(o, b)| *o += b); + // The three thirds: how much of the old state to keep, what to put in its + // place, and what to say about this position. + for i in 0..r { + let keep = cpu::sigmoid(out[i]); + state[i] = keep * state[i] + (1.0 - keep) * out[r + i].tanh(); + } + let said: Vec = out[2 * r..].iter().map(|o| o.tanh()).collect(); + let mut corrected = matvec(&head.step_out, h, r, &said); + for ((c, bias), base) in corrected.iter_mut().zip(&head.step_out_bias).zip(at) { + *c += bias + base; + } + cpu::matvec_bf16(self.unembed, self.vocab_out, h, &corrected, &mut scores); + let mut best = 0; + for (i, s) in scores.iter().enumerate() { + if *s > scores[best] { + best = i; + } + } + guesses.push(best as u32); + previous = best; + } + guesses + } +} diff --git a/crates/dluth-model/tests/inkling_draft.rs b/crates/dluth-model/tests/inkling_draft.rs index 191bc23..07ff0cd 100644 --- a/crates/dluth-model/tests/inkling_draft.rs +++ b/crates/dluth-model/tests/inkling_draft.rs @@ -2,6 +2,7 @@ //! exactly as if they had never been fed, and generation with guesses produces exactly the //! tokens generation without them produces, whatever the guesses are. +use dluth_model::inkling::CpuVecs; use dluth_model::inkling::{load_config, DraftStats, Drafter, InklingCpu, LookupDrafter, NoDraft, MAX_DRAFT, MAX_UNDO}; use dluth_model::weights::Weights; use dluth_model::ModelError; @@ -140,7 +141,7 @@ struct Scripted { guesses: usize, } -impl Drafter for Scripted { +impl Drafter for Scripted { fn draft(&mut self, tokens: &[u32], most: usize) -> Vec { self.asked += 1; let done = tokens.len() - self.prompt; @@ -156,7 +157,7 @@ impl Drafter for Scripted { /// Guesses more than it was asked for, and tokens that do not exist. struct Unruly; -impl Drafter for Unruly { +impl Drafter for Unruly { fn draft(&mut self, tokens: &[u32], most: usize) -> Vec { let mut out = vec![tokens[tokens.len() - 1]; most + 5]; out[1] = 4_000_000; @@ -173,7 +174,7 @@ fn generation_with_guesses_gives_the_tokens_of_generation_without() { let mut model = InklingCpu::new(load_config(&dir).unwrap(), &weights, 64).unwrap(); let want = model.generate_greedy(prompt, max_new, u32::MAX).unwrap(); assert_eq!(want.len(), max_new); - let mut drafted = |drafter: &mut dyn Drafter, most: usize| -> DraftStats { + let mut drafted = |drafter: &mut dyn Drafter, most: usize| -> DraftStats { let mut seen = Vec::new(); let (got, stats) = model.generate_greedy_drafted(prompt, max_new, u32::MAX, drafter, most, |t| seen.push(t)).unwrap(); diff --git a/crates/dluth-model/tests/inkling_mtp.rs b/crates/dluth-model/tests/inkling_mtp.rs new file mode 100644 index 0000000..7f9835c --- /dev/null +++ b/crates/dluth-model/tests/inkling_mtp.rs @@ -0,0 +1,260 @@ +//! The draft head as a guesser. On the tiny model with a head of random weights the +//! guesses are worthless, which is the point: whatever the head proposes, the text must be +//! the text of plain generation. On the real model with its real head (when the weights +//! are at hand) the guesses must be good. + +use dluth_model::inkling::mtp::{load_mtp_config, MtpConfig, MtpDrafter, MtpHead}; +use dluth_model::inkling::{load_config, CpuVecs, Drafter, 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") +} + +/// A directory under the system's temporary one, removed when dropped. +struct Scratch(PathBuf); +impl Scratch { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("dluth-mtp-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } +} +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn tiny_config(hidden: usize, applications: usize) -> MtpConfig { + MtpConfig { + hidden, + layers: 2, + heads: 4, + kv_heads: 2, + head_dim: 4, + inner: 24, + theta: 10_000.0, + eps: 1e-6, + block: 4, + rank: 6, + targets: vec![1, 3, applications], + } +} + +/// The head's tensors for `cfg`, with fixed pseudo-random BF16 values, as a safetensors +/// file. `skip` leaves one tensor out and `short` gives one a value too few. +fn write_head(dir: &Path, cfg: &MtpConfig, vocab: usize, skip: Option<&str>, short: Option<&str>) { + let (h, q, kv, d, r) = (cfg.hidden, cfg.heads * cfg.head_dim, cfg.kv_heads * cfg.head_dim, cfg.head_dim, cfg.rank); + let mut tensors: Vec<(String, Vec)> = vec![ + ("fuse_weight".into(), vec![cfg.layers + 1, cfg.targets.len()]), + ("mask_embed".into(), vec![h]), + ("norm.weight".into(), vec![h]), + ("markov_head.markov_w1.weight".into(), vec![vocab, r]), + ("markov_head.rnn_proj.weight".into(), vec![3 * r, 2 * r + 2 * h]), + ("markov_head.rnn_proj.bias".into(), vec![3 * r]), + ("markov_head.hidden_out.weight".into(), vec![h, r]), + ("markov_head.hidden_out.bias".into(), vec![h]), + ("markov_head.dflare_norm.weight".into(), vec![h]), + ]; + for i in 0..cfg.layers { + for (name, shape) in [ + ("input_layernorm.weight", vec![h]), + ("post_attention_layernorm.weight", vec![h]), + ("dflare_norm.weight", vec![h]), + ("self_attn.q_proj.weight", vec![q, h]), + ("self_attn.k_proj.weight", vec![kv, h]), + ("self_attn.v_proj.weight", vec![kv, h]), + ("self_attn.o_proj.weight", vec![h, q]), + ("self_attn.k_proj_ctx.weight", vec![kv, h]), + ("self_attn.v_proj_ctx.weight", vec![kv, h]), + ("self_attn.q_norm.weight", vec![d]), + ("self_attn.k_norm.weight", vec![d]), + ("self_attn.k_norm_ctx.weight", vec![d]), + ("mlp.gate_proj.weight", vec![cfg.inner, h]), + ("mlp.up_proj.weight", vec![cfg.inner, h]), + ("mlp.down_proj.weight", vec![h, cfg.inner]), + ] { + tensors.push((format!("layers.{i}.{name}"), shape)); + } + } + let mut header = serde_json::Map::new(); + let mut data: Vec = Vec::new(); + let mut seed = 0x2545_F491_4F6C_DD1Du64; + for (name, mut shape) in tensors { + if skip == Some(name.as_str()) { + continue; + } + if short == Some(name.as_str()) { + *shape.last_mut().unwrap() -= 1; + } + let count: usize = shape.iter().product(); + let start = data.len(); + for _ in 0..count { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + // A value in [-0.5, 0.5), norm weights around 1; as BF16, the top half of the float. + let unit = (seed >> 40) as f32 / (1u64 << 24) as f32 - 0.5; + let value = if name.ends_with("norm.weight") || name.ends_with("norm_ctx.weight") { + 1.0 + unit * 0.2 + } else { + unit + }; + data.extend_from_slice(&((value.to_bits() >> 16) as u16).to_le_bytes()); + } + header.insert(name, serde_json::json!({"dtype": "BF16", "shape": shape, "data_offsets": [start, data.len()]})); + } + let header = serde_json::Value::Object(header).to_string(); + let mut bytes = (header.len() as u64).to_le_bytes().to_vec(); + bytes.extend_from_slice(header.as_bytes()); + bytes.extend_from_slice(&data); + std::fs::write(dir.join("mtp.safetensors"), bytes).unwrap(); +} + +fn prompt() -> Vec { + (41..64).map(|i| ((i * 37 + 11) % 256) as u32).collect() +} + +#[test] +fn whatever_the_head_proposes_the_text_is_that_of_plain_generation() { + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let cfg = load_config(&dir).unwrap(); + let scratch = Scratch::new("generate"); + let head_cfg = tiny_config(cfg.hidden, cfg.layer_passes()); + write_head(&scratch.0, &head_cfg, cfg.vocab, None, None); + let head = MtpHead::load(&scratch.0, head_cfg.clone()).unwrap(); + let embed = weights.bytes("model.llm.embed.weight").unwrap(); + let unembed = weights.bytes("model.llm.unembed.weight").unwrap(); + let embed_norm: Vec = weights + .bytes("model.llm.embed_norm.weight") + .unwrap() + .as_chunks::<2>() + .0 + .iter() + .map(|c| f32::from_bits((u16::from_le_bytes(*c) as u32) << 16)) + .collect(); + let (vocab_out, eos) = (cfg.vocab_out, u32::MAX); + let mut model = InklingCpu::new(cfg, &weights, 96).unwrap(); + let want = model.generate_greedy(&prompt(), 40, eos).unwrap(); + + let mut drafter = MtpDrafter::new(&head, embed, embed_norm.clone(), unembed, vocab_out).unwrap(); + assert_eq!(Drafter::::wants(&drafter), head_cfg.targets); + for most in [3, 1, 15] { + let (got, stats) = model.generate_greedy_drafted(&prompt(), 40, eos, &mut drafter, most, |_| {}).unwrap(); + assert_eq!(got, want, "up to {most} guesses"); + // The head proposes at every sweep: as many as asked, or as its block has room for. + let per_sweep = most.min(head_cfg.block - 1); + assert!(stats.drafted > stats.sweeps * per_sweep / 2 && stats.drafted <= stats.sweeps * per_sweep, "{stats:?}"); + assert_eq!(stats.sweeps + stats.accepted, 39); + } + // It keeps step with the text: asked about a text it was not told of, it proposes nothing. + let text: Vec = prompt().into_iter().chain(want.iter().copied()).collect(); + assert!(drafter.draft(&text[..10], 3).is_empty()); + assert!(drafter.draft(&[], 3).is_empty()); + assert!(drafter.draft(&text, 0).is_empty()); + // And told of a batch out of step, it says so. + let e = drafter.fed(7, 1, &[]).unwrap_err(); + assert!(matches!(e, ModelError::Capacity(_)), "{e}"); + // A new text starts it afresh. + let (again, _) = model.generate_greedy_drafted(&prompt(), 12, eos, &mut drafter, 3, |_| {}).unwrap(); + assert_eq!(again, want[..12]); +} + +#[test] +fn a_head_that_does_not_fit_its_config_is_refused() { + let cfg = tiny_config(32, 16); + let scratch = Scratch::new("refuse"); + write_head(&scratch.0, &cfg, 300, None, None); + assert!(MtpHead::load(&scratch.0, cfg.clone()).is_ok()); + // Another width than the file holds; a tensor missing; a tensor a value short. + let mut wider = cfg.clone(); + wider.hidden = 40; + assert!(matches!(MtpHead::load(&scratch.0, wider), Err(ModelError::Format(m)) if m.contains("expected"))); + write_head(&scratch.0, &cfg, 300, Some("layers.1.self_attn.k_proj_ctx.weight"), None); + assert!(MtpHead::load(&scratch.0, cfg.clone()).is_err()); + write_head(&scratch.0, &cfg, 300, None, Some("markov_head.rnn_proj.weight")); + assert!(matches!(MtpHead::load(&scratch.0, cfg.clone()), Err(ModelError::Format(m)) if m.contains("rnn_proj"))); + let empty = Scratch::new("empty"); + assert!(MtpHead::load(&empty.0, cfg).is_err()); +} + +#[test] +fn the_head_s_config_is_read_from_the_model_s() { + let scratch = Scratch::new("config"); + let write = |mtp: serde_json::Value| { + let mut root = serde_json::json!({"model_type": "inkling2_loop"}); + if !mtp.is_null() { + root["mtp_config"] = mtp; + } + std::fs::write(scratch.0.join("config.json"), root.to_string()).unwrap(); + }; + let full = serde_json::json!({ + "hidden_size": 2304, "num_hidden_layers": 3, "num_attention_heads": 24, "num_key_value_heads": 8, + "head_dim": 128, "intermediate_size": 9216, "rms_norm_eps": 1e-6, "rope_theta": 1000000.0, + "block_size": 8, "markov_rank": 256, "markov_head_type": "rnn_hidden", "target_layer_ids": [5, 23, 41, 48] + }); + write(full.clone()); + let cfg = load_mtp_config(&scratch.0).unwrap().unwrap(); + assert_eq!((cfg.hidden, cfg.layers, cfg.heads, cfg.kv_heads, cfg.head_dim), (2304, 3, 24, 8, 128)); + assert_eq!((cfg.inner, cfg.block, cfg.rank, cfg.theta), (9216, 8, 256, 1_000_000.0)); + assert_eq!(cfg.targets, [5, 23, 41, 48]); + // No head; another kind of sequential step; targets out of order; a field missing. + write(serde_json::Value::Null); + assert_eq!(load_mtp_config(&scratch.0).unwrap(), None); + let mut other = full.clone(); + other["markov_head_type"] = "markov".into(); + write(other); + assert!(matches!(load_mtp_config(&scratch.0), Err(ModelError::Unsupported(_)))); + let mut unordered = full.clone(); + unordered["target_layer_ids"] = serde_json::json!([5, 41, 23]); + write(unordered); + assert!(matches!(load_mtp_config(&scratch.0), Err(ModelError::Format(_)))); + let mut missing = full; + missing.as_object_mut().unwrap().remove("markov_rank"); + write(missing); + assert!(matches!(load_mtp_config(&scratch.0), Err(ModelError::Format(m)) if m.contains("markov_rank"))); +} + +/// The real head on the real model: the text must be the same, and the guesses good. On +/// this prompt plain generation takes one sweep per token; the head as worked out takes +/// well under half as many. +#[test] +fn the_real_head_guesses_well_and_changes_nothing() { + 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"][1]["prompt_ids"].clone()).unwrap(); + let weights = Weights::open_dir(&dir).unwrap(); + let cfg = load_config(&dir).unwrap(); + let head = MtpHead::load(&dir, load_mtp_config(&dir).unwrap().expect("a draft head")).unwrap(); + let embed_norm: Vec = weights + .bytes("model.llm.embed_norm.weight") + .unwrap() + .as_chunks::<2>() + .0 + .iter() + .map(|c| f32::from_bits((u16::from_le_bytes(*c) as u32) << 16)) + .collect(); + let mut drafter = MtpDrafter::new( + &head, + weights.bytes("model.llm.embed.weight").unwrap(), + embed_norm, + weights.bytes("model.llm.unembed.weight").unwrap(), + cfg.vocab_out, + ) + .unwrap(); + let eos = cfg.eos; + let new = 48; + let mut model = InklingCpu::new(cfg, &weights, prompt.len() + new + 16).unwrap(); + let want = model.generate_greedy(&prompt, new, eos).unwrap(); + let (got, stats) = model.generate_greedy_drafted(&prompt, new, eos, &mut drafter, 5, |_| {}).unwrap(); + eprintln!("the real head: {} tokens, {stats:?}", got.len()); + assert_eq!(got, want); + assert!(stats.sweeps * 2 < want.len() - 1, "{stats:?} for {} tokens", want.len()); +} diff --git a/crates/dluth-serve/src/engine.rs b/crates/dluth-serve/src/engine.rs index e6fff2e..8651d50 100644 --- a/crates/dluth-serve/src/engine.rs +++ b/crates/dluth-serve/src/engine.rs @@ -206,7 +206,7 @@ impl Engine for InklingEngine<'_, '_, O> { }), }); let mut lookup = LookupDrafter::new(self.options.match_run.max(4), self.options.match_run); - let drafter: &mut dyn Drafter = if self.options.guesses == 0 { &mut NoDraft } else { &mut lookup }; + let drafter: &mut dyn Drafter = if self.options.guesses == 0 { &mut NoDraft } else { &mut lookup }; let mut reader = ReplyReader::new(self.tokenizer, self.markers); let mut stops = StopFilter::new(&request.stop); From 128507bb9e7620b24d0236073eb6e92f357912a3 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:50:48 -0800 Subject: [PATCH 2/9] feat(cuda): the draft head on the device; the generation example measures it --- crates/dluth-cuda/examples/generate.rs | 73 ++ crates/dluth-cuda/kernels/draft_head.cu | 117 +++ crates/dluth-cuda/src/draft_head.rs | 808 ++++++++++++++++++ crates/dluth-cuda/src/lib.rs | 1 + crates/dluth-cuda/src/ops.rs | 12 + .../dluth-cuda/tests/inkling_golden_cuda.rs | 143 ++++ crates/dluth-model/tests/inkling_mtp.rs | 104 +-- crates/dluth-model/tests/tiny_head/mod.rs | 105 +++ 8 files changed, 1263 insertions(+), 100 deletions(-) create mode 100644 crates/dluth-cuda/kernels/draft_head.cu create mode 100644 crates/dluth-cuda/src/draft_head.rs create mode 100644 crates/dluth-model/tests/tiny_head/mod.rs diff --git a/crates/dluth-cuda/examples/generate.rs b/crates/dluth-cuda/examples/generate.rs index 88ecc6e..c73bcae 100644 --- a/crates/dluth-cuda/examples/generate.rs +++ b/crates/dluth-cuda/examples/generate.rs @@ -73,6 +73,79 @@ fn main() { } return; } + if mode.as_deref() == Some("head") { + // Generation twice on the same model: without guesses, then with the model's own + // draft head proposing up to `most` tokens per sweep. + use dluth_cuda::draft_head::CudaDraftHead; + use dluth_model::inkling::mtp::load_mtp_config; + let most: usize = args.next().map_or(4, |n| n.parse().expect("how many guesses per sweep")); + let (h, vocab_out) = (cfg.hidden, cfg.vocab_out); + let mut ops = CudaOps::new(&dev, &module).expect("the kernels"); + let unembed = &weights.bytes("model.llm.unembed.weight").expect("the output table")[..vocab_out * h * 2]; + let table = ops.device_weight(unembed).expect("the output table on the device"); + let embed_norm: Vec = weights + .bytes("model.llm.embed_norm.weight") + .expect("the embedding norm") + .as_chunks::<2>() + .0 + .iter() + .map(|c| f32::from_bits((u16::from_le_bytes(*c) as u32) << 16)) + .collect(); + let capacity = ids.len() + max_new; + let started = Instant::now(); + let mut head = CudaDraftHead::load( + &dev, + &module, + &dir, + load_mtp_config(&dir).expect("the head's configuration").expect("a draft head"), + weights.bytes("model.llm.embed.weight").expect("the embedding table"), + embed_norm, + table, + vocab_out, + capacity, + ) + .expect("the draft head"); + println!("the draft head loaded in {:.1} s", started.elapsed().as_secs_f64()); + let mut model = Inkling::with_ops(cfg, &weights, capacity, ops).expect("the model"); + model.set_prompt_batch(16).expect("a prompt batch"); + let mut timed = |drafter: &mut dyn dluth_model::inkling::Drafter, most: usize| { + let mut first = None; + let (tokens, stats) = model + .generate_greedy_drafted(&ids, max_new, eos, drafter, most, |_| { + first.get_or_insert_with(Instant::now); + }) + .expect("generation"); + let seconds = first.map_or(0.0, |f| f.elapsed().as_secs_f64()); + (tokens, stats, seconds) + }; + timed(&mut dluth_model::inkling::NoDraft, 0); + let (plain, _, plain_seconds) = timed(&mut dluth_model::inkling::NoDraft, 0); + let (drafted, stats, seconds) = timed(&mut head, most); + println!("{}", tokenizer.decode(&drafted)); + let n = plain.len().saturating_sub(1) as f64; + println!("without guesses: {n:.0} tokens in {plain_seconds:.2} s, {:.1} tokens per second", n / plain_seconds); + println!( + "with the draft head, up to {most} guesses: {:.2} s, {:.1} tokens per second; {} sweeps, {} guessed, {} right", + seconds, + n / seconds, + stats.sweeps, + stats.drafted, + stats.accepted + ); + println!("the same tokens: {}", plain == drafted); + let per_sweep = |d: std::time::Duration| d.as_secs_f64() * 1e3 / stats.sweeps.max(1) as f64; + println!( + "per sweep: {:.1} ms in all; of the head's part, {:.1} ms the block, {:.1} ms the step on the host, {:.1} ms the guesses' scores", + seconds * 1e3 / stats.sweeps.max(1) as f64, + per_sweep(head.spent[0]), + per_sweep(head.spent[1]), + per_sweep(head.spent[2]) + ); + if let Some(error) = &head.last_error { + println!("the head's last error: {error}"); + } + return; + } if mode.as_deref() == Some("draft") { // Generation twice on the same model: without guesses, then with guesses looked up // in the text so far (the last `run` tokens, where they last appeared), `most` at a diff --git a/crates/dluth-cuda/kernels/draft_head.cu b/crates/dluth-cuda/kernels/draft_head.cu new file mode 100644 index 0000000..52b8eb3 --- /dev/null +++ b/crates/dluth-cuda/kernels/draft_head.cu @@ -0,0 +1,117 @@ +// The draft head's operations that are not matrix products or the model's own small +// operations. The head (a small network that guesses the next few tokens) is described +// where it is implemented on the CPU, dluth-model's inkling/mtp.rs; each kernel here +// names the part of that implementation it stands for. + +// Each vector of `dim` in `x`: divided by sqrt(mean of its squares + eps), multiplied +// element by element by `weights` (one vector of `dim`, the same for all), then rotated by +// its position: element i and element i + dim/2 are a pair, turned by the angle +// position * theta^(-2i/dim). `x` holds, for each of `count` positions, `heads` vectors; +// the positions are `pos`, `pos + 1`, ... One block of threads per vector; dim is at most +// 256 and even. +// CPU reference: MtpHead::head_norm_rope (cpu::rmsnorm per head, then cpu::rope_inplace). +extern "C" __global__ void head_norm_rope(float* x, const float* weights, unsigned int count, + unsigned int heads, unsigned int dim, float eps, + unsigned long long pos, float theta) { + __shared__ float part[256]; + __shared__ float normed[256]; + unsigned int vector = blockIdx.x; + if (vector >= count * heads) return; + float* v = x + (size_t)vector * dim; + float squares = 0.0f; + for (unsigned int i = threadIdx.x; i < dim; i += blockDim.x) squares += v[i] * v[i]; + part[threadIdx.x] = squares; + __syncthreads(); + if (threadIdx.x == 0) { + for (unsigned int t = 1; t < blockDim.x; ++t) squares += part[t]; + part[0] = 1.0f / sqrtf(squares / (float)dim + eps); + } + __syncthreads(); + float scale = part[0]; + for (unsigned int i = threadIdx.x; i < dim; i += blockDim.x) normed[i] = v[i] * scale * weights[i]; + __syncthreads(); + unsigned int half = dim / 2; + float at = (float)(pos + vector / heads); + for (unsigned int i = threadIdx.x; i < half; i += blockDim.x) { + float frequency = 1.0f / powf(theta, (float)(2 * i) / (float)dim); + float s, c; + sincosf(at * frequency, &s, &c); + float a = normed[i], b = normed[i + half]; + v[i] = a * c - b * s; + v[i + half] = a * s + b * c; + } +} + +// The block's attention scores. A block of `block` positions follows `context` positions +// of text. For block position k, head h and key j: the dot product of the head's query +// with key j's vector for the head's key-value group, times `scale`. Keys 0 to +// context - 1 are the text's (`context_keys`, one row of kv_heads * dim per position); +// keys context to context + block - 1 are the block's own (`block_keys`): every block +// position sees the whole block. Each (position, head) has a run of context + block scores. +// CPU reference: the scoring in MtpDrafter::block. +extern "C" __global__ void draft_scores(const float* q, const float* context_keys, const float* block_keys, + float* scores, unsigned int heads, unsigned int kv_heads, + unsigned int dim, unsigned long long context, + unsigned int block, float scale) { + unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; + unsigned long long keys = context + block; + unsigned long long run = index / keys; + unsigned long long j = index % keys; + if (run >= (unsigned long long)block * heads) return; + unsigned int h = (unsigned int)(run % heads); + size_t group = (size_t)(h / (heads / kv_heads)) * dim; + const float* key = (j < context ? context_keys + j * kv_heads * dim : block_keys + (j - context) * kv_heads * dim) + group; + const float* query = q + run * dim; + float dot = 0.0f; + for (unsigned int i = 0; i < dim; ++i) dot += query[i] * key[i]; + scores[index] = dot * scale; +} + +// The weighted sum of the values for the block's attention: out[k][h][e] = sum over the +// keys j of weights[k][h][j] times value j's element e for the head's group. `segs` +// threads share one output element, each taking every segs-th key, combined with warp +// shuffles (segs a power of two up to 32, the block size a multiple of 32). +// CPU reference: the summing in MtpDrafter::block. +extern "C" __global__ void draft_values(const float* weights, const float* context_values, + const float* block_values, float* out, unsigned int heads, + unsigned int kv_heads, unsigned int dim, + unsigned long long context, unsigned int block, + unsigned int segs) { + unsigned long long thread = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; + unsigned long long element = thread / segs; + unsigned int seg = (unsigned int)(thread % segs); + unsigned long long run = element / dim; + unsigned int e = (unsigned int)(element % dim); + unsigned long long keys = context + block; + bool live = run < (unsigned long long)block * heads; + float total = 0.0f; + if (live) { + unsigned int h = (unsigned int)(run % heads); + size_t column = (size_t)(h / (heads / kv_heads)) * dim + e; + const float* w = weights + run * keys; + for (unsigned long long j = seg; j < keys; j += segs) { + const float* value = j < context ? context_values + j * kv_heads * dim : block_values + (j - context) * kv_heads * dim; + total += w[j] * value[column]; + } + } + for (unsigned int offset = segs / 2; offset > 0; offset /= 2) total += __shfl_xor_sync(0xffffffffu, total, offset); + if (live && seg == 0) out[element] = total; +} + +// out[i] = gate[i] * sigmoid(gate[i]) * up[i]: the gated activation of the head's +// feed-forward part. CPU reference: cpu::silu_mul. +extern "C" __global__ void silu_mul(const float* gate, const float* up, float* out, unsigned int n) { + unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + float g = gate[i]; + out[i] = g / (1.0f + expf(-g)) * up[i]; +} + +// out[i] = w0 * a[i] + w1 * b[i] + w2 * c[i] + w3 * d[i]: the mix of up to four of the +// model's values that a layer of the head reads its context from (unused ones are given a +// weight of 0 and any valid pointer). CPU reference: the sum in MtpHead::mixed. +extern "C" __global__ void mix_four(const float* a, const float* b, const float* c, const float* d, + float* out, float w0, float w1, float w2, float w3, unsigned int n) { + unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) out[i] = w0 * a[i] + w1 * b[i] + w2 * c[i] + w3 * d[i]; +} diff --git a/crates/dluth-cuda/src/draft_head.rs b/crates/dluth-cuda/src/draft_head.rs new file mode 100644 index 0000000..5c2f4b4 --- /dev/null +++ b/crates/dluth-cuda/src/draft_head.rs @@ -0,0 +1,808 @@ +//! The model's draft head on the device: a guesser for `Inkling::generate_greedy_drafted`. +//! +//! What the head computes is written up, with its sources, in dluth-model's +//! `inkling/mtp.rs`, which is also the reference this is checked against. Here its three +//! layers are kernel launches over a block of up to eight positions, and its matrices are +//! read in the form they are stored. +//! +//! The head's last part goes one guess at a time: each guess needs the scores of the whole +//! vocabulary for a hidden state that depends on the guess before it. Reading the model's +//! output table once per guess would cost more than the guesses save. But a guess's hidden +//! state is the block's hidden state plus a correction, and the correction is a fixed +//! matrix applied to a small vector the recurrent step produces: +//! +//! scores = table . (hidden + out . said + bias) +//! = table . hidden + (table . out) . said + table . bias +//! +//! `table . hidden` is one product for the whole block. `table . out` and `table . bias` +//! do not depend on the text and are computed once, when the head is loaded. That leaves, +//! per guess, a small matrix times `said`: a ninth of the output table's bytes. +//! +//! The step's own projection is split the same way: the parts that read a hidden state +//! and the other wide input are products on the device, done once per block; the host is +//! left with the small part that reads the step's state and the last token. + +use crate::attention::Attention; +use crate::device::CudaDevice; +use crate::error::CudaError; +use crate::floats::Floats; +use crate::matmat::{Bf16Matrix, Matmat}; +use crate::module::{Kernel, Module}; +use crate::ops::DeviceVec; +use crate::small::Small; +use dluth_core::{bf16_to_f32, Backend, Buffer}; +use dluth_kernels::cpu; +use dluth_model::inkling::mtp::MtpConfig; +use dluth_model::inkling::Drafter; +use dluth_model::safetensors::SafetensorsFile; +use dluth_model::ModelError; +use std::ffi::c_void; +use std::path::Path; + +/// Threads per row for the matrix kernels, as for the model. +const SEGS: u32 = 16; +/// Threads that share one element of the block attention's output. +const VALUE_SEGS: u32 = 16; +const _: () = assert!(VALUE_SEGS.is_power_of_two() && VALUE_SEGS <= 32); +/// Most positions the head is told of at once: the model's largest batch. +const MOST_FED: usize = 16; +/// The model's values a layer's context is mixed from: at most this many. +const MIXED: usize = 4; + +fn failed(e: impl std::fmt::Display) -> ModelError { + ModelError::Device(e.to_string()) +} + +fn floats(bytes: &[u8]) -> Vec { + bytes.as_chunks::<2>().0.iter().map(|c| bf16_to_f32(u16::from_le_bytes(*c))).collect() +} + +fn ptr(p: &mut u64) -> *mut c_void { + p as *mut u64 as *mut c_void +} +fn num(p: &mut u32) -> *mut c_void { + p as *mut u32 as *mut c_void +} +fn real(p: &mut f32) -> *mut c_void { + p as *mut f32 as *mut c_void +} + +/// One layer's weights on the device: norms as floats, matrices as stored (BF16). +struct Layer { + input_norm: Buffer, + post_norm: Buffer, + context_norm: Buffer, + q_norm: Buffer, + k_norm: Buffer, + k_norm_context: Buffer, + q: Buffer, + k: Buffer, + v: Buffer, + o: Buffer, + k_context: Buffer, + v_context: Buffer, + gate: Buffer, + up: Buffer, + down: Buffer, + /// A key and a value for every position of the text read so far. + context_keys: Buffer, + context_values: Buffer, +} + +/// Buffers the head computes in, sized once for a whole block. +struct Scratch { + z: [Buffer; 2], + normed: Buffer, + q: Buffer, + k: Buffer, + v: Buffer, + scores: Buffer, + attended: Buffer, + o: Buffer, + gate: Buffer, + up: Buffer, + act: Buffer, + /// The whole block's scores under the model's output table. + base: Buffer, + /// `base` with the output table times the step's bias added, position by position. + base_bias: Buffer, + said: Buffer, + correction: Buffer, + sum: Buffer, + other: Buffer, + /// The step's projection of each block position's hidden state, and of `other`. + step_hidden: Buffer, + step_other: Buffer, + /// For the positions the head is told of. + mixed: Buffer, + mixed_normed: Buffer, + fed_k: Buffer, + fed_v: Buffer, +} + +/// The draft head on a CUDA device. +pub struct CudaDraftHead<'m> { + dev: &'m CudaDevice, + matmat: Matmat<'m>, + small: Small<'m>, + attention: Attention<'m>, + norm_rope: Kernel<'m>, + scores: Kernel<'m>, + values: Kernel<'m>, + silu: Kernel<'m>, + mix: Kernel<'m>, + cfg: MtpConfig, + /// For each layer and for the recurrent step: the weight of each target value. + mixes: Vec<[f32; MIXED]>, + layers: Vec, + norm: Buffer, + step_norm: Buffer, + /// The recurrent step's mix of the model's values, per position of the text. + context_step: Buffer, + /// The model's output table on the device (the model's own copy), its real tokens. + unembed: Buffer, + vocab_out: usize, + /// The output table times the step's output matrix, `vocab_out` rows of `rank`, as + /// BF16: half the bytes to read per guess, and precise enough for a guess. + table_out: Buffer, + /// The parts of the step's projection that read a hidden state and the other wide + /// input, as stored (BF16), 3 * rank rows of the model's width each. + step_hidden: Buffer, + step_other: Buffer, + /// The output table times the step's output bias. + table_bias: Buffer, + scratch: Scratch, + // What the recurrent step needs on the host. + mask: Vec, + embed: &'m [u8], + embed_norm: Vec, + token_vectors: Vec, + /// The part of the step's projection that reads its state and the last token's vector: + /// 3 * rank rows of 2 * rank. + step_small: Vec, + step_bias: Vec, + /// Positions of the text the head has been told of, and how many it has room for. + positions: usize, + capacity: usize, + owned: Vec, + staging: Vec, + /// Why the last call to `draft` proposed nothing, if a device call failed. + pub last_error: Option, + /// Where the head's time went, summed over every call: the block (its layers and the + /// block's scores, until the device has finished), the recurrent step on the host, and + /// the scores of each guess on the device with their copies. + pub spent: [std::time::Duration; 3], +} + +impl<'m> CudaDraftHead<'m> { + /// Loads `mtp.safetensors` from `dir` to the device. `embed` and `embed_norm` are the + /// model's embedding table as stored and its embedding norm's weights; `unembed` is the + /// model's output table already on the device (see `CudaOps::device_weight`), which + /// must stay there as long as this head is used; `vocab_out` how many of its rows are + /// tokens. `capacity` is the longest text, in positions. + #[allow(clippy::too_many_arguments)] + pub fn load( + dev: &'m CudaDevice, + module: &'m Module<'m>, + dir: &Path, + cfg: MtpConfig, + embed: &'m [u8], + embed_norm: Vec, + unembed: Buffer, + vocab_out: usize, + capacity: usize, + ) -> Result { + let file = SafetensorsFile::open(&dir.join("mtp.safetensors"))?; + let (h, d, r) = (cfg.hidden, cfg.head_dim, cfg.rank); + let (qw, kvw, inner, block) = (cfg.heads * d, cfg.kv_heads * d, cfg.inner, cfg.block); + if cfg.targets.len() > MIXED || d > 256 || block > 16 || capacity == 0 { + return Err(ModelError::Unsupported(format!( + "a draft head with {} target values, heads of {d} and blocks of {block}", + cfg.targets.len() + ))); + } + let have = dev.size_of(&unembed).map_err(failed)?; + if embed_norm.len() != h || have < vocab_out * h * 2 || !embed.len().is_multiple_of(h * 2) { + return Err(ModelError::Format("draft head: the model's tables do not have the head's width".into())); + } + let mut owned: Vec = Vec::new(); + let stored = |name: &str, len: usize| -> Result<&[u8], ModelError> { + let bytes = file.bytes(name)?; + if bytes.len() != len * 2 { + return Err(ModelError::Format(format!( + "draft head: {name} holds {} values where {len} are expected", + bytes.len() / 2 + ))); + } + Ok(bytes) + }; + // Fresh buffers that no kernel has been given: filled without waiting. + let mut put = |bytes: &[u8]| -> Result { + let buffer = dev.alloc(bytes.len()).map_err(failed)?; + dev.upload(&buffer, bytes).map_err(failed)?; + owned.push(buffer); + Ok(buffer) + }; + let as_floats = |values: &[f32]| -> Vec { values.iter().flat_map(|v| v.to_le_bytes()).collect() }; + let mut layers = Vec::with_capacity(cfg.layers); + for i in 0..cfg.layers { + let p = format!("layers.{i}"); + let mut norm = |name: &str, len: usize| -> Result { + put(&as_floats(&floats(stored(&format!("{p}.{name}.weight"), len)?))) + }; + let (input_norm, post_norm, context_norm) = + (norm("input_layernorm", h)?, norm("post_attention_layernorm", h)?, norm("dflare_norm", h)?); + let (q_norm, k_norm, k_norm_context) = + (norm("self_attn.q_norm", d)?, norm("self_attn.k_norm", d)?, norm("self_attn.k_norm_ctx", d)?); + let mut matrix = |name: &str, len: usize| -> Result { + put(stored(&format!("{p}.{name}.weight"), len)?) + }; + layers.push(Layer { + input_norm, + post_norm, + context_norm, + q_norm, + k_norm, + k_norm_context, + q: matrix("self_attn.q_proj", qw * h)?, + k: matrix("self_attn.k_proj", kvw * h)?, + v: matrix("self_attn.v_proj", kvw * h)?, + o: matrix("self_attn.o_proj", h * qw)?, + k_context: matrix("self_attn.k_proj_ctx", kvw * h)?, + v_context: matrix("self_attn.v_proj_ctx", kvw * h)?, + gate: matrix("mlp.gate_proj", inner * h)?, + up: matrix("mlp.up_proj", inner * h)?, + down: matrix("mlp.down_proj", h * inner)?, + context_keys: Buffer { handle: 0, bytes: 0 }, + context_values: Buffer { handle: 0, bytes: 0 }, + }); + } + let norm = put(&as_floats(&floats(stored("norm.weight", h)?)))?; + let step_norm = put(&as_floats(&floats(stored("markov_head.dflare_norm.weight", h)?)))?; + let weights = floats(stored("fuse_weight", (cfg.layers + 1) * cfg.targets.len())?); + let mixes = weights + .chunks_exact(cfg.targets.len()) + .map(|row| { + let mut row = row.to_vec(); + cpu::softmax_inplace(&mut row); + let mut four = [0.0f32; MIXED]; + four[..row.len()].copy_from_slice(&row); + four + }) + .collect(); + let token_vectors = file.bytes("markov_head.markov_w1.weight")?.to_vec(); + if token_vectors.is_empty() || !token_vectors.len().is_multiple_of(r * 2) { + return Err(ModelError::Format("draft head: the token vectors are not whole rows".into())); + } + // The step's projection reads four things side by side: its state and the last + // token's vector (small, and different for every guess: kept on the host), a block + // position's hidden state, and the other wide input (both on the device already: + // those columns go there). + let step_stored = stored("markov_head.rnn_proj.weight", 3 * r * (2 * r + 2 * h))?; + let row_bytes = (2 * r + 2 * h) * 2; + let columns = |from: usize, to: usize| -> Vec { + step_stored.chunks_exact(row_bytes).flat_map(|row| row[from * 2..to * 2].iter().copied()).collect() + }; + let step_small = floats(&columns(0, 2 * r)); + let (step_hidden, step_other) = (put(&columns(2 * r, 2 * r + h))?, put(&columns(2 * r + h, 2 * r + 2 * h))?); + let step_bias = floats(stored("markov_head.rnn_proj.bias", 3 * r)?); + let step_out = floats(stored("markov_head.hidden_out.weight", h * r)?); + let step_out_bias = floats(stored("markov_head.hidden_out.bias", h)?); + let mask = floats(stored("mask_embed", h)?); + + let mut alloc = |floats: usize| -> Result { + let buffer = dev.alloc(floats.max(4) * 4).map_err(failed)?; + owned.push(buffer); + Ok(buffer) + }; + for layer in &mut layers { + layer.context_keys = alloc(capacity * kvw)?; + layer.context_values = alloc(capacity * kvw)?; + } + let context_step = alloc(capacity * h)?; + let fed = MOST_FED.max(block); + let scratch = Scratch { + z: [alloc(block * h)?, alloc(block * h)?], + normed: alloc(fed * h)?, + q: alloc(block * qw)?, + k: alloc(block * kvw)?, + v: alloc(block * kvw)?, + scores: alloc(block * cfg.heads * (capacity + block))?, + attended: alloc(block * qw)?, + o: alloc(block * h)?, + gate: alloc(block * inner)?, + up: alloc(block * inner)?, + act: alloc(block * inner)?, + base: alloc(fed * vocab_out)?, + base_bias: alloc(block * vocab_out)?, + said: alloc(r)?, + correction: alloc(vocab_out)?, + sum: alloc(vocab_out)?, + other: alloc(h)?, + step_hidden: alloc(block * 3 * r)?, + step_other: alloc(3 * r)?, + mixed: alloc(fed * h)?, + mixed_normed: alloc(fed * h)?, + fed_k: alloc(fed * kvw)?, + fed_v: alloc(fed * kvw)?, + }; + let (table_columns, table_bias) = (alloc(r * vocab_out)?, alloc(vocab_out)?); + + let matmat = Matmat::new(dev, module).map_err(failed)?; + let small = Small::new(dev, module).map_err(failed)?; + // The output table times the step's output matrix, a few of its columns at a time, + // and times its bias. `normed` and `base` serve as the scratch for it. + let table = Bf16Matrix { buffer: &unembed, offset: 0, rows: vocab_out, cols: h }; + let send = |buffer: &Buffer, values: &[f32]| -> Result<(), ModelError> { + dev.synchronize().map_err(failed)?; + dev.upload(buffer, &as_floats(values)).map_err(failed) + }; + let mut done = 0; + while done < r { + let n = (r - done).min(fed); + // Column c of the matrix, as a vector of the model's width. + let columns: Vec = (done..done + n) + .flat_map(|c| (0..h).map(move |row| (row, c))) + .map(|(row, c)| step_out[row * r + c]) + .collect(); + send(&scratch.normed, &columns)?; + matmat.bf16(table, &scratch.normed, n, &scratch.base, SEGS).map_err(failed)?; + small + .copy( + Floats::first(&scratch.base, n * vocab_out), + Floats { buffer: &table_columns, at: done * vocab_out, len: n * vocab_out }, + ) + .map_err(failed)?; + done += n; + } + send(&scratch.normed, &step_out_bias)?; + matmat.bf16(table, &scratch.normed, 1, &scratch.base, SEGS).map_err(failed)?; + small.copy(Floats::first(&scratch.base, vocab_out), Floats::first(&table_bias, vocab_out)).map_err(failed)?; + dev.synchronize().map_err(failed)?; + // Column after column was the natural order to compute it in; a product wants it + // row after row, and BF16 halves what each guess reads. + let mut column_bytes = vec![0u8; r * vocab_out * 4]; + dev.download(&table_columns, &mut column_bytes).map_err(failed)?; + let column_floats = column_bytes.as_chunks::<4>().0; + let mut rows = vec![0u8; vocab_out * r * 2]; + for (token, row) in rows.chunks_exact_mut(r * 2).enumerate() { + for (c, out) in row.as_chunks_mut::<2>().0.iter_mut().enumerate() { + let bits = f32::from_le_bytes(column_floats[c * vocab_out + token]).to_bits(); + // To the nearest BF16 value: add half of the part that is cut off. + *out = ((bits.wrapping_add(0x8000) >> 16) as u16).to_le_bytes(); + } + } + drop(column_bytes); + let table_out = dev.alloc(rows.len()).map_err(failed)?; + dev.upload(&table_out, &rows).map_err(failed)?; + owned.push(table_out); + + Ok(CudaDraftHead { + dev, + matmat, + small, + attention: Attention::new(dev, module).map_err(failed)?, + norm_rope: module.kernel("head_norm_rope").map_err(failed)?, + scores: module.kernel("draft_scores").map_err(failed)?, + values: module.kernel("draft_values").map_err(failed)?, + silu: module.kernel("silu_mul").map_err(failed)?, + mix: module.kernel("mix_four").map_err(failed)?, + cfg, + mixes, + layers, + norm, + step_norm, + context_step, + unembed, + vocab_out, + table_out, + step_hidden, + step_other, + table_bias, + scratch, + mask, + embed, + embed_norm, + token_vectors, + step_small, + step_bias, + positions: 0, + capacity, + owned, + staging: Vec::new(), + last_error: None, + spent: Default::default(), + }) + } + + fn grid(n: usize) -> (u32, u32, u32) { + ((n as u32).div_ceil(256), 1, 1) + } + + /// In place: each of `count * heads` vectors of the head size in `x` normalized with + /// `weights` and rotated for its position, the first position being `pos`. + fn head_norm_rope( + &self, + x: &Buffer, + weights: &Buffer, + count: usize, + heads: usize, + pos: usize, + ) -> Result<(), CudaError> { + let d = self.cfg.head_dim; + Floats::first(x, count * heads * d).check(self.dev, "head_norm_rope", count * heads * d)?; + Floats::first(weights, d).check(self.dev, "head_norm_rope", d)?; + let (mut px, mut pw, mut c, mut h, mut dim) = (x.handle, weights.handle, count as u32, heads as u32, d as u32); + let (mut eps, mut p, mut theta) = (self.cfg.eps, pos as u64, self.cfg.theta); + let mut args = [ + ptr(&mut px), + ptr(&mut pw), + num(&mut c), + num(&mut h), + num(&mut dim), + real(&mut eps), + ptr(&mut p), + real(&mut theta), + ]; + // SAFETY: the arguments match head_norm_rope(float*, const float*, unsigned, + // unsigned, unsigned, float, unsigned long long, float). One block per vector reads + // and writes that vector's `dim` floats of `x` and reads `dim` of `weights`; both + // extents were checked. The block has 128 threads and `dim` is at most 256, the + // size of the kernel's shared arrays (checked when the head was loaded). + unsafe { self.norm_rope.launch(((count * heads) as u32, 1, 1), (128, 1, 1), &mut args) } + } + + /// The mix of the model's values for `row` (a layer, or the step as the last row), for + /// the first `count` positions of `states`, into `scratch.mixed`. + fn mix_values(&self, row: usize, states: &[DeviceVec], count: usize) -> Result<(), CudaError> { + let n = count * self.cfg.hidden; + let mut addresses = [states[0].buffer().handle; MIXED]; + for (slot, state) in addresses.iter_mut().zip(states) { + Floats::first(state.buffer(), n).check(self.dev, "mix_four", n)?; + *slot = state.buffer().handle; + } + Floats::first(&self.scratch.mixed, n).check(self.dev, "mix_four", n)?; + let [mut a, mut b, mut c, mut d] = addresses; + let [mut w0, mut w1, mut w2, mut w3] = self.mixes[row]; + let (mut out, mut len) = (self.scratch.mixed.handle, n as u32); + let mut args = [ + ptr(&mut a), + ptr(&mut b), + ptr(&mut c), + ptr(&mut d), + ptr(&mut out), + real(&mut w0), + real(&mut w1), + real(&mut w2), + real(&mut w3), + num(&mut len), + ]; + // SAFETY: the arguments match mix_four(4 const float*, float*, 4 float, unsigned). + // It reads n floats of each of the four inputs (a slot without a value repeats the + // first, with a weight of 0) and writes n to the scratch buffer, which is none of + // them; all were checked. + unsafe { self.mix.launch(Self::grid(n), (256, 1, 1), &mut args) } + } + + fn told(&mut self, first: usize, kept: usize, states: &[DeviceVec]) -> Result<(), CudaError> { + let (h, kv, d) = (self.cfg.hidden, self.cfg.kv_heads, self.cfg.head_dim); + let kvw = kv * d; + let s = &self.scratch; + let pos = self.positions; + let _ = first; + for (index, layer) in self.layers.iter().enumerate() { + self.mix_values(index, states, kept)?; + let (mixed, normed) = (Floats::first(&s.mixed, kept * h), Floats::first(&s.mixed_normed, kept * h)); + self.small.rmsnorm(mixed, Floats::first(&layer.context_norm, h), normed, self.cfg.eps)?; + let matrix = |buffer| Bf16Matrix { buffer, offset: 0, rows: kvw, cols: h }; + self.matmat.bf16(matrix(&layer.k_context), &s.mixed_normed, kept, &s.fed_k, SEGS)?; + self.head_norm_rope(&s.fed_k, &layer.k_norm_context, kept, kv, pos)?; + self.small.copy( + Floats::first(&s.fed_k, kept * kvw), + Floats { buffer: &layer.context_keys, at: pos * kvw, len: kept * kvw }, + )?; + self.matmat.bf16(matrix(&layer.v_context), &s.mixed_normed, kept, &s.fed_v, SEGS)?; + self.small.copy( + Floats::first(&s.fed_v, kept * kvw), + Floats { buffer: &layer.context_values, at: pos * kvw, len: kept * kvw }, + )?; + } + self.mix_values(self.cfg.layers, states, kept)?; + self.small.rmsnorm( + Floats::first(&s.mixed, kept * h), + Floats::first(&self.step_norm, h), + Floats { buffer: &self.context_step, at: pos * h, len: kept * h }, + self.cfg.eps, + )?; + self.positions += kept; + Ok(()) + } + + fn upload(&mut self, buffer: &Buffer, values: &[f32]) -> Result<(), CudaError> { + self.staging.clear(); + self.staging.extend(values.iter().flat_map(|v| v.to_le_bytes())); + self.dev.upload(buffer, &self.staging).map_err(|e| CudaError::Device(e.to_string())) + } + + fn download(&mut self, buffer: &Buffer, len: usize) -> Result, CudaError> { + self.staging.clear(); + self.staging.resize(len * 4, 0); + self.dev.download(buffer, &mut self.staging).map_err(|e| CudaError::Device(e.to_string()))?; + Ok(self.staging.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect()) + } + + fn wait(&self) -> Result<(), CudaError> { + self.dev.synchronize().map_err(|e| CudaError::Device(e.to_string())) + } + + /// The block's hidden states after the head's layers and final norm, in + /// `scratch.normed`, and its scores under the output table, in `scratch.base`, for the + /// anchor `token` at position `t` and `count` positions in all. + fn block(&mut self, token: u32, t: usize, count: usize) -> Result<(), CudaError> { + let cfg = self.cfg.clone(); + let (h, d, heads, kv) = (cfg.hidden, cfg.head_dim, cfg.heads, cfg.kv_heads); + let (qw, kvw, inner) = (heads * d, kv * d, cfg.inner); + let row = &self.embed[token as usize * h * 2..(token as usize + 1) * h * 2]; + let mut input = vec![0.0f32; h]; + cpu::rmsnorm(&floats(row), &self.embed_norm, cfg.eps, &mut input); + for _ in 1..count { + input.extend_from_slice(&self.mask); + } + // The device has nothing of the head's to do at this point, but the rule holds + // anyway: wait, then write. + self.wait()?; + let z0 = self.scratch.z[0]; + self.upload(&z0, &input)?; + let s = &self.scratch; + let keys = t + count; + let runs = count * heads; + for layer in &self.layers { + let (z, z_next) = (Floats::first(&s.z[0], count * h), Floats::first(&s.z[1], count * h)); + let normed = Floats::first(&s.normed, count * h); + self.small.rmsnorm(z, Floats::first(&layer.input_norm, h), normed, cfg.eps)?; + let matrix = |buffer, rows, cols| Bf16Matrix { buffer, offset: 0, rows, cols }; + self.matmat.bf16(matrix(&layer.q, qw, h), &s.normed, count, &s.q, SEGS)?; + self.head_norm_rope(&s.q, &layer.q_norm, count, heads, t)?; + self.matmat.bf16(matrix(&layer.k, kvw, h), &s.normed, count, &s.k, SEGS)?; + self.head_norm_rope(&s.k, &layer.k_norm, count, kv, t)?; + self.matmat.bf16(matrix(&layer.v, kvw, h), &s.normed, count, &s.v, SEGS)?; + + // Scores of every block position and head against the text and the block. + Floats::first(&s.q, runs * d).check(self.dev, "draft_scores", runs * d)?; + Floats::first(&layer.context_keys, t * kvw).check(self.dev, "draft_scores", t * kvw)?; + Floats::first(&layer.context_values, t * kvw).check(self.dev, "draft_values", t * kvw)?; + Floats::first(&s.k, count * kvw).check(self.dev, "draft_scores", count * kvw)?; + Floats::first(&s.v, count * kvw).check(self.dev, "draft_values", count * kvw)?; + Floats::first(&s.scores, runs * keys).check(self.dev, "draft_scores", runs * keys)?; + Floats::first(&s.attended, runs * d).check(self.dev, "draft_values", runs * d)?; + let (mut pq, mut pck, mut pbk, mut ps) = + (s.q.handle, layer.context_keys.handle, s.k.handle, s.scores.handle); + let (mut nh, mut nkv, mut dim, mut context, mut block) = + (heads as u32, kv as u32, d as u32, t as u64, count as u32); + let mut scale = 1.0 / (d as f32).sqrt(); + let mut args = [ + ptr(&mut pq), + ptr(&mut pck), + ptr(&mut pbk), + ptr(&mut ps), + num(&mut nh), + num(&mut nkv), + num(&mut dim), + ptr(&mut context), + num(&mut block), + real(&mut scale), + ]; + // SAFETY: the arguments match draft_scores(3 const float*, float*, unsigned, + // unsigned, unsigned, unsigned long long, unsigned, float). It reads runs * dim + // floats of the queries, `context` rows of the context keys and `block` rows of + // the block's keys (kv_heads * dim each), and writes runs * (context + block) + // scores; all checked just above, in buffers that are distinct. + unsafe { self.scores.launch(Self::grid(runs * keys), (256, 1, 1), &mut args)? }; + self.attention.softmax_runs(Floats::first(&s.scores, runs * keys), runs, keys)?; + let (mut pcv, mut pbv, mut pa, mut segs) = + (layer.context_values.handle, s.v.handle, s.attended.handle, VALUE_SEGS); + let mut args = [ + ptr(&mut ps), + ptr(&mut pcv), + ptr(&mut pbv), + ptr(&mut pa), + num(&mut nh), + num(&mut nkv), + num(&mut dim), + ptr(&mut context), + num(&mut block), + num(&mut segs), + ]; + // SAFETY: the arguments match draft_values(3 const float*, float*, unsigned, + // unsigned, unsigned, unsigned long long, unsigned, unsigned). It reads the + // scores just made, `context` rows of the context values and `block` rows of + // the block's values, and writes runs * dim floats; all checked above. VALUE_SEGS + // is a power of two up to 32 and the block size a multiple of 32, as its + // shuffles need. + unsafe { self.values.launch(Self::grid(runs * d * VALUE_SEGS as usize), (256, 1, 1), &mut args)? }; + + self.matmat.bf16(matrix(&layer.o, h, qw), &s.attended, count, &s.o, SEGS)?; + self.small.add(z, Floats::first(&s.o, count * h), z_next)?; + self.small.rmsnorm(z_next, Floats::first(&layer.post_norm, h), normed, cfg.eps)?; + self.matmat.bf16(matrix(&layer.gate, inner, h), &s.normed, count, &s.gate, SEGS)?; + self.matmat.bf16(matrix(&layer.up, inner, h), &s.normed, count, &s.up, SEGS)?; + let n = count * inner; + Floats::first(&s.gate, n).check(self.dev, "silu_mul", n)?; + Floats::first(&s.up, n).check(self.dev, "silu_mul", n)?; + Floats::first(&s.act, n).check(self.dev, "silu_mul", n)?; + let (mut pg, mut pu, mut pact, mut len) = (s.gate.handle, s.up.handle, s.act.handle, n as u32); + let mut args = [ptr(&mut pg), ptr(&mut pu), ptr(&mut pact), num(&mut len)]; + // SAFETY: the arguments match silu_mul(const float*, const float*, float*, + // unsigned); it reads n floats of each input and writes n to a third buffer, + // all checked. + unsafe { self.silu.launch(Self::grid(n), (256, 1, 1), &mut args)? }; + // The feed-forward output goes through `o`, which attention is done with. + self.matmat.bf16(matrix(&layer.down, h, inner), &s.act, count, &s.o, SEGS)?; + self.small.add(z_next, Floats::first(&s.o, count * h), z)?; + } + self.small.rmsnorm( + Floats::first(&s.z[0], count * h), + Floats::first(&self.norm, h), + Floats::first(&s.normed, count * h), + cfg.eps, + )?; + let table = Bf16Matrix { buffer: &self.unembed, offset: 0, rows: self.vocab_out, cols: h }; + self.matmat.bf16(table, &s.normed, count, &s.base, SEGS)?; + let vocab = self.vocab_out; + for k in 1..count { + self.small.add( + Floats { buffer: &s.base, at: k * vocab, len: vocab }, + Floats::first(&self.table_bias, vocab), + Floats { buffer: &s.base_bias, at: k * vocab, len: vocab }, + )?; + } + // The step's two wide inputs go through their parts of its projection here: each + // block position's hidden state, and the step's mix of the model's values at the + // last position read. + let r3 = 3 * cfg.rank; + self.matmat.bf16( + Bf16Matrix { buffer: &self.step_hidden, offset: 0, rows: r3, cols: h }, + &s.normed, + count, + &s.step_hidden, + SEGS, + )?; + self.small.copy(Floats { buffer: &self.context_step, at: (t - 1) * h, len: h }, Floats::first(&s.other, h))?; + self.matmat.bf16( + Bf16Matrix { buffer: &self.step_other, offset: 0, rows: r3, cols: h }, + &s.other, + 1, + &s.step_other, + SEGS, + ) + } + + fn guess(&mut self, tokens: &[u32], most: usize) -> Result, CudaError> { + let (h, r) = (self.cfg.hidden, self.cfg.rank); + let Some((&anchor, before)) = tokens.split_last() else { + return Ok(Vec::new()); + }; + let t = before.len(); + let room = most.min(self.cfg.block - 1); + let known = self.token_vectors.len() / (r * 2); + if room == 0 || t == 0 || t != self.positions || (anchor as usize + 1) * h * 2 > self.embed.len() { + return Ok(Vec::new()); + } + let started = std::time::Instant::now(); + self.block(anchor, t, room + 1)?; + self.wait()?; + self.spent[0] += started.elapsed(); + let (step_hidden, step_other) = (self.scratch.step_hidden, self.scratch.step_other); + let from_hidden = self.download(&step_hidden, (room + 1) * 3 * r)?; + let from_other = self.download(&step_other, 3 * r)?; + let vocab = self.vocab_out; + let mut state = vec![0.0f32; r]; + let mut previous = anchor as usize; + let mut guesses = Vec::with_capacity(room); + for k in 1..=room { + if previous >= known { + break; + } + let started = std::time::Instant::now(); + let vector = floats(&self.token_vectors[previous * r * 2..(previous + 1) * r * 2]); + let input: Vec = state.iter().chain(&vector).copied().collect(); + let mut out = vec![0.0f32; 3 * r]; + for (i, (o, row)) in out.iter_mut().zip(self.step_small.chunks_exact(2 * r)).enumerate() { + let small: f32 = row.iter().zip(&input).map(|(a, b)| a * b).sum(); + *o = small + from_hidden[k * 3 * r + i] + from_other[i] + self.step_bias[i]; + } + for i in 0..r { + let keep = cpu::sigmoid(out[i]); + state[i] = keep * state[i] + (1.0 - keep) * out[r + i].tanh(); + } + let said: Vec = out[2 * r..].iter().map(|o| o.tanh()).collect(); + self.spent[1] += started.elapsed(); + let started = std::time::Instant::now(); + // The device is idle here: the last thing done was a download. + let said_buffer = self.scratch.said; + self.upload(&said_buffer, &said)?; + let s = &self.scratch; + self.matmat.bf16( + Bf16Matrix { buffer: &self.table_out, offset: 0, rows: vocab, cols: r }, + &s.said, + 1, + &s.correction, + SEGS, + )?; + self.small.add( + Floats::first(&s.correction, vocab), + Floats { buffer: &s.base_bias, at: k * vocab, len: vocab }, + Floats::first(&s.sum, vocab), + )?; + self.wait()?; + let sum = self.scratch.sum; + let scores = self.download(&sum, vocab)?; + let mut best = 0; + for (i, v) in scores.iter().enumerate() { + if *v > scores[best] { + best = i; + } + } + guesses.push(best as u32); + previous = best; + self.spent[2] += started.elapsed(); + } + Ok(guesses) + } +} + +impl Drafter for CudaDraftHead<'_> { + fn wants(&self) -> Vec { + self.cfg.targets.clone() + } + + fn fed(&mut self, first: usize, kept: usize, states: &[DeviceVec]) -> Result<(), ModelError> { + if first == 0 { + self.positions = 0; + } + let h = self.cfg.hidden; + let fits = states.len() == self.cfg.targets.len() + && first == self.positions + && kept <= MOST_FED + && kept <= self.capacity - self.positions + && states.iter().all(|s| s.width() == h && s.count() >= kept); + if !fits { + return Err(ModelError::Capacity(format!( + "draft head: told of {kept} positions from {first} with {} values; it has read {} of {} positions and wants {} values", + states.len(), + self.positions, + self.capacity, + self.cfg.targets.len() + ))); + } + if kept == 0 { + return Ok(()); + } + self.told(first, kept, states).map_err(failed) + } + + fn draft(&mut self, tokens: &[u32], most: usize) -> Vec { + match self.guess(tokens, most) { + Ok(guesses) => { + self.last_error = None; + guesses + } + Err(e) => { + // A guesser that cannot guess proposes nothing: the text does not depend on it. + self.last_error = Some(e.to_string()); + Vec::new() + } + } + } +} + +impl Drop for CudaDraftHead<'_> { + fn drop(&mut self) { + // After everything started has finished; a failure leaves the buffers to the + // context's end. + let _ = self.dev.synchronize(); + for buffer in self.owned.drain(..) { + let _ = self.dev.free(buffer); + } + } +} diff --git a/crates/dluth-cuda/src/lib.rs b/crates/dluth-cuda/src/lib.rs index 1052b45..1081cf6 100644 --- a/crates/dluth-cuda/src/lib.rs +++ b/crates/dluth-cuda/src/lib.rs @@ -10,6 +10,7 @@ pub mod attention; pub mod blockmat; mod device; +pub mod draft_head; mod error; pub mod expert_ops; pub mod floats; diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs index afb9405..6f32db3 100644 --- a/crates/dluth-cuda/src/ops.rs +++ b/crates/dluth-cuda/src/ops.rs @@ -101,6 +101,11 @@ impl DeviceVec { self.0.len / self.0.count } + /// The device buffer that holds the values, from its start. + pub(crate) fn buffer(&self) -> &Buffer { + &self.0.buffer + } + fn all(&self) -> Floats<'_> { Floats::first(&self.0.buffer, self.0.len) } @@ -229,6 +234,13 @@ impl<'m> CudaOps<'m> { self.stats.clone() } + /// The device copy of a weight matrix of the model, made now if it has not been used + /// yet. For something beside the model that reads the model's own weights (the draft + /// head reads its output table). The copy lives as long as these operations do. + pub fn device_weight(&mut self, bytes: &[u8]) -> Result { + self.weight(bytes) + } + /// Bytes of weights copied to the device so far. pub fn weight_bytes(&self) -> usize { self.weight_bytes diff --git a/crates/dluth-cuda/tests/inkling_golden_cuda.rs b/crates/dluth-cuda/tests/inkling_golden_cuda.rs index 366313e..c2a00e2 100644 --- a/crates/dluth-cuda/tests/inkling_golden_cuda.rs +++ b/crates/dluth-cuda/tests/inkling_golden_cuda.rs @@ -4,6 +4,8 @@ #[path = "../../dluth-model/tests/common/mod.rs"] mod common; +#[path = "../../dluth-model/tests/tiny_head/mod.rs"] +mod tiny_head; use dluth_cuda::inkling::CudaProducts; use dluth_cuda::{CudaDevice, Module}; @@ -433,6 +435,147 @@ mod on_the_device { } } + /// A drafter that passes everything on and keeps what was proposed. + struct Recording(D, Vec>); + impl> dluth_model::inkling::Drafter for Recording { + fn draft(&mut self, tokens: &[u32], most: usize) -> Vec { + let guesses = self.0.draft(tokens, most); + self.1.push(guesses.clone()); + guesses + } + fn wants(&self) -> Vec { + self.0.wants() + } + fn fed(&mut self, first: usize, kept: usize, states: &[V]) -> Result<(), dluth_model::ModelError> { + self.0.fed(first, kept, states) + } + } + + fn embed_norm_of(weights: &Weights) -> Vec { + let bytes = weights.bytes("model.llm.embed_norm.weight").unwrap(); + bytes.as_chunks::<2>().0.iter().map(|c| dluth_core::bf16_to_f32(u16::from_le_bytes(*c))).collect() + } + + /// The draft head on the device against the head on the CPU, both of random weights on + /// the tiny model: the same text as plain generation, and the same proposals sweep + /// after sweep. The proposals come from the scores of the whole vocabulary, so two that + /// agree had every step of the head agree closely. + #[test] + fn the_draft_head_on_the_device_proposes_what_the_cpu_head_proposes() { + use dluth_cuda::draft_head::CudaDraftHead; + use dluth_model::inkling::mtp::{MtpDrafter, MtpHead}; + 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 scratch = tiny_head::Scratch::new("device"); + let head_cfg = tiny_head::tiny_config(cfg.hidden, cfg.layer_passes()); + tiny_head::write_head(&scratch.0, &head_cfg, cfg.vocab, None, None); + let embed = weights.bytes("model.llm.embed.weight").unwrap(); + let unembed = &weights.bytes("model.llm.unembed.weight").unwrap()[..cfg.vocab_out * cfg.hidden * 2]; + let prompt: Vec = (41..64).map(|p| ((p * 37 + 11) % 256) as u32).collect(); + + let cpu_head = MtpHead::load(&scratch.0, head_cfg.clone()).unwrap(); + let mut on_cpu = Recording( + MtpDrafter::new(&cpu_head, embed, embed_norm_of(&weights), unembed, cfg.vocab_out).unwrap(), + Vec::new(), + ); + let mut cpu = InklingCpu::new(load_config(&dir).unwrap(), &weights, 96).unwrap(); + let want = cpu.generate_greedy(&prompt, 40, u32::MAX).unwrap(); + let (cpu_text, cpu_stats) = cpu.generate_greedy_drafted(&prompt, 40, u32::MAX, &mut on_cpu, 3, |_| {}).unwrap(); + assert_eq!(cpu_text, want); + + let dev = CudaDevice::open(0).expect("GPU"); + let module = Module::load_embedded(&dev).unwrap(); + let mut ops = CudaOps::new(&dev, &module).unwrap(); + let table = ops.device_weight(unembed).unwrap(); + let before = dev.live_buffers(); + { + let head = CudaDraftHead::load( + &dev, + &module, + &scratch.0, + head_cfg.clone(), + embed, + embed_norm_of(&weights), + table, + cfg.vocab_out, + 96, + ) + .unwrap(); + let mut on_gpu = Recording(head, Vec::new()); + let mut gpu = Inkling::with_ops(load_config(&dir).unwrap(), &weights, 96, ops).unwrap(); + let plain = gpu.generate_greedy(&prompt, 40, u32::MAX).unwrap(); + let (gpu_text, gpu_stats) = + gpu.generate_greedy_drafted(&prompt, 40, u32::MAX, &mut on_gpu, 3, |_| {}).unwrap(); + assert_eq!(gpu_text, plain); + assert_eq!(on_gpu.0.last_error, None); + assert!(gpu_stats.drafted >= gpu_stats.sweeps * 2, "the head proposes at every sweep: {gpu_stats:?}"); + // Where the two models chose the same text, the two heads were asked the same + // questions, and must have answered alike nearly always (a near-tie between two + // tokens' scores can fall either way). + if plain == want { + assert_eq!(on_gpu.1.len(), on_cpu.1.len()); + let same = on_gpu.1.iter().zip(&on_cpu.1).filter(|(a, b)| a == b).count(); + eprintln!("device head: {same} of {} proposals identical to the CPU head's; {gpu_stats:?} against {cpu_stats:?}", on_cpu.1.len()); + assert!(same * 10 >= on_cpu.1.len() * 9, "{same} of {}", on_cpu.1.len()); + } else { + eprintln!("the two models' texts differ at a near-tie; the heads were not compared"); + } + // A second text starts the head afresh; a text it was not told of gets no proposal. + let (again, _) = gpu.generate_greedy_drafted(&prompt, 12, u32::MAX, &mut on_gpu, 3, |_| {}).unwrap(); + assert_eq!(again, plain[..12]); + use dluth_model::inkling::Drafter; + assert!(Drafter::::draft(&mut on_gpu.0, &prompt[..5], 3).is_empty()); + assert!(on_gpu.0.fed(3, 1, &[]).is_err()); + } + // The head gave back every buffer it took; the model's are gone with the model. + assert!(dev.live_buffers() < before); + } + + /// The real head on the real model on the device: the same text as plain generation, + /// in well under half the sweeps. + #[test] + fn the_real_draft_head_guesses_well_on_the_device() { + use dluth_cuda::draft_head::CudaDraftHead; + use dluth_model::inkling::mtp::load_mtp_config; + 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"][1]["prompt_ids"].clone()).unwrap(); + let weights = Weights::open_dir(&dir).unwrap(); + let cfg = load_config(&dir).unwrap(); + let (eos, vocab_out, h) = (cfg.eos, cfg.vocab_out, cfg.hidden); + let dev = CudaDevice::open(0).expect("GPU"); + let module = Module::load_embedded(&dev).unwrap(); + let mut ops = CudaOps::new(&dev, &module).unwrap(); + let unembed = &weights.bytes("model.llm.unembed.weight").unwrap()[..vocab_out * h * 2]; + let table = ops.device_weight(unembed).unwrap(); + let mut head = CudaDraftHead::load( + &dev, + &module, + &dir, + load_mtp_config(&dir).unwrap().expect("a draft head"), + weights.bytes("model.llm.embed.weight").unwrap(), + embed_norm_of(&weights), + table, + vocab_out, + 256, + ) + .unwrap(); + let mut model = Inkling::with_ops(cfg, &weights, 256, ops).unwrap(); + let new = 96; + let want = model.generate_greedy(&prompt, new, eos).unwrap(); + let (got, stats) = model.generate_greedy_drafted(&prompt, new, eos, &mut head, 5, |_| {}).unwrap(); + eprintln!("the real head on the device: {} tokens, {stats:?}", got.len()); + assert_eq!(head.last_error, None); + assert_eq!(got, want); + assert!(stats.sweeps * 2 < want.len() - 1, "{stats:?} for {} tokens", want.len()); + } + /// More positions than a launch takes are refused before anything is computed, and the /// model goes on as if it had not been asked. #[test] diff --git a/crates/dluth-model/tests/inkling_mtp.rs b/crates/dluth-model/tests/inkling_mtp.rs index 7f9835c..e3daaef 100644 --- a/crates/dluth-model/tests/inkling_mtp.rs +++ b/crates/dluth-model/tests/inkling_mtp.rs @@ -3,115 +3,19 @@ //! the text of plain generation. On the real model with its real head (when the weights //! are at hand) the guesses must be good. -use dluth_model::inkling::mtp::{load_mtp_config, MtpConfig, MtpDrafter, MtpHead}; +mod tiny_head; + +use dluth_model::inkling::mtp::{load_mtp_config, MtpDrafter, MtpHead}; use dluth_model::inkling::{load_config, CpuVecs, Drafter, InklingCpu}; use dluth_model::weights::Weights; use dluth_model::ModelError; use std::path::{Path, PathBuf}; +use tiny_head::{tiny_config, write_head, Scratch}; fn tiny() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/tiny-inkling") } -/// A directory under the system's temporary one, removed when dropped. -struct Scratch(PathBuf); -impl Scratch { - fn new(name: &str) -> Self { - let dir = std::env::temp_dir().join(format!("dluth-mtp-{name}-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - Scratch(dir) - } -} -impl Drop for Scratch { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } -} - -fn tiny_config(hidden: usize, applications: usize) -> MtpConfig { - MtpConfig { - hidden, - layers: 2, - heads: 4, - kv_heads: 2, - head_dim: 4, - inner: 24, - theta: 10_000.0, - eps: 1e-6, - block: 4, - rank: 6, - targets: vec![1, 3, applications], - } -} - -/// The head's tensors for `cfg`, with fixed pseudo-random BF16 values, as a safetensors -/// file. `skip` leaves one tensor out and `short` gives one a value too few. -fn write_head(dir: &Path, cfg: &MtpConfig, vocab: usize, skip: Option<&str>, short: Option<&str>) { - let (h, q, kv, d, r) = (cfg.hidden, cfg.heads * cfg.head_dim, cfg.kv_heads * cfg.head_dim, cfg.head_dim, cfg.rank); - let mut tensors: Vec<(String, Vec)> = vec![ - ("fuse_weight".into(), vec![cfg.layers + 1, cfg.targets.len()]), - ("mask_embed".into(), vec![h]), - ("norm.weight".into(), vec![h]), - ("markov_head.markov_w1.weight".into(), vec![vocab, r]), - ("markov_head.rnn_proj.weight".into(), vec![3 * r, 2 * r + 2 * h]), - ("markov_head.rnn_proj.bias".into(), vec![3 * r]), - ("markov_head.hidden_out.weight".into(), vec![h, r]), - ("markov_head.hidden_out.bias".into(), vec![h]), - ("markov_head.dflare_norm.weight".into(), vec![h]), - ]; - for i in 0..cfg.layers { - for (name, shape) in [ - ("input_layernorm.weight", vec![h]), - ("post_attention_layernorm.weight", vec![h]), - ("dflare_norm.weight", vec![h]), - ("self_attn.q_proj.weight", vec![q, h]), - ("self_attn.k_proj.weight", vec![kv, h]), - ("self_attn.v_proj.weight", vec![kv, h]), - ("self_attn.o_proj.weight", vec![h, q]), - ("self_attn.k_proj_ctx.weight", vec![kv, h]), - ("self_attn.v_proj_ctx.weight", vec![kv, h]), - ("self_attn.q_norm.weight", vec![d]), - ("self_attn.k_norm.weight", vec![d]), - ("self_attn.k_norm_ctx.weight", vec![d]), - ("mlp.gate_proj.weight", vec![cfg.inner, h]), - ("mlp.up_proj.weight", vec![cfg.inner, h]), - ("mlp.down_proj.weight", vec![h, cfg.inner]), - ] { - tensors.push((format!("layers.{i}.{name}"), shape)); - } - } - let mut header = serde_json::Map::new(); - let mut data: Vec = Vec::new(); - let mut seed = 0x2545_F491_4F6C_DD1Du64; - for (name, mut shape) in tensors { - if skip == Some(name.as_str()) { - continue; - } - if short == Some(name.as_str()) { - *shape.last_mut().unwrap() -= 1; - } - let count: usize = shape.iter().product(); - let start = data.len(); - for _ in 0..count { - seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - // A value in [-0.5, 0.5), norm weights around 1; as BF16, the top half of the float. - let unit = (seed >> 40) as f32 / (1u64 << 24) as f32 - 0.5; - let value = if name.ends_with("norm.weight") || name.ends_with("norm_ctx.weight") { - 1.0 + unit * 0.2 - } else { - unit - }; - data.extend_from_slice(&((value.to_bits() >> 16) as u16).to_le_bytes()); - } - header.insert(name, serde_json::json!({"dtype": "BF16", "shape": shape, "data_offsets": [start, data.len()]})); - } - let header = serde_json::Value::Object(header).to_string(); - let mut bytes = (header.len() as u64).to_le_bytes().to_vec(); - bytes.extend_from_slice(header.as_bytes()); - bytes.extend_from_slice(&data); - std::fs::write(dir.join("mtp.safetensors"), bytes).unwrap(); -} - fn prompt() -> Vec { (41..64).map(|i| ((i * 37 + 11) % 256) as u32).collect() } diff --git a/crates/dluth-model/tests/tiny_head/mod.rs b/crates/dluth-model/tests/tiny_head/mod.rs new file mode 100644 index 0000000..3d5709e --- /dev/null +++ b/crates/dluth-model/tests/tiny_head/mod.rs @@ -0,0 +1,105 @@ +//! A draft head of random weights, small enough for tests, written as the file a real one +//! comes in. Shared by the CPU head's tests and the device head's. +#![allow(dead_code)] + +use dluth_model::inkling::mtp::MtpConfig; +use std::path::{Path, PathBuf}; + +/// A directory under the system's temporary one, removed when dropped. +pub struct Scratch(pub PathBuf); +impl Scratch { + pub fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("dluth-mtp-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } +} +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +pub fn tiny_config(hidden: usize, applications: usize) -> MtpConfig { + MtpConfig { + hidden, + layers: 2, + heads: 4, + kv_heads: 2, + head_dim: 4, + inner: 24, + theta: 10_000.0, + eps: 1e-6, + block: 4, + rank: 6, + targets: vec![1, 3, applications], + } +} + +/// The head's tensors for `cfg`, with fixed pseudo-random BF16 values, as a safetensors +/// file. `skip` leaves one tensor out and `short` gives one a value too few. +pub fn write_head(dir: &Path, cfg: &MtpConfig, vocab: usize, skip: Option<&str>, short: Option<&str>) { + let (h, q, kv, d, r) = (cfg.hidden, cfg.heads * cfg.head_dim, cfg.kv_heads * cfg.head_dim, cfg.head_dim, cfg.rank); + let mut tensors: Vec<(String, Vec)> = vec![ + ("fuse_weight".into(), vec![cfg.layers + 1, cfg.targets.len()]), + ("mask_embed".into(), vec![h]), + ("norm.weight".into(), vec![h]), + ("markov_head.markov_w1.weight".into(), vec![vocab, r]), + ("markov_head.rnn_proj.weight".into(), vec![3 * r, 2 * r + 2 * h]), + ("markov_head.rnn_proj.bias".into(), vec![3 * r]), + ("markov_head.hidden_out.weight".into(), vec![h, r]), + ("markov_head.hidden_out.bias".into(), vec![h]), + ("markov_head.dflare_norm.weight".into(), vec![h]), + ]; + for i in 0..cfg.layers { + for (name, shape) in [ + ("input_layernorm.weight", vec![h]), + ("post_attention_layernorm.weight", vec![h]), + ("dflare_norm.weight", vec![h]), + ("self_attn.q_proj.weight", vec![q, h]), + ("self_attn.k_proj.weight", vec![kv, h]), + ("self_attn.v_proj.weight", vec![kv, h]), + ("self_attn.o_proj.weight", vec![h, q]), + ("self_attn.k_proj_ctx.weight", vec![kv, h]), + ("self_attn.v_proj_ctx.weight", vec![kv, h]), + ("self_attn.q_norm.weight", vec![d]), + ("self_attn.k_norm.weight", vec![d]), + ("self_attn.k_norm_ctx.weight", vec![d]), + ("mlp.gate_proj.weight", vec![cfg.inner, h]), + ("mlp.up_proj.weight", vec![cfg.inner, h]), + ("mlp.down_proj.weight", vec![h, cfg.inner]), + ] { + tensors.push((format!("layers.{i}.{name}"), shape)); + } + } + let mut header = serde_json::Map::new(); + let mut data: Vec = Vec::new(); + let mut seed = 0x2545_F491_4F6C_DD1Du64; + for (name, mut shape) in tensors { + if skip == Some(name.as_str()) { + continue; + } + if short == Some(name.as_str()) { + *shape.last_mut().unwrap() -= 1; + } + let count: usize = shape.iter().product(); + let start = data.len(); + for _ in 0..count { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + // A value in [-0.5, 0.5), norm weights around 1; as BF16, the top half of the float. + let unit = (seed >> 40) as f32 / (1u64 << 24) as f32 - 0.5; + let value = if name.ends_with("norm.weight") || name.ends_with("norm_ctx.weight") { + 1.0 + unit * 0.2 + } else { + unit + }; + data.extend_from_slice(&((value.to_bits() >> 16) as u16).to_le_bytes()); + } + header.insert(name, serde_json::json!({"dtype": "BF16", "shape": shape, "data_offsets": [start, data.len()]})); + } + let header = serde_json::Value::Object(header).to_string(); + let mut bytes = (header.len() as u64).to_le_bytes().to_vec(); + bytes.extend_from_slice(header.as_bytes()); + bytes.extend_from_slice(&data); + std::fs::write(dir.join("mtp.safetensors"), bytes).unwrap(); +} From 2c71639988c57a198f5e4429746beda3f948662b Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:52:11 -0800 Subject: [PATCH 3/9] feat(serve): the engine's guesser is told of what is fed; dluth-cuda serve uses the model's draft head --- crates/dluth-cuda/src/bin/dluth-cuda.rs | 47 +++++++++++++++++++-- crates/dluth-serve/src/cli.rs | 42 ++++++++++++++++--- crates/dluth-serve/src/engine.rs | 44 +++++++++++++++++-- crates/dluth-serve/tests/engine.rs | 56 +++++++++++++++++++++++++ crates/dluth/src/main.rs | 2 +- 5 files changed, 176 insertions(+), 15 deletions(-) diff --git a/crates/dluth-cuda/src/bin/dluth-cuda.rs b/crates/dluth-cuda/src/bin/dluth-cuda.rs index 81d463f..d068a04 100644 --- a/crates/dluth-cuda/src/bin/dluth-cuda.rs +++ b/crates/dluth-cuda/src/bin/dluth-cuda.rs @@ -6,9 +6,11 @@ //! through the model, which copies every layer's weights to the device, so that the first //! request does not pay for that. -use dluth_cuda::ops::CudaOps; +use dluth_cuda::draft_head::CudaDraftHead; +use dluth_cuda::ops::{CudaOps, DeviceVec}; use dluth_cuda::{CudaDevice, Module}; -use dluth_model::inkling::{load_config, model_kind, Inkling, ModelKind}; +use dluth_model::inkling::mtp::load_mtp_config; +use dluth_model::inkling::{load_config, model_kind, Drafter, Inkling, ModelKind}; use dluth_model::tokenizer::Tokenizer; use dluth_model::weights::Weights; use dluth_serve::cli; @@ -29,7 +31,44 @@ fn run(args: &[String]) -> Result<(), String> { let cfg = load_config(&args.model).map_err(|e| text(&e))?; let dev = CudaDevice::open(0).map_err(|e| text(&e))?; let module = Module::load_embedded(&dev).map_err(|e| text(&e))?; - let ops = CudaOps::new(&dev, &module).map_err(|e| text(&e))?; + let mut ops = CudaOps::new(&dev, &module).map_err(|e| text(&e))?; + // The model's own draft head, if the checkpoint has one: it proposes tokens that the + // model then checks several at a time. It reads the model's output table on the device. + let mut args = args; + let head: Option + '_>> = match load_mtp_config(&args.model).map_err(|e| text(&e))? { + Some(head_cfg) if args.head && args.model.join("mtp.safetensors").exists() => { + let (h, vocab_out) = (cfg.hidden, cfg.vocab_out); + let unembed = &weights.bytes("model.llm.unembed.weight").map_err(|e| text(&e))?[..vocab_out * h * 2]; + let table = ops.device_weight(unembed).map_err(|e| text(&e))?; + let embed_norm: Vec = weights + .bytes("model.llm.embed_norm.weight") + .map_err(|e| text(&e))? + .as_chunks::<2>() + .0 + .iter() + .map(|c| f32::from_bits((u16::from_le_bytes(*c) as u32) << 16)) + .collect(); + let embed = weights.bytes("model.llm.embed.weight").map_err(|e| text(&e))?; + let head = CudaDraftHead::load( + &dev, + &module, + &args.model, + head_cfg, + embed, + embed_norm, + table, + vocab_out, + args.context, + ) + .map_err(|e| text(&e))?; + // Two guesses a sweep is where this head pays best on this machine. + if !args.guesses_given { + args.options.guesses = 2; + } + Some(Box::new(head)) + } + _ => None, + }; let mut model = Inkling::with_ops(cfg, &weights, args.context, ops).map_err(|e| text(&e))?; // Any token will do: each layer's weights go to the device the first time the layer runs. @@ -40,7 +79,7 @@ fn run(args: &[String]) -> Result<(), String> { model.ops().weight_bytes() as f64 / 1e9, started.elapsed().as_secs_f64() ); - cli::run(model, &tokenizer, &args) + cli::run(model, &tokenizer, &args, head) } fn main() -> ExitCode { diff --git a/crates/dluth-serve/src/cli.rs b/crates/dluth-serve/src/cli.rs index 301d544..6be807e 100644 --- a/crates/dluth-serve/src/cli.rs +++ b/crates/dluth-serve/src/cli.rs @@ -3,7 +3,7 @@ use crate::engine::{InklingEngine, Options}; use crate::server::{serve, Config}; use dluth_model::inkling::prompt::Effort; -use dluth_model::inkling::{Inkling, Ops}; +use dluth_model::inkling::{Drafter, Inkling, Ops}; use dluth_model::tokenizer::Tokenizer; use std::net::TcpListener; use std::path::PathBuf; @@ -12,7 +12,7 @@ use std::sync::Arc; pub const USAGE: &str = "serve --model [--listen ] [--context ] \ [--name ] [--guesses ] [--match ] [--prompt-batch ] \ -[--temperature ] [--effort ] [--queue ]"; +[--temperature ] [--effort ] [--queue ] [--head on|off]"; /// The environment variable that, when set, is the key clients must send. pub const KEY_VARIABLE: &str = "DLUTH_API_KEY"; @@ -26,6 +26,10 @@ pub struct ServeArgs { pub context: usize, pub queue: usize, pub options: Options, + /// Whether `--guesses` was given, for a program whose default depends on the guesser. + pub guesses_given: bool, + /// Whether the model's own draft head is to be used where there is one. + pub head: bool, } /// Reads the arguments after `serve`. The error is a sentence for the person who typed them. @@ -36,6 +40,8 @@ pub fn parse(args: &[String]) -> Result { context: 8192, queue: Config::default().queue, options: Options::default(), + guesses_given: false, + head: true, }; let mut name = None; let mut it = args.iter(); @@ -53,7 +59,17 @@ pub fn parse(args: &[String]) -> Result { "--listen" => out.listen = value.clone(), "--context" => out.context = count(2)?, "--name" => name = Some(value.clone()), - "--guesses" => out.options.guesses = count(0)?, + "--guesses" => { + out.options.guesses = count(0)?; + out.guesses_given = true; + } + "--head" => { + out.head = match value.as_str() { + "on" => true, + "off" => false, + other => return Err(format!("--head {other}: on or off is needed")), + } + } "--match" => out.options.match_run = count(1)?, "--prompt-batch" => out.options.prompt_batch = count(1)?, "--queue" => out.queue = count(1)?, @@ -80,18 +96,28 @@ pub fn parse(args: &[String]) -> Result { /// Serves `model` until the process ends. Prints where it listens and one line per request /// to standard error; never a key, a prompt or a reply. -pub fn run(model: Inkling<'_, O>, tokenizer: &Tokenizer, args: &ServeArgs) -> Result<(), String> { +pub fn run<'t, O: Ops>( + model: Inkling<'_, O>, + tokenizer: &'t Tokenizer, + args: &ServeArgs, + drafter: Option + 't>>, +) -> Result<(), String> { let listener = TcpListener::bind(&args.listen).map_err(|e| format!("cannot listen on {}: {e}", args.listen))?; let address = listener.local_addr().map_err(|e| e.to_string())?; let api_key = std::env::var(KEY_VARIABLE).ok().filter(|k| !k.is_empty()); eprintln!( - "serving {} on http://{address}/v1 (context {} tokens, {} guesses per sweep, {})", + "serving {} on http://{address}/v1 (context {} tokens, {} guesses per sweep from {}, {})", args.options.name, model.capacity(), args.options.guesses, + if drafter.is_some() { "the model's draft head" } else { "the text itself" }, if api_key.is_some() { "a key is required" } else { "no key is required" } ); - let mut engine = InklingEngine::new(model, tokenizer, args.options.clone()); + let mut engine = match drafter { + Some(drafter) => InklingEngine::with_drafter(model, tokenizer, args.options.clone(), drafter) + .map_err(|e| format!("the drafter does not fit the model: {e:?}"))?, + None => InklingEngine::new(model, tokenizer, args.options.clone()), + }; let config = Config { api_key, queue: args.queue, ..Config::default() }; serve(listener, &mut engine, config, Arc::new(AtomicBool::new(false)), &mut |line| eprintln!("{line}")) .map_err(|e| e.to_string()) @@ -118,6 +144,9 @@ mod tests { assert_eq!((a.listen.as_str(), a.context, a.queue, a.options.name.as_str()), ("0.0.0.0:9000", 4096, 2, "mine")); assert_eq!((a.options.guesses, a.options.match_run, a.options.prompt_batch), (0, 3, 8)); assert_eq!((a.options.temperature, a.options.effort), (0.0, Effort::Low)); + assert!(a.guesses_given && a.head); + let a = parse(&args("--model m --head off")).unwrap(); + assert!(!a.guesses_given && !a.head); } #[test] @@ -131,6 +160,7 @@ mod tests { ("--model m --temperature -1", "--temperature -1"), ("--model m --effort extreme", "extreme"), ("--model m --port 80", "unknown argument --port"), + ("--model m --head maybe", "on or off"), ] { let e = parse(&args(text)).unwrap_err(); assert!(e.contains(word), "{text}: {e}"); diff --git a/crates/dluth-serve/src/engine.rs b/crates/dluth-serve/src/engine.rs index 8651d50..ef224e8 100644 --- a/crates/dluth-serve/src/engine.rs +++ b/crates/dluth-serve/src/engine.rs @@ -10,7 +10,7 @@ use crate::api::{ChatRequest, Usage}; use crate::reply::{Delta, Markers, ReplyReader, StopFilter}; use dluth_model::inkling::prompt::{chat, more_turns, Effort, Message, Role}; use dluth_model::inkling::sample::{Sampler, Sampling}; -use dluth_model::inkling::{Drafter, Inkling, LookupDrafter, NoDraft, Ops}; +use dluth_model::inkling::{Drafter, Inkling, LookupDrafter, Ops}; use dluth_model::tokenizer::Tokenizer; use dluth_model::ModelError; use std::time::Instant; @@ -85,6 +85,21 @@ impl Default for Options { } } +/// A drafter that is told of what is fed and proposes nothing. +struct Told<'a, V>(&'a mut dyn Drafter); + +impl Drafter for Told<'_, V> { + fn draft(&mut self, _tokens: &[u32], _most: usize) -> Vec { + Vec::new() + } + fn wants(&self) -> Vec { + self.0.wants() + } + fn fed(&mut self, first: usize, kept: usize, states: &[V]) -> Result<(), ModelError> { + self.0.fed(first, kept, states) + } +} + /// The conversation answered last. struct Served { messages: Vec, @@ -98,6 +113,9 @@ struct Served { /// An Inkling model answering chat requests. pub struct InklingEngine<'w, 't, O: Ops> { model: Inkling<'w, O>, + /// What proposes tokens. It is told of every batch the model is fed, so that one which + /// reads the model's values keeps step with the text the model holds. + drafter: Box + 't>, tokenizer: &'t Tokenizer, markers: Markers, options: Options, @@ -115,9 +133,24 @@ fn refused(e: ModelError) -> EngineError { } impl<'w, 't, O: Ops> InklingEngine<'w, 't, O> { + /// An engine whose guesses, if `options.guesses` is not 0, come from the text itself + /// (`LookupDrafter`). pub fn new(model: Inkling<'w, O>, tokenizer: &'t Tokenizer, options: Options) -> Self { + let lookup = LookupDrafter::new(options.match_run.max(4), options.match_run); + // The lookup wants none of the model's values, so asking for them cannot fail. + Self::with_drafter(model, tokenizer, options, Box::new(lookup)).unwrap_or_else(|_| unreachable!()) + } + + /// An engine whose guesses come from `drafter` (the model's draft head, for one). + pub fn with_drafter( + mut model: Inkling<'w, O>, + tokenizer: &'t Tokenizer, + options: Options, + drafter: Box + 't>, + ) -> Result { + model.tap(&drafter.wants()).map_err(refused)?; let markers = Markers::of(tokenizer); - InklingEngine { model, tokenizer, markers, options, held: Vec::new(), served: None, requests: 0 } + Ok(InklingEngine { model, drafter, tokenizer, markers, options, held: Vec::new(), served: None, requests: 0 }) } /// The prompt's tokens. If the request continues the conversation answered last, they @@ -154,6 +187,7 @@ impl<'w, 't, O: Ops> InklingEngine<'w, 't, O> { let mut pos = start; for batch in tokens[start..].chunks(self.options.prompt_batch.max(1)) { self.model.feed(batch, pos)?; + self.drafter.fed(pos, batch.len(), self.model.tapped())?; pos += batch.len(); } Ok(start) @@ -205,8 +239,10 @@ impl Engine for InklingEngine<'_, '_, O> { nanos ^ self.requests.wrapping_mul(0x9E37_79B9_7F4A_7C15) }), }); - let mut lookup = LookupDrafter::new(self.options.match_run.max(4), self.options.match_run); - let drafter: &mut dyn Drafter = if self.options.guesses == 0 { &mut NoDraft } else { &mut lookup }; + // With no guesses asked for, nothing proposes; the engine's drafter is still told of + // what is fed, so that it is in step when guesses are asked for again. + let mut told = Told(self.drafter.as_mut()); + let drafter: &mut dyn Drafter = if self.options.guesses == 0 { &mut told } else { self.drafter.as_mut() }; let mut reader = ReplyReader::new(self.tokenizer, self.markers); let mut stops = StopFilter::new(&request.stop); diff --git a/crates/dluth-serve/tests/engine.rs b/crates/dluth-serve/tests/engine.rs index bffcd62..9140dfa 100644 --- a/crates/dluth-serve/tests/engine.rs +++ b/crates/dluth-serve/tests/engine.rs @@ -1,6 +1,9 @@ //! The engine with the tiny model on the CPU: what it hands out is what the model, used //! directly, produces for the same tokens; and a conversation that goes on is not read again. +#[path = "../../dluth-model/tests/tiny_head/mod.rs"] +mod tiny_head; + use dluth_model::inkling::prompt::{chat, more_turns, Effort, Message, Role}; use dluth_model::inkling::sample::{Sampler, Sampling}; use dluth_model::inkling::{load_config, InklingCpu, NoDraft}; @@ -236,3 +239,56 @@ fn stop_strings_limits_and_refusals() { let (got, _, _) = ask(&mut engine, &request(messages, 30, 0.0, 0)); assert_eq!(got, whole); } + +/// The engine with the model's draft head as its guesser (a head of random weights here): +/// the replies are those of the model used directly, and the head keeps step with the text +/// across a conversation that goes on and one that starts over. +#[test] +fn the_engine_with_a_draft_head_hands_out_the_same_replies() { + use dluth_model::inkling::mtp::{MtpDrafter, MtpHead}; + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let tokenizer = Tokenizer::from_file(&dir.join("tokenizer.json")).unwrap(); + let cfg = load_config(&dir).unwrap(); + let scratch = tiny_head::Scratch::new("engine"); + let head_cfg = tiny_head::tiny_config(cfg.hidden, cfg.layer_passes()); + tiny_head::write_head(&scratch.0, &head_cfg, cfg.vocab, None, None); + let head = MtpHead::load(&scratch.0, head_cfg).unwrap(); + let embed_norm: Vec = weights + .bytes("model.llm.embed_norm.weight") + .unwrap() + .as_chunks::<2>() + .0 + .iter() + .map(|c| f32::from_bits((u16::from_le_bytes(*c) as u32) << 16)) + .collect(); + let drafter = MtpDrafter::new( + &head, + weights.bytes("model.llm.embed.weight").unwrap(), + embed_norm, + weights.bytes("model.llm.unembed.weight").unwrap(), + cfg.vocab_out, + ) + .unwrap(); + let mut plain = InklingCpu::new(load_config(&dir).unwrap(), &weights, 256).unwrap(); + let model = InklingCpu::new(cfg, &weights, 256).unwrap(); + let options = Options { guesses: 3, ..Options::default() }; + let mut engine = InklingEngine::with_drafter(model, &tokenizer, options, Box::new(drafter)).unwrap(); + + let first = vec![user("hello there")]; + let prompt = tokenizer.encode(&chat(&first, Effort::None)).unwrap(); + for (messages, tokens, new) in + [(first.clone(), prompt.clone(), 30), (vec![user("another start")], Vec::new(), 12), (first.clone(), prompt, 9)] + { + let tokens = if tokens.is_empty() { tokenizer.encode(&chat(&messages, Effort::None)).unwrap() } else { tokens }; + let (got, _, usage) = ask(&mut engine, &request(messages, new, 0.0, 0)); + assert_eq!(got, direct(&mut plain, &tokenizer, &tokens, new, Sampling::greedy()).1); + // The head proposed at every sweep that had room for a guess. + assert!(usage.guessed >= usage.sweeps.saturating_sub(1), "{usage:?}"); + } + // Drawn tokens too: the guesses are compared with what was drawn. + let messages = vec![user("draw something")]; + let tokens = tokenizer.encode(&chat(&messages, Effort::None)).unwrap(); + let (got, _, _) = ask(&mut engine, &request(messages, 25, 1.0, 5)); + assert_eq!(got, direct(&mut plain, &tokenizer, &tokens, 25, Sampling { temperature: 1.0, top_p: 1.0, seed: 5 }).1); +} diff --git a/crates/dluth/src/main.rs b/crates/dluth/src/main.rs index d979a2a..0361fa6 100644 --- a/crates/dluth/src/main.rs +++ b/crates/dluth/src/main.rs @@ -180,7 +180,7 @@ fn serve(args: &[String]) -> Result<(), Failure> { let tokenizer = Tokenizer::from_file(&args.model.join("tokenizer.json")).map_err(refused)?; let cfg = inkling::load_config(&args.model).map_err(refused)?; let model = InklingCpu::new(cfg, &weights, args.context).map_err(refused)?; - dluth_serve::cli::run(model, &tokenizer, &args).map_err(Failure::Failed) + dluth_serve::cli::run(model, &tokenizer, &args, None).map_err(Failure::Failed) } fn run(args: &[String]) -> Result<(), Failure> { From 47b24a11efeee01ad8869050b55f60ab6773eac7 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:54:25 -0800 Subject: [PATCH 4/9] docs: note 25, the model's own guesser --- docs/learning/25-the-draft-head.md | 94 ++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 docs/learning/25-the-draft-head.md diff --git a/docs/learning/25-the-draft-head.md b/docs/learning/25-the-draft-head.md new file mode 100644 index 0000000..eadeefd --- /dev/null +++ b/docs/learning/25-the-draft-head.md @@ -0,0 +1,94 @@ +# 25. The model's own guesser + +Note 23 built the machinery for guesses: propose a few tokens, let one sweep of the model check them, take +back the wrong ones. Its guesser looked the text up in itself, and was right too rarely on ordinary text to +pay. Inkling 2's checkpoint includes a small network trained for exactly this job, in a file of its own +(`mtp.safetensors`, 636 MB). This note is about that network: what it computes, how that was found out, and +what it is worth. + +## What it does + +The model has read the text up to some position and chosen the next token, the anchor. The head is given a +block: the anchor's embedding, then placeholders for the positions that follow. + +- **Three layers refine the block.** Each is attention followed by a gated feed-forward part, as in an + ordinary small transformer, with one addition: in attention, the block's positions also look at every + earlier position of the text. What they see there is not the text's tokens but the model's own work: for + each position, a mix of four of the model's intermediate values (its running sum after 5, 23, 41 and all + 48 layer applications), normalized, with a key and a value projection of their own. The mix is fixed: a + softmax over a row of learned weights, one row per layer. +- **That gives every placeholder a hidden state at once.** Scored against the model's output table, the + first placeholder is right about the next token more than half the time. The later ones are not: each + was computed without knowing which tokens were chosen before it. +- **A small recurrent step repairs that, left to right.** Its state is 256 numbers. For each placeholder + it reads its state, a learned vector for the token just guessed, the placeholder's hidden state and one + more mix of the model's values, and produces a new state and a correction that is added to the hidden + state. The corrected state is scored, the best token is the guess, and the step moves on. + +## How it was found out + +The design follows two public papers (DFlare, arXiv 2606.02091, for the layers and the mixing of the +model's values; DSpark, arXiv 2607.05147, for the recurrent step). They do not settle this checkpoint's +details: where positions enter, which values are mixed, what the step's inputs are and what is done with +its output. + +A guesser has a property that makes those findable: it cannot be wrong, only useless. So each open point +became a switch, and each combination was scored by how often the head's guesses were the tokens the model +actually chose on real text. A reading that is right announces itself. Without rotary positions the first +guess was right 1 time in 12; with them, 9 in 12. The anchor's own position guesses nothing; the first +placeholder does. And so on, through a few hundred combinations for the layers and a few thousand for the +step. + +One lesson came out of it. To score the step's readings quickly, the true token was ranked among the 64 +tokens the layers alone liked best. Under that shortcut, one reading (use the step's output alone, not +added to the hidden state) looked best. In real generation it was the worst: 91 sweeps for 100 tokens, +where the right reading takes 40. The shortcut had kept a bad reading among good candidates. The real test +took ten minutes; it should have been the first one. + +Some points are still open (which of two nearly equal values the last of the four is, whether a placeholder +sees the ones after it, what exactly the step's fourth input is). Each is worth a few percent of right +guesses at most, and can be settled the same way. + +## Making it cheap enough + +A sweep of the model over three positions costs about 50 ms on the GB10. A guesser that costs 16 ms on top +eats what it saves, and the first version did. Two things brought it to 8: + +- **The step's scores do not go through the output table again.** A guess's hidden state is the + placeholder's hidden state plus a fixed matrix times the step's small output. So the table times that + matrix is computed once, when the head is loaded (a product of 200,000 by 256), and each guess reads + that product and adds the scores the block already has. A ninth of the bytes of the table, and half of + that again by storing the product as BF16, which is precise enough for a guess. +- **The step's projection is split by what it reads.** Its two wide inputs are known for the whole block + before the first guess, so their parts of the projection are products on the device, once per block. + The host is left with the part that reads the state and the last token: 768 by 512. + +Half of the remaining 8 ms is the block's scores over the whole vocabulary. + +## What it is worth + +Inkling 2 Mini on the GB10, one prompt, 199 tokens after the first, the highest score at every step: + +| Guesses per sweep | Tokens per second | Sweeps | Guessed | Right | +|---|---|---|---|---| +| none | 28.1 | 199 | | | +| 1 | 30.9 | 126 | 125 | 73 | +| 2 | 33.5 | 102 | 203 | 97 | +| 3 | 31.4 | 97 | 288 | 102 | +| 4 | 30.0 | 91 | 364 | 108 | + +The text is the same in every row. Two guesses is the best trade on this machine: the first guess is right +58 percent of the time, the second, given the first, about as often, and after that the price of a wider +sweep outruns the guesses it lands. On code, where more is predictable, the same setting gave 39 tokens +per second; with tokens drawn at temperature 1, 30. + +## How it is checked + +- The CPU head, in 32-bit floats, is the reference. With a head of random weights on the tiny model, the + text of generation is that of plain generation whatever the head proposes. With the real weights on a + recorded prompt it must also need fewer than half the sweeps. +- The device head against the CPU head, same random weights, same text: the same proposals, sweep after + sweep (38 of 38). Proposals come from scores over the whole vocabulary, so two heads that agree on them + agreed closely at every step before. +- The engine with a head as its guesser hands out the replies of the model used directly, with the + highest score and with drawn tokens, across conversations that go on and that start over. From 07a40b953d9a3c486da953675c54cd5e5e4a35d6 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:55:30 -0800 Subject: [PATCH 5/9] test: the tiny head's proposals, written down --- crates/dluth-model/tests/inkling_mtp.rs | 54 +++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/crates/dluth-model/tests/inkling_mtp.rs b/crates/dluth-model/tests/inkling_mtp.rs index e3daaef..3d8996d 100644 --- a/crates/dluth-model/tests/inkling_mtp.rs +++ b/crates/dluth-model/tests/inkling_mtp.rs @@ -66,6 +66,60 @@ fn whatever_the_head_proposes_the_text_is_that_of_plain_generation() { assert_eq!(again, want[..12]); } +/// A drafter that passes everything on and keeps what was proposed. +struct Recording<'a>(MtpDrafter<'a>, Vec>); +impl Drafter for Recording<'_> { + fn draft(&mut self, tokens: &[u32], most: usize) -> Vec { + let guesses = self.0.draft(tokens, most); + self.1.push(guesses.clone()); + guesses + } + fn wants(&self) -> Vec { + self.0.wants() + } + fn fed(&mut self, first: usize, kept: usize, states: &[CpuVecs]) -> Result<(), ModelError> { + self.0.fed(first, kept, states) + } +} + +/// What the head of random weights proposes on the tiny model, written down. That the +/// head's arithmetic is right is shown with the real weights (the last test here: a wrong +/// head does not guess well). This test is what notices a change to that arithmetic on a +/// machine without them: any part of the head that is altered alters these proposals. +#[test] +fn the_head_s_proposals_on_the_tiny_model_are_what_they_were() { + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let cfg = load_config(&dir).unwrap(); + let scratch = Scratch::new("pinned"); + let head_cfg = tiny_config(cfg.hidden, cfg.layer_passes()); + write_head(&scratch.0, &head_cfg, cfg.vocab, None, None); + let head = MtpHead::load(&scratch.0, head_cfg).unwrap(); + let embed_norm: Vec = weights + .bytes("model.llm.embed_norm.weight") + .unwrap() + .as_chunks::<2>() + .0 + .iter() + .map(|c| f32::from_bits((u16::from_le_bytes(*c) as u32) << 16)) + .collect(); + let drafter = MtpDrafter::new( + &head, + weights.bytes("model.llm.embed.weight").unwrap(), + embed_norm, + weights.bytes("model.llm.unembed.weight").unwrap(), + cfg.vocab_out, + ) + .unwrap(); + let mut recording = Recording(drafter, Vec::new()); + let mut model = InklingCpu::new(cfg, &weights, 96).unwrap(); + model.generate_greedy_drafted(&prompt(), 8, u32::MAX, &mut recording, 3, |_| {}).unwrap(); + let want: [&[u32]; 6] = PINNED; + assert_eq!(recording.1[..6], want.map(<[u32]>::to_vec), "{:?}", &recording.1[..6]); +} + +const PINNED: [&[u32]; 6] = [&[264, 264, 187], &[264, 21, 21], &[21, 21, 264], &[7, 279, 187], &[104, 104], &[210]]; + #[test] fn a_head_that_does_not_fit_its_config_is_refused() { let cfg = tiny_config(32, 16); From f38112bfa1417f95e7320e57b68eb37780ec8eb8 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:06:33 -0800 Subject: [PATCH 6/9] test: planted bugs for the draft head on the CPU, on the device and in its plumbing; two regenerated --- tools/mutants/112-draft-not-undone.patch | 6 +++--- tools/mutants/153-head-no-rotation.patch | 16 ++++++++++++++++ .../mutants/154-head-mix-without-softmax.patch | 16 ++++++++++++++++ tools/mutants/155-head-anchor-guesses.patch | 17 +++++++++++++++++ .../mutants/156-head-context-keys-plain.patch | 17 +++++++++++++++++ tools/mutants/157-head-step-output-alone.patch | 17 +++++++++++++++++ tools/mutants/158-head-state-never-kept.patch | 17 +++++++++++++++++ .../159-head-previous-token-stuck.patch | 16 ++++++++++++++++ .../160-head-sees-its-own-future-only.patch | 17 +++++++++++++++++ tools/mutants/161-taps-off-by-one.patch | 15 +++++++++++++++ tools/mutants/162-drafter-told-of-undone.patch | 15 +++++++++++++++ .../mutants/163-engine-drafter-not-told.patch | 14 ++++++++++++++ .../mutants/164-device-head-no-rotation.patch | 18 ++++++++++++++++++ .../165-device-head-block-keys-of-first.patch | 16 ++++++++++++++++ .../166-device-head-values-skip-context.patch | 16 ++++++++++++++++ .../167-device-head-silu-without-gate.patch | 16 ++++++++++++++++ .../168-device-head-mix-first-only.patch | 14 ++++++++++++++ .../169-device-head-step-other-of-first.patch | 16 ++++++++++++++++ .../170-device-head-scores-without-bias.patch | 16 ++++++++++++++++ .../171-device-head-positions-at-start.patch | 16 ++++++++++++++++ tools/mutants/40-inkling-shared-history.patch | 10 +++++----- 21 files changed, 313 insertions(+), 8 deletions(-) create mode 100644 tools/mutants/153-head-no-rotation.patch create mode 100644 tools/mutants/154-head-mix-without-softmax.patch create mode 100644 tools/mutants/155-head-anchor-guesses.patch create mode 100644 tools/mutants/156-head-context-keys-plain.patch create mode 100644 tools/mutants/157-head-step-output-alone.patch create mode 100644 tools/mutants/158-head-state-never-kept.patch create mode 100644 tools/mutants/159-head-previous-token-stuck.patch create mode 100644 tools/mutants/160-head-sees-its-own-future-only.patch create mode 100644 tools/mutants/161-taps-off-by-one.patch create mode 100644 tools/mutants/162-drafter-told-of-undone.patch create mode 100644 tools/mutants/163-engine-drafter-not-told.patch create mode 100644 tools/mutants/164-device-head-no-rotation.patch create mode 100644 tools/mutants/165-device-head-block-keys-of-first.patch create mode 100644 tools/mutants/166-device-head-values-skip-context.patch create mode 100644 tools/mutants/167-device-head-silu-without-gate.patch create mode 100644 tools/mutants/168-device-head-mix-first-only.patch create mode 100644 tools/mutants/169-device-head-step-other-of-first.patch create mode 100644 tools/mutants/170-device-head-scores-without-bias.patch create mode 100644 tools/mutants/171-device-head-positions-at-start.patch diff --git a/tools/mutants/112-draft-not-undone.patch b/tools/mutants/112-draft-not-undone.patch index bd8878f..7ee8d91 100644 --- a/tools/mutants/112-draft-not-undone.patch +++ b/tools/mutants/112-draft-not-undone.patch @@ -1,13 +1,13 @@ # test: cargo test -p dluth-model --test inkling_draft generation_with_guesses_gives # Bug: the guesses that were not kept stay fed. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 2fdd02c..9e2f8a7 100644 +index a5af02c..4efc096 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -1311,7 +1311,7 @@ impl<'w, O: Ops> Inkling<'w, O> { - return Err(ModelError::Device("a sweep returned no scores".into())); +@@ -1374,7 +1374,7 @@ impl<'w, O: Ops> Inkling<'w, O> { } stats.accepted += kept - 1; + drafter.fed(pos, kept, &self.tapped)?; - self.undo(batch.len() - kept)?; + self.undo(0)?; pos += kept; diff --git a/tools/mutants/153-head-no-rotation.patch b/tools/mutants/153-head-no-rotation.patch new file mode 100644 index 0000000..58157e1 --- /dev/null +++ b/tools/mutants/153-head-no-rotation.patch @@ -0,0 +1,16 @@ +# test: cargo test -p dluth-model --test inkling_mtp the_head_s_proposals +# test-weights: cargo test --release -p dluth-model --test inkling_mtp the_real_head +# weights-env: DLUTH_INKLING2_MINI +# Bug: the head's queries and keys are not rotated by their positions. +diff --git a/crates/dluth-model/src/inkling/mtp.rs b/crates/dluth-model/src/inkling/mtp.rs +index cc5303f..2d475f9 100644 +--- a/crates/dluth-model/src/inkling/mtp.rs ++++ b/crates/dluth-model/src/inkling/mtp.rs +@@ -229,7 +229,6 @@ impl MtpHead { + let normed = rms(head, w, self.cfg.eps); + head.copy_from_slice(&normed); + } +- cpu::rope_inplace(x, heads, self.cfg.head_dim, pos, self.cfg.theta); + } + + /// The mix of the target values at one position for `row` (a layer, or the recurrent diff --git a/tools/mutants/154-head-mix-without-softmax.patch b/tools/mutants/154-head-mix-without-softmax.patch new file mode 100644 index 0000000..3acdf50 --- /dev/null +++ b/tools/mutants/154-head-mix-without-softmax.patch @@ -0,0 +1,16 @@ +# test: cargo test -p dluth-model --test inkling_mtp the_head_s_proposals +# test-weights: cargo test --release -p dluth-model --test inkling_mtp the_real_head +# weights-env: DLUTH_INKLING2_MINI +# Bug: the head mixes the model's values with the stored weights as they are, not their softmax. +diff --git a/crates/dluth-model/src/inkling/mtp.rs b/crates/dluth-model/src/inkling/mtp.rs +index cc5303f..c3e39aa 100644 +--- a/crates/dluth-model/src/inkling/mtp.rs ++++ b/crates/dluth-model/src/inkling/mtp.rs +@@ -175,7 +175,6 @@ impl MtpHead { + .chunks_exact(cfg.targets.len()) + .map(|row| { + let mut weights = row.to_vec(); +- cpu::softmax_inplace(&mut weights); + weights + }) + .collect(); diff --git a/tools/mutants/155-head-anchor-guesses.patch b/tools/mutants/155-head-anchor-guesses.patch new file mode 100644 index 0000000..cb2b1e2 --- /dev/null +++ b/tools/mutants/155-head-anchor-guesses.patch @@ -0,0 +1,17 @@ +# test: cargo test -p dluth-model --test inkling_mtp the_head_s_proposals +# test-weights: cargo test --release -p dluth-model --test inkling_mtp the_real_head +# weights-env: DLUTH_INKLING2_MINI +# Bug: the head's first guess is read from the anchor's position, not the first placeholder's. +diff --git a/crates/dluth-model/src/inkling/mtp.rs b/crates/dluth-model/src/inkling/mtp.rs +index cc5303f..b2aa239 100644 +--- a/crates/dluth-model/src/inkling/mtp.rs ++++ b/crates/dluth-model/src/inkling/mtp.rs +@@ -410,7 +410,7 @@ impl Drafter for MtpDrafter<'_> { + let mut previous = anchor as usize; + let mut guesses = Vec::with_capacity(room); + let mut scores = vec![0.0f32; self.vocab_out]; +- for at in hidden.iter().skip(1) { ++ for at in hidden.iter() { + if previous >= known { + break; + } diff --git a/tools/mutants/156-head-context-keys-plain.patch b/tools/mutants/156-head-context-keys-plain.patch new file mode 100644 index 0000000..bb99a26 --- /dev/null +++ b/tools/mutants/156-head-context-keys-plain.patch @@ -0,0 +1,17 @@ +# test: cargo test -p dluth-model --test inkling_mtp the_head_s_proposals +# test-weights: cargo test --release -p dluth-model --test inkling_mtp the_real_head +# weights-env: DLUTH_INKLING2_MINI +# Bug: the context's keys go through the block's key projection instead of their own. +diff --git a/crates/dluth-model/src/inkling/mtp.rs b/crates/dluth-model/src/inkling/mtp.rs +index cc5303f..db7d80a 100644 +--- a/crates/dluth-model/src/inkling/mtp.rs ++++ b/crates/dluth-model/src/inkling/mtp.rs +@@ -379,7 +379,7 @@ impl Drafter for MtpDrafter<'_> { + let pos = self.context.positions; + for (index, layer) in head.layers.iter().enumerate() { + let mixed = head.mixed(index, &layer.context_norm, &targets); +- let mut key = matvec(&layer.k_context, kv * d, h, &mixed); ++ let mut key = matvec(&layer.k, kv * d, h, &mixed); + head.head_norm_rope(&mut key, kv, &layer.k_norm_context, pos); + self.context.keys[index].extend(key); + self.context.values[index].extend(matvec(&layer.v_context, kv * d, h, &mixed)); diff --git a/tools/mutants/157-head-step-output-alone.patch b/tools/mutants/157-head-step-output-alone.patch new file mode 100644 index 0000000..1425fa1 --- /dev/null +++ b/tools/mutants/157-head-step-output-alone.patch @@ -0,0 +1,17 @@ +# test: cargo test -p dluth-model --test inkling_mtp the_head_s_proposals +# test-weights: cargo test --release -p dluth-model --test inkling_mtp the_real_head +# weights-env: DLUTH_INKLING2_MINI +# Bug: the recurrent step's output replaces the hidden state instead of being added to it. +diff --git a/crates/dluth-model/src/inkling/mtp.rs b/crates/dluth-model/src/inkling/mtp.rs +index cc5303f..5ec7889 100644 +--- a/crates/dluth-model/src/inkling/mtp.rs ++++ b/crates/dluth-model/src/inkling/mtp.rs +@@ -427,7 +427,7 @@ impl Drafter for MtpDrafter<'_> { + let said: Vec = out[2 * r..].iter().map(|o| o.tanh()).collect(); + let mut corrected = matvec(&head.step_out, h, r, &said); + for ((c, bias), base) in corrected.iter_mut().zip(&head.step_out_bias).zip(at) { +- *c += bias + base; ++ *c += bias + 0.0 * base; + } + cpu::matvec_bf16(self.unembed, self.vocab_out, h, &corrected, &mut scores); + let mut best = 0; diff --git a/tools/mutants/158-head-state-never-kept.patch b/tools/mutants/158-head-state-never-kept.patch new file mode 100644 index 0000000..43ef999 --- /dev/null +++ b/tools/mutants/158-head-state-never-kept.patch @@ -0,0 +1,17 @@ +# test: cargo test -p dluth-model --test inkling_mtp the_head_s_proposals +# test-weights: cargo test --release -p dluth-model --test inkling_mtp the_real_head +# weights-env: DLUTH_INKLING2_MINI +# Bug: the recurrent step never keeps any of its state. +diff --git a/crates/dluth-model/src/inkling/mtp.rs b/crates/dluth-model/src/inkling/mtp.rs +index cc5303f..457cab0 100644 +--- a/crates/dluth-model/src/inkling/mtp.rs ++++ b/crates/dluth-model/src/inkling/mtp.rs +@@ -422,7 +422,7 @@ impl Drafter for MtpDrafter<'_> { + // place, and what to say about this position. + for i in 0..r { + let keep = cpu::sigmoid(out[i]); +- state[i] = keep * state[i] + (1.0 - keep) * out[r + i].tanh(); ++ state[i] = out[r + i].tanh(); + } + let said: Vec = out[2 * r..].iter().map(|o| o.tanh()).collect(); + let mut corrected = matvec(&head.step_out, h, r, &said); diff --git a/tools/mutants/159-head-previous-token-stuck.patch b/tools/mutants/159-head-previous-token-stuck.patch new file mode 100644 index 0000000..d2b8c76 --- /dev/null +++ b/tools/mutants/159-head-previous-token-stuck.patch @@ -0,0 +1,16 @@ +# test: cargo test -p dluth-model --test inkling_mtp the_head_s_proposals +# test-weights: cargo test --release -p dluth-model --test inkling_mtp the_real_head +# weights-env: DLUTH_INKLING2_MINI +# Bug: the recurrent step is always given the anchor as the token just guessed. +diff --git a/crates/dluth-model/src/inkling/mtp.rs b/crates/dluth-model/src/inkling/mtp.rs +index cc5303f..cc422ba 100644 +--- a/crates/dluth-model/src/inkling/mtp.rs ++++ b/crates/dluth-model/src/inkling/mtp.rs +@@ -437,7 +437,6 @@ impl Drafter for MtpDrafter<'_> { + } + } + guesses.push(best as u32); +- previous = best; + } + guesses + } diff --git a/tools/mutants/160-head-sees-its-own-future-only.patch b/tools/mutants/160-head-sees-its-own-future-only.patch new file mode 100644 index 0000000..00536a1 --- /dev/null +++ b/tools/mutants/160-head-sees-its-own-future-only.patch @@ -0,0 +1,17 @@ +# test: cargo test -p dluth-model --test inkling_mtp the_head_s_proposals +# test-weights: cargo test --release -p dluth-model --test inkling_mtp the_real_head +# weights-env: DLUTH_INKLING2_MINI +# Bug: the block's attention leaves out the text before the anchor. +diff --git a/crates/dluth-model/src/inkling/mtp.rs b/crates/dluth-model/src/inkling/mtp.rs +index cc5303f..27ea5eb 100644 +--- a/crates/dluth-model/src/inkling/mtp.rs ++++ b/crates/dluth-model/src/inkling/mtp.rs +@@ -321,7 +321,7 @@ impl<'a> MtpDrafter<'a> { + // a placeholder sees the placeholders after it too. + let mut scores: Vec = context_keys + .chunks_exact(width) +- .take(t) ++ .take(0) + .map(|key| dot(&key[group * d..(group + 1) * d])) + .collect(); + scores.extend(keys.iter().map(|key| dot(&key[group * d..(group + 1) * d]))); diff --git a/tools/mutants/161-taps-off-by-one.patch b/tools/mutants/161-taps-off-by-one.patch new file mode 100644 index 0000000..a27a481 --- /dev/null +++ b/tools/mutants/161-taps-off-by-one.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-model --test inkling_mtp the_head_s_proposals +# Bug: the model hands a drafter its values one layer application early. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index a5af02c..787688f 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -1045,7 +1045,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + }; + let at = Arrival { pos, messages: messages.as_deref() }; + x = apply_layer(cfg, ops, layer, &mut self.passes[index], &x, &mut blocks, at)?; +- if self.taps.contains(&(index + 1)) { ++ if self.taps.contains(&(index + 2)) { + self.tapped.push(x.clone()); + } + } diff --git a/tools/mutants/162-drafter-told-of-undone.patch b/tools/mutants/162-drafter-told-of-undone.patch new file mode 100644 index 0000000..0a614b1 --- /dev/null +++ b/tools/mutants/162-drafter-told-of-undone.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-model --test inkling_mtp whatever_the_head +# Bug: a drafter is told that every position of a sweep was kept, the wrong guesses too. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index a5af02c..651e2fd 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -1373,7 +1373,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + return Err(ModelError::Device("a sweep returned no scores".into())); + } + stats.accepted += kept - 1; +- drafter.fed(pos, kept, &self.tapped)?; ++ drafter.fed(pos, batch.len(), &self.tapped)?; + self.undo(batch.len() - kept)?; + pos += kept; + } diff --git a/tools/mutants/163-engine-drafter-not-told.patch b/tools/mutants/163-engine-drafter-not-told.patch new file mode 100644 index 0000000..8df7b4f --- /dev/null +++ b/tools/mutants/163-engine-drafter-not-told.patch @@ -0,0 +1,14 @@ +# test: cargo test --release -p dluth-serve --test engine the_engine_with_a_draft_head +# Bug: the engine does not tell its drafter of the prompt it feeds. +diff --git a/crates/dluth-serve/src/engine.rs b/crates/dluth-serve/src/engine.rs +index ef224e8..8c9180a 100644 +--- a/crates/dluth-serve/src/engine.rs ++++ b/crates/dluth-serve/src/engine.rs +@@ -187,7 +187,6 @@ impl<'w, 't, O: Ops> InklingEngine<'w, 't, O> { + let mut pos = start; + for batch in tokens[start..].chunks(self.options.prompt_batch.max(1)) { + self.model.feed(batch, pos)?; +- self.drafter.fed(pos, batch.len(), self.model.tapped())?; + pos += batch.len(); + } + Ok(start) diff --git a/tools/mutants/164-device-head-no-rotation.patch b/tools/mutants/164-device-head-no-rotation.patch new file mode 100644 index 0000000..aa43f45 --- /dev/null +++ b/tools/mutants/164-device-head-no-rotation.patch @@ -0,0 +1,18 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_draft_head +# needs: gpu +# Bug: the device head's vectors are normalized and not rotated. +diff --git a/crates/dluth-cuda/kernels/draft_head.cu b/crates/dluth-cuda/kernels/draft_head.cu +index 52b8eb3..edf30d8 100644 +--- a/crates/dluth-cuda/kernels/draft_head.cu ++++ b/crates/dluth-cuda/kernels/draft_head.cu +@@ -37,8 +37,8 @@ extern "C" __global__ void head_norm_rope(float* x, const float* weights, unsign + float s, c; + sincosf(at * frequency, &s, &c); + float a = normed[i], b = normed[i + half]; +- v[i] = a * c - b * s; +- v[i + half] = a * s + b * c; ++ v[i] = a; ++ v[i + half] = b; + } + } + diff --git a/tools/mutants/165-device-head-block-keys-of-first.patch b/tools/mutants/165-device-head-block-keys-of-first.patch new file mode 100644 index 0000000..d4ef148 --- /dev/null +++ b/tools/mutants/165-device-head-block-keys-of-first.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_draft_head +# needs: gpu +# Bug: every block position's key is taken for the first block position's. +diff --git a/crates/dluth-cuda/kernels/draft_head.cu b/crates/dluth-cuda/kernels/draft_head.cu +index 52b8eb3..c4c4b48 100644 +--- a/crates/dluth-cuda/kernels/draft_head.cu ++++ b/crates/dluth-cuda/kernels/draft_head.cu +@@ -60,7 +60,7 @@ extern "C" __global__ void draft_scores(const float* q, const float* context_key + if (run >= (unsigned long long)block * heads) return; + unsigned int h = (unsigned int)(run % heads); + size_t group = (size_t)(h / (heads / kv_heads)) * dim; +- const float* key = (j < context ? context_keys + j * kv_heads * dim : block_keys + (j - context) * kv_heads * dim) + group; ++ const float* key = (j < context ? context_keys + j * kv_heads * dim : block_keys) + group; + const float* query = q + run * dim; + float dot = 0.0f; + for (unsigned int i = 0; i < dim; ++i) dot += query[i] * key[i]; diff --git a/tools/mutants/166-device-head-values-skip-context.patch b/tools/mutants/166-device-head-values-skip-context.patch new file mode 100644 index 0000000..580d919 --- /dev/null +++ b/tools/mutants/166-device-head-values-skip-context.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_draft_head +# needs: gpu +# Bug: the block's attention adds up the block's own values only. +diff --git a/crates/dluth-cuda/kernels/draft_head.cu b/crates/dluth-cuda/kernels/draft_head.cu +index 52b8eb3..6db0598 100644 +--- a/crates/dluth-cuda/kernels/draft_head.cu ++++ b/crates/dluth-cuda/kernels/draft_head.cu +@@ -91,7 +91,7 @@ extern "C" __global__ void draft_values(const float* weights, const float* conte + const float* w = weights + run * keys; + for (unsigned long long j = seg; j < keys; j += segs) { + const float* value = j < context ? context_values + j * kv_heads * dim : block_values + (j - context) * kv_heads * dim; +- total += w[j] * value[column]; ++ if (j >= context) total += w[j] * value[column]; + } + } + for (unsigned int offset = segs / 2; offset > 0; offset /= 2) total += __shfl_xor_sync(0xffffffffu, total, offset); diff --git a/tools/mutants/167-device-head-silu-without-gate.patch b/tools/mutants/167-device-head-silu-without-gate.patch new file mode 100644 index 0000000..5bc3e51 --- /dev/null +++ b/tools/mutants/167-device-head-silu-without-gate.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_draft_head +# needs: gpu +# Bug: the feed-forward activation leaves out the sigmoid. +diff --git a/crates/dluth-cuda/kernels/draft_head.cu b/crates/dluth-cuda/kernels/draft_head.cu +index 52b8eb3..7becc24 100644 +--- a/crates/dluth-cuda/kernels/draft_head.cu ++++ b/crates/dluth-cuda/kernels/draft_head.cu +@@ -104,7 +104,7 @@ extern "C" __global__ void silu_mul(const float* gate, const float* up, float* o + unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + float g = gate[i]; +- out[i] = g / (1.0f + expf(-g)) * up[i]; ++ out[i] = g * up[i]; + } + + // out[i] = w0 * a[i] + w1 * b[i] + w2 * c[i] + w3 * d[i]: the mix of up to four of the diff --git a/tools/mutants/168-device-head-mix-first-only.patch b/tools/mutants/168-device-head-mix-first-only.patch new file mode 100644 index 0000000..4389dec --- /dev/null +++ b/tools/mutants/168-device-head-mix-first-only.patch @@ -0,0 +1,14 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_draft_head +# needs: gpu +# Bug: the mix of the model's values is its first value alone. +diff --git a/crates/dluth-cuda/kernels/draft_head.cu b/crates/dluth-cuda/kernels/draft_head.cu +index 52b8eb3..2f40b44 100644 +--- a/crates/dluth-cuda/kernels/draft_head.cu ++++ b/crates/dluth-cuda/kernels/draft_head.cu +@@ -113,5 +113,5 @@ extern "C" __global__ void silu_mul(const float* gate, const float* up, float* o + extern "C" __global__ void mix_four(const float* a, const float* b, const float* c, const float* d, + float* out, float w0, float w1, float w2, float w3, unsigned int n) { + unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; +- if (i < n) out[i] = w0 * a[i] + w1 * b[i] + w2 * c[i] + w3 * d[i]; ++ if (i < n) out[i] = a[i]; + } diff --git a/tools/mutants/169-device-head-step-other-of-first.patch b/tools/mutants/169-device-head-step-other-of-first.patch new file mode 100644 index 0000000..1afc383 --- /dev/null +++ b/tools/mutants/169-device-head-step-other-of-first.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_draft_head +# needs: gpu +# Bug: the step's other input is the mix at the text's first position, not its last. +diff --git a/crates/dluth-cuda/src/draft_head.rs b/crates/dluth-cuda/src/draft_head.rs +index 5c2f4b4..376070f 100644 +--- a/crates/dluth-cuda/src/draft_head.rs ++++ b/crates/dluth-cuda/src/draft_head.rs +@@ -667,7 +667,7 @@ impl<'m> CudaDraftHead<'m> { + &s.step_hidden, + SEGS, + )?; +- self.small.copy(Floats { buffer: &self.context_step, at: (t - 1) * h, len: h }, Floats::first(&s.other, h))?; ++ self.small.copy(Floats { buffer: &self.context_step, at: 0, len: h }, Floats::first(&s.other, h))?; + self.matmat.bf16( + Bf16Matrix { buffer: &self.step_other, offset: 0, rows: r3, cols: h }, + &s.other, diff --git a/tools/mutants/170-device-head-scores-without-bias.patch b/tools/mutants/170-device-head-scores-without-bias.patch new file mode 100644 index 0000000..6ef2bae --- /dev/null +++ b/tools/mutants/170-device-head-scores-without-bias.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_draft_head +# needs: gpu +# Bug: a guess's scores leave out the output table times the step's bias. +diff --git a/crates/dluth-cuda/src/draft_head.rs b/crates/dluth-cuda/src/draft_head.rs +index 5c2f4b4..a00de67 100644 +--- a/crates/dluth-cuda/src/draft_head.rs ++++ b/crates/dluth-cuda/src/draft_head.rs +@@ -731,7 +731,7 @@ impl<'m> CudaDraftHead<'m> { + )?; + self.small.add( + Floats::first(&s.correction, vocab), +- Floats { buffer: &s.base_bias, at: k * vocab, len: vocab }, ++ Floats { buffer: &s.base, at: k * vocab, len: vocab }, + Floats::first(&s.sum, vocab), + )?; + self.wait()?; diff --git a/tools/mutants/171-device-head-positions-at-start.patch b/tools/mutants/171-device-head-positions-at-start.patch new file mode 100644 index 0000000..5a97bfa --- /dev/null +++ b/tools/mutants/171-device-head-positions-at-start.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::the_draft_head +# needs: gpu +# Bug: the device head stores every told position's keys at the start of the text. +diff --git a/crates/dluth-cuda/src/draft_head.rs b/crates/dluth-cuda/src/draft_head.rs +index 5c2f4b4..972b0d2 100644 +--- a/crates/dluth-cuda/src/draft_head.rs ++++ b/crates/dluth-cuda/src/draft_head.rs +@@ -488,7 +488,7 @@ impl<'m> CudaDraftHead<'m> { + let (h, kv, d) = (self.cfg.hidden, self.cfg.kv_heads, self.cfg.head_dim); + let kvw = kv * d; + let s = &self.scratch; +- let pos = self.positions; ++ let pos = 0; + let _ = first; + for (index, layer) in self.layers.iter().enumerate() { + self.mix_values(index, states, kept)?; diff --git a/tools/mutants/40-inkling-shared-history.patch b/tools/mutants/40-inkling-shared-history.patch index c9e919f..ae81a63 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 306a8fc..dcaaf9f 100644 +index a5af02c..ae94b0b 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -798,7 +798,8 @@ impl<'w, O: Ops> Inkling<'w, O> { +@@ -1044,7 +1044,8 @@ impl<'w, O: Ops> Inkling<'w, O> { _ => None, }; let at = Arrival { pos, messages: messages.as_deref() }; - 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, ops, layer, &mut self.passes[shared], &x, &mut blocks, at)?; - } - - self.last = Some((x, blocks)); + if self.taps.contains(&(index + 1)) { + self.tapped.push(x.clone()); + } From 35019cdc6f5a4a68ce9ec23b2f2a8f82ec3e3ff5 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:15:43 -0800 Subject: [PATCH 7/9] docs: the README says what the draft head gives; a formula in a doc comment is marked as text --- README.md | 12 +++++++----- crates/dluth-cuda/src/draft_head.rs | 6 ++++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 7bad7cb..22e48dd 100644 --- a/README.md +++ b/README.md @@ -18,9 +18,10 @@ CPU, slowly, as the reference each faster path is checked against. within four times the reference's own difference from itself (about 0.00015; measured: 0.00005). A tiny model of the same architecture, small enough to exercise every rule, is checked the same way in CI. -On the GB10, Inkling 2 Mini generates about 24 tokens per second one token at a time and reads a prompt at -about 120 tokens per second. Guessed tokens are checked several per sweep of the weights, which speeds up -text that repeats itself; the model's own draft head is not used yet. Deliberately planted bugs must make +On the GB10, Inkling 2 Mini generates about 28 tokens per second one token at a time and reads a prompt at +about 120 tokens per second. With the draft head that ships in the checkpoint proposing tokens, which the +model checks several per sweep of the weights, it generates 30 to 39 tokens per second depending on the +text, and the text is the same as without. Deliberately planted bugs must make named tests fail, on the CPU and on the GPU. cargo run --release -- generate --model --prompt "What is the capital of Ireland?" @@ -41,8 +42,9 @@ CPU, which is only good for trying the interface). It answers `POST /v1/chat/com | `--listen ` | where to listen; `0.0.0.0:8080` for other machines | `127.0.0.1:8080` | | `--context ` | longest conversation, prompt and reply together | 8192 | | `--name ` | the name the model is listed under | the directory's name | -| `--guesses ` | guessed tokens checked per sweep; 0 for none | 4 | -| `--match ` | last tokens that must have appeared before for a guess | 2 | +| `--guesses ` | guessed tokens checked per sweep; 0 for none | 2 with the draft head, else 4 | +| `--head on\|off` | use the checkpoint's draft head as the guesser, where it has one (GPU only) | on | +| `--match ` | without the head: last tokens that must have appeared before for a guess | 2 | | `--prompt-batch ` | tokens of a prompt read per sweep, at most 16 on the GPU | 16 | | `--temperature ` | used when a request does not set one; 0 is greedy | 1 | | `--effort ` | reasoning effort when a request does not set `reasoning_effort` | high | diff --git a/crates/dluth-cuda/src/draft_head.rs b/crates/dluth-cuda/src/draft_head.rs index 5c2f4b4..593d957 100644 --- a/crates/dluth-cuda/src/draft_head.rs +++ b/crates/dluth-cuda/src/draft_head.rs @@ -11,8 +11,10 @@ //! state is the block's hidden state plus a correction, and the correction is a fixed //! matrix applied to a small vector the recurrent step produces: //! -//! scores = table . (hidden + out . said + bias) -//! = table . hidden + (table . out) . said + table . bias +//! ```text +//! scores = table . (hidden + out . said + bias) +//! = table . hidden + (table . out) . said + table . bias +//! ``` //! //! `table . hidden` is one product for the whole block. `table . out` and `table . bias` //! do not depend on the text and are computed once, when the head is loaded. That leaves, From 78368cf437feaaccad8788abe0640873b7b74e70 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:30:20 -0800 Subject: [PATCH 8/9] fix: a head switched off or unreadable is done without; wrong guesses are undone before the drafter is told; an engine that asks for no guesses does not keep a drafter in step; review fixes --- crates/dluth-cuda/src/bin/dluth-cuda.rs | 17 ++++++++-- crates/dluth-cuda/src/draft_head.rs | 6 +++- .../dluth-cuda/tests/inkling_golden_cuda.rs | 3 +- crates/dluth-model/src/inkling/model.rs | 5 ++- crates/dluth-model/src/inkling/mtp.rs | 8 +++++ crates/dluth-model/tests/inkling_mtp.rs | 3 +- crates/dluth-serve/src/engine.rs | 32 +++++++------------ crates/dluth-serve/tests/engine.rs | 25 +++++++++++++++ 8 files changed, 72 insertions(+), 27 deletions(-) diff --git a/crates/dluth-cuda/src/bin/dluth-cuda.rs b/crates/dluth-cuda/src/bin/dluth-cuda.rs index d068a04..c2da05c 100644 --- a/crates/dluth-cuda/src/bin/dluth-cuda.rs +++ b/crates/dluth-cuda/src/bin/dluth-cuda.rs @@ -35,8 +35,21 @@ fn run(args: &[String]) -> Result<(), String> { // The model's own draft head, if the checkpoint has one: it proposes tokens that the // model then checks several at a time. It reads the model's output table on the device. let mut args = args; - let head: Option + '_>> = match load_mtp_config(&args.model).map_err(|e| text(&e))? { - Some(head_cfg) if args.head && args.model.join("mtp.safetensors").exists() => { + if args.options.prompt_batch > 16 { + return Err("--prompt-batch: the device takes at most 16 positions at a time".into()); + } + // A head that is switched off is not looked at; one whose description cannot be read + // is done without, with the reason said. + let described = if args.head { + load_mtp_config(&args.model).unwrap_or_else(|e| { + eprintln!("going without the draft head: {e}"); + None + }) + } else { + None + }; + let head: Option + '_>> = match described { + Some(head_cfg) if args.model.join("mtp.safetensors").exists() => { let (h, vocab_out) = (cfg.hidden, cfg.vocab_out); let unembed = &weights.bytes("model.llm.unembed.weight").map_err(|e| text(&e))?[..vocab_out * h * 2]; let table = ops.device_weight(unembed).map_err(|e| text(&e))?; diff --git a/crates/dluth-cuda/src/draft_head.rs b/crates/dluth-cuda/src/draft_head.rs index 593d957..9314a58 100644 --- a/crates/dluth-cuda/src/draft_head.rs +++ b/crates/dluth-cuda/src/draft_head.rs @@ -197,7 +197,7 @@ impl<'m> CudaDraftHead<'m> { let file = SafetensorsFile::open(&dir.join("mtp.safetensors"))?; let (h, d, r) = (cfg.hidden, cfg.head_dim, cfg.rank); let (qw, kvw, inner, block) = (cfg.heads * d, cfg.kv_heads * d, cfg.inner, cfg.block); - if cfg.targets.len() > MIXED || d > 256 || block > 16 || capacity == 0 { + if cfg.targets.is_empty() || cfg.targets.len() > MIXED || d > 256 || block > 16 || capacity == 0 { return Err(ModelError::Unsupported(format!( "a draft head with {} target values, heads of {d} and blocks of {block}", cfg.targets.len() @@ -375,6 +375,10 @@ impl<'m> CudaDraftHead<'m> { } } drop(column_bytes); + // The columns were only the way to the rows: nothing reads them again, and no + // kernel is running. + owned.retain(|b| b.handle != table_columns.handle); + dev.free(table_columns).map_err(failed)?; let table_out = dev.alloc(rows.len()).map_err(failed)?; dev.upload(&table_out, &rows).map_err(failed)?; owned.push(table_out); diff --git a/crates/dluth-cuda/tests/inkling_golden_cuda.rs b/crates/dluth-cuda/tests/inkling_golden_cuda.rs index c2a00e2..2baa388 100644 --- a/crates/dluth-cuda/tests/inkling_golden_cuda.rs +++ b/crates/dluth-cuda/tests/inkling_golden_cuda.rs @@ -528,7 +528,8 @@ mod on_the_device { assert!(Drafter::::draft(&mut on_gpu.0, &prompt[..5], 3).is_empty()); assert!(on_gpu.0.fed(3, 1, &[]).is_err()); } - // The head gave back every buffer it took; the model's are gone with the model. + // Head and model are gone, and with them more buffers than the head ever took: a head + // that kept its buffers would leave the count above where it was. assert!(dev.live_buffers() < before); } diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index a5af02c..a6aff22 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs @@ -1373,8 +1373,11 @@ impl<'w, O: Ops> Inkling<'w, O> { return Err(ModelError::Device("a sweep returned no scores".into())); } stats.accepted += kept - 1; - drafter.fed(pos, kept, &self.tapped)?; + // The wrong guesses are taken back first, so that a drafter that fails here leaves + // the model holding the text and nothing else. The values it is given are the + // batch's, which an undo does not touch. self.undo(batch.len() - kept)?; + drafter.fed(pos, kept, &self.tapped)?; pos += kept; } Ok(stats) diff --git a/crates/dluth-model/src/inkling/mtp.rs b/crates/dluth-model/src/inkling/mtp.rs index cc5303f..a82b420 100644 --- a/crates/dluth-model/src/inkling/mtp.rs +++ b/crates/dluth-model/src/inkling/mtp.rs @@ -169,6 +169,9 @@ impl MtpHead { } Ok(floats(bytes)) }; + if cfg.targets.is_empty() { + return Err(ModelError::Format("draft head: no target values".into())); + } let rows = cfg.layers + 1; let stored = get("fuse_weight", rows * cfg.targets.len())?; let mixes = stored @@ -371,6 +374,11 @@ impl Drafter for MtpDrafter<'_> { ))); } let (h, d, kv) = (cfg.hidden, cfg.head_dim, cfg.kv_heads); + if states.iter().any(|s| s.rows().len() < kept) { + return Err(ModelError::Capacity(format!( + "draft head: told that {kept} positions of a smaller batch stay" + ))); + } for b in 0..kept { let targets: Vec<&[f32]> = states.iter().map(|s| &s.rows()[b][..]).collect(); if targets.iter().any(|t| t.len() != h) { diff --git a/crates/dluth-model/tests/inkling_mtp.rs b/crates/dluth-model/tests/inkling_mtp.rs index 3d8996d..7aebd7c 100644 --- a/crates/dluth-model/tests/inkling_mtp.rs +++ b/crates/dluth-model/tests/inkling_mtp.rs @@ -85,7 +85,8 @@ impl Drafter for Recording<'_> { /// What the head of random weights proposes on the tiny model, written down. That the /// head's arithmetic is right is shown with the real weights (the last test here: a wrong /// head does not guess well). This test is what notices a change to that arithmetic on a -/// machine without them: any part of the head that is altered alters these proposals. +/// machine without them: the bugs planted in the head's parts (tools/mutants) each change +/// these proposals. #[test] fn the_head_s_proposals_on_the_tiny_model_are_what_they_were() { let dir = tiny(); diff --git a/crates/dluth-serve/src/engine.rs b/crates/dluth-serve/src/engine.rs index ef224e8..064621a 100644 --- a/crates/dluth-serve/src/engine.rs +++ b/crates/dluth-serve/src/engine.rs @@ -85,21 +85,6 @@ impl Default for Options { } } -/// A drafter that is told of what is fed and proposes nothing. -struct Told<'a, V>(&'a mut dyn Drafter); - -impl Drafter for Told<'_, V> { - fn draft(&mut self, _tokens: &[u32], _most: usize) -> Vec { - Vec::new() - } - fn wants(&self) -> Vec { - self.0.wants() - } - fn fed(&mut self, first: usize, kept: usize, states: &[V]) -> Result<(), ModelError> { - self.0.fed(first, kept, states) - } -} - /// The conversation answered last. struct Served { messages: Vec, @@ -148,7 +133,9 @@ impl<'w, 't, O: Ops> InklingEngine<'w, 't, O> { options: Options, drafter: Box + 't>, ) -> Result { - model.tap(&drafter.wants()).map_err(refused)?; + if options.guesses > 0 { + model.tap(&drafter.wants()).map_err(refused)?; + } let markers = Markers::of(tokenizer); Ok(InklingEngine { model, drafter, tokenizer, markers, options, held: Vec::new(), served: None, requests: 0 }) } @@ -187,7 +174,9 @@ impl<'w, 't, O: Ops> InklingEngine<'w, 't, O> { let mut pos = start; for batch in tokens[start..].chunks(self.options.prompt_batch.max(1)) { self.model.feed(batch, pos)?; - self.drafter.fed(pos, batch.len(), self.model.tapped())?; + if self.options.guesses > 0 { + self.drafter.fed(pos, batch.len(), self.model.tapped())?; + } pos += batch.len(); } Ok(start) @@ -239,10 +228,11 @@ impl Engine for InklingEngine<'_, '_, O> { nanos ^ self.requests.wrapping_mul(0x9E37_79B9_7F4A_7C15) }), }); - // With no guesses asked for, nothing proposes; the engine's drafter is still told of - // what is fed, so that it is in step when guesses are asked for again. - let mut told = Told(self.drafter.as_mut()); - let drafter: &mut dyn Drafter = if self.options.guesses == 0 { &mut told } else { self.drafter.as_mut() }; + // With no guesses asked for, the drafter is neither asked nor told of anything: + // keeping one in step costs time, and this engine never changes its mind. + let mut nothing = dluth_model::inkling::NoDraft; + let drafter: &mut dyn Drafter = + if self.options.guesses == 0 { &mut nothing } else { self.drafter.as_mut() }; let mut reader = ReplyReader::new(self.tokenizer, self.markers); let mut stops = StopFilter::new(&request.stop); diff --git a/crates/dluth-serve/tests/engine.rs b/crates/dluth-serve/tests/engine.rs index 9140dfa..b61d8e3 100644 --- a/crates/dluth-serve/tests/engine.rs +++ b/crates/dluth-serve/tests/engine.rs @@ -286,6 +286,31 @@ fn the_engine_with_a_draft_head_hands_out_the_same_replies() { // The head proposed at every sweep that had room for a guess. assert!(usage.guessed >= usage.sweeps.saturating_sub(1), "{usage:?}"); } + // A conversation that goes on: the head has read what the model holds and is told only + // of the new turn. A reply must end for that, which with random weights is luck: take + // the first seed whose reply does. + let eos = plain.config().eos; + let prompt = tokenizer.encode(&chat(&first, Effort::None)).unwrap(); + let (seed, reply_tokens, reply) = (0..400u64) + .find_map(|seed| { + let sampling = Sampling { temperature: 1.0, top_p: 1.0, seed }; + let (new, text) = direct(&mut plain, &tokenizer, &prompt, 60, sampling); + (new.last() == Some(&eos) && new.len() > 3).then_some((seed, new, text)) + }) + .expect("a reply that ends"); + let (got, _, _) = ask(&mut engine, &request(first.clone(), 60, 1.0, seed)); + assert_eq!(got, reply); + let mut longer = first.clone(); + longer.push(Message { role: Role::Assistant, content: reply, reasoning: None }); + longer.push(user("and then?")); + let (got, _, usage) = ask(&mut engine, &request(longer.clone(), 20, 0.0, 0)); + assert_eq!(usage.reused_tokens, prompt.len() + reply_tokens.len() - 1); + let mut whole = prompt.clone(); + whole.extend(&reply_tokens); + whole.extend(tokenizer.encode(&more_turns(&longer[2..])).unwrap()); + assert_eq!(got, direct(&mut plain, &tokenizer, &whole, 20, Sampling::greedy()).1); + assert!(usage.guessed >= usage.sweeps.saturating_sub(1), "the head kept proposing: {usage:?}"); + // Drawn tokens too: the guesses are compared with what was drawn. let messages = vec![user("draw something")]; let tokens = tokenizer.encode(&chat(&messages, Effort::None)).unwrap(); From 98913dfdab2235ccc8eb3b3365b1944abf0ac946 Mon Sep 17 00:00:00 2001 From: "defilan-agent[bot]" <355440997+defilan-agent[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:30:43 -0800 Subject: [PATCH 9/9] test: three planted bugs regenerated --- tools/mutants/112-draft-not-undone.patch | 12 ++++++------ tools/mutants/162-drafter-told-of-undone.patch | 12 ++++++------ tools/mutants/163-engine-drafter-not-told.patch | 10 +++++----- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/tools/mutants/112-draft-not-undone.patch b/tools/mutants/112-draft-not-undone.patch index 7ee8d91..287049c 100644 --- a/tools/mutants/112-draft-not-undone.patch +++ b/tools/mutants/112-draft-not-undone.patch @@ -1,15 +1,15 @@ # test: cargo test -p dluth-model --test inkling_draft generation_with_guesses_gives # Bug: the guesses that were not kept stay fed. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index a5af02c..4efc096 100644 +index a6aff22..2b76167 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -1374,7 +1374,7 @@ impl<'w, O: Ops> Inkling<'w, O> { - } - stats.accepted += kept - 1; - drafter.fed(pos, kept, &self.tapped)?; +@@ -1376,7 +1376,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + // The wrong guesses are taken back first, so that a drafter that fails here leaves + // the model holding the text and nothing else. The values it is given are the + // batch's, which an undo does not touch. - self.undo(batch.len() - kept)?; + self.undo(0)?; + drafter.fed(pos, kept, &self.tapped)?; pos += kept; } - Ok(stats) diff --git a/tools/mutants/162-drafter-told-of-undone.patch b/tools/mutants/162-drafter-told-of-undone.patch index 0a614b1..96681d7 100644 --- a/tools/mutants/162-drafter-told-of-undone.patch +++ b/tools/mutants/162-drafter-told-of-undone.patch @@ -1,15 +1,15 @@ # test: cargo test -p dluth-model --test inkling_mtp whatever_the_head # Bug: a drafter is told that every position of a sweep was kept, the wrong guesses too. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index a5af02c..651e2fd 100644 +index a6aff22..ebacf0e 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -1373,7 +1373,7 @@ impl<'w, O: Ops> Inkling<'w, O> { - return Err(ModelError::Device("a sweep returned no scores".into())); - } - stats.accepted += kept - 1; +@@ -1377,7 +1377,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + // the model holding the text and nothing else. The values it is given are the + // batch's, which an undo does not touch. + self.undo(batch.len() - kept)?; - drafter.fed(pos, kept, &self.tapped)?; + drafter.fed(pos, batch.len(), &self.tapped)?; - self.undo(batch.len() - kept)?; pos += kept; } + Ok(stats) diff --git a/tools/mutants/163-engine-drafter-not-told.patch b/tools/mutants/163-engine-drafter-not-told.patch index 8df7b4f..663c2d5 100644 --- a/tools/mutants/163-engine-drafter-not-told.patch +++ b/tools/mutants/163-engine-drafter-not-told.patch @@ -1,14 +1,14 @@ # test: cargo test --release -p dluth-serve --test engine the_engine_with_a_draft_head # Bug: the engine does not tell its drafter of the prompt it feeds. diff --git a/crates/dluth-serve/src/engine.rs b/crates/dluth-serve/src/engine.rs -index ef224e8..8c9180a 100644 +index 064621a..b299f8e 100644 --- a/crates/dluth-serve/src/engine.rs +++ b/crates/dluth-serve/src/engine.rs -@@ -187,7 +187,6 @@ impl<'w, 't, O: Ops> InklingEngine<'w, 't, O> { - let mut pos = start; +@@ -175,7 +175,6 @@ impl<'w, 't, O: Ops> InklingEngine<'w, 't, O> { for batch in tokens[start..].chunks(self.options.prompt_batch.max(1)) { self.model.feed(batch, pos)?; -- self.drafter.fed(pos, batch.len(), self.model.tapped())?; + if self.options.guesses > 0 { +- self.drafter.fed(pos, batch.len(), self.model.tapped())?; + } pos += batch.len(); } - Ok(start)