diff --git a/crates/dluth-cuda/examples/generate.rs b/crates/dluth-cuda/examples/generate.rs index d056dfa..2026aaa 100644 --- a/crates/dluth-cuda/examples/generate.rs +++ b/crates/dluth-cuda/examples/generate.rs @@ -9,6 +9,10 @@ //! last word only the matrix products run there and the rest on the CPU, as an earlier step //! of the port did, with that step's own breakdown of a token's time. //! +//! With `draft [guesses per sweep] [tokens that must match]` as the last words, the text is +//! generated without guesses and then with guesses looked up in the text so far, and both +//! speeds are printed. +//! //! Greedy, reasoning effort "none". Speed is counted from the first generated token to the //! last, so loading the weights and reading the prompt are not in it. In the default mode //! the text is then read again in batches of 1 to 16 positions, to show what a batch costs. @@ -69,6 +73,42 @@ fn main() { } 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 + // time. The first run also brings the weights to the device. + let most: usize = args.next().map_or(4, |n| n.parse().expect("how many guesses per sweep")); + let run: usize = args.next().map_or(2, |n| n.parse().expect("how many tokens must match")); + 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 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 dluth_model::inkling::LookupDrafter::new(run.max(4), run), 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 up to {most} guesses after a match of {run}: {:.2} s, {:.1} tokens per second; {} sweeps, {} guessed, {} right", + seconds, + n / seconds, + stats.sweeps, + stats.drafted, + stats.accepted + ); + println!("the same tokens: {}", plain == drafted); + return; + } if mode.as_deref() != Some("products") { let ops = CudaOps::new(&dev, &module).expect("the kernels"); let stats = ops.stats(); diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu index 10196bd..ac774e9 100644 --- a/crates/dluth-cuda/kernels/attention.cu +++ b/crates/dluth-cuda/kernels/attention.cu @@ -76,26 +76,29 @@ extern "C" __global__ void head_rmsnorm_plain(const float* x, float* out, unsign } // The token `lag` steps before position b of a batch whose first token is at `pos`, -// channel c: from the batch itself if it is that recent, else from a ring of the last -// n - 1 tokens before the batch; zero before the start of the sequence. +// channel c: from the batch itself if it is that recent, else from a ring of `slots` +// recent tokens (the token at position p is in slot p % slots; at least the n - 1 before +// the batch are there); zero before the start of the sequence. __device__ __forceinline__ float earlier_token(const float* current, const float* ring, unsigned int channels, - unsigned int n, unsigned long long pos, unsigned int b, + unsigned int slots, unsigned long long pos, unsigned int b, unsigned int lag, unsigned int c) { if (b >= lag) return current[(size_t)(b - lag) * channels + c]; unsigned long long at = pos + b; - return at >= lag ? ring[((at - lag) % (n - 1)) * channels + c] : 0.0f; + return at >= lag ? ring[((at - lag) % slots) * channels + c] : 0.0f; } // Short convolution with fixed taps, for a batch of `batch` consecutive tokens of // `channels` floats: taps[c * n + j] weighs the token n - 1 - j steps back. // out[b][c] = (sum of taps times tokens + current[b][c]) * norm +// The ring may have more than the n - 1 slots a convolution reads; the spare ones are what +// lets the newest tokens be taken back (the tokens before them are still there). // With a batch of one, the token then takes its place in the ring. With a larger batch // the ring is only read here (another position's thread may be reading the slot a write // would hit); `ring_store` puts the batch's last tokens in afterwards. // CPU reference: sconv::fixed, token after token. extern "C" __global__ void sconv_fixed(const float* current, float* ring, const float* taps, float* out, unsigned int channels, unsigned int n, unsigned long long pos, - float norm, unsigned int batch) { + float norm, unsigned int batch, unsigned int slots) { unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; unsigned int b = (unsigned int)(index / channels); unsigned int c = (unsigned int)(index % channels); @@ -103,9 +106,10 @@ extern "C" __global__ void sconv_fixed(const float* current, float* ring, const float x = current[index]; const float* w = taps + (size_t)c * n; float sum = w[n - 1] * x; - for (unsigned int j = 0; j + 1 < n; ++j) sum += w[j] * earlier_token(current, ring, channels, n, pos, b, n - 1 - j, c); + for (unsigned int j = 0; j + 1 < n; ++j) + sum += w[j] * earlier_token(current, ring, channels, slots, pos, b, n - 1 - j, c); out[index] = (sum + x) * norm; - if (batch == 1 && n > 1) ring[(pos % (n - 1)) * channels + c] = x; + if (batch == 1 && n > 1) ring[(pos % slots) * channels + c] = x; } // Short convolution whose taps are a fixed part per channel plus a part computed for each @@ -115,7 +119,7 @@ extern "C" __global__ void sconv_fixed(const float* current, float* ring, const extern "C" __global__ void sconv_dynamic(const float* current, float* ring, const float* fixed_taps, const float* token_taps, float* out, unsigned int channels, unsigned int n, unsigned int heads, unsigned long long pos, - float norm, unsigned int batch) { + float norm, unsigned int batch, unsigned int slots) { unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; unsigned int b = (unsigned int)(index / channels); unsigned int c = (unsigned int)(index % channels); @@ -125,22 +129,22 @@ extern "C" __global__ void sconv_dynamic(const float* current, float* ring, cons float sum = (fixed_taps[c] + head_taps[0]) * x; for (unsigned int lag = 1; lag < n; ++lag) sum += (fixed_taps[(size_t)lag * channels + c] + head_taps[lag]) - * earlier_token(current, ring, channels, n, pos, b, lag, c); + * earlier_token(current, ring, channels, slots, pos, b, lag, c); out[index] = (sum + x) * norm; - if (batch == 1 && n > 1) ring[(pos % (n - 1)) * channels + c] = x; + if (batch == 1 && n > 1) ring[(pos % slots) * channels + c] = x; } -// After a convolution over a batch larger than one: the batch's last n - 1 tokens (or all -// of them, if it has fewer) take their places in the ring. The token at position p goes to -// slot p % (n - 1); the tokens stored here have different slots. +// After a convolution over a batch larger than one: the batch's last `slots` tokens (all of +// them, if it has no more) take their places in the ring. The token at position p goes to +// slot p % slots; the tokens stored here have different slots. extern "C" __global__ void ring_store(const float* current, float* ring, unsigned int channels, - unsigned int n, unsigned long long pos, unsigned int batch) { + unsigned int slots, unsigned long long pos, unsigned int batch) { unsigned long long index = (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x; unsigned int b = (unsigned int)(index / channels); unsigned int c = (unsigned int)(index % channels); - if (b >= batch || n < 2) return; - if (batch - b > n - 1) return; - ring[((pos + b) % (n - 1)) * channels + c] = current[index]; + if (b >= batch || slots == 0) return; + if (batch - b > slots) return; + ring[((pos + b) % slots) * channels + c] = current[index]; } // The keys or values of a batch go to their rows of the history: the token at position p diff --git a/crates/dluth-cuda/src/attention.rs b/crates/dluth-cuda/src/attention.rs index ef803dd..482a1a4 100644 --- a/crates/dluth-cuda/src/attention.rs +++ b/crates/dluth-cuda/src/attention.rs @@ -194,7 +194,11 @@ impl<'m> Attention<'m> { /// The short convolution with fixed taps (`channels * n` of them) of a batch of `batch` /// consecutive tokens, the first at `pos`, written to `out`. `current` and `out` hold - /// the tokens one after another. `ring` holds the `n - 1` tokens before the batch. + /// the tokens one after another. `ring` holds recent tokens, at least the `n - 1` before + /// the batch: it is a whole number of slots of one token each, at least `n - 1` of them, + /// and the token at position p is in slot `p % slots`. With more slots than `n - 1`, + /// tokens older than a convolution reads stay available, which is what lets the newest + /// tokens be dropped again: feed the next batch at an earlier position. /// /// With a batch of one the token then takes its place in the ring. With a larger batch /// the ring is left as it was: call `ring_store` after this. Batches must be given in @@ -211,7 +215,7 @@ impl<'m> Attention<'m> { batch: usize, ) -> Result<(), CudaError> { let what = "sconv_fixed"; - let channels = self.conv_checks(what, current, ring, out, n, batch)?; + let (channels, slots) = self.conv_checks(what, current, ring, out, n, batch)?; taps.check(self.dev, what, channels * n)?; if taps.overlaps(&out) || taps.overlaps(&ring) { return refuse(what, "the taps overlap the output or the ring".into()); @@ -219,6 +223,7 @@ impl<'m> Attention<'m> { let (mut pc, mut pr, mut pt, mut po) = (current.address(), ring.address(), taps.address(), out.address()); let (mut c, mut taps_n, mut p, mut b) = (channels as u32, n as u32, pos as u64, batch as u32); let mut norm = 1.0 / ((n + 1) as f32).sqrt(); + let mut s = slots as u32; let mut args = [ ptr(&mut pc), ptr(&mut pr), @@ -229,10 +234,12 @@ impl<'m> Attention<'m> { big(&mut p), real(&mut norm), num(&mut b), + num(&mut s), ]; // SAFETY: the arguments match sconv_fixed(const float*, float*, const float*, float*, - // unsigned, unsigned, unsigned long long, float, unsigned). It reads batch * channels - // floats of `current`, channels * n of `taps` and (n - 1) * channels of `ring`, + // unsigned, unsigned, unsigned long long, float, unsigned, unsigned). It reads + // batch * channels floats of `current`, channels * n of `taps` and slots below + // `slots` of `ring`, which holds slots * channels floats, // writes batch * channels to `out`, and writes the ring only for a batch of one; all // checked, and `out` overlaps none of the inputs. unsafe { self.sconv_fixed.launch((blocks((batch * channels) as u64, 256)?, 1, 1), (256, 1, 1), &mut args) } @@ -255,7 +262,7 @@ impl<'m> Attention<'m> { batch: usize, ) -> Result<(), CudaError> { let what = "sconv_dynamic"; - let channels = self.conv_checks(what, current, ring, out, n, batch)?; + let (channels, slots) = self.conv_checks(what, current, ring, out, n, batch)?; if heads == 0 || !channels.is_multiple_of(heads) { return refuse(what, format!("{channels} channels in {heads} heads")); } @@ -273,6 +280,7 @@ impl<'m> Attention<'m> { let (mut c, mut taps_n, mut h, mut p, mut b) = (channels as u32, n as u32, heads as u32, pos as u64, batch as u32); let mut norm = 1.0 / ((2 * n + 1) as f32).sqrt(); + let mut s = slots as u32; let mut args = [ ptr(&mut pc), ptr(&mut pr), @@ -285,15 +293,17 @@ impl<'m> Attention<'m> { big(&mut p), real(&mut norm), num(&mut b), + num(&mut s), ]; // SAFETY: the arguments match sconv_dynamic(const float*, float*, const float*, // const float*, float*, unsigned, unsigned, unsigned, unsigned long long, float, - // unsigned). Extents as for sconv_fixed, plus batch * heads * n floats of + // unsigned, unsigned). Extents as for sconv_fixed, plus batch * heads * n floats of // `token_taps`; all checked. unsafe { self.sconv_dynamic.launch((blocks((batch * channels) as u64, 256)?, 1, 1), (256, 1, 1), &mut args) } } - /// Checks what both convolutions share and returns the number of channels. + /// Checks what both convolutions share and returns the number of channels and of the + /// ring's slots. fn conv_checks( &self, what: &str, @@ -302,7 +312,7 @@ impl<'m> Attention<'m> { out: Floats, n: usize, batch: usize, - ) -> Result { + ) -> Result<(usize, usize), CudaError> { if n == 0 || n > 64 || batch == 0 || batch > MAX_BATCH || !current.len.is_multiple_of(batch) { return refuse(what, format!("{n} taps, {} floats for a batch of {batch}", current.len)); } @@ -312,8 +322,10 @@ impl<'m> Attention<'m> { } current.check(self.dev, what, batch * channels)?; out.check(self.dev, what, batch * channels)?; + let mut slots = 0; if n > 1 { - ring.check(self.dev, what, (n - 1) * channels)?; + slots = Self::ring_slots(what, ring, channels, n)?; + ring.check(self.dev, what, slots * channels)?; if ring.overlaps(¤t) || ring.overlaps(&out) { return refuse(what, "the ring overlaps the tokens or the output".into()); } @@ -321,12 +333,21 @@ impl<'m> Attention<'m> { if out.overlaps(¤t) { return refuse(what, "the output overlaps the tokens".into()); } - Ok(channels) + Ok((channels, slots)) } - /// After a convolution over a batch larger than one: the batch's last `n - 1` tokens - /// take their places in `ring`. After a batch of one, which stored its token itself, - /// it stores the same token again. + /// How many tokens a ring holds: a whole number, at least the `n - 1` a convolution reads. + fn ring_slots(what: &str, ring: Floats, channels: usize, n: usize) -> Result { + let slots = ring.len / channels; + if !ring.len.is_multiple_of(channels) || slots < n - 1 || slots > 1 << 16 { + return refuse(what, format!("a ring of {} floats for {} tokens of {channels}", ring.len, n - 1)); + } + Ok(slots) + } + + /// After a convolution over a batch larger than one: the batch's tokens take their + /// places in `ring` (all of them if the ring has that many slots, else the last ones). + /// After a batch of one, which stored its token itself, it stores the same token again. pub fn ring_store( &self, current: Floats, @@ -346,17 +367,19 @@ impl<'m> Attention<'m> { if channels == 0 || channels > 1 << 24 { return refuse(what, format!("{channels} channels")); } + let slots = Self::ring_slots(what, ring, channels, n)?; current.check(self.dev, what, batch * channels)?; - ring.check(self.dev, what, (n - 1) * channels)?; + ring.check(self.dev, what, slots * channels)?; if ring.overlaps(¤t) { return refuse(what, "the ring overlaps the tokens".into()); } let (mut pc, mut pr) = (current.address(), ring.address()); - let (mut c, mut taps_n, mut p, mut b) = (channels as u32, n as u32, pos as u64, batch as u32); - let mut args = [ptr(&mut pc), ptr(&mut pr), num(&mut c), num(&mut taps_n), big(&mut p), num(&mut b)]; + let (mut c, mut s, mut p, mut b) = (channels as u32, slots as u32, pos as u64, batch as u32); + let mut args = [ptr(&mut pc), ptr(&mut pr), num(&mut c), num(&mut s), big(&mut p), num(&mut b)]; // SAFETY: the arguments match ring_store(const float*, float*, unsigned, unsigned, // unsigned long long, unsigned). It reads batch * channels floats of `current` and - // writes at most (n - 1) * channels of `ring`, each slot from one token; all checked. + // writes into slots below `slots` of `ring`, each slot from one token (it stores at + // most `slots` consecutive tokens); all checked. unsafe { self.ring_store.launch((blocks((batch * channels) as u64, 256)?, 1, 1), (256, 1, 1), &mut args) } } diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs index acf8619..e777e21 100644 --- a/crates/dluth-cuda/src/ops.rs +++ b/crates/dluth-cuda/src/ops.rs @@ -38,6 +38,17 @@ use std::rc::Rc; /// Threads per row for the matrix kernels: the measured best on the real shapes. const SEGS: u32 = 16; +/// Slots in a convolution's ring of recent tokens: the `taps - 1` it reads and a batch +/// more, so that a batch's tokens never take the slots of the tokens just before it, and +/// the newest tokens can be undone. +fn ring_slots(taps: usize) -> usize { + if taps < 2 { + 0 + } else { + taps - 1 + MAX_BATCH + } +} + fn failed(e: impl std::fmt::Display) -> ModelError { ModelError::Device(e.to_string()) } @@ -548,7 +559,7 @@ impl<'m> CudaOps<'m> { let n = taps.len() / channels; let taps = self.param(taps)?; let out = self.vecs(batch, channels)?; - let ring = Floats::first(ring, (n - 1) * channels); + let ring = Floats::first(ring, ring_slots(n) * channels); self.attention .sconv_fixed(x.all(), ring, Floats::first(&taps, n * channels), out.all(), n, pos, batch) .map_err(failed)?; @@ -574,7 +585,7 @@ impl<'m> CudaOps<'m> { let width = cfg.kv_heads * cfg.head_dim; let (n, batch) = (cfg.conv_taps, input.count()); let projected = self.bf16(matrix, width, cfg.hidden, input)?; - let ring = Floats::first(ring, (n - 1) * width); + let ring = Floats::first(ring, ring_slots(n) * width); match conv { KvConv::Fixed { taps } => { let taps = self.param(taps)?; @@ -610,7 +621,7 @@ impl<'m> Ops for CudaOps<'m> { type Pass = DevicePass; fn new_pass(&mut self, cfg: &InklingConfig, local: bool, max_seq: usize) -> Result { - let (h, width, recent) = (cfg.hidden, cfg.kv_heads * cfg.head_dim, cfg.conv_taps - 1); + let (h, width, recent) = (cfg.hidden, cfg.kv_heads * cfg.head_dim, ring_slots(cfg.conv_taps)); let window = local.then_some(cfg.window); // A layer with a window needs the rows of the window, and more for a batch: the // first token of a batch still sees tokens whose rows, with only `window` of them, @@ -639,6 +650,31 @@ impl<'m> Ops for CudaOps<'m> { Ok(()) } + fn undo(&mut self, pass: &mut DevicePass, undone: usize) -> Result<(), ModelError> { + if undone >= MAX_BATCH { + return Err(ModelError::Capacity(format!("{undone} tokens cannot be undone; at most {}", MAX_BATCH - 1))); + } + // Nothing on the device needs changing. The undone tokens are of the last batch, at + // most MAX_BATCH - 1 = 15 of them, and what they wrote is never read again before it + // is written again. The sizes this rests on are set from MAX_BATCH in `new_pass` and + // `ring_slots` and must move with it: a history with a window has + // `window + MAX_BATCH - 1` rows, and the last token of a batch takes the row of the + // token `window + 15` before it, at least `window` before the batch's first, where a + // token after the first sees back `window - 1`; a ring has `taps - 1 + MAX_BATCH` + // slots, and the last token of a batch takes the slot of the token `taps + 15` + // before it, at least `taps` before the batch's first, where a convolution after + // the first reads back `taps - 1`. + // - their rows of the histories are beyond every later token's view until those + // positions are fed again, which writes them first; and the rows they took over, + // in a history with a window, belonged to tokens at least `window` positions + // before the batch's first token, which no token after it can see; + // - their slots of the convolutions' rings likewise, and the slots they took over + // held tokens further before the batch's first token than a convolution looks + // back (a ring has a batch more slots than a convolution reads). + let _ = pass; + Ok(()) + } + fn count(&self, x: &DeviceVec) -> usize { x.count() } @@ -982,6 +1018,9 @@ impl<'m> Ops for TimedOps<'m> { fn reset_pass(&mut self, pass: &mut DevicePass) -> Result<(), ModelError> { self.inner.reset_pass(pass) } + fn undo(&mut self, pass: &mut DevicePass, undone: usize) -> Result<(), ModelError> { + self.inner.undo(pass, undone) + } fn count(&self, x: &DeviceVec) -> usize { self.inner.count(x) } diff --git a/crates/dluth-cuda/tests/attention.rs b/crates/dluth-cuda/tests/attention.rs index 80c858f..7970697 100644 --- a/crates/dluth-cuda/tests/attention.rs +++ b/crates/dluth-cuda/tests/attention.rs @@ -222,6 +222,93 @@ fn both_short_convolutions_match_the_cpu_token_after_token() { } } +/// A ring with a batch more slots than a convolution reads: each sweep feeds a few true +/// tokens followed by wrong ones, and the next sweep starts after the true ones, as if the +/// wrong ones had never been fed. Every true token's output must match the CPU fed the true +/// tokens alone. +#[test] +fn spare_slots_let_a_convolution_take_tokens_back() { + let dev = CudaDevice::open(0).expect("GPU"); + let (module,) = kernels(&dev); + let at = Attention::new(&dev, &module).unwrap(); + let mut rng = Lcg(11); + let (channels, n, heads) = (36, 4, 4); + let slots = n - 1 + MAX_BATCH; + let fixed_taps = rng.vec(channels * n, 0.7); + let most = MAX_BATCH * channels; + let (d_taps, d_cur, d_out) = + (upload(&dev, &fixed_taps), dev.alloc(most * 4).unwrap(), dev.alloc(most * 4).unwrap()); + let d_token_taps = dev.alloc(MAX_BATCH * heads * n * 4).unwrap(); + let junk = vec![99.0f32; slots * channels]; + let (ring_fixed, ring_dynamic) = (upload(&dev, &junk), upload(&dev, &junk)); + let ring = |b| Floats::first(b, slots * channels); + let (mut recent_fixed, mut recent_dynamic) = (vec![0.0f32; (n - 1) * channels], vec![0.0f32; (n - 1) * channels]); + // (true tokens, wrong tokens after them) per sweep. + let sweeps = + [(1usize, 3usize), (1, MAX_BATCH - 1), (4, 1), (2, 0), (1, 1), (3, 7), (1, 0), (5, 11), (MAX_BATCH, 0)]; + let mut pos = 0; + for round in 0..4 { + for (right, wrong) in sweeps { + let batch = right + wrong; + // The wrong tokens are large, so that one leaking into a later output shows. + let mut current = rng.vec(right * channels, 2.0); + current.extend(rng.vec(wrong * channels, 50.0)); + let token_taps = rng.vec(batch * heads * n, 0.5); + put(&dev, &d_cur, ¤t); + put(&dev, &d_token_taps, &token_taps); + let cur = Floats::first(&d_cur, batch * channels); + let out = Floats::first(&d_out, batch * channels); + at.sconv_fixed(cur, ring(&ring_fixed), Floats::first(&d_taps, channels * n), out, n, pos, batch).unwrap(); + if batch > 1 { + at.ring_store(cur, ring(&ring_fixed), n, pos, batch).unwrap(); + } + let got_fixed = download(&dev, &d_out, batch * channels); + at.sconv_dynamic( + cur, + ring(&ring_dynamic), + Floats::first(&d_taps, channels * n), + Floats::first(&d_token_taps, batch * heads * n), + out, + n, + heads, + pos, + batch, + ) + .unwrap(); + if batch > 1 { + at.ring_store(cur, ring(&ring_dynamic), n, pos, batch).unwrap(); + } + let got_dynamic = download(&dev, &d_out, batch * channels); + for b in 0..right { + let token = ¤t[b * channels..(b + 1) * channels]; + let mut want = vec![0.0f32; channels]; + sconv::fixed(&recent_fixed, token, &fixed_taps, &mut want); + let what = format!("round {round}, token {} ({right} true, {wrong} wrong)", pos + b); + close( + &format!("sconv_fixed, {what}"), + &got_fixed[b * channels..(b + 1) * channels], + &want, + |_| 8.0, + 4.0, + ); + remember(&mut recent_fixed, token); + let taps = &token_taps[b * heads * n..(b + 1) * heads * n]; + sconv::dynamic(&recent_dynamic, token, &fixed_taps, taps, heads, &mut want); + close( + &format!("sconv_dynamic, {what}"), + &got_dynamic[b * channels..(b + 1) * channels], + &want, + |_| 8.0, + 4.0, + ); + remember(&mut recent_dynamic, token); + } + // The wrong tokens are dropped by going on from where the true ones ended. + pos += right; + } + } +} + /// Runs `tokens` tokens through attention with a history of `cap` rows (`history` is the /// rows and the window) on the device, in /// batches of the sizes in `batches` (taken in turn), and compares every output with @@ -492,6 +579,7 @@ fn requests_that_would_leave_the_buffers_are_refused() { refused("more rows stored than the history has", at.store_rows(f(&c, 72), f(&a, 64), 8, 8, 0, 9)); refused("rows stored from inside the history", at.store_rows(f(&a, 8), f(&a, 64), 8, 8, 0, 1)); refused("rows the buffer does not hold", at.store_rows(f(&b, 64), f(&a, 64), 8, 8, 0, 9)); + refused("a ring that is not whole tokens", at.sconv_fixed(f(&a, 16), f(&b, 50), f(&c, 64), f(&c, 16), 4, 0, 1)); refused("a ring that is the tokens", at.ring_store(f(&a, 32), f(&a, 48), 4, 0, 2)); refused("tokens the batch does not divide", at.ring_store(f(&a, 33), f(&b, 48), 4, 0, 2)); refused("a softmax over a run of one", at.softmax_runs(f(&a, 4), 4, 1)); diff --git a/crates/dluth-cuda/tests/inkling_golden_cuda.rs b/crates/dluth-cuda/tests/inkling_golden_cuda.rs index b118810..88f5d2f 100644 --- a/crates/dluth-cuda/tests/inkling_golden_cuda.rs +++ b/crates/dluth-cuda/tests/inkling_golden_cuda.rs @@ -273,6 +273,105 @@ mod on_the_device { assert_eq!(batched.generate_greedy(&tokens[..21], 10, u32::MAX).unwrap(), alone); } + /// Sweeps of a few true tokens followed by wrong ones, which are then undone: every true + /// position's scores against the CPU model fed the true tokens alone, over more tokens + /// than the local layers' histories have rows. + #[test] + fn undone_tokens_leave_no_trace_on_the_device() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/tiny-inkling"); + let golden: serde_json::Value = + serde_json::from_slice(&std::fs::read(dir.join("golden.json")).unwrap()).unwrap(); + let tol = 4.0 * golden["reference_self_difference"].as_f64().unwrap() as f32; + let weights = Weights::open_dir(&dir).unwrap(); + let dev = CudaDevice::open(0).expect("GPU"); + let module = Module::load_embedded(&dev).unwrap(); + let cfg = load_config(&dir).unwrap(); + let vocab = cfg.vocab_out; + let mut gpu = Inkling::with_ops(cfg, &weights, 128, CudaOps::new(&dev, &module).unwrap()).unwrap(); + let mut cpu = InklingCpu::new(load_config(&dir).unwrap(), &weights, 128).unwrap(); + let text: Vec = (0..100).map(|p| ((p * 37 + 11) % 256) as u32).collect(); + let sweeps = [(1usize, 3usize), (1, 15), (4, 1), (2, 0), (1, 1), (3, 7), (1, 0), (5, 11)]; + let (mut pos, mut turn, mut worst) = (0, 0, 0.0f32); + while pos < text.len() { + let (right, wrong) = sweeps[turn % sweeps.len()]; + turn += 1; + let right = right.min(text.len() - pos); + let mut batch = text[pos..pos + right].to_vec(); + batch.extend((0..wrong).map(|i| ((pos * 13 + i * 5 + 200) % 256) as u32)); + let got = gpu.forward_tokens(&batch, pos).unwrap(); + let mut want = Vec::new(); + for i in 0..right { + want = cpu.forward_token(text[pos + i], pos + i).unwrap(); + let what = format!("position {} in sweep {turn}", pos + i); + worst = worst.max(close_scores(&got[i * vocab..(i + 1) * vocab], &want, tol, &what)); + } + gpu.undo(wrong).unwrap(); + pos += right; + close_scores(&gpu.next_scores().unwrap(), &want, tol, &format!("after undoing in sweep {turn}")); + } + eprintln!("device with undone tokens: largest log-probability difference from the CPU model: {worst}"); + // A whole batch of 16 cannot be undone down to nothing, nor 16 tokens at once. + gpu.feed(&text[..16], 0).unwrap(); + assert!(gpu.undo(16).is_err()); + gpu.undo(15).unwrap(); + assert_eq!(gpu.next_position(), 1); + // A small batch keeps its first token too. Nothing on the device would notice if it + // did not: the model refuses. + gpu.feed(&text[1..5], 1).unwrap(); + assert!(gpu.undo(4).is_err()); + gpu.undo(3).unwrap(); + assert_eq!(gpu.next_position(), 2); + } + + /// Generation with guesses on the device gives the tokens of generation without, with + /// right guesses, wrong guesses and guesses from the text itself. + #[test] + 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 { + fn draft(&mut self, tokens: &[u32], most: usize) -> Vec { + let done = tokens.len() - self.1; + let wrong_every = self.2; + self.0[done.min(self.0.len())..] + .iter() + .take(most) + .enumerate() + .map( + |(i, &t)| { + if wrong_every != 0 && (done + i).is_multiple_of(wrong_every) { + (t + 1) % 256 + } else { + t + } + }, + ) + .collect() + } + } + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/tiny-inkling"); + let weights = Weights::open_dir(&dir).unwrap(); + let dev = CudaDevice::open(0).expect("GPU"); + let module = Module::load_embedded(&dev).unwrap(); + let mut gpu = + Inkling::with_ops(load_config(&dir).unwrap(), &weights, 64, CudaOps::new(&dev, &module).unwrap()).unwrap(); + let prompt: Vec = (41..64).map(|p| ((p * 37 + 11) % 256) as u32).collect(); + let want = gpu.generate_greedy(&prompt, 40, u32::MAX).unwrap(); + let (got, stats) = gpu + .generate_greedy_drafted(&prompt, 40, u32::MAX, &mut Scripted(want.clone(), prompt.len(), 0), 15, |_| {}) + .unwrap(); + assert_eq!(got, want); + assert_eq!((stats.sweeps, stats.accepted), (3, 36)); + let (got, stats) = gpu + .generate_greedy_drafted(&prompt, 40, u32::MAX, &mut Scripted(want.clone(), prompt.len(), 3), 5, |_| {}) + .unwrap(); + assert_eq!(got, want); + assert!(stats.accepted > 5 && stats.accepted < stats.drafted, "{stats:?}"); + let (got, _) = + gpu.generate_greedy_drafted(&prompt, 40, u32::MAX, &mut LookupDrafter::new(3, 1), 4, |_| {}).unwrap(); + assert_eq!(got, want); + } + /// 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/src/inkling/draft.rs b/crates/dluth-model/src/inkling/draft.rs new file mode 100644 index 0000000..e952fe1 --- /dev/null +++ b/crates/dluth-model/src/inkling/draft.rs @@ -0,0 +1,112 @@ +//! Guesses at the next few tokens, for the model to check in one sweep. +//! +//! Generation one token at a time reads every weight once per token. If the next few +//! tokens can be guessed, they can be fed as one batch behind the token just chosen: each +//! position's scores then say what the model would have chosen there, so the guesses are +//! checked one after another, and the first wrong one and everything after it is undone +//! (`Inkling::undo`). The text produced is exactly what generation without guesses +//! 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 { + /// 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; +} + +/// Never guesses. +pub struct NoDraft; + +impl Drafter for NoDraft { + fn draft(&mut self, _tokens: &[u32], _most: usize) -> Vec { + Vec::new() + } +} + +/// Guesses that the text goes on as it did the last time it read like this: it looks for +/// the most recent earlier place where the last few tokens appeared, and proposes what +/// followed them there. Text that repeats itself (code, lists, quoted passages, an answer +/// that restates the question) is guessed well; text that does not is not guessed at all. +/// Each guess scans the text once per run length tried. +pub struct LookupDrafter { + /// The longest run of last tokens to look for, tried first. + pub longest: usize, + /// The shortest run that still counts as "reads like this". + pub shortest: usize, +} + +impl LookupDrafter { + /// Looks for the last `longest` tokens first, then for fewer, down to `shortest`. + /// Both are at least 1. + pub fn new(longest: usize, shortest: usize) -> Self { + let shortest = shortest.max(1); + LookupDrafter { longest: longest.max(shortest), shortest } + } +} + +impl Drafter for LookupDrafter { + fn draft(&mut self, tokens: &[u32], most: usize) -> Vec { + if most == 0 { + return Vec::new(); + } + for run in (self.shortest..=self.longest).rev() { + if tokens.len() <= run { + continue; + } + let wanted = &tokens[tokens.len() - run..]; + // The most recent earlier place, which must be followed by at least one token + // that is not part of the run being matched against itself. + let found = (0..tokens.len() - run).rev().find(|&start| &tokens[start..start + run] == wanted); + if let Some(start) = found { + let after = start + run; + return tokens[after..tokens.len().min(after + most)].to_vec(); + } + } + Vec::new() + } +} + +/// What guessing did during one generation. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct DraftStats { + /// Sweeps through the model after the prompt. + pub sweeps: usize, + /// Guessed tokens that were fed. + pub drafted: usize, + /// Guessed tokens that were what the model chose. + pub accepted: usize, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[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. + 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]); + assert_eq!(d.draft(&[1, 2, 3, 4, 5, 9, 1, 2, 3], 1), [4]); + // A longer match wins over a more recent shorter one: "7 8" then 1, but "8" then 2 later. + assert_eq!(d.draft(&[7, 8, 1, 5, 8, 2, 7, 8], 1), [1]); + // Among matches of the same length the most recent wins. + assert_eq!(d.draft(&[6, 1, 6, 2, 6], 1), [2]); + // A token that repeats matches itself one place back. + assert_eq!(d.draft(&[4, 4, 4], 2), [4]); + } + + #[test] + fn lookup_proposes_nothing_without_a_match_or_room() { + let mut d = LookupDrafter::new(3, 2); + 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()); + } +} diff --git a/crates/dluth-model/src/inkling/mod.rs b/crates/dluth-model/src/inkling/mod.rs index 9e6d08a..3315744 100644 --- a/crates/dluth-model/src/inkling/mod.rs +++ b/crates/dluth-model/src/inkling/mod.rs @@ -1,11 +1,13 @@ //! Inkling 2 Mini: a looped mixture-of-experts model (text part only). pub mod config; +pub mod draft; pub mod model; pub mod prompt; pub use config::{load_config, model_kind, validate_weights, Checked, ExpertFormat, InklingConfig, ModelKind}; +pub use draft::{DraftStats, Drafter, LookupDrafter, NoDraft}; pub use model::{ CpuBlend, CpuOps, CpuProducts, CpuVecs, ExpertLayer, ExpertMatrices, Gate, Inkling, InklingCpu, KvConv, Layer, Ops, - PassState, Products, BLEND_EPS, + PassState, Products, BLEND_EPS, MAX_DRAFT, MAX_UNDO, }; diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs index 061f305..86093f8 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs @@ -12,6 +12,7 @@ //! previous pass and merges them in through small learned gates. use super::config::{validate_weights, ExpertFormat, InklingConfig}; +use super::draft::{DraftStats, Drafter}; use crate::error::ModelError; use crate::weights::Weights; use dluth_core::bf16_to_f32; @@ -20,6 +21,13 @@ use dluth_kernels::{blockfloat, cpu, depthmix, router, sconv, sinkattn}; /// The normalization inside every blend across depth uses this fixed epsilon. pub const BLEND_EPS: f32 = 1e-6; +/// The most tokens that can be undone at once (see `Inkling::undo`). +pub const MAX_UNDO: usize = 16; + +/// The most guessed tokens fed in one sweep (see `Inkling::generate_greedy_drafted`): with +/// the token they follow, a batch of `MAX_UNDO`. +pub const MAX_DRAFT: usize = MAX_UNDO - 1; + fn bf16_values(w: &Weights, name: &str) -> Result, ModelError> { Ok(w.bytes(name)?.as_chunks::<2>().0.iter().map(|c| bf16_to_f32(u16::from_le_bytes(*c))).collect()) } @@ -314,6 +322,11 @@ pub trait Ops { fn new_pass(&mut self, cfg: &InklingConfig, local: bool, max_seq: usize) -> Result; /// Forgets every token. fn reset_pass(&mut self, pass: &mut Self::Pass) -> Result<(), ModelError>; + /// Forgets the last `undone` tokens, which were all fed in the last batch and did not + /// include its first token. The pass is then as if they had never been fed. The model + /// never asks for more than `MAX_UNDO`; an implementation whose batches are smaller + /// can take back fewer (one less than its largest batch) and refuses more. + fn undo(&mut self, pass: &mut Self::Pass, undone: usize) -> Result<(), ModelError>; /// How many positions a value holds. fn count(&self, x: &Self::V) -> usize; @@ -413,18 +426,40 @@ impl Ops for CpuOps<'_> { Ok(PassState { keys: History::new(kv_width, window, max_seq)?, values: History::new(kv_width, window, max_seq)?, - k_recent: vec![0.0; recent * kv_width], - v_recent: vec![0.0; recent * kv_width], - attn_recent: vec![0.0; recent * h], - expert_recent: vec![0.0; recent * h], + k_recent: ConvMemory::new(recent, kv_width), + v_recent: ConvMemory::new(recent, kv_width), + attn_recent: ConvMemory::new(recent, h), + expert_recent: ConvMemory::new(recent, h), }) } + fn undo(&mut self, pass: &mut PassState, undone: usize) -> Result<(), ModelError> { + if undone > MAX_UNDO || undone > pass.keys.len || undone > pass.values.len { + return Err(ModelError::Capacity(format!("{undone} tokens cannot be undone; at most {MAX_UNDO}"))); + } + for memory in [&pass.k_recent, &pass.v_recent, &pass.attn_recent, &pass.expert_recent] { + if undone >= memory.fed_tokens() { + return Err(ModelError::Capacity(format!( + "{undone} tokens cannot be undone: the last batch had {} and keeps its first", + memory.fed_tokens() + ))); + } + } + // A history only grows at its end, and keeps enough older tokens for what is left + // to see its whole window (see `History::push`). + pass.keys.len -= undone; + pass.values.len -= undone; + for memory in [&mut pass.k_recent, &mut pass.v_recent, &mut pass.attn_recent, &mut pass.expert_recent] { + memory.undo(undone); + } + Ok(()) + } + fn reset_pass(&mut self, pass: &mut PassState) -> Result<(), ModelError> { pass.keys.len = 0; pass.values.len = 0; - for recent in [&mut pass.k_recent, &mut pass.v_recent, &mut pass.attn_recent, &mut pass.expert_recent] { - recent.fill(0.0); + for memory in [&mut pass.k_recent, &mut pass.v_recent, &mut pass.attn_recent, &mut pass.expert_recent] { + memory.clear(); } Ok(()) } @@ -521,6 +556,8 @@ impl Ops for CpuOps<'_> { let [q, k, v] = inputs; same_count("attention", q, k)?; same_count("attention", q, v)?; + pass.k_recent.start(); + pass.v_recent.start(); // In order: each token's key and value are remembered before the next token looks. let mut rows = Vec::with_capacity(q.0.len()); for i in 0..q.0.len() { @@ -531,10 +568,11 @@ impl Ops for CpuOps<'_> { fn attn_conv(&mut self, layer: &Layer, pass: &mut PassState, x: &CpuVecs) -> Result { let mut rows = Vec::with_capacity(x.0.len()); + pass.attn_recent.start(); for x in &x.0 { let mut out = vec![0.0f32; x.len()]; - sconv::fixed(&pass.attn_recent, x, &layer.attn_taps, &mut out); - remember(&mut pass.attn_recent, x); + sconv::fixed(&pass.attn_recent.recent, x, &layer.attn_taps, &mut out); + pass.attn_recent.remember(x); rows.push(out); } Ok(CpuVecs(rows)) @@ -542,10 +580,11 @@ impl Ops for CpuOps<'_> { fn expert_conv(&mut self, layer: &Layer, pass: &mut PassState, x: &CpuVecs) -> Result { let mut rows = Vec::with_capacity(x.0.len()); + pass.expert_recent.start(); for x in &x.0 { let mut out = vec![0.0f32; x.len()]; - sconv::fixed(&pass.expert_recent, x, &layer.expert_taps, &mut out); - remember(&mut pass.expert_recent, x); + sconv::fixed(&pass.expert_recent.recent, x, &layer.expert_taps, &mut out); + pass.expert_recent.remember(x); rows.push(out); } Ok(CpuVecs(rows)) @@ -592,10 +631,11 @@ struct History { } impl History { - /// Reserves room for `positions` tokens (twice the window for a local layer, so old - /// tokens can be dropped in batches), or refuses if the memory cannot be had. + /// Reserves room for `positions` tokens (for a local layer twice the window, so old + /// tokens can be dropped in batches, plus the tokens that can be undone), or refuses if + /// the memory cannot be had. fn new(width: usize, window: Option, max_seq: usize) -> Result { - let positions = window.map_or(max_seq, |w| (2 * w).min(max_seq.max(w))); + let positions = window.map_or(max_seq, |w| (2 * w + MAX_UNDO).min(max_seq.max(w))); let refusal = || ModelError::Capacity(format!("cannot reserve attention history for {positions} positions of {width}")); let len = positions.checked_mul(width).ok_or_else(refusal)?; @@ -609,8 +649,9 @@ impl History { let capacity = self.data.len() / self.width; if let Some(window) = self.window.filter(|_| self.len == capacity) { // Full: keep the newest `window - 1` tokens, which with the one being added - // is everything a local layer can see. - let keep = window.saturating_sub(1).min(self.len); + // is everything a local layer can see, and `MAX_UNDO` more: if the newest + // tokens are undone, what is left must still see its whole window. + let keep = (window.saturating_sub(1) + MAX_UNDO).min(self.len); self.data.copy_within((self.len - keep) * self.width..self.len * self.width, 0); self.len = keep; } @@ -630,11 +671,60 @@ impl History { pub struct PassState { keys: History, values: History, - /// The last few inputs of each of the four convolutions, oldest first. - k_recent: Vec, - v_recent: Vec, - attn_recent: Vec, - expert_recent: Vec, + /// The last few inputs of each of the four convolutions. + k_recent: ConvMemory, + v_recent: ConvMemory, + attn_recent: ConvMemory, + expert_recent: ConvMemory, +} + +/// What a short convolution remembers: its last few inputs, oldest first, and enough of +/// the last batch to take its newest tokens back. +struct ConvMemory { + recent: Vec, + width: usize, + /// `recent` as it was when the last batch started. + before: Vec, + /// The inputs of the last batch, in order. + fed: Vec, +} + +impl ConvMemory { + fn new(tokens: usize, width: usize) -> Self { + ConvMemory { recent: vec![0.0; tokens * width], width, before: vec![0.0; tokens * width], fed: Vec::new() } + } + + fn clear(&mut self) { + self.recent.fill(0.0); + self.before.fill(0.0); + self.fed.clear(); + } + + /// A batch starts here. + fn start(&mut self) { + self.before.copy_from_slice(&self.recent); + self.fed.clear(); + } + + fn remember(&mut self, current: &[f32]) { + remember(&mut self.recent, current); + self.fed.extend_from_slice(current); + } + + fn fed_tokens(&self) -> usize { + self.fed.len() / self.width.max(1) + } + + /// Takes back the last `undone` tokens of the last batch: the memory as it was when + /// the batch started, then the batch's remaining tokens again. + fn undo(&mut self, undone: usize) { + let kept = (self.fed_tokens() - undone) * self.width; + self.fed.truncate(kept); + self.recent.copy_from_slice(&self.before); + for token in self.fed.chunks_exact(self.width) { + remember(&mut self.recent, token); + } + } } /// Slides a convolution's memory forward by one token. @@ -685,6 +775,8 @@ pub struct Inkling<'w, O: Ops> { cached: usize, /// How many tokens of a prompt `generate_greedy` feeds at once. prompt_batch: usize, + /// How many positions of the last batch are still fed: all of them, or fewer after `undo`. + kept: usize, /// The hidden state after the last layer, before the final blend, and the finished /// blocks at that point. None until a token has been fed. last: Option<(O::V, Vec)>, @@ -826,6 +918,7 @@ impl<'w, O: Ops> Inkling<'w, O> { max_seq, cached: 0, prompt_batch: 1, + kept: 0, last: None, ops, cfg, @@ -843,6 +936,7 @@ impl<'w, O: Ops> Inkling<'w, O> { self.ops.reset_pass(pass)?; } self.cached = 0; + self.kept = 0; self.last = None; Ok(()) } @@ -923,6 +1017,7 @@ impl<'w, O: Ops> Inkling<'w, O> { self.last = Some((x, blocks)); self.cached = pos + tokens.len(); + self.kept = tokens.len(); Ok(()) } @@ -934,13 +1029,20 @@ impl<'w, O: Ops> Inkling<'w, O> { }; let (cfg, ops) = (&self.cfg, &mut self.ops); let count = ops.count(last); + if !only_last && self.kept != count { + return Err(ModelError::Capacity(format!( + "the scores of a batch of {count} were asked for after {} of its tokens were undone", + count - self.kept + ))); + } let picked: Vec; let mut candidates: Vec<&O::V> = if only_last && count > 1 { // The output table is the largest matrix of the model; scoring positions nobody - // will read would cost a sweep of it each. + // will read would cost a sweep of it each. The last position still fed is the + // batch's last unless tokens were undone. let mut rows = Vec::with_capacity(blocks.len() + 1); for v in blocks.iter().chain(std::iter::once(last)) { - rows.push(ops.row(v, count - 1)?); + rows.push(ops.row(v, self.kept - 1)?); } picked = rows; picked.iter().collect() @@ -989,6 +1091,33 @@ impl<'w, O: Ops> Inkling<'w, O> { self.logits(true) } + /// Takes back the last `undone` tokens, as if they had never been fed. They must all be + /// of the last batch fed, which keeps at least its first token, and at most `MAX_UNDO`. + /// This is how guessed tokens that turned out wrong are dropped: feed the guesses as a + /// batch, read every position's scores, then undo from the first wrong guess on. + pub fn undo(&mut self, undone: usize) -> Result<(), ModelError> { + if undone == 0 { + return Ok(()); + } + if undone >= self.kept || undone > MAX_UNDO { + return Err(ModelError::Capacity(format!( + "{undone} tokens cannot be undone: the last batch has {} left and keeps its first, and at most {MAX_UNDO} can be undone", + self.kept + ))); + } + for pass in &mut self.passes { + self.ops.undo(pass, undone)?; + } + self.cached -= undone; + self.kept -= undone; + Ok(()) + } + + /// The position the next token fed must have. + pub fn next_position(&self) -> usize { + self.cached + } + /// Feeds one token at position `pos` and returns the scores for the token after it. /// Positions must be fed in order. Position 0 starts a new sequence. pub fn forward_token(&mut self, token: u32, pos: usize) -> Result, ModelError> { @@ -1041,6 +1170,99 @@ impl<'w, O: Ops> Inkling<'w, O> { } } +impl<'w, O: Ops> Inkling<'w, O> { + /// Greedy generation with guessed tokens checked in batches. The tokens returned are + /// the ones `generate_greedy` returns (exactly, where a batch computes exactly what + /// token by token computes; otherwise up to a tie between two scores); what changes is + /// how many sweeps through the model they take. + /// + /// After each token chosen, `drafter` is asked for up to `most` tokens (at most + /// `MAX_DRAFT`) that might follow. They are fed in one batch behind the chosen token. + /// Position by position, the scores say what the model chooses next: while that is the + /// guess, the guess is kept and the next position's scores count; at the first + /// difference the model's own choice is taken and the remaining guesses are undone. + pub fn generate_greedy_drafted( + &mut self, + prompt_ids: &[u32], + max_new: usize, + eos: u32, + drafter: &mut dyn Drafter, + most: usize, + mut on_token: impl FnMut(u32), + ) -> Result<(Vec, DraftStats), ModelError> { + if prompt_ids.is_empty() { + return Err(ModelError::Capacity("empty prompt: generation needs at least one token".into())); + } + if prompt_ids.len() + max_new > self.max_seq { + return Err(ModelError::Capacity(format!( + "prompt of {} tokens plus {max_new} new tokens exceeds the history of {} positions", + prompt_ids.len(), + self.max_seq + ))); + } + let mut stats = DraftStats::default(); + let mut generated = Vec::with_capacity(max_new); + if max_new == 0 { + return Ok((generated, stats)); + } + let mut pos = 0; + for batch in prompt_ids.chunks(self.prompt_batch) { + self.advance(batch, pos)?; + pos += batch.len(); + } + let (vocab, vocab_out) = (self.cfg.vocab, self.cfg.vocab_out); + let mut text = prompt_ids.to_vec(); + let mut next = argmax(&self.logits(true)?); + generated.push(next); + text.push(next); + on_token(next); + while next != eos && generated.len() < max_new { + // A sweep with k guesses can produce k + 1 tokens: no more guesses than there + // is room for tokens. The positions fit, because the prompt and `max_new` + // tokens do. + let room = (max_new - generated.len() - 1).min(most).min(MAX_DRAFT); + let mut batch = vec![next]; + if room > 0 { + let guesses = drafter.draft(&text, room); + // A guess is only a guess: never more than asked for, never outside the + // vocabulary. + batch.extend(guesses.into_iter().take(room).take_while(|g| (*g as usize) < vocab)); + } + let guessed = batch.len() - 1; + let scores = if guessed == 0 { + self.advance(&batch, pos)?; + self.logits(true)? + } else { + self.forward_tokens(&batch, pos)? + }; + stats.sweeps += 1; + stats.drafted += guessed; + // Position i's scores are for the token after batch[i]. While the model's + // choice is the next guess, that guess stands and the next position counts. + let mut kept = 0; + for (i, at) in scores.chunks_exact(vocab_out).enumerate() { + next = argmax(at); + kept = i + 1; + generated.push(next); + text.push(next); + on_token(next); + if next == eos || generated.len() == max_new || batch.get(i + 1) != Some(&next) { + break; + } + } + if kept == 0 { + // One run of scores per token fed: none would mean the operations returned + // nothing for a batch. + return Err(ModelError::Device("a sweep returned no scores".into())); + } + stats.accepted += kept - 1; + self.undo(batch.len() - kept)?; + pos += kept; + } + Ok((generated, stats)) + } +} + /// Merges a message into a sublayer input: `(1 - forget) * x + gain * message`, where /// forget and gain come from a small network that looks at both. fn merge( @@ -1073,7 +1295,7 @@ fn project_kv( p: &mut dyn Products, matrix: &[u8], conv: &KvConv, - recent: &mut [f32], + memory: &mut ConvMemory, input: &[f32], ) -> Result, ModelError> { let width = cfg.kv_heads * cfg.head_dim; @@ -1081,15 +1303,15 @@ fn project_kv( p.bf16(matrix, width, cfg.hidden, input, &mut projected)?; let mut out = vec![0.0f32; width]; match conv { - KvConv::Fixed { taps } => sconv::fixed(recent, &projected, taps, &mut out), + KvConv::Fixed { taps } => sconv::fixed(&memory.recent, &projected, taps, &mut out), KvConv::Dynamic { fixed_taps, token_proj } => { let mut token_taps = vec![0.0f32; cfg.kv_heads * cfg.conv_taps]; let taps = token_taps.len(); p.bf16(token_proj, taps, cfg.hidden, input, &mut token_taps)?; - sconv::dynamic(recent, &projected, fixed_taps, &token_taps, cfg.kv_heads, &mut out); + sconv::dynamic(&memory.recent, &projected, fixed_taps, &token_taps, cfg.kv_heads, &mut out); } } - remember(recent, &projected); + memory.remember(&projected); Ok(out) } @@ -1313,8 +1535,30 @@ mod tests { assert_eq!(global.visible().1, i + 1); } assert_eq!(global.visible().0[0], 0.0); - // The local history never grew past twice its window. - assert_eq!(local.data.len(), 6); + // The local history never grew past twice its window and what can be undone. + assert_eq!(local.data.len(), 6 + MAX_UNDO); + } + + #[test] + fn the_scores_of_a_whole_batch_are_refused_once_part_of_it_is_undone() { + // No public function asks for this (scoring every position always follows a feed); + // the guard is what keeps a later one from handing out scores of undone tokens. + let dir = TinyModel::inkling().write(); + let weights = Weights::open_dir(dir.path()).unwrap(); + let mut model = InklingCpu::new(load_config(dir.path()).unwrap(), &weights, 16).unwrap(); + model.feed(&[1, 2, 3, 4], 0).unwrap(); + assert!(model.logits(false).is_ok()); + model.undo(2).unwrap(); + let e = model.logits(false).unwrap_err(); + assert!(matches!(e, ModelError::Capacity(ref m) if m.contains("undone")), "{e}"); + // The last position still fed can be scored, and is the second token's. + let after_undo = model.logits(true).unwrap(); + let mut fresh = InklingCpu::new(load_config(dir.path()).unwrap(), &weights, 16).unwrap(); + fresh.feed(&[1, 2], 0).unwrap(); + // Compared as bits: this unit-test model's weights are not trained or even scaled, + // and its scores need not be numbers. + let bits = |v: Vec| v.into_iter().map(f32::to_bits).collect::>(); + assert_eq!(bits(after_undo), bits(fresh.logits(true).unwrap())); } #[test] diff --git a/crates/dluth-model/tests/inkling_draft.rs b/crates/dluth-model/tests/inkling_draft.rs new file mode 100644 index 0000000..d8a135a --- /dev/null +++ b/crates/dluth-model/tests/inkling_draft.rs @@ -0,0 +1,271 @@ +//! Guessed tokens: feeding them in a batch and undoing the wrong ones leaves the model +//! 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::{load_config, DraftStats, Drafter, InklingCpu, LookupDrafter, NoDraft, MAX_DRAFT, MAX_UNDO}; +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") +} + +fn tokens(n: usize) -> Vec { + (0..n).map(|i| ((i * 37 + 11) % 256) as u32).collect() +} + +fn one_at_a_time(model: &mut InklingCpu, tokens: &[u32]) -> Vec> { + tokens.iter().enumerate().map(|(pos, &t)| model.forward_token(t, pos).unwrap()).collect() +} + +/// 100 tokens, far past the point where the tiny model's local histories (window 8) drop +/// their oldest tokens. Each sweep feeds a few true tokens followed by wrong ones, reads the +/// scores, and undoes the wrong ones: every true position's scores must be bit for bit what +/// feeding the true tokens alone gives. +#[test] +fn undone_tokens_leave_no_trace() { + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let cfg = load_config(&dir).unwrap(); + let vocab = cfg.vocab_out; + let text = tokens(100); + let mut model = InklingCpu::new(cfg, &weights, 128).unwrap(); + let want = one_at_a_time(&mut model, &text); + + // (true tokens, wrong tokens after them) per sweep, taken in turn. + let sweeps = [(1usize, 3usize), (1, MAX_UNDO), (4, 1), (2, 0), (1, 1), (3, 7), (1, 0), (5, MAX_UNDO)]; + let (mut pos, mut turn) = (0, 0); + while pos < text.len() { + let (right, wrong) = sweeps[turn % sweeps.len()]; + turn += 1; + let right = right.min(text.len() - pos); + let mut batch = text[pos..pos + right].to_vec(); + batch.extend((0..wrong).map(|i| ((pos * 13 + i * 5 + 200) % 256) as u32)); + let got = model.forward_tokens(&batch, pos).unwrap(); + for i in 0..right { + assert!(got[i * vocab..(i + 1) * vocab] == want[pos + i][..], "position {} in sweep {turn}", pos + i); + } + model.undo(wrong).unwrap(); + pos += right; + assert_eq!(model.next_position(), pos); + // After undoing, the scores after the last token still fed are the true ones. + assert!(model.next_scores().unwrap() == want[pos - 1], "after undoing in sweep {turn}"); + } + assert!(turn > 20, "the sweeps should come round several times"); +} + +/// The tightest case for a local history on the CPU: it is full, the last token of a batch +/// of 17 makes it drop its old tokens, and then the 16 tokens after the batch's first are +/// undone. What is left must be exactly the window the next token sees. +#[test] +fn an_undo_right_after_a_history_dropped_old_tokens_leaves_a_whole_window() { + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let cfg = load_config(&dir).unwrap(); + // A local history holds twice the window plus what can be undone. + let capacity = 2 * cfg.window + MAX_UNDO; + let text = tokens(capacity + 8); + let mut model = InklingCpu::new(load_config(&dir).unwrap(), &weights, 128).unwrap(); + let want = one_at_a_time(&mut model, &text); + // Fill it to 16 short of full, so that a batch of 17 fills it and its last token is + // the one that makes it drop. + let before = capacity - MAX_UNDO; + model.feed(&text[..before], 0).unwrap(); + let mut batch = vec![text[before]]; + batch.extend((0..MAX_UNDO).map(|i| (200 + i) as u32)); + model.forward_tokens(&batch, before).unwrap(); + model.undo(MAX_UNDO).unwrap(); + assert!(model.next_scores().unwrap() == want[before]); + let got = model.forward_tokens(&text[before + 1..], before + 1).unwrap(); + for (i, scores) in got.chunks_exact(want[0].len()).enumerate() { + assert!(scores == want[before + 1 + i].as_slice(), "position {}", before + 1 + i); + } +} + +#[test] +fn what_cannot_be_undone_is_refused_and_changes_nothing() { + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let text = tokens(40); + let mut model = InklingCpu::new(load_config(&dir).unwrap(), &weights, 64).unwrap(); + let want = one_at_a_time(&mut model, &text); + let refused = |r: Result<(), ModelError>, what: &str| { + let e = r.unwrap_err(); + assert!(matches!(e, ModelError::Capacity(_)) && e.to_string().contains(what), "{e}"); + }; + + model.feed(&text[..3], 0).unwrap(); + model.feed(&text[3..8], 3).unwrap(); + // The whole last batch; more than it; into the batch before it. + refused(model.undo(5), "keeps its first"); + refused(model.undo(6), "keeps its first"); + model.undo(2).unwrap(); + // What is left of the batch is three tokens: two of them can still go, not three. + refused(model.undo(3), "keeps its first"); + // A refused batch after an undo changes nothing either, and the scores after the last + // token still fed are that token's. + let e = model.forward_tokens(&[], 6).unwrap_err(); + assert!(e.to_string().contains("empty"), "{e}"); + assert!(model.next_scores().unwrap() == want[5]); + model.undo(2).unwrap(); + assert_eq!(model.next_position(), 4); + assert!(model.next_scores().unwrap() == want[3]); + // A batch of one has nothing to undo; undoing nothing is always fine. + model.feed(&text[4..5], 4).unwrap(); + refused(model.undo(1), "keeps its first"); + model.undo(0).unwrap(); + // More than can be undone at once, from a batch large enough. + model.feed(&text[5..5 + MAX_UNDO + 4], 5).unwrap(); + refused(model.undo(MAX_UNDO + 1), "at most"); + model.undo(MAX_UNDO).unwrap(); + assert_eq!(model.next_position(), 9); + // After all that the sequence goes on to the same scores. + let got = model.forward_tokens(&text[9..20], 9).unwrap(); + for (i, scores) in got.chunks_exact(want[0].len()).enumerate() { + assert!(scores == want[9 + i].as_slice(), "position {}", 9 + i); + } + // Nothing fed yet on a fresh model: nothing to undo. + let mut fresh = InklingCpu::new(load_config(&dir).unwrap(), &weights, 64).unwrap(); + refused(fresh.undo(1), "keeps its first"); +} + +/// Knows the text the model will produce and guesses it, wrongly at chosen places. +struct Scripted { + truth: Vec, + prompt: usize, + /// Every `wrong_every`-th guess is wrong (0: none). + wrong_every: usize, + asked: usize, + guesses: usize, +} + +impl Drafter for Scripted { + fn draft(&mut self, tokens: &[u32], most: usize) -> Vec { + self.asked += 1; + let done = tokens.len() - self.prompt; + let mut out = Vec::new(); + for &t in self.truth[done.min(self.truth.len())..].iter().take(most) { + self.guesses += 1; + let wrong = self.wrong_every != 0 && self.guesses.is_multiple_of(self.wrong_every); + out.push(if wrong { (t + 1) % 256 } else { t }); + } + out + } +} + +/// Guesses more than it was asked for, and tokens that do not exist. +struct 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; + out + } +} + +#[test] +fn generation_with_guesses_gives_the_tokens_of_generation_without() { + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let prompt = &tokens(64)[41..64]; + let max_new = 40; + 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 seen = Vec::new(); + let (got, stats) = + model.generate_greedy_drafted(prompt, max_new, u32::MAX, drafter, most, |t| seen.push(t)).unwrap(); + assert_eq!(got, want, "most {most}"); + assert_eq!(seen, want, "the tokens are reported once each, in order"); + stats + }; + + // No guesses: one sweep per token after the first, which comes from the prompt. + assert_eq!(drafted(&mut NoDraft, 4), DraftStats { sweeps: max_new - 1, drafted: 0, accepted: 0 }); + assert_eq!(drafted(&mut LookupDrafter::new(3, 1), 0).drafted, 0); + + // Every guess right, 4 at a time: 5 tokens a sweep, and no guess past the last token. + let script = + |wrong_every| Scripted { truth: want.clone(), prompt: prompt.len(), wrong_every, asked: 0, guesses: 0 }; + let stats = drafted(&mut script(0), 4); + assert_eq!(stats, DraftStats { sweeps: 8, drafted: 31, accepted: 31 }); + // As many as a sweep takes: 16 tokens a sweep, 39 tokens after the first in 3 sweeps. + let stats = drafted(&mut script(0), 100); + assert_eq!((stats.sweeps, stats.accepted), (3, 36)); + assert!(stats.drafted <= 3 * MAX_DRAFT); + + // Every guess wrong: nothing accepted, a sweep per token, and still the same text. + let stats = drafted(&mut script(1), 6); + assert_eq!((stats.sweeps, stats.accepted), (max_new - 1, 0)); + assert!(stats.drafted > 100); + // Some wrong: fewer sweeps than tokens, more than with all right. + let stats = drafted(&mut script(3), 4); + assert!(stats.accepted > 10 && stats.accepted < stats.drafted, "{stats:?}"); + assert!(stats.sweeps > 8 && stats.sweeps < max_new - 1, "{stats:?}"); + assert_eq!(stats.sweeps + stats.accepted, max_new - 1, "each sweep gives one token plus its right guesses"); + + // Guesses from the text itself, and a drafter that does not keep to what it was asked. + let stats = drafted(&mut LookupDrafter::new(3, 1), 4); + assert_eq!(stats.sweeps + stats.accepted, max_new - 1); + drafted(&mut Unruly, 3); +} + +#[test] +fn generation_with_guesses_stops_at_the_end_token_and_at_the_limits() { + let dir = tiny(); + let weights = Weights::open_dir(&dir).unwrap(); + let prompt = &tokens(64)[41..64]; + let mut model = InklingCpu::new(load_config(&dir).unwrap(), &weights, 64).unwrap(); + let plain = model.generate_greedy(prompt, 30, u32::MAX).unwrap(); + // Take the 12th generated token as the end token: both ways must stop on it, included, + // even when it is reached as an accepted guess in the middle of a sweep. + let eos = plain[11]; + let want = model.generate_greedy(prompt, 30, eos).unwrap(); + assert!(want.len() <= 12 && *want.last().unwrap() == eos); + for most in [1, 3, 7] { + let mut all_right = + Scripted { truth: plain.clone(), prompt: prompt.len(), wrong_every: 0, asked: 0, guesses: 0 }; + let (got, _) = model.generate_greedy_drafted(prompt, 30, eos, &mut all_right, most, |_| {}).unwrap(); + assert_eq!(got, want, "most {most}"); + // The model is left in order: it can go straight on to another generation. + assert_eq!(model.generate_greedy(prompt, 30, eos).unwrap(), want); + } + // One new token needs no sweep after the prompt; none gives none. + let (got, stats) = + model.generate_greedy_drafted(prompt, 1, u32::MAX, &mut LookupDrafter::new(3, 1), 4, |_| {}).unwrap(); + assert_eq!((got, stats.sweeps), (plain[..1].to_vec(), 0)); + let (got, _) = model.generate_greedy_drafted(prompt, 0, u32::MAX, &mut NoDraft, 4, |_| {}).unwrap(); + assert!(got.is_empty()); + // The same refusals as without guesses, before anything is computed. + let too_long = model.generate_greedy_drafted(prompt, 42, u32::MAX, &mut NoDraft, 4, |_| {}); + assert!(matches!(too_long, Err(ModelError::Capacity(_)))); + assert!(matches!( + model.generate_greedy_drafted(&[], 4, u32::MAX, &mut NoDraft, 4, |_| {}), + Err(ModelError::Capacity(_)) + )); +} + +#[test] +fn the_real_model_generates_the_same_tokens_with_guesses() { + 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 = cfg.eos; + let mut model = InklingCpu::new(cfg, &weights, 64).unwrap(); + let want = model.generate_greedy(&prompt, 12, eos).unwrap(); + // Half the guesses right, so that both keeping and undoing happen on real weights. + let mut half = Scripted { truth: want.clone(), prompt: prompt.len(), wrong_every: 2, asked: 0, guesses: 0 }; + let (got, stats) = model.generate_greedy_drafted(&prompt, 12, eos, &mut half, 3, |_| {}).unwrap(); + eprintln!("real model with guesses: {stats:?}"); + assert_eq!(got, want); + assert!(stats.accepted > 0 && stats.accepted < stats.drafted); +} diff --git a/docs/learning/23-guessing-ahead.md b/docs/learning/23-guessing-ahead.md new file mode 100644 index 0000000..e2e4da1 --- /dev/null +++ b/docs/learning/23-guessing-ahead.md @@ -0,0 +1,77 @@ +# 23. Guessing ahead + +Note 22 ended with a table: a sweep through the model over four positions costs 58 milliseconds, against 36 +for one. This note is about the first use of that: guess the next few tokens, and let one sweep check them. + +## Checking guesses + +After a token is chosen, suppose something proposes the three tokens that follow. Feed four positions in one +batch: the chosen token, then the three guesses. The scores at the first position are the model's choice for +the token after the chosen one. If that is the first guess, the second position was fed the right text, so +its scores count too, and so on. At the first position whose choice is not the next guess, the model's own +choice is taken, and everything fed after it was fed on a wrong text and is thrown away. + +The text that comes out is the text generation without guesses produces. A right guess is a token for a +fraction of a sweep. A wrong one costs the part of the sweep spent on it. In this step the choice at each +position is the highest score. Nothing in the idea needs that: a guess could as well be compared with a +token drawn from the scores, which is left for the step that draws tokens. + +## Taking tokens back + +Throwing away means the model must be as if the wrong guesses had never been fed. Three things remember +tokens: + +- **The attention histories.** A token only ever looks backwards, so the rows of undone tokens are never in + view, and they are written again when those positions are fed again. On the device there is nothing to + do. The spare rows a windowed history got for batches (note 22) are what keeps the older tokens from + having been overwritten. On the CPU a history is shortened, and when it drops old tokens it now keeps + `window - 1 + 16` of them, which leaves exactly a window after 16 are undone. +- **The short convolutions' memories** of their last three inputs. A batch used to leave only its last + three tokens there. On the device a memory now has a batch more slots than a convolution reads, so the + tokens before an undone one are still there. On the CPU, which is the reference and not in a hurry, a + memory keeps what it was when the last batch started and what the batch fed, and rebuilds itself. +- **The model's own count** of what it has been fed. + +The rule that makes this small: only tokens of the last batch can be undone, never its first, and at most 16 +(15 on the device, where a batch is at most 16 positions and keeps its first). + +## Where guesses come from + +This step has the plainest source there is: the text itself. `LookupDrafter` looks for the most recent +earlier place where the last few tokens appeared and proposes what followed them there. It needs no weights +and costs a scan of the text per sweep, which is nothing next to a sweep at these lengths. It guesses well +where a text repeats itself and proposes nothing where it does not. + +Inkling 2 Mini on the GB10, at most 200 new tokens, up to 4 guesses per sweep after a match of the last 4, +3 or 2 tokens (the longest that matches). Speeds are counted after the first new token; every sweep gives +one token plus its right guesses, so sweeps and right guesses add up to the tokens counted: + +| Prompt | Tokens counted | Without guesses | With | Sweeps | Guessed | Right | +|---|---|---|---|---|---|---| +| A Rust function and three tests | 199 | 23.9 tok/s | 24.6 | 175 | 96 | 24 | +| Three paragraphs of explanation | 199 | 24.0 | 25.3 | 175 | 69 | 24 | +| A sentence repeated five times (the reply ends early) | 168 | 24.2 | 33.0 | 107 | 94 | 61 | + +In every run the tokens were the same with and without guesses. On ordinary text the gain is a few percent: +a quarter to a third of the guesses are right, and the wrong ones nearly use up what the right ones save. On text that +repeats, two thirds are right and generation is a third faster. + +So the mechanism works and its cost is as the table of note 22 predicted, and the lookup is too weak a +guesser for ordinary text. The model's checkpoint includes a small network trained to make such guesses +(`mtp.safetensors`), which this engine does not load yet. It would plug into the same place: something that +implements `Drafter`. + +## How it was checked + +- CPU, tiny model: 100 tokens fed in sweeps of true tokens followed by wrong ones that are then undone, + past the point where local histories drop old tokens; every true position's scores are bit for bit those + of the true tokens fed alone. +- Generation with guesses that are all right, all wrong, a third wrong, looked up, and from a drafter that + returns more than asked and tokens that do not exist: the tokens are those of plain generation each + time, and the numbers of sweeps and accepted guesses are what they must be. +- Device: the same undo test against the CPU model at the bar of the recordings; a convolution with spare + slots against the CPU with wrong tokens fed and dropped; generation with guesses gives the tokens of + generation without. +- Planted bugs: a wrong guess kept; guesses not undone; a convolution memory not restored; a history + without its spare tokens; values not shortened; the whole batch undone; device memories without spare + slots; a token stored in the slot of a short ring. diff --git a/tools/mutants/100-batch-conv-ignores-batch.patch b/tools/mutants/100-batch-conv-ignores-batch.patch index 3ecf507..48c4fa5 100644 --- a/tools/mutants/100-batch-conv-ignores-batch.patch +++ b/tools/mutants/100-batch-conv-ignores-batch.patch @@ -2,14 +2,14 @@ # needs: gpu # Bug: a convolution over a batch takes every earlier token from the ring, which does not hold the batch's own tokens yet. diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu -index 10196bd..dc419e3 100644 +index ac774e9..a43ffce 100644 --- a/crates/dluth-cuda/kernels/attention.cu +++ b/crates/dluth-cuda/kernels/attention.cu -@@ -81,7 +81,6 @@ extern "C" __global__ void head_rmsnorm_plain(const float* x, float* out, unsign +@@ -82,7 +82,6 @@ extern "C" __global__ void head_rmsnorm_plain(const float* x, float* out, unsign __device__ __forceinline__ float earlier_token(const float* current, const float* ring, unsigned int channels, - unsigned int n, unsigned long long pos, unsigned int b, + unsigned int slots, unsigned long long pos, unsigned int b, unsigned int lag, unsigned int c) { - if (b >= lag) return current[(size_t)(b - lag) * channels + c]; unsigned long long at = pos + b; - return at >= lag ? ring[((at - lag) % (n - 1)) * channels + c] : 0.0f; + return at >= lag ? ring[((at - lag) % slots) * channels + c] : 0.0f; } diff --git a/tools/mutants/101-batch-ring-keeps-first-tokens.patch b/tools/mutants/101-batch-ring-keeps-first-tokens.patch index 446a3e7..8b32ee0 100644 --- a/tools/mutants/101-batch-ring-keeps-first-tokens.patch +++ b/tools/mutants/101-batch-ring-keeps-first-tokens.patch @@ -1,16 +1,16 @@ # test: cargo test --release -p dluth-cuda --test attention both_short_convolutions # needs: gpu -# Bug: after a batch, the ring is given the batch's first tokens, not its last. +# Bug: after a batch, a ring with fewer slots than the batch has tokens is given the batch's first tokens, not its last. diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu -index 10196bd..15ef7d0 100644 +index ac774e9..41543ac 100644 --- a/crates/dluth-cuda/kernels/attention.cu +++ b/crates/dluth-cuda/kernels/attention.cu -@@ -139,7 +139,7 @@ extern "C" __global__ void ring_store(const float* current, float* ring, unsigne +@@ -143,7 +143,7 @@ extern "C" __global__ void ring_store(const float* current, float* ring, unsigne unsigned int b = (unsigned int)(index / channels); unsigned int c = (unsigned int)(index % channels); - if (b >= batch || n < 2) return; -- if (batch - b > n - 1) return; -+ if (b >= n - 1) return; - ring[((pos + b) % (n - 1)) * channels + c] = current[index]; + if (b >= batch || slots == 0) return; +- if (batch - b > slots) return; ++ if (b >= slots) return; + ring[((pos + b) % slots) * channels + c] = current[index]; } diff --git a/tools/mutants/111-draft-wrong-guess-kept.patch b/tools/mutants/111-draft-wrong-guess-kept.patch new file mode 100644 index 0000000..181144c --- /dev/null +++ b/tools/mutants/111-draft-wrong-guess-kept.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-model --test inkling_draft generation_with_guesses_gives +# Bug: a wrong guess is kept, and the tokens after it are read from a sweep that followed the wrong text. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index 665ee07..169fa36 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -1245,7 +1245,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + generated.push(next); + text.push(next); + on_token(next); +- if next == eos || generated.len() == max_new || batch.get(i + 1) != Some(&next) { ++ if next == eos || generated.len() == max_new || i + 1 == batch.len() { + break; + } + } diff --git a/tools/mutants/112-draft-not-undone.patch b/tools/mutants/112-draft-not-undone.patch new file mode 100644 index 0000000..461e666 --- /dev/null +++ b/tools/mutants/112-draft-not-undone.patch @@ -0,0 +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 86093f8..5a47e62 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -1256,7 +1256,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + return Err(ModelError::Device("a sweep returned no scores".into())); + } + stats.accepted += kept - 1; +- self.undo(batch.len() - kept)?; ++ self.undo(0)?; + pos += kept; + } + Ok((generated, stats)) diff --git a/tools/mutants/113-undo-conv-memory-kept.patch b/tools/mutants/113-undo-conv-memory-kept.patch new file mode 100644 index 0000000..ff04280 --- /dev/null +++ b/tools/mutants/113-undo-conv-memory-kept.patch @@ -0,0 +1,14 @@ +# test: cargo test -p dluth-model --test inkling_draft undone_tokens +# Bug: undoing leaves the undone tokens in the convolutions' memories. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index 665ee07..8c7f42d 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -719,7 +719,6 @@ impl ConvMemory { + fn undo(&mut self, undone: usize) { + let kept = (self.fed_tokens() - undone) * self.width; + self.fed.truncate(kept); +- self.recent.copy_from_slice(&self.before); + for token in self.fed.chunks_exact(self.width) { + remember(&mut self.recent, token); + } diff --git a/tools/mutants/114-undo-history-without-spare.patch b/tools/mutants/114-undo-history-without-spare.patch new file mode 100644 index 0000000..0f0a3fe --- /dev/null +++ b/tools/mutants/114-undo-history-without-spare.patch @@ -0,0 +1,15 @@ +# test: cargo test -p dluth-model --test inkling_draft undone_tokens +# Bug: a windowed history that drops old tokens keeps none for what is left after an undo. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index 665ee07..469554a 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -650,7 +650,7 @@ impl History { + // Full: keep the newest `window - 1` tokens, which with the one being added + // is everything a local layer can see, and `MAX_UNDO` more: if the newest + // tokens are undone, what is left must still see its whole window. +- let keep = (window.saturating_sub(1) + MAX_UNDO).min(self.len); ++ let keep = window.saturating_sub(1).min(self.len); + self.data.copy_within((self.len - keep) * self.width..self.len * self.width, 0); + self.len = keep; + } diff --git a/tools/mutants/115-undo-values-not-shortened.patch b/tools/mutants/115-undo-values-not-shortened.patch new file mode 100644 index 0000000..ae4d09c --- /dev/null +++ b/tools/mutants/115-undo-values-not-shortened.patch @@ -0,0 +1,14 @@ +# test: cargo test -p dluth-model --test inkling_draft undone_tokens +# Bug: undoing shortens the history of keys and not that of values. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index 665ee07..2871721 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -447,7 +447,6 @@ impl Ops for CpuOps<'_> { + // A history only grows at its end, and keeps enough older tokens for what is left + // to see its whole window (see `History::push`). + pass.keys.len -= undone; +- pass.values.len -= undone; + for memory in [&mut pass.k_recent, &mut pass.v_recent, &mut pass.attn_recent, &mut pass.expert_recent] { + memory.undo(undone); + } diff --git a/tools/mutants/116-undo-whole-batch-allowed.patch b/tools/mutants/116-undo-whole-batch-allowed.patch new file mode 100644 index 0000000..2e8c446 --- /dev/null +++ b/tools/mutants/116-undo-whole-batch-allowed.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::undone_tokens +# needs: gpu +# Bug: the whole last batch can be undone, its first token too. +diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs +index 665ee07..c0e384e 100644 +--- a/crates/dluth-model/src/inkling/model.rs ++++ b/crates/dluth-model/src/inkling/model.rs +@@ -1098,7 +1098,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + if undone == 0 { + return Ok(()); + } +- if undone >= self.kept || undone > MAX_UNDO { ++ if undone > self.kept || undone > MAX_UNDO { + return Err(ModelError::Capacity(format!( + "{undone} tokens cannot be undone: the last batch has {} left and keeps its first, and at most {MAX_UNDO} can be undone", + self.kept diff --git a/tools/mutants/117-undo-ring-without-spare.patch b/tools/mutants/117-undo-ring-without-spare.patch new file mode 100644 index 0000000..c829d08 --- /dev/null +++ b/tools/mutants/117-undo-ring-without-spare.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test inkling_golden_cuda on_the_device::undone_tokens +# needs: gpu +# Bug: the device's convolution memories have no spare slots, so undone tokens have overwritten the tokens before them. +diff --git a/crates/dluth-cuda/src/ops.rs b/crates/dluth-cuda/src/ops.rs +index 59af758..91864f5 100644 +--- a/crates/dluth-cuda/src/ops.rs ++++ b/crates/dluth-cuda/src/ops.rs +@@ -45,7 +45,7 @@ fn ring_slots(taps: usize) -> usize { + if taps < 2 { + 0 + } else { +- taps - 1 + MAX_BATCH ++ taps - 1 + } + } + diff --git a/tools/mutants/118-undo-ring-slot-of-short-ring.patch b/tools/mutants/118-undo-ring-slot-of-short-ring.patch new file mode 100644 index 0000000..7927ab9 --- /dev/null +++ b/tools/mutants/118-undo-ring-slot-of-short-ring.patch @@ -0,0 +1,16 @@ +# test: cargo test --release -p dluth-cuda --test attention spare_slots +# needs: gpu +# Bug: a single token is stored in the slot a ring without spare slots would use. +diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu +index ac774e9..d80c3e4 100644 +--- a/crates/dluth-cuda/kernels/attention.cu ++++ b/crates/dluth-cuda/kernels/attention.cu +@@ -109,7 +109,7 @@ extern "C" __global__ void sconv_fixed(const float* current, float* ring, const + for (unsigned int j = 0; j + 1 < n; ++j) + sum += w[j] * earlier_token(current, ring, channels, slots, pos, b, n - 1 - j, c); + out[index] = (sum + x) * norm; +- if (batch == 1 && n > 1) ring[(pos % slots) * channels + c] = x; ++ if (batch == 1 && n > 1) ring[(pos % (n - 1)) * channels + c] = x; + } + + // Short convolution whose taps are a fixed part per channel plus a part computed for each diff --git a/tools/mutants/78-conv-ring-before-start.patch b/tools/mutants/78-conv-ring-before-start.patch index dc20aac..fa0a679 100644 --- a/tools/mutants/78-conv-ring-before-start.patch +++ b/tools/mutants/78-conv-ring-before-start.patch @@ -2,15 +2,15 @@ # needs: gpu # Bug: a convolution reads its ring for tokens before the start of the sequence. diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu -index 10196bd..203030d 100644 +index ac774e9..47b21c0 100644 --- a/crates/dluth-cuda/kernels/attention.cu +++ b/crates/dluth-cuda/kernels/attention.cu -@@ -83,7 +83,7 @@ __device__ __forceinline__ float earlier_token(const float* current, const float +@@ -84,7 +84,7 @@ __device__ __forceinline__ float earlier_token(const float* current, const float unsigned int lag, unsigned int c) { if (b >= lag) return current[(size_t)(b - lag) * channels + c]; unsigned long long at = pos + b; -- return at >= lag ? ring[((at - lag) % (n - 1)) * channels + c] : 0.0f; -+ return ring[((at + (unsigned long long)(n - 1) * lag - lag) % (n - 1)) * channels + c]; +- return at >= lag ? ring[((at - lag) % slots) * channels + c] : 0.0f; ++ return ring[((at + (unsigned long long)slots * lag - lag) % slots) * channels + c]; } // Short convolution with fixed taps, for a batch of `batch` consecutive tokens of diff --git a/tools/mutants/79-conv-token-taps-ignored.patch b/tools/mutants/79-conv-token-taps-ignored.patch index be41646..391a08f 100644 --- a/tools/mutants/79-conv-token-taps-ignored.patch +++ b/tools/mutants/79-conv-token-taps-ignored.patch @@ -2,15 +2,15 @@ # needs: gpu # Bug: the dynamic convolution leaves out the taps computed for the token at earlier tokens. diff --git a/crates/dluth-cuda/kernels/attention.cu b/crates/dluth-cuda/kernels/attention.cu -index 10196bd..07920ae 100644 +index ac774e9..698f069 100644 --- a/crates/dluth-cuda/kernels/attention.cu +++ b/crates/dluth-cuda/kernels/attention.cu -@@ -124,7 +124,7 @@ extern "C" __global__ void sconv_dynamic(const float* current, float* ring, cons +@@ -128,7 +128,7 @@ extern "C" __global__ void sconv_dynamic(const float* current, float* ring, cons const float* head_taps = token_taps + ((size_t)b * heads + c / (channels / heads)) * n; float sum = (fixed_taps[c] + head_taps[0]) * x; for (unsigned int lag = 1; lag < n; ++lag) - sum += (fixed_taps[(size_t)lag * channels + c] + head_taps[lag]) + sum += fixed_taps[(size_t)lag * channels + c] - * earlier_token(current, ring, channels, n, pos, b, lag, c); + * earlier_token(current, ring, channels, slots, pos, b, lag, c); out[index] = (sum + x) * norm; - if (batch == 1 && n > 1) ring[(pos % (n - 1)) * channels + c] = x; + if (batch == 1 && n > 1) ring[(pos % slots) * channels + c] = x; diff --git a/tools/mutants/95-batch-scores-of-first.patch b/tools/mutants/95-batch-scores-of-first.patch index bb2a722..2d1a463 100644 --- a/tools/mutants/95-batch-scores-of-first.patch +++ b/tools/mutants/95-batch-scores-of-first.patch @@ -1,14 +1,14 @@ # test: cargo test -p dluth-model --test inkling_batch feeding_without_scoring # Bug: asked for the scores after the last token of a batch, the model scores its first. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 149e860..dfca664 100644 +index 665ee07..5739596 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -940,7 +940,7 @@ impl<'w, O: Ops> Inkling<'w, O> { - // will read would cost a sweep of it each. +@@ -1041,7 +1041,7 @@ impl<'w, O: Ops> Inkling<'w, O> { + // batch's last unless tokens were undone. let mut rows = Vec::with_capacity(blocks.len() + 1); for v in blocks.iter().chain(std::iter::once(last)) { -- rows.push(ops.row(v, count - 1)?); +- rows.push(ops.row(v, self.kept - 1)?); + rows.push(ops.row(v, 0)?); } picked = rows; diff --git a/tools/mutants/96-batch-counts-one-token.patch b/tools/mutants/96-batch-counts-one-token.patch index 3eff103..734eeae 100644 --- a/tools/mutants/96-batch-counts-one-token.patch +++ b/tools/mutants/96-batch-counts-one-token.patch @@ -1,15 +1,15 @@ # test: cargo test -p dluth-model --test inkling_batch any_split # Bug: after a batch the model believes only one token was fed. diff --git a/crates/dluth-model/src/inkling/model.rs b/crates/dluth-model/src/inkling/model.rs -index 149e860..003b686 100644 +index 665ee07..bfcdbe7 100644 --- a/crates/dluth-model/src/inkling/model.rs +++ b/crates/dluth-model/src/inkling/model.rs -@@ -922,7 +922,7 @@ impl<'w, O: Ops> Inkling<'w, O> { +@@ -1015,7 +1015,7 @@ impl<'w, O: Ops> Inkling<'w, O> { } self.last = Some((x, blocks)); - self.cached = pos + tokens.len(); + self.cached = pos + 1; + self.kept = tokens.len(); Ok(()) } -