Skip to main content

frink_models/
draft_model.rs

1//! A second, smaller GGUF used as the drafter for speculative decoding.
2//!
3//! [`crate::speculative`] already had the half that is hard to get
4//! right: the rejection rule, which makes speculation lossless at every
5//! temperature rather than only at `--temp 0`. What it did not have was
6//! a drafter worth running. The only implementation in the tree is
7//! [`crate::speculative::PromptLookupSpeculator`], an n-gram match over
8//! the history with no model at all. It is free, and it helps on
9//! repetitive text, and it cannot carry a coding workload.
10//!
11//! # Why this is the item that moves the ceiling
12//!
13//! Decode reads every weight in the model to emit one token, so
14//!
15//! ```text
16//! tokens/sec <= memory bandwidth / model bytes
17//! ```
18//!
19//! is arithmetic, not engineering. A 17 GB checkpoint on a 960 GB/s
20//! card cannot pass about 56 tok/s however good the kernels are. Better
21//! kernels move an engine toward that number; they cannot move it past.
22//!
23//! A draft model changes what is read per token instead of how fast it
24//! is read. A 2 GB drafter proposes `k` tokens, the target checks all
25//! `k` in ONE pass over its 17 GB, good guesses are kept and bad ones
26//! discarded, and the text is exactly what the target would have
27//! written alone.
28//!
29//! # The two things this has to get right
30//!
31//! **The draft KV must roll back.** While proposing, the drafter
32//! advances its own cache over tokens the target has not accepted and
33//! may never accept. If those rows are left in place, the drafter's
34//! context silently diverges from the target's. Nothing errors: the
35//! accept rate just decays, which reads as "this drafter is bad" rather
36//! than "this drafter is desynchronised". [`DraftModelSpeculator`]
37//! therefore truncates to `synced` at the top of every `propose`, and
38//! `synced` only ever counts tokens the caller's history actually
39//! contains.
40//!
41//! This is the repo's dominant bug shape in its usual dress: two
42//! structures that must agree about one thing, here the target's
43//! history and the drafter's cache, with nothing enforcing it. What
44//! enforces it is that `synced` is derived from the history passed in
45//! on every call rather than remembered independently, so the drafter
46//! cannot hold an opinion about the history that the history disagrees
47//! with.
48//!
49//! **The vocabularies must match.** See [`VocabMismatch`].
50
51use crate::config::ModelConfig;
52use crate::decoder::Decoder;
53use crate::penalty_window::PenaltyWindow;
54use crate::sampling::{sampling_distribution, Sampler, SamplingParams};
55use crate::speculative::{DraftBlock, DraftDist, Drafter};
56use frink_core::cache::KvCache;
57
58/// The draft and target checkpoints do not agree about token ids.
59///
60/// This is the failure that costs a day, because it does not look like
61/// a failure. The rejection rule compares the drafter's `q(x)` with the
62/// target's `p(x)` at the same index `x`. If the two checkpoints number
63/// their vocabularies differently, those are probabilities of different
64/// tokens, the rule is comparing unrelated numbers, and the output is
65/// no longer the target's distribution. What comes out is fluent text,
66/// with no error and a plausible-looking accept rate.
67///
68/// So it is refused at construction, which per this repo's rule is
69/// coverage rather than a defect: a partly-implemented thing must stop
70/// and say what is missing instead of computing something else.
71///
72/// Vocabulary size is checked first because it is cheap and catches
73/// most real mismatches (a 32000-token Llama drafter against a
74/// 152064-token Qwen target). Equal sizes do not imply equal
75/// vocabularies, though, so the caller that has both tokenizers should
76/// also compare them; `vocab_size` is what a `Decoder` alone can see.
77#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
78pub enum VocabMismatch {
79    #[error(
80        "draft and target checkpoints disagree about vocabulary size ({draft} vs {target}), so a \
81         draft token id does not name the same token in both. Speculative decoding compares the \
82         drafter's probability for a token id against the target's probability for that same id, \
83         which would be comparing unrelated tokens: the result would not be the target's \
84         distribution, and it would look exactly like text that is. Use a draft model from the \
85         same family and tokenizer as the target"
86    )]
87    Size { draft: usize, target: usize },
88}
89
90/// A [`Drafter`] backed by a second [`Decoder`].
91///
92/// Owns its own KV caches, entirely separate from the target's. The two
93/// models run over the same token sequence but have different layer
94/// counts, head counts and head dimensions, so nothing about the two
95/// caches is shared.
96pub struct DraftModelSpeculator {
97    decoder: Decoder,
98    kv_caches: Vec<KvCache>,
99    /// How many tokens of the caller's history this drafter's KV holds.
100    ///
101    /// Never an independent record of "what I have seen": it is
102    /// recomputed against the history handed to `propose`, so a
103    /// rejected block cannot leave it overstating what is committed.
104    synced: usize,
105    sampling: SamplingParams,
106    rng: Sampler,
107    /// Positions whose draft probability fell below this stop the
108    /// block. A drafter that is guessing is worse than no drafter: the
109    /// target pays for the position either way, and a rejection also
110    /// throws away every position after it.
111    min_prob: f32,
112    max_draft: usize,
113}
114
115impl DraftModelSpeculator {
116    /// True when this drafter's KV really lives in the host caches it
117    /// owns.
118    ///
119    /// A backend that keeps KV on the device leaves these at zero, and
120    /// a drafter cannot roll back rows it cannot see. Callers check
121    /// this after one warm-up rather than discovering it as a wrong
122    /// accept rate.
123    pub fn keeps_host_kv(&self) -> bool {
124        // ROWS: the question is whether K/V actually landed in the
125        // host buffer, which a device-resident backend leaves empty.
126        self.kv_caches.first().is_some_and(|c| c.rows() > 0)
127    }
128
129    /// How many tokens of history this drafter's KV currently holds.
130    /// Exposed so a caller can assert the drafter kept up.
131    pub fn synced_len(&self) -> usize {
132        self.synced
133    }
134
135    /// Fails when the two checkpoints cannot be compared token for
136    /// token. See [`VocabMismatch`].
137    /// `decoder` is taken by value and has its KV-window policy turned
138    /// OFF (#61). [`Self::sync`] rolls the draft cache back to an
139    /// arbitrary committed length -- potentially the whole history,
140    /// after a long run of rejections -- and a windowed cache cannot
141    /// represent a rollback past the rows it kept. The drafter is a
142    /// small model whose KV is a small fraction of the target's, so
143    /// this gives up almost none of the saving.
144    pub fn new(
145        mut decoder: Decoder,
146        target_config: &ModelConfig,
147        sampling: SamplingParams,
148        seed: u64,
149        max_draft: usize,
150        min_prob: f32,
151    ) -> Result<Self, VocabMismatch> {
152        decoder.kv_window = crate::decoder::KvWindowPolicy::off();
153        let draft_vocab = decoder.config.vocab_size;
154        let target_vocab = target_config.vocab_size;
155        if draft_vocab != target_vocab {
156            return Err(VocabMismatch::Size {
157                draft: draft_vocab,
158                target: target_vocab,
159            });
160        }
161        let kv_caches = decoder.config.new_kv_caches();
162        Ok(DraftModelSpeculator {
163            decoder,
164            kv_caches,
165            synced: 0,
166            sampling,
167            rng: Sampler::new(seed),
168            min_prob,
169            max_draft,
170        })
171    }
172
173    /// Drops every cached row past `len`, on every layer.
174    fn truncate_to(&mut self, len: usize) {
175        for cache in &mut self.kv_caches {
176            cache.truncate(len);
177        }
178    }
179
180    /// Brings the draft cache up to `history` and returns the logits
181    /// that follow its last token.
182    ///
183    /// Feeds only the tokens the cache does not already hold, which is
184    /// what makes drafting cheap across a long conversation: the first
185    /// call pays for the prompt and every later call pays for the
186    /// handful of tokens the target committed since.
187    ///
188    /// The cache is rolled back to at most `history.len() - 1` rather
189    /// than `history.len()`, and that off-by-one is load-bearing. The
190    /// logits a block is drafted from are the ones that follow the last
191    /// committed token, and they exist only as the return value of the
192    /// forward pass that consumed it. Truncating to the full history
193    /// would leave nothing to feed, so there would be no logits to
194    /// draft from and every call after a rollback would propose
195    /// nothing: speculation would quietly stop happening while
196    /// remaining perfectly correct, which is the kind of failure that
197    /// shows up as a benchmark result months later.
198    ///
199    /// The cost is re-feeding exactly one token per call. That is one
200    /// step of the small model, against a block of them saved.
201    fn sync(&mut self, history: &[usize]) -> Vec<f32> {
202        debug_assert!(
203            !history.is_empty(),
204            "callers return early on an empty history"
205        );
206        // Everything past what the caller's history contains was
207        // drafted and not accepted. It is not context, it is a guess
208        // the target threw away.
209        // Derived from the CACHE, not only from `self.synced`. The
210        // cache is the authority on how many rows exist, and a backend
211        // that keeps its KV somewhere other than this host `KvCache`
212        // leaves it at zero however many tokens were fed. Trusting the
213        // counter there truncated to 7 rows of a cache holding 0 and
214        // panicked on a real Metal run. That is the same lesson as the
215        // batched prefill: read the cursor, do not keep a copy of it.
216        // ROWS, for the same reason: this bounds what can be kept by
217        // what is really there, not by what the counter believes.
218        let held = self.kv_caches.first().map_or(0, |c| c.rows());
219        let keep = self.synced.min(history.len() - 1).min(held);
220        self.truncate_to(keep);
221        self.synced = keep;
222
223        let mut logits = Vec::new();
224        while self.synced < history.len() {
225            let pos = self.synced;
226            logits = self
227                .decoder
228                .forward_token(history[pos], pos, &mut self.kv_caches);
229            self.synced += 1;
230        }
231        logits
232    }
233}
234
235impl Drafter for DraftModelSpeculator {
236    fn propose(&mut self, history: &[usize], _target_hidden: &[f32], max_len: usize) -> DraftBlock {
237        let budget = max_len.min(self.max_draft);
238        if budget == 0 || history.is_empty() {
239            return DraftBlock::empty();
240        }
241
242        let mut logits = self.sync(history);
243
244        let mut tokens = Vec::with_capacity(budget);
245        let mut dists = Vec::with_capacity(budget);
246
247        for _ in 0..budget {
248            // `history` is everything the target has committed --
249            // prompt included -- and `tokens` is what this block has
250            // proposed on top of it, so the drafter's penalties see the
251            // same sequence the target's would. The block used to clone
252            // `history` per call to concatenate the two; the window
253            // borrows both halves instead.
254            // The XTC roll comes off THIS drafter's own stream, so the
255            // distribution reported as `q` below is the one the token
256            // was actually drawn from even when XTC is configured.
257            let xtc_roll = self.rng.xtc_roll(&self.sampling);
258            let probs = sampling_distribution(
259                &logits,
260                &self.sampling,
261                PenaltyWindow::new(history, &tokens),
262                xtc_roll,
263            );
264            let token = self.rng.sample_from(&probs);
265
266            // `q` MUST be the distribution this token was actually
267            // sampled from, truncation and all, or the rejection rule
268            // is corrected against a lie. `sampling_distribution`
269            // returns exactly that, so it is what gets reported.
270            let dist = DraftDist::from_dense(&probs);
271            let q = dist.prob(token);
272            if q < self.min_prob {
273                // Stop before committing this token, so the cache is
274                // not advanced over a position nobody drafted.
275                break;
276            }
277
278            tokens.push(token);
279            dists.push(dist);
280
281            let pos = self.synced;
282            logits = self.decoder.forward_token(token, pos, &mut self.kv_caches);
283            self.synced += 1;
284        }
285
286        DraftBlock::new(tokens, dists)
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293    use crate::config::test_dense_fixture;
294
295    fn drafter(vocab: usize, max_draft: usize, min_prob: f32) -> DraftModelSpeculator {
296        let target = {
297            let mut c = test_dense_fixture();
298            c.vocab_size = vocab;
299            c
300        };
301        let decoder = Decoder::new_random_small(test_dense_fixture(), 2, vocab);
302        DraftModelSpeculator::new(
303            decoder,
304            &target,
305            SamplingParams::default(),
306            7,
307            max_draft,
308            min_prob,
309        )
310        .expect("matching vocabularies")
311    }
312
313    /// A draft model whose vocabulary differs from the target's is
314    /// refused at construction, not accepted and corrected later.
315    ///
316    /// There is nothing to correct. The rejection rule compares the
317    /// drafter's probability for token id `x` against the target's
318    /// probability for token id `x`; if the two checkpoints number
319    /// their vocabularies differently those are different tokens, and
320    /// the output is no longer the target's distribution while looking
321    /// exactly like text that is. Fluent, plausible accept rate, no
322    /// error. That is the one failure this engine refuses to serve.
323    #[test]
324    fn a_draft_model_with_a_different_vocabulary_is_refused_by_name() {
325        let mut target = test_dense_fixture();
326        target.vocab_size = 64;
327        let decoder = Decoder::new_random_small(test_dense_fixture(), 2, 32);
328
329        let err = DraftModelSpeculator::new(decoder, &target, SamplingParams::default(), 0, 4, 0.0)
330            .err()
331            .expect("32 != 64");
332
333        assert_eq!(
334            err,
335            VocabMismatch::Size {
336                draft: 32,
337                target: 64
338            }
339        );
340        let msg = err.to_string();
341        // The message has to say both numbers and why it matters, or
342        // the next person reads it as an arbitrary compatibility rule
343        // and looks for a flag to turn it off.
344        assert!(msg.contains("32") && msg.contains("64"), "{msg}");
345        assert!(msg.contains("same family and tokenizer"), "{msg}");
346    }
347
348    /// The drafter proposes a block and reports one distribution per
349    /// token, which is what the rejection rule needs to run at all.
350    #[test]
351    fn a_block_carries_one_honest_distribution_per_drafted_token() {
352        let mut d = drafter(32, 4, 0.0);
353        let block = d.propose(&[1, 2, 3], &[], 4);
354
355        assert_eq!(block.len(), 4, "the whole budget was drafted");
356        assert_eq!(block.tokens().len(), block.dists().len());
357        for (token, dist) in block.tokens().iter().zip(block.dists()) {
358            // `q(x)` for the token actually sampled must be nonzero:
359            // the rule divides by it.
360            assert!(
361                dist.prob(*token) > 0.0,
362                "a drafter must report the distribution it sampled from"
363            );
364        }
365    }
366
367    /// **The rollback.** After a block is proposed, the drafter's cache
368    /// holds rows for tokens the target has not accepted. The next call
369    /// arrives with a history that does not contain them, and those
370    /// rows must be gone before anything else is fed.
371    ///
372    /// Left in place, the drafter's context silently diverges from the
373    /// target's: every later proposal is conditioned on tokens that
374    /// were thrown away. Nothing errors. The accept rate decays, which
375    /// reads as "this drafter is bad" rather than "this drafter is
376    /// desynchronised", and that is why this is asserted on the cache
377    /// length rather than on output quality.
378    #[test]
379    fn the_draft_cache_rolls_back_the_positions_the_target_did_not_accept() {
380        let mut d = drafter(32, 4, 0.0);
381
382        let block = d.propose(&[1, 2, 3], &[], 4);
383        assert_eq!(block.len(), 4);
384        assert_eq!(
385            d.synced, 7,
386            "3 of history plus 4 drafted are in the cache after proposing"
387        );
388
389        // The target accepted exactly one of them, so the caller's
390        // history grew by one, not by four.
391        d.propose(&[1, 2, 3, block.tokens()[0]], &[], 4);
392
393        assert_eq!(
394            d.kv_caches[0].positions(),
395            d.synced,
396            "every layer's cache agrees with the drafter's own count"
397        );
398        assert_eq!(
399            d.synced, 8,
400            "4 committed tokens plus 4 freshly drafted, NOT 7 stale rows plus more"
401        );
402    }
403
404    /// A history shorter than what the cache holds is a rollback too,
405    /// and the arithmetic must not underflow into a huge truncate.
406    #[test]
407    fn a_history_shorter_than_the_cache_truncates_rather_than_underflowing() {
408        let mut d = drafter(32, 4, 0.0);
409        d.propose(&[1, 2, 3, 4, 5], &[], 4);
410        assert_eq!(d.synced, 9);
411
412        d.propose(&[1, 2], &[], 1);
413        assert_eq!(d.synced, 3, "2 of history plus 1 drafted");
414        assert_eq!(d.kv_caches[0].positions(), 3);
415    }
416
417    /// Drafting stops when the drafter's own probability for the token
418    /// it just sampled falls below the floor.
419    ///
420    /// A guessing drafter is worse than none: the target pays for the
421    /// position either way, and a rejection also discards every
422    /// position after it. With the floor above 1.0 nothing can clear
423    /// it, so the block is empty and the caller falls back to one
424    /// ordinary decode step.
425    #[test]
426    fn a_drafter_below_the_probability_floor_proposes_nothing() {
427        let mut d = drafter(32, 4, 1.01);
428        let block = d.propose(&[1, 2, 3], &[], 4);
429        assert!(block.is_empty(), "nothing clears a floor above 1.0");
430        assert_eq!(
431            d.synced, 3,
432            "and the cache holds the history only, no abandoned draft rows"
433        );
434    }
435
436    /// `max_draft` is a ceiling the caller's budget cannot raise.
437    #[test]
438    fn the_configured_maximum_bounds_the_callers_budget() {
439        let mut d = drafter(32, 2, 0.0);
440        assert_eq!(d.propose(&[1, 2, 3], &[], 8).len(), 2);
441    }
442
443    /// An empty history has nothing to condition on, and a zero budget
444    /// asked for nothing. Both propose nothing rather than panicking.
445    #[test]
446    fn an_empty_history_or_a_zero_budget_proposes_nothing() {
447        let mut d = drafter(32, 4, 0.0);
448        assert!(d.propose(&[], &[], 4).is_empty());
449        assert!(d.propose(&[1, 2], &[], 0).is_empty());
450    }
451
452    /// **The property the whole feature exists to preserve.**
453    ///
454    /// A draft model is only worth having if the text is exactly what
455    /// the target would have written alone. At temperature 0 that is
456    /// checkable exactly: token for token against a plain
457    /// `forward_token` loop over an identically seeded target.
458    ///
459    /// This is the test that catches a desynchronised draft cache, a
460    /// dishonest `q`, or an off-by-one in the block, because all three
461    /// change the output rather than announcing themselves. A drafter
462    /// is allowed to be bad; it is not allowed to be consulted in a way
463    /// that changes the answer.
464    ///
465    /// The drafter here is a genuinely different model from the target
466    /// (a different random seed, half the layers), so it is wrong
467    /// often, which is exactly the case where rejection and rollback
468    /// have to work.
469    #[test]
470    fn a_draft_model_does_not_change_what_the_target_writes() {
471        use crate::speculative::speculative_decode;
472
473        let cfg = test_dense_fixture();
474        let vocab = 32;
475        let prompt = vec![1usize, 2, 3, 4, 1, 2];
476        let max_new = 8;
477
478        let target = Decoder::new_random_small(cfg.clone(), 4, vocab);
479        let mut caches: Vec<KvCache> = target.config.new_kv_caches();
480
481        // A different model, not a copy of the target: two layers
482        // rather than four, so it disagrees constantly.
483        let draft = Decoder::new_random_small(cfg.clone(), 2, vocab);
484        let mut drafter =
485            DraftModelSpeculator::new(draft, &target.config, SamplingParams::default(), 11, 4, 0.0)
486                .expect("matching vocabularies");
487
488        let result = speculative_decode(&target, &prompt, max_new, &mut caches, &mut drafter);
489
490        // The same target, decoded the ordinary way.
491        let plain = Decoder::new_random_small(cfg, 4, vocab);
492        let mut plain_caches: Vec<KvCache> = plain.config.new_kv_caches();
493        let mut pending = plain
494            .forward_batch(&prompt, 0, &mut plain_caches)
495            .pop()
496            .expect("a non-empty prompt returns logits");
497        let mut greedy = Vec::with_capacity(max_new);
498        for pos in (prompt.len()..).take(max_new) {
499            let tok = pending
500                .iter()
501                .enumerate()
502                .max_by(|a, b| a.1.partial_cmp(b.1).expect("logits are finite"))
503                .map(|(i, _)| i)
504                .expect("a non-empty vocabulary");
505            greedy.push(tok);
506            pending = plain.forward_token(tok, pos, &mut plain_caches);
507        }
508
509        assert_eq!(
510            result.generated_tokens, greedy,
511            "a draft model may make decoding faster and may not make it different"
512        );
513    }
514
515    /// **`q` must be the distribution the token was really sampled
516    /// from**, at every temperature.
517    ///
518    /// The rejection rule accepts with probability `min(1, p(x)/q(x))`
519    /// and resamples from `max(0, p - q)`. A drafter that overstates
520    /// its own confidence, reporting a point mass for a token it
521    /// actually drew from a spread distribution, makes `p/q` too small:
522    /// tokens get rejected that should have been accepted, and the
523    /// residual it resamples from is not the right residual. The output
524    /// stops being the target's distribution.
525    ///
526    /// This cannot be caught at temperature 0, where the true
527    /// distribution IS a point mass and a dishonest report is
528    /// accidentally correct. That is exactly why this test sets a
529    /// temperature: a suite that only checks greedy decoding will pass
530    /// a drafter that lies.
531    #[test]
532    fn the_reported_distribution_is_the_one_sampled_from_at_temperature() {
533        let target = {
534            let mut c = test_dense_fixture();
535            c.vocab_size = 32;
536            c
537        };
538        let decoder = Decoder::new_random_small(test_dense_fixture(), 2, 32);
539        let sampling = SamplingParams {
540            temperature: 1.0,
541            ..SamplingParams::default()
542        };
543        let mut d = DraftModelSpeculator::new(decoder, &target, sampling.clone(), 3, 4, 0.0)
544            .expect("matching vocabularies");
545
546        let block = d.propose(&[1, 2, 3], &[], 4);
547        assert_eq!(block.len(), 4);
548
549        let spread = block.dists().iter().any(|dist| dist.support().len() > 1);
550        assert!(
551            spread,
552            "at temperature 1.0 a real model's draft distribution is not a point mass;              if it were, this test could not tell an honest report from a lie"
553        );
554
555        for (token, dist) in block.tokens().iter().zip(block.dists()) {
556            let q = dist.prob(*token);
557            assert!(q > 0.0, "the sampled token must be in its own support");
558            assert!(
559                q < 1.0,
560                "a spread distribution reported as certainty is the lie this test exists for"
561            );
562            let total: f32 = dist.support().iter().map(|&(_, p)| p).sum();
563            assert!(
564                (total - 1.0).abs() < 1e-4,
565                "a reported distribution must be normalised, got {total}"
566            );
567        }
568    }
569}