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