ferrox_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 ferrox_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 = (0..decoder.config.n_layers)
162 .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
163 .collect();
164 Ok(DraftModelSpeculator {
165 decoder,
166 kv_caches,
167 synced: 0,
168 sampling,
169 rng: Sampler::new(seed),
170 min_prob,
171 max_draft,
172 })
173 }
174
175 /// Drops every cached row past `len`, on every layer.
176 fn truncate_to(&mut self, len: usize) {
177 for cache in &mut self.kv_caches {
178 cache.truncate(len);
179 }
180 }
181
182 /// Brings the draft cache up to `history` and returns the logits
183 /// that follow its last token.
184 ///
185 /// Feeds only the tokens the cache does not already hold, which is
186 /// what makes drafting cheap across a long conversation: the first
187 /// call pays for the prompt and every later call pays for the
188 /// handful of tokens the target committed since.
189 ///
190 /// The cache is rolled back to at most `history.len() - 1` rather
191 /// than `history.len()`, and that off-by-one is load-bearing. The
192 /// logits a block is drafted from are the ones that follow the last
193 /// committed token, and they exist only as the return value of the
194 /// forward pass that consumed it. Truncating to the full history
195 /// would leave nothing to feed, so there would be no logits to
196 /// draft from and every call after a rollback would propose
197 /// nothing: speculation would quietly stop happening while
198 /// remaining perfectly correct, which is the kind of failure that
199 /// shows up as a benchmark result months later.
200 ///
201 /// The cost is re-feeding exactly one token per call. That is one
202 /// step of the small model, against a block of them saved.
203 fn sync(&mut self, history: &[usize]) -> Vec<f32> {
204 debug_assert!(
205 !history.is_empty(),
206 "callers return early on an empty history"
207 );
208 // Everything past what the caller's history contains was
209 // drafted and not accepted. It is not context, it is a guess
210 // the target threw away.
211 // Derived from the CACHE, not only from `self.synced`. The
212 // cache is the authority on how many rows exist, and a backend
213 // that keeps its KV somewhere other than this host `KvCache`
214 // leaves it at zero however many tokens were fed. Trusting the
215 // counter there truncated to 7 rows of a cache holding 0 and
216 // panicked on a real Metal run. That is the same lesson as the
217 // batched prefill: read the cursor, do not keep a copy of it.
218 // ROWS, for the same reason: this bounds what can be kept by
219 // what is really there, not by what the counter believes.
220 let held = self.kv_caches.first().map_or(0, |c| c.rows());
221 let keep = self.synced.min(history.len() - 1).min(held);
222 self.truncate_to(keep);
223 self.synced = keep;
224
225 let mut logits = Vec::new();
226 while self.synced < history.len() {
227 let pos = self.synced;
228 logits = self
229 .decoder
230 .forward_token(history[pos], pos, &mut self.kv_caches);
231 self.synced += 1;
232 }
233 logits
234 }
235}
236
237impl Drafter for DraftModelSpeculator {
238 fn propose(&mut self, history: &[usize], _target_hidden: &[f32], max_len: usize) -> DraftBlock {
239 let budget = max_len.min(self.max_draft);
240 if budget == 0 || history.is_empty() {
241 return DraftBlock::empty();
242 }
243
244 let mut logits = self.sync(history);
245
246 let mut tokens = Vec::with_capacity(budget);
247 let mut dists = Vec::with_capacity(budget);
248
249 for _ in 0..budget {
250 // `history` is everything the target has committed --
251 // prompt included -- and `tokens` is what this block has
252 // proposed on top of it, so the drafter's penalties see the
253 // same sequence the target's would. The block used to clone
254 // `history` per call to concatenate the two; the window
255 // borrows both halves instead.
256 let probs = sampling_distribution(
257 &logits,
258 &self.sampling,
259 PenaltyWindow::new(history, &tokens),
260 );
261 let token = self.rng.sample_from(&probs);
262
263 // `q` MUST be the distribution this token was actually
264 // sampled from, truncation and all, or the rejection rule
265 // is corrected against a lie. `sampling_distribution`
266 // returns exactly that, so it is what gets reported.
267 let dist = DraftDist::from_dense(&probs);
268 let q = dist.prob(token);
269 if q < self.min_prob {
270 // Stop before committing this token, so the cache is
271 // not advanced over a position nobody drafted.
272 break;
273 }
274
275 tokens.push(token);
276 dists.push(dist);
277
278 let pos = self.synced;
279 logits = self.decoder.forward_token(token, pos, &mut self.kv_caches);
280 self.synced += 1;
281 }
282
283 DraftBlock::new(tokens, dists)
284 }
285}
286
287#[cfg(test)]
288mod tests {
289 use super::*;
290 use crate::config::test_dense_fixture;
291
292 fn drafter(vocab: usize, max_draft: usize, min_prob: f32) -> DraftModelSpeculator {
293 let target = {
294 let mut c = test_dense_fixture();
295 c.vocab_size = vocab;
296 c
297 };
298 let decoder = Decoder::new_random_small(test_dense_fixture(), 2, vocab);
299 DraftModelSpeculator::new(
300 decoder,
301 &target,
302 SamplingParams::default(),
303 7,
304 max_draft,
305 min_prob,
306 )
307 .expect("matching vocabularies")
308 }
309
310 /// A draft model whose vocabulary differs from the target's is
311 /// refused at construction, not accepted and corrected later.
312 ///
313 /// There is nothing to correct. The rejection rule compares the
314 /// drafter's probability for token id `x` against the target's
315 /// probability for token id `x`; if the two checkpoints number
316 /// their vocabularies differently those are different tokens, and
317 /// the output is no longer the target's distribution while looking
318 /// exactly like text that is. Fluent, plausible accept rate, no
319 /// error. That is the one failure this engine refuses to serve.
320 #[test]
321 fn a_draft_model_with_a_different_vocabulary_is_refused_by_name() {
322 let mut target = test_dense_fixture();
323 target.vocab_size = 64;
324 let decoder = Decoder::new_random_small(test_dense_fixture(), 2, 32);
325
326 let err = DraftModelSpeculator::new(decoder, &target, SamplingParams::default(), 0, 4, 0.0)
327 .err()
328 .expect("32 != 64");
329
330 assert_eq!(
331 err,
332 VocabMismatch::Size {
333 draft: 32,
334 target: 64
335 }
336 );
337 let msg = err.to_string();
338 // The message has to say both numbers and why it matters, or
339 // the next person reads it as an arbitrary compatibility rule
340 // and looks for a flag to turn it off.
341 assert!(msg.contains("32") && msg.contains("64"), "{msg}");
342 assert!(msg.contains("same family and tokenizer"), "{msg}");
343 }
344
345 /// The drafter proposes a block and reports one distribution per
346 /// token, which is what the rejection rule needs to run at all.
347 #[test]
348 fn a_block_carries_one_honest_distribution_per_drafted_token() {
349 let mut d = drafter(32, 4, 0.0);
350 let block = d.propose(&[1, 2, 3], &[], 4);
351
352 assert_eq!(block.len(), 4, "the whole budget was drafted");
353 assert_eq!(block.tokens().len(), block.dists().len());
354 for (token, dist) in block.tokens().iter().zip(block.dists()) {
355 // `q(x)` for the token actually sampled must be nonzero:
356 // the rule divides by it.
357 assert!(
358 dist.prob(*token) > 0.0,
359 "a drafter must report the distribution it sampled from"
360 );
361 }
362 }
363
364 /// **The rollback.** After a block is proposed, the drafter's cache
365 /// holds rows for tokens the target has not accepted. The next call
366 /// arrives with a history that does not contain them, and those
367 /// rows must be gone before anything else is fed.
368 ///
369 /// Left in place, the drafter's context silently diverges from the
370 /// target's: every later proposal is conditioned on tokens that
371 /// were thrown away. Nothing errors. The accept rate decays, which
372 /// reads as "this drafter is bad" rather than "this drafter is
373 /// desynchronised", and that is why this is asserted on the cache
374 /// length rather than on output quality.
375 #[test]
376 fn the_draft_cache_rolls_back_the_positions_the_target_did_not_accept() {
377 let mut d = drafter(32, 4, 0.0);
378
379 let block = d.propose(&[1, 2, 3], &[], 4);
380 assert_eq!(block.len(), 4);
381 assert_eq!(
382 d.synced, 7,
383 "3 of history plus 4 drafted are in the cache after proposing"
384 );
385
386 // The target accepted exactly one of them, so the caller's
387 // history grew by one, not by four.
388 d.propose(&[1, 2, 3, block.tokens()[0]], &[], 4);
389
390 assert_eq!(
391 d.kv_caches[0].positions(),
392 d.synced,
393 "every layer's cache agrees with the drafter's own count"
394 );
395 assert_eq!(
396 d.synced, 8,
397 "4 committed tokens plus 4 freshly drafted, NOT 7 stale rows plus more"
398 );
399 }
400
401 /// A history shorter than what the cache holds is a rollback too,
402 /// and the arithmetic must not underflow into a huge truncate.
403 #[test]
404 fn a_history_shorter_than_the_cache_truncates_rather_than_underflowing() {
405 let mut d = drafter(32, 4, 0.0);
406 d.propose(&[1, 2, 3, 4, 5], &[], 4);
407 assert_eq!(d.synced, 9);
408
409 d.propose(&[1, 2], &[], 1);
410 assert_eq!(d.synced, 3, "2 of history plus 1 drafted");
411 assert_eq!(d.kv_caches[0].positions(), 3);
412 }
413
414 /// Drafting stops when the drafter's own probability for the token
415 /// it just sampled falls below the floor.
416 ///
417 /// A guessing drafter is worse than none: the target pays for the
418 /// position either way, and a rejection also discards every
419 /// position after it. With the floor above 1.0 nothing can clear
420 /// it, so the block is empty and the caller falls back to one
421 /// ordinary decode step.
422 #[test]
423 fn a_drafter_below_the_probability_floor_proposes_nothing() {
424 let mut d = drafter(32, 4, 1.01);
425 let block = d.propose(&[1, 2, 3], &[], 4);
426 assert!(block.is_empty(), "nothing clears a floor above 1.0");
427 assert_eq!(
428 d.synced, 3,
429 "and the cache holds the history only, no abandoned draft rows"
430 );
431 }
432
433 /// `max_draft` is a ceiling the caller's budget cannot raise.
434 #[test]
435 fn the_configured_maximum_bounds_the_callers_budget() {
436 let mut d = drafter(32, 2, 0.0);
437 assert_eq!(d.propose(&[1, 2, 3], &[], 8).len(), 2);
438 }
439
440 /// An empty history has nothing to condition on, and a zero budget
441 /// asked for nothing. Both propose nothing rather than panicking.
442 #[test]
443 fn an_empty_history_or_a_zero_budget_proposes_nothing() {
444 let mut d = drafter(32, 4, 0.0);
445 assert!(d.propose(&[], &[], 4).is_empty());
446 assert!(d.propose(&[1, 2], &[], 0).is_empty());
447 }
448
449 /// **The property the whole feature exists to preserve.**
450 ///
451 /// A draft model is only worth having if the text is exactly what
452 /// the target would have written alone. At temperature 0 that is
453 /// checkable exactly: token for token against a plain
454 /// `forward_token` loop over an identically seeded target.
455 ///
456 /// This is the test that catches a desynchronised draft cache, a
457 /// dishonest `q`, or an off-by-one in the block, because all three
458 /// change the output rather than announcing themselves. A drafter
459 /// is allowed to be bad; it is not allowed to be consulted in a way
460 /// that changes the answer.
461 ///
462 /// The drafter here is a genuinely different model from the target
463 /// (a different random seed, half the layers), so it is wrong
464 /// often, which is exactly the case where rejection and rollback
465 /// have to work.
466 #[test]
467 fn a_draft_model_does_not_change_what_the_target_writes() {
468 use crate::speculative::speculative_decode;
469
470 let cfg = test_dense_fixture();
471 let vocab = 32;
472 let prompt = vec![1usize, 2, 3, 4, 1, 2];
473 let max_new = 8;
474
475 let target = Decoder::new_random_small(cfg.clone(), 4, vocab);
476 let mut caches: Vec<KvCache> = (0..target.config.n_layers)
477 .map(|_| KvCache::new(target.config.n_kv_heads, target.config.head_dim))
478 .collect();
479
480 // A different model, not a copy of the target: two layers
481 // rather than four, so it disagrees constantly.
482 let draft = Decoder::new_random_small(cfg.clone(), 2, vocab);
483 let mut drafter =
484 DraftModelSpeculator::new(draft, &target.config, SamplingParams::default(), 11, 4, 0.0)
485 .expect("matching vocabularies");
486
487 let result = speculative_decode(&target, &prompt, max_new, &mut caches, &mut drafter);
488
489 // The same target, decoded the ordinary way.
490 let plain = Decoder::new_random_small(cfg, 4, vocab);
491 let mut plain_caches: Vec<KvCache> = (0..plain.config.n_layers)
492 .map(|_| KvCache::new(plain.config.n_kv_heads, plain.config.head_dim))
493 .collect();
494 let mut pending = plain
495 .forward_batch(&prompt, 0, &mut plain_caches)
496 .pop()
497 .expect("a non-empty prompt returns logits");
498 let mut greedy = Vec::with_capacity(max_new);
499 for pos in (prompt.len()..).take(max_new) {
500 let tok = pending
501 .iter()
502 .enumerate()
503 .max_by(|a, b| a.1.partial_cmp(b.1).expect("logits are finite"))
504 .map(|(i, _)| i)
505 .expect("a non-empty vocabulary");
506 greedy.push(tok);
507 pending = plain.forward_token(tok, pos, &mut plain_caches);
508 }
509
510 assert_eq!(
511 result.generated_tokens, greedy,
512 "a draft model may make decoding faster and may not make it different"
513 );
514 }
515
516 /// **`q` must be the distribution the token was really sampled
517 /// from**, at every temperature.
518 ///
519 /// The rejection rule accepts with probability `min(1, p(x)/q(x))`
520 /// and resamples from `max(0, p - q)`. A drafter that overstates
521 /// its own confidence, reporting a point mass for a token it
522 /// actually drew from a spread distribution, makes `p/q` too small:
523 /// tokens get rejected that should have been accepted, and the
524 /// residual it resamples from is not the right residual. The output
525 /// stops being the target's distribution.
526 ///
527 /// This cannot be caught at temperature 0, where the true
528 /// distribution IS a point mass and a dishonest report is
529 /// accidentally correct. That is exactly why this test sets a
530 /// temperature: a suite that only checks greedy decoding will pass
531 /// a drafter that lies.
532 #[test]
533 fn the_reported_distribution_is_the_one_sampled_from_at_temperature() {
534 let target = {
535 let mut c = test_dense_fixture();
536 c.vocab_size = 32;
537 c
538 };
539 let decoder = Decoder::new_random_small(test_dense_fixture(), 2, 32);
540 let sampling = SamplingParams {
541 temperature: 1.0,
542 ..SamplingParams::default()
543 };
544 let mut d = DraftModelSpeculator::new(decoder, &target, sampling.clone(), 3, 4, 0.0)
545 .expect("matching vocabularies");
546
547 let block = d.propose(&[1, 2, 3], &[], 4);
548 assert_eq!(block.len(), 4);
549
550 let spread = block.dists().iter().any(|dist| dist.support().len() > 1);
551 assert!(
552 spread,
553 "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"
554 );
555
556 for (token, dist) in block.tokens().iter().zip(block.dists()) {
557 let q = dist.prob(*token);
558 assert!(q > 0.0, "the sampled token must be in its own support");
559 assert!(
560 q < 1.0,
561 "a spread distribution reported as certainty is the lie this test exists for"
562 );
563 let total: f32 = dist.support().iter().map(|&(_, p)| p).sum();
564 assert!(
565 (total - 1.0).abs() < 1e-4,
566 "a reported distribution must be normalised, got {total}"
567 );
568 }
569 }
570}