Skip to main content

ferrox_models/
speculative.rs

1//! Speculative decoding: propose several candidate next tokens with
2//! something cheap, then verify them all in a single
3//! `Decoder::forward_batch` call instead of one `forward_token` call
4//! per token.
5//!
6//! Two halves, deliberately separated:
7//!
8//! * **Drafting** is the [`Drafter`] trait. The only implementation in
9//!   the tree is [`PromptLookupSpeculator`], an n-gram match over the
10//!   history with no model at all (the same idea as vLLM's "prompt
11//!   lookup decoding"), chosen because it needs no GPU, no second set
12//!   of weights and no checkpoint to be useful. A model-based drafter
13//!   (MTP head, EAGLE, dFlash) is a second impl of the same trait.
14//! * **Verification** is [`speculative_decode_with`], and it does not
15//!   know or care which drafter proposed the block.
16//!
17//! # Losslessness is the property that matters most here
18//!
19//! Speculative decoding is only worth having if it produces exactly the
20//! same *distribution* the target model would have produced on its own,
21//! just faster. This module implements the speculative-sampling
22//! rejection rule (Leviathan et al. 2023 / Chen et al. 2023): a draft
23//! token `x` proposed with draft probability `q(x)` is accepted with
24//! probability `min(1, p(x)/q(x))`, and on rejection the position is
25//! resampled from the normalised residual `max(0, p - q)`. That rule is
26//! lossless at *every* temperature.
27//!
28//! It is worth being precise about what the previous accept test --
29//! `argmax(target_logits[i]) == guess` -- actually guaranteed, because
30//! it looks like the same thing and is not. Argmax matching is exactly
31//! the special case of the rule above at `temperature = 0`, where `p`
32//! is a point mass: `p(x)` is 1 when the guess is the argmax and 0
33//! otherwise, so acceptance is certain or impossible and the residual
34//! collapses back onto the argmax. Above temperature 0 it is a
35//! different algorithm with a different output distribution -- it
36//! silently biases generation toward the target's argmax, because a
37//! draft token only survives if it happens to be the most likely one.
38//! [`accept_or_resample`] is therefore not an optimisation; it is the
39//! difference between "lossless" being true and being a claim.
40//!
41//! The invariant is tested directly, not assumed:
42//! `resampling_reproduces_the_target_distribution` pushes two hundred
43//! thousand tokens through the accept/reject rule with deliberately bad
44//! draft distributions and asserts the empirical output matches the
45//! target distribution;
46//! `speculative_decode_at_temperature_matches_plain_sampling` compares
47//! a real decode at temperature 1.0 against the target's own exactly
48//! enumerated per-position marginals; and
49//! `speculative_decode_matches_greedy_token_for_token` asserts
50//! token-for-token identity with a plain `forward_token` loop at
51//! temperature 0.
52
53use crate::decoder::Decoder;
54use crate::penalty_window::PenaltyWindow;
55use crate::sampling::{sampling_distribution, Sampler, SamplingParams};
56use ferrox_core::cache::KvCache;
57
58/// The distribution one drafted position was sampled from, as its
59/// complete support: `(token id, probability)` pairs summing to 1.
60///
61/// Sparse rather than a dense vocabulary-length vector because the
62/// distributions drafters actually produce are sparse: a prompt-lookup
63/// drafter's support is a single token, and a real drafter's is a
64/// top-k, not 150k floats per drafted position per step.
65///
66/// # Contract
67///
68/// The support must be the distribution the draft token was *actually*
69/// sampled from. Losslessness does not require the drafter to be good,
70/// or even sane -- the rejection rule corrects any `q` -- but it does
71/// require `q` to be honest. A drafter that truncates its own softmax
72/// to a top-k before sampling must report the truncated, renormalised
73/// distribution, not the full softmax it started from.
74#[derive(Debug, Clone, PartialEq, Default)]
75pub struct DraftDist {
76    support: Vec<(usize, f32)>,
77}
78
79impl DraftDist {
80    /// A drafter that is certain: all probability on one token. This is
81    /// what a lookup-table drafter honestly reports -- it did not
82    /// sample, it asserted.
83    pub fn deterministic(token: usize) -> Self {
84        DraftDist {
85            support: vec![(token, 1.0)],
86        }
87    }
88
89    /// The nonzero entries of a dense probability vector.
90    pub fn from_dense(probs: &[f32]) -> Self {
91        DraftDist {
92            support: probs
93                .iter()
94                .enumerate()
95                .filter(|&(_, &p)| p > 0.0)
96                .map(|(i, &p)| (i, p))
97                .collect(),
98        }
99    }
100
101    /// Builds from explicit `(token, probability)` pairs.
102    pub fn from_support(support: Vec<(usize, f32)>) -> Self {
103        DraftDist { support }
104    }
105
106    pub fn support(&self) -> &[(usize, f32)] {
107        &self.support
108    }
109
110    /// `q(token)`, or 0.0 for a token outside the support.
111    pub fn prob(&self, token: usize) -> f32 {
112        self.support
113            .iter()
114            .find(|&&(t, _)| t == token)
115            .map(|&(_, p)| p)
116            .unwrap_or(0.0)
117    }
118}
119
120/// A block of drafted tokens plus, per position, the distribution that
121/// position was drawn from.
122///
123/// `tokens` and `dists` are the same length by construction: the
124/// verification rule needs `q` for every token it might have to reject,
125/// so a block that carried tokens without distributions could not be
126/// verified losslessly at all.
127#[derive(Debug, Clone, Default, PartialEq)]
128pub struct DraftBlock {
129    tokens: Vec<usize>,
130    dists: Vec<DraftDist>,
131}
132
133impl DraftBlock {
134    pub fn empty() -> Self {
135        DraftBlock::default()
136    }
137
138    /// Panics if the two vectors disagree in length -- an unverifiable
139    /// block is a programming error in the drafter, not a runtime
140    /// condition to degrade around.
141    pub fn new(tokens: Vec<usize>, dists: Vec<DraftDist>) -> Self {
142        assert_eq!(
143            tokens.len(),
144            dists.len(),
145            "a draft block needs one draft distribution per drafted token"
146        );
147        DraftBlock { tokens, dists }
148    }
149
150    /// A block from a drafter that has no distribution to offer: every
151    /// position is reported as certain. Correct (and lossless) for a
152    /// lookup drafter; wrong for a model-based one, which must report
153    /// its real softmax.
154    pub fn deterministic(tokens: Vec<usize>) -> Self {
155        let dists = tokens
156            .iter()
157            .map(|&t| DraftDist::deterministic(t))
158            .collect();
159        DraftBlock { tokens, dists }
160    }
161
162    pub fn tokens(&self) -> &[usize] {
163        &self.tokens
164    }
165
166    pub fn dists(&self) -> &[DraftDist] {
167        &self.dists
168    }
169
170    pub fn len(&self) -> usize {
171        self.tokens.len()
172    }
173
174    pub fn is_empty(&self) -> bool {
175        self.tokens.is_empty()
176    }
177
178    /// Drops everything past `len` positions, keeping tokens and
179    /// distributions in step.
180    pub fn truncate(&mut self, len: usize) {
181        self.tokens.truncate(len);
182        self.dists.truncate(len);
183    }
184}
185
186/// Proposes a block of candidate continuation tokens.
187///
188/// The signature carries two things a plain `fn(&[usize]) -> Vec<usize>`
189/// cannot express, and both are load-bearing:
190///
191/// * **Per-position draft probabilities**, without which
192///   [`accept_or_resample`] cannot run and speculation is only lossless
193///   at temperature 0.
194/// * **The target model's hidden state** for the last position whose KV
195///   is committed. Every model-based drafter worth having (EAGLE, MTP,
196///   dFlash) conditions on it, and `Decoder::forward_batch_with_hidden`
197///   already computes it as a by-product of verification, so a drafter
198///   that wanted it would otherwise have to run the target twice.
199///   Drafters that do not need it, like [`PromptLookupSpeculator`],
200///   ignore the argument.
201pub trait Drafter {
202    /// Proposes at most `max_len` tokens to follow `history`.
203    /// `target_hidden` is the target model's final-layer hidden state
204    /// for `history`'s last token, or empty when none is available yet
205    /// (which a drafter that needs it must handle by proposing
206    /// nothing).
207    /// Takes `&mut self` because a drafter that is itself a model
208    /// carries KV state across calls, and hiding that behind interior
209    /// mutability would put a runtime borrow check on the hot path to
210    /// buy nothing. A stateless drafter simply ignores it.
211    fn propose(&mut self, history: &[usize], target_hidden: &[f32], max_len: usize) -> DraftBlock;
212}
213
214/// Proposes candidate continuation tokens by looking for the longest
215/// available match of the most recent `ngram_size` tokens earlier in
216/// `history`, and returning up to `max_draft_len` tokens that followed
217/// that earlier occurrence. Returns an empty block if no match is found
218/// or `history` is too short to contain one.
219///
220/// This is deliberately simple (last-match-wins, not best-match or a
221/// frequency-weighted choice): the whole point of prompt-lookup
222/// decoding is that it's nearly free to compute, since a wrong guess
223/// costs nothing but a rejected batch position, not a correctness bug.
224#[derive(Debug, Clone, Copy)]
225pub struct PromptLookupSpeculator {
226    pub ngram_size: usize,
227    pub max_draft_len: usize,
228}
229
230impl PromptLookupSpeculator {
231    pub fn new(ngram_size: usize, max_draft_len: usize) -> Self {
232        assert!(ngram_size >= 1, "ngram_size must be at least 1");
233        assert!(max_draft_len >= 1, "max_draft_len must be at least 1");
234        PromptLookupSpeculator {
235            ngram_size,
236            max_draft_len,
237        }
238    }
239
240    /// Looks for the most recent earlier occurrence of `history`'s
241    /// last `ngram_size` tokens, scanning from the end backwards so
242    /// the *most recent* match wins (most likely to reflect current
243    /// context, e.g. a loop the model is currently in). Returns the
244    /// tokens that followed that occurrence, truncated to
245    /// `max_draft_len`.
246    pub fn propose_tokens(&self, history: &[usize]) -> Vec<usize> {
247        if history.len() < self.ngram_size + 1 {
248            return Vec::new();
249        }
250        let needle = &history[history.len() - self.ngram_size..];
251
252        // Search every earlier start position, latest first. The last
253        // possible start that still leaves room for the needle without
254        // overlapping into the needle itself is history.len() -
255        // ngram_size - 1 (exclusive of the needle's own occurrence).
256        let last_possible_start = history.len() - self.ngram_size - 1;
257        for start in (0..=last_possible_start).rev() {
258            if &history[start..start + self.ngram_size] == needle {
259                let continuation_start = start + self.ngram_size;
260                let available = history.len() - continuation_start;
261                let take = available.min(self.max_draft_len);
262                return history[continuation_start..continuation_start + take].to_vec();
263            }
264        }
265        Vec::new()
266    }
267}
268
269impl Drafter for PromptLookupSpeculator {
270    fn propose(&mut self, history: &[usize], _target_hidden: &[f32], max_len: usize) -> DraftBlock {
271        let mut tokens = self.propose_tokens(history);
272        tokens.truncate(max_len.min(self.max_draft_len));
273        DraftBlock::deterministic(tokens)
274    }
275}
276
277/// The speculative-sampling accept/reject decision for one drafted
278/// position.
279///
280/// `target` is the target model's *final* sampling distribution for
281/// this position -- what [`sampling_distribution`] returns, i.e. after
282/// penalties, temperature, top-k and top-p, because that is the
283/// distribution the non-speculative path would have drawn from.
284/// `draft` is the distribution `token` was drawn from.
285///
286/// Returns `None` when the draft token is accepted, and
287/// `Some(replacement)` when it is rejected -- the replacement is drawn
288/// from the normalised residual `max(0, target - draft)`, which is what
289/// makes the combined procedure's output distribution equal to
290/// `target` exactly rather than approximately.
291///
292/// A token with `draft(token) == 0.0` violates the [`DraftDist`]
293/// contract (it could not have been sampled from `draft`); it is
294/// accepted, matching the `p/q -> infinity` limit, rather than
295/// silently biasing the result.
296pub fn accept_or_resample(
297    target: &[f32],
298    draft: &DraftDist,
299    token: usize,
300    rng: &mut Sampler,
301) -> Option<usize> {
302    let p = target.get(token).copied().unwrap_or(0.0);
303    let q = draft.prob(token);
304    if q <= 0.0 || p >= q {
305        return None;
306    }
307    // p < q, so the accept probability p/q is a real coin flip.
308    if rng.uniform() < p / q {
309        return None;
310    }
311
312    // Rejected: draw the replacement from the normalised residual.
313    let mut residual = target.to_vec();
314    for &(t, qt) in draft.support() {
315        if let Some(r) = residual.get_mut(t) {
316            *r = (*r - qt).max(0.0);
317        }
318    }
319    let total: f32 = residual.iter().sum();
320    if total <= 0.0 {
321        // Only reachable when target and draft are the same
322        // distribution, in which case acceptance was certain and we
323        // cannot be here -- but sampling from nothing is not an option,
324        // so fall back to the target itself.
325        return Some(rng.sample_from(target));
326    }
327    for r in residual.iter_mut() {
328        *r /= total;
329    }
330    Some(rng.sample_from(&residual))
331}
332
333/// Everything `speculative_decode_with` needs beyond the model, the
334/// prompt and the drafter.
335#[derive(Debug, Clone, Default)]
336pub struct SpeculativeOptions {
337    pub max_new_tokens: usize,
338    /// Absolute position of the first `prompt_tokens` token in the KV
339    /// cache: 0 for a fresh cache, `cache.seq_len` when resuming a
340    /// warm one (a prefix-cache hit, or a second call continuing the
341    /// first). Every position and every rollback length inside the
342    /// decode loop is absolute, so a non-zero base is not a special
343    /// case -- see `rolls_back_to_absolute_positions_on_a_warm_cache`.
344    pub start_pos: usize,
345    /// The sampling configuration the *target* model would have used
346    /// without speculation. Verification is lossless with respect to
347    /// exactly these parameters (see [`accept_or_resample`]).
348    pub sampling: SamplingParams,
349    pub seed: u64,
350}
351
352/// Result of a speculative decode run, with the counters that make its
353/// actual savings observable rather than just assumed.
354#[derive(Debug, Clone, Default)]
355pub struct SpeculativeDecodeResult {
356    pub generated_tokens: Vec<usize>,
357    /// Number of `Decoder::forward_batch` calls made (prefill counts as
358    /// one call, each subsequent accept/reject round counts as one
359    /// more, regardless of how many tokens that round produced).
360    pub forward_calls: usize,
361    /// Total tokens produced across all rounds -- always equal to
362    /// `generated_tokens.len()`, kept as a separate field so the ratio
363    /// `tokens_generated / forward_calls` (the actual speedup metric)
364    /// is easy to read directly off this struct.
365    pub tokens_generated: usize,
366    /// Verification rounds: `forward_calls` minus the prefill call.
367    /// This is the denominator of the published *acceptance length*
368    /// metric.
369    pub verification_steps: usize,
370    /// Draft tokens the target actually evaluated. Positions past a
371    /// rejection are never evaluated, so they are not counted here --
372    /// counting them would deflate the accept rate by the drafter's
373    /// block size rather than by its accuracy.
374    pub drafted_tokens: usize,
375    /// Draft tokens accepted.
376    pub accepted_tokens: usize,
377    /// Per drafted position (0 = first token after the anchor), how
378    /// many times that position was *evaluated*, i.e. reached without
379    /// an earlier rejection ending the round.
380    pub evaluated_at_position: Vec<usize>,
381    /// Per drafted position, how many times it was accepted.
382    pub accepted_at_position: Vec<usize>,
383}
384
385impl SpeculativeDecodeResult {
386    /// Average tokens produced per `forward_batch` call. 1.0 means
387    /// speculation never helped (every round produced exactly the
388    /// anchor token); higher means draft tokens were accepted.
389    pub fn tokens_per_call(&self) -> f64 {
390        if self.forward_calls == 0 {
391            0.0
392        } else {
393            self.tokens_generated as f64 / self.forward_calls as f64
394        }
395    }
396
397    /// The published metric: completion tokens per verification step.
398    /// `None` when nothing was verified (an empty run), because a zero
399    /// there would read as "speculation made things worse" rather than
400    /// "speculation did not run".
401    ///
402    /// Deliberately not the same number as [`Self::tokens_per_call`],
403    /// which charges the one-off prefill call against the average and
404    /// so understates a short run.
405    pub fn acceptance_length(&self) -> Option<f64> {
406        if self.verification_steps == 0 {
407            None
408        } else {
409            Some(self.tokens_generated as f64 / self.verification_steps as f64)
410        }
411    }
412
413    /// Fraction of drafted positions accepted, over all positions.
414    pub fn accept_rate(&self) -> Option<f64> {
415        if self.drafted_tokens == 0 {
416            None
417        } else {
418            Some(self.accepted_tokens as f64 / self.drafted_tokens as f64)
419        }
420    }
421
422    /// Accept rate at each drafted position, conditional on that
423    /// position having been reached.
424    ///
425    /// A single mean cannot distinguish a drafter that is uniformly
426    /// mediocre from one that is excellent at position 0 and useless by
427    /// position 7, and the two want opposite responses (raise the block
428    /// size, or lower it). The published motivation for dFlash2's
429    /// two-tap convolution is exactly this curve falling from 99.5% to
430    /// 87.8% across a block, so it has to be visible per position or
431    /// the diagnosis is not testable here.
432    pub fn accept_rate_per_position(&self) -> Vec<f64> {
433        self.evaluated_at_position
434            .iter()
435            .zip(self.accepted_at_position.iter())
436            .map(|(&seen, &ok)| {
437                if seen == 0 {
438                    0.0
439                } else {
440                    ok as f64 / seen as f64
441                }
442            })
443            .collect()
444    }
445
446    fn record_position(&mut self, position: usize, accepted: bool) {
447        if self.evaluated_at_position.len() <= position {
448            self.evaluated_at_position.resize(position + 1, 0);
449            self.accepted_at_position.resize(position + 1, 0);
450        }
451        self.evaluated_at_position[position] += 1;
452        self.drafted_tokens += 1;
453        if accepted {
454            self.accepted_at_position[position] += 1;
455            self.accepted_tokens += 1;
456        }
457    }
458}
459
460/// Greedy speculative decode over a **fresh** KV cache, with
461/// prompt-lookup drafting. Thin wrapper over
462/// [`speculative_decode_with`], kept for callers that want the original
463/// no-options shape.
464pub fn speculative_decode<D: Drafter + ?Sized>(
465    decoder: &Decoder,
466    prompt_tokens: &[usize],
467    max_new_tokens: usize,
468    kv_caches: &mut [KvCache],
469    drafter: &mut D,
470) -> SpeculativeDecodeResult {
471    speculative_decode_observed(
472        decoder,
473        prompt_tokens,
474        kv_caches,
475        drafter,
476        &mut |_| true,
477        &SpeculativeOptions {
478            max_new_tokens,
479            ..SpeculativeOptions::default()
480        },
481    )
482}
483
484/// Decodes `options.max_new_tokens` tokens, using `drafter` to propose
485/// candidate continuations and verifying each block in a single batched
486/// call.
487///
488/// `prompt_tokens` is processed as one prefill batch (one
489/// `forward_batch` call for the whole prompt, not one per prompt token
490/// -- itself a real saving independent of speculation).
491///
492/// # Cache state
493///
494/// `kv_caches` may be warm. `options.start_pos` states where
495/// `prompt_tokens` begins, and must equal every cache's current
496/// `seq_len` -- the caches hold exactly the context preceding the
497/// prompt, and this function appends to them. On return they hold that
498/// context plus the prompt plus every generated token *except* the last
499/// (whose KV is not computed until it is fed, which the next call does
500/// for free by passing it as the anchor).
501///
502/// # Output distribution
503///
504/// Identical to plain token-at-a-time sampling from `decoder` with
505/// `options.sampling`, at any temperature. See the module docs.
506pub fn speculative_decode_with<D: Drafter + ?Sized>(
507    decoder: &Decoder,
508    prompt_tokens: &[usize],
509    kv_caches: &mut [KvCache],
510    drafter: &mut D,
511    options: &SpeculativeOptions,
512) -> SpeculativeDecodeResult {
513    speculative_decode_observed(
514        decoder,
515        prompt_tokens,
516        kv_caches,
517        drafter,
518        &mut |_| true,
519        options,
520    )
521}
522
523/// [`speculative_decode_with`], plus an observer called once per
524/// committed token, in order, which can end the run by returning
525/// `false`.
526///
527/// This exists so a caller that streams output, or that stops on an EOS
528/// or a stop string, does not have to write a second copy of the
529/// verification loop. Copying that loop to vary it is how this project
530/// lost five model features from one duplicated decode path, and the
531/// rejection rule is the last code in the tree that should be
532/// duplicated: a subtly different copy is still lossless-looking.
533///
534/// The observer sees a token only once it is COMMITTED, so it never
535/// sees a draft that was rejected. Returning `false` ends generation
536/// after the current verification block finishes, which keeps the KV
537/// caches in the single consistent state this function documents;
538/// `generated_tokens` is truncated at the token that said stop, so the
539/// caller's output and the returned tokens agree.
540pub fn speculative_decode_observed<D: Drafter + ?Sized>(
541    decoder: &Decoder,
542    prompt_tokens: &[usize],
543    kv_caches: &mut [KvCache],
544    drafter: &mut D,
545    on_token: &mut dyn FnMut(usize) -> bool,
546    options: &SpeculativeOptions,
547) -> SpeculativeDecodeResult {
548    assert!(!prompt_tokens.is_empty(), "prompt must not be empty");
549    for cache in kv_caches.iter() {
550        assert_eq!(
551            cache.seq_len, options.start_pos,
552            "start_pos must be the caches' current length: they hold exactly the \
553             context preceding the prompt"
554        );
555    }
556
557    let mut result = SpeculativeDecodeResult::default();
558    if options.max_new_tokens == 0 {
559        return result;
560    }
561
562    let mut rng = Sampler::new(options.seed);
563    let mut history: Vec<usize> = prompt_tokens.to_vec();
564    let mut generated: Vec<usize> = Vec::with_capacity(options.max_new_tokens);
565
566    // Prefill: one batched call over the whole prompt.
567    let (prefill_logits, prefill_hidden) =
568        decoder.forward_batch_with_hidden(prompt_tokens, options.start_pos, kv_caches);
569    result.forward_calls += 1;
570    let last = prefill_logits
571        .last()
572        .expect("prompt_tokens is non-empty, so forward_batch returns at least one logits vector");
573    let mut target_hidden = prefill_hidden.last().cloned().unwrap_or_default();
574
575    // `pending` is decided but its KV is not in the cache yet: it is
576    // fed as the anchor of the next batch, which is what lets one
577    // forward call both commit it and verify a block after it.
578    let mut pending = {
579        // Split ONE structure rather than pairing `history` with the
580        // separate `generated` vector: the two would then have to agree
581        // about every push, which is exactly the shape this fix exists
582        // to remove.
583        let (seen_prompt, seen_generated) = history.split_at(prompt_tokens.len());
584        let probs = sampling_distribution(
585            last,
586            &options.sampling,
587            PenaltyWindow::new(seen_prompt, seen_generated),
588        );
589        rng.sample_from(&probs)
590    };
591    let mut pos = options.start_pos + prompt_tokens.len();
592
593    // Set when the observer asks to stop. The current block still runs
594    // to completion so the caches end in the one state this function
595    // documents, and `generated` is cut back to this length afterwards.
596    let mut stop_at: Option<usize> = None;
597
598    loop {
599        generated.push(pending);
600        history.push(pending);
601        if !on_token(pending) {
602            stop_at = Some(generated.len());
603            break;
604        }
605        if generated.len() == options.max_new_tokens {
606            break;
607        }
608        // One short of the remaining budget on purpose: the last token
609        // of the run is always committed as an anchor at the top of the
610        // loop, never as an accepted draft. That keeps the cache in
611        // exactly one state on return (see the doc comment) instead of
612        // one state when the budget runs out on an anchor and another
613        // when it runs out mid-block -- and it costs nothing, because
614        // the drafted position it gives up is one whose KV would have
615        // had to be discarded anyway.
616        let draft_budget = options.max_new_tokens - generated.len() - 1;
617
618        // The drafter is asked to continue a history that *includes*
619        // `pending`, because the first drafted token lands at pos + 1.
620        let mut draft = drafter.propose(&history, &target_hidden, draft_budget);
621        draft.truncate(draft_budget);
622
623        let mut batch = Vec::with_capacity(1 + draft.len());
624        batch.push(pending);
625        batch.extend_from_slice(draft.tokens());
626
627        let (batch_logits, batch_hidden) =
628            decoder.forward_batch_with_hidden(&batch, pos, kv_caches);
629        result.forward_calls += 1;
630        result.verification_steps += 1;
631
632        // batch_logits[i] is the target's distribution for the position
633        // right after batch[i], i.e. the distribution draft token i
634        // should be judged against.
635        let mut accepted = 0usize;
636        let mut replacement: Option<usize> = None;
637        for (i, (&token, dist)) in draft.tokens().iter().zip(draft.dists()).enumerate() {
638            let (seen_prompt, seen_generated) = history.split_at(prompt_tokens.len());
639            let target = sampling_distribution(
640                &batch_logits[i],
641                &options.sampling,
642                PenaltyWindow::new(seen_prompt, seen_generated),
643            );
644            match accept_or_resample(&target, dist, token, &mut rng) {
645                None => {
646                    result.record_position(i, true);
647                    accepted += 1;
648                    history.push(token);
649                    generated.push(token);
650                    if stop_at.is_none() && !on_token(token) {
651                        // Keep verifying the rest of the block: the
652                        // loop below truncates the caches to exactly
653                        // what was committed, and leaving early here
654                        // would skip that.
655                        stop_at = Some(generated.len());
656                    }
657                }
658                Some(resampled) => {
659                    result.record_position(i, false);
660                    replacement = Some(resampled);
661                    break;
662                }
663            }
664        }
665
666        // Every position past `accepted` was computed from a token that
667        // is not going to be committed, so its KV is wrong. Lengths are
668        // absolute, which is what makes a warm cache work: `pos` is
669        // already offset by start_pos.
670        let committed_len = pos + 1 + accepted;
671        if accepted < draft.len() {
672            for cache in kv_caches.iter_mut() {
673                cache.truncate(committed_len);
674            }
675        }
676        debug_assert!(kv_caches.iter().all(|c| c.seq_len == committed_len));
677
678        target_hidden = batch_hidden[accepted].clone();
679        pending = match replacement {
680            // A rejected position was resampled from the residual; that
681            // token is committed and becomes the next anchor.
682            Some(tok) => tok,
683            // Every draft token was accepted, so the last row of the
684            // batch predicts a genuinely new position -- the free bonus
685            // token that makes a fully-accepted block worth `k + 1`.
686            None => {
687                let (seen_prompt, seen_generated) = history.split_at(prompt_tokens.len());
688                let probs = sampling_distribution(
689                    &batch_logits[accepted],
690                    &options.sampling,
691                    PenaltyWindow::new(seen_prompt, seen_generated),
692                );
693                rng.sample_from(&probs)
694            }
695        };
696        pos = committed_len;
697        if stop_at.is_some() {
698            break;
699        }
700        debug_assert!(generated.len() < options.max_new_tokens);
701    }
702
703    if let Some(len) = stop_at {
704        // The observer said stop at this token. Everything after it was
705        // produced by a block that had already been dispatched, and the
706        // caller never saw it.
707        generated.truncate(len);
708    } else {
709        debug_assert_eq!(generated.len(), options.max_new_tokens);
710    }
711    result.tokens_generated = generated.len();
712    result.generated_tokens = generated;
713    result
714}
715
716#[cfg(test)]
717mod tests {
718    use super::*;
719    use crate::config::glm_5_2;
720    use crate::ModelConfig;
721    use std::cell::RefCell;
722
723    fn tiny_test_config() -> ModelConfig {
724        let mut cfg = glm_5_2();
725        cfg.hidden_dim = 16;
726        cfg.n_heads = 4;
727        cfg.n_kv_heads = 2;
728        cfg.head_dim = 4;
729        cfg.moe.hidden_dim = 16;
730        cfg.moe.n_experts = 6;
731        cfg.moe.n_experts_active = 2;
732        cfg.moe.n_shared_experts = 1;
733        cfg.moe.expert_ffn_dim = 8;
734        cfg
735    }
736
737    fn caches(decoder: &Decoder) -> Vec<KvCache> {
738        (0..decoder.layers.len())
739            .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
740            .collect()
741    }
742
743    fn argmax(logits: &[f32]) -> usize {
744        logits
745            .iter()
746            .enumerate()
747            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
748            .map(|(i, _)| i)
749            .unwrap_or(0)
750    }
751
752    /// A drafter that always proposes the same block, with a
753    /// configurable draft distribution, and records the history it was
754    /// asked about.
755    struct FixedDrafter {
756        block: DraftBlock,
757        seen_history: RefCell<Vec<Vec<usize>>>,
758        seen_hidden_len: RefCell<Vec<usize>>,
759    }
760
761    impl FixedDrafter {
762        fn new(block: DraftBlock) -> Self {
763            FixedDrafter {
764                block,
765                seen_history: RefCell::new(Vec::new()),
766                seen_hidden_len: RefCell::new(Vec::new()),
767            }
768        }
769    }
770
771    impl Drafter for FixedDrafter {
772        fn propose(
773            &mut self,
774            history: &[usize],
775            target_hidden: &[f32],
776            max_len: usize,
777        ) -> DraftBlock {
778            self.seen_history.borrow_mut().push(history.to_vec());
779            self.seen_hidden_len.borrow_mut().push(target_hidden.len());
780            let mut block = self.block.clone();
781            block.truncate(max_len);
782            block
783        }
784    }
785
786    // ---- PromptLookupSpeculator tests ----
787
788    #[test]
789    fn proposes_the_continuation_after_a_real_repeat() {
790        let mut spec = PromptLookupSpeculator::new(2, 4);
791        // "...1 2 3 4 5 9 9 9 1 2" -> earlier "1 2" occurs at the very
792        // start (indices 0-1); the 4 tokens that followed it are
793        // "3 4 5 9" (capped at max_draft_len=4).
794        let history = vec![1, 2, 3, 4, 5, 9, 9, 9, 1, 2];
795        assert_eq!(spec.propose_tokens(&history), vec![3, 4, 5, 9]);
796        assert_eq!(
797            spec.propose(&history, &[], 8),
798            DraftBlock::deterministic(vec![3, 4, 5, 9])
799        );
800    }
801
802    #[test]
803    fn respects_max_draft_len() {
804        let spec = PromptLookupSpeculator::new(2, 2);
805        let history = vec![1, 2, 3, 4, 5, 6, 7, 1, 2];
806        assert_eq!(spec.propose_tokens(&history), vec![3, 4]);
807    }
808
809    #[test]
810    fn returns_empty_when_no_earlier_match_exists() {
811        let spec = PromptLookupSpeculator::new(2, 4);
812        let history = vec![1, 2, 3, 4, 5];
813        assert_eq!(spec.propose_tokens(&history), Vec::<usize>::new());
814    }
815
816    #[test]
817    fn returns_empty_when_history_too_short() {
818        let spec = PromptLookupSpeculator::new(3, 4);
819        let history = vec![1, 2, 3];
820        assert_eq!(spec.propose_tokens(&history), Vec::<usize>::new());
821    }
822
823    #[test]
824    fn finds_the_most_recent_match_when_several_exist() {
825        let spec = PromptLookupSpeculator::new(1, 3);
826        // needle = [9]. Earlier occurrences at index 0 (-> [8,7,6]) and
827        // index 4 (-> [5,4,9]); most recent (index 4) should win.
828        let history = vec![9, 8, 7, 6, 9, 5, 4, 9];
829        assert_eq!(spec.propose_tokens(&history), vec![5, 4, 9]);
830    }
831
832    #[test]
833    fn the_trait_caps_a_block_at_the_callers_budget() {
834        let mut spec = PromptLookupSpeculator::new(2, 4);
835        let history = vec![1, 2, 3, 4, 5, 9, 9, 9, 1, 2];
836        let block = spec.propose(&history, &[], 2);
837        assert_eq!(block.tokens(), &[3, 4]);
838        assert_eq!(block.dists().len(), 2);
839    }
840
841    // ---- the rejection rule ----
842
843    #[test]
844    fn a_draft_at_least_as_likely_under_the_target_is_always_accepted() {
845        let target = vec![0.6f32, 0.3, 0.1];
846        let draft = DraftDist::from_dense(&[0.5, 0.4, 0.1]);
847        let mut rng = Sampler::new(1);
848        for _ in 0..100 {
849            // p(0)=0.6 >= q(0)=0.5, so token 0 is never rejected.
850            assert_eq!(accept_or_resample(&target, &draft, 0, &mut rng), None);
851        }
852    }
853
854    #[test]
855    fn a_draft_the_target_rules_out_is_always_rejected() {
856        let target = vec![0.5f32, 0.5, 0.0];
857        let draft = DraftDist::deterministic(2);
858        let mut rng = Sampler::new(2);
859        for _ in 0..50 {
860            let replacement = accept_or_resample(&target, &draft, 2, &mut rng);
861            let tok = replacement.expect("p(2) = 0 means token 2 can never be accepted");
862            assert!(tok < 2, "residual must never resample the rejected token");
863        }
864    }
865
866    #[test]
867    fn resampling_reproduces_the_target_distribution() {
868        // THE invariant. Draw a token from the draft distribution, run
869        // it through the accept/reject rule, and the result must be
870        // distributed as the TARGET, no matter how bad the draft is.
871        //
872        // A test that only checked "it runs" would pass on the old
873        // argmax rule, which concentrates mass on the target's argmax
874        // and is not the target distribution at all.
875        let target = vec![0.30f32, 0.25, 0.20, 0.15, 0.07, 0.03];
876        let drafts = [
877            // A drafter that is simply wrong about which token is likely.
878            DraftDist::from_dense(&[0.02, 0.03, 0.05, 0.10, 0.30, 0.50]),
879            // A deterministic drafter, i.e. prompt lookup.
880            DraftDist::deterministic(3),
881            // A drafter whose support misses most of the target's.
882            DraftDist::from_support(vec![(0, 0.5), (5, 0.5)]),
883            // A perfect drafter.
884            DraftDist::from_dense(&target),
885        ];
886        let draws = 200_000;
887        for (d, draft) in drafts.iter().enumerate() {
888            let mut rng = Sampler::new(0xA11CE + d as u64);
889            let mut counts = vec![0usize; target.len()];
890            for _ in 0..draws {
891                // Sample the draft token from the draft distribution --
892                // the rule is only lossless when q is honest about
893                // where the token came from.
894                let dense = {
895                    let mut v = vec![0.0f32; target.len()];
896                    for &(t, p) in draft.support() {
897                        v[t] = p;
898                    }
899                    v
900                };
901                let x = rng.sample_from(&dense);
902                let out = accept_or_resample(&target, draft, x, &mut rng).unwrap_or(x);
903                counts[out] += 1;
904            }
905            let tv: f64 = counts
906                .iter()
907                .enumerate()
908                .map(|(i, &c)| (c as f64 / draws as f64 - target[i] as f64).abs())
909                .sum::<f64>()
910                / 2.0;
911            assert!(
912                tv < 0.01,
913                "draft {d}: speculative output distribution differs from the target \
914                 (total variation {tv:.4}); counts={counts:?}"
915            );
916        }
917    }
918
919    // ---- speculative_decode correctness tests ----
920
921    #[test]
922    fn speculative_decode_matches_greedy_token_for_token() {
923        // Quality-neutrality at temperature 0: token-for-token identity
924        // against a plain sequential forward_token loop on a
925        // separately constructed but identically-seeded decoder.
926        let cfg = tiny_test_config();
927        let vocab = 8;
928        let prompt = vec![1usize, 2, 3, 4, 1, 2];
929        let max_new = 6;
930
931        let decoder_a = Decoder::new_random_small(cfg.clone(), 2, vocab);
932        let mut caches_a = caches(&decoder_a);
933        let mut speculator = PromptLookupSpeculator::new(2, 3);
934        let result =
935            speculative_decode(&decoder_a, &prompt, max_new, &mut caches_a, &mut speculator);
936
937        let decoder_b = Decoder::new_random_small(cfg, 2, vocab);
938        let mut caches_b = caches(&decoder_b);
939        let mut pending = decoder_b
940            .forward_batch(&prompt, 0, &mut caches_b)
941            .pop()
942            .unwrap();
943        let mut greedy = Vec::with_capacity(max_new);
944        for pos in (prompt.len()..).take(max_new) {
945            let tok = argmax(&pending);
946            greedy.push(tok);
947            pending = decoder_b.forward_token(tok, pos, &mut caches_b);
948        }
949
950        assert_eq!(
951            result.generated_tokens, greedy,
952            "speculative decode must produce exactly the same tokens as plain greedy decode"
953        );
954    }
955
956    /// The exact per-position marginal distributions of plain
957    /// token-at-a-time sampling from `decoder`, by enumerating every
958    /// prefix rather than sampling them. Only tractable because the
959    /// test model has a 6-token vocabulary and the horizon is 3, but
960    /// worth it: the speculative sampler is then compared against the
961    /// truth, not against a second noisy estimate of it.
962    fn exact_marginals(
963        decoder: &Decoder,
964        prompt: &[usize],
965        params: &SamplingParams,
966        depth: usize,
967        vocab: usize,
968    ) -> Vec<Vec<f64>> {
969        #[allow(clippy::too_many_arguments)]
970        fn walk(
971            decoder: &Decoder,
972            kv: &[KvCache],
973            logits: &[f32],
974            history: &mut Vec<usize>,
975            weight: f64,
976            level: usize,
977            depth: usize,
978            pos: usize,
979            params: &SamplingParams,
980            marginals: &mut [Vec<f64>],
981        ) {
982            // `history` is already prompt-then-generated, and the
983            // window only ever reads the tail of the two halves
984            // together, so the whole sequence goes in the first one.
985            let probs = sampling_distribution(logits, params, PenaltyWindow::new(history, &[]));
986            for (token, &p) in probs.iter().enumerate() {
987                if p <= 0.0 {
988                    continue;
989                }
990                marginals[level][token] += weight * p as f64;
991                if level + 1 == depth {
992                    continue;
993                }
994                let mut branch: Vec<KvCache> = kv.to_vec();
995                let next = decoder.forward_token(token, pos, &mut branch);
996                history.push(token);
997                walk(
998                    decoder,
999                    &branch,
1000                    &next,
1001                    history,
1002                    weight * p as f64,
1003                    level + 1,
1004                    depth,
1005                    pos + 1,
1006                    params,
1007                    marginals,
1008                );
1009                history.pop();
1010            }
1011        }
1012
1013        let mut marginals = vec![vec![0.0f64; vocab]; depth];
1014        let mut kv = caches(decoder);
1015        let logits = decoder.forward_batch(prompt, 0, &mut kv).pop().unwrap();
1016        let mut history = prompt.to_vec();
1017        walk(
1018            decoder,
1019            &kv,
1020            &logits,
1021            &mut history,
1022            1.0,
1023            0,
1024            depth,
1025            prompt.len(),
1026            params,
1027            &mut marginals,
1028        );
1029        marginals
1030    }
1031
1032    /// Speculation and plain token-at-a-time decoding must agree about
1033    /// WHICH tokens the penalties look back over, including the prompt.
1034    ///
1035    /// This is issue #55's other half. `SpeculativeOptions` used to
1036    /// carry a `penalty_history_start` knob whose only job was to let a
1037    /// caller line the two paths up by hand, which meant nothing failed
1038    /// when they drifted -- and `--model-draft` shipped setting it to
1039    /// `prompt.len()` because the plain loop penalised the generated
1040    /// tokens alone. Both now go through `PenaltyWindow`, and this test
1041    /// is what notices if one of them stops.
1042    ///
1043    /// Greedy on purpose: the assertion is token-for-token equality, so
1044    /// a one-token disagreement in the window is a hard failure rather
1045    /// than a shift in a sampled distribution. The prompt repeats
1046    /// tokens 1 and 2, so the penalty has something to bite on from the
1047    /// very first generated position.
1048    #[test]
1049    fn speculation_and_plain_decoding_penalise_the_same_window() {
1050        let cfg = tiny_test_config();
1051        let vocab = 6;
1052        let prompt = vec![0usize, 1, 2, 3, 1];
1053        let max_new = 6;
1054        let params = SamplingParams {
1055            temperature: 0.0,
1056            repetition_penalty: 3.0,
1057            penalty_last_n: 8,
1058            ..SamplingParams::default()
1059        };
1060
1061        let decoder = Decoder::new_random_small(cfg, 2, vocab);
1062
1063        // Plain token-at-a-time decoding, penalising over the same
1064        // window `Sampler::sample` would use on any decode loop.
1065        let mut kv = caches(&decoder);
1066        let mut pos = 0usize;
1067        let mut logits = Vec::new();
1068        for &tok in &prompt {
1069            logits = decoder.forward_token(tok, pos, &mut kv);
1070            pos += 1;
1071        }
1072        let mut sampler = Sampler::new(7);
1073        let mut plain: Vec<usize> = Vec::new();
1074        for _ in 0..max_new {
1075            let next = sampler.sample(&logits, &params, PenaltyWindow::new(&prompt, &plain));
1076            plain.push(next);
1077            logits = decoder.forward_token(next, pos, &mut kv);
1078            pos += 1;
1079        }
1080
1081        let mut speculator = PromptLookupSpeculator::new(2, 3);
1082        let mut spec_kv = caches(&decoder);
1083        let out = speculative_decode_with(
1084            &decoder,
1085            &prompt,
1086            &mut spec_kv,
1087            &mut speculator,
1088            &SpeculativeOptions {
1089                max_new_tokens: max_new,
1090                sampling: params.clone(),
1091                seed: 7,
1092                ..SpeculativeOptions::default()
1093            },
1094        );
1095        assert_eq!(
1096            out.generated_tokens, plain,
1097            "speculation changed the text at --repeat-penalty {}",
1098            params.repetition_penalty
1099        );
1100
1101        // And the penalty is doing something here, or the equality
1102        // above is satisfied by a window nobody reads.
1103        let mut off = params.clone();
1104        off.repetition_penalty = 1.0;
1105        let mut kv = caches(&decoder);
1106        let mut pos = 0usize;
1107        let mut logits = Vec::new();
1108        for &tok in &prompt {
1109            logits = decoder.forward_token(tok, pos, &mut kv);
1110            pos += 1;
1111        }
1112        let mut sampler = Sampler::new(7);
1113        let mut unpenalised: Vec<usize> = Vec::new();
1114        for _ in 0..max_new {
1115            let next = sampler.sample(&logits, &off, PenaltyWindow::new(&prompt, &unpenalised));
1116            unpenalised.push(next);
1117            logits = decoder.forward_token(next, pos, &mut kv);
1118            pos += 1;
1119        }
1120        assert_ne!(
1121            unpenalised, plain,
1122            "the penalty must change this generation, or the agreement above proves nothing"
1123        );
1124    }
1125
1126    #[test]
1127    fn speculative_decode_at_temperature_matches_plain_sampling() {
1128        // The end-to-end half of the losslessness claim, and the one
1129        // the old argmax accept test fails: at temperature > 0 the
1130        // per-position output distribution of speculative decoding must
1131        // equal that of plain token-at-a-time sampling from the same
1132        // target. Argmax matching passes every other test in this file
1133        // and fails this one, because accepting a draft only when it is
1134        // the target's most likely token pushes mass onto the argmax.
1135        let cfg = tiny_test_config();
1136        let vocab = 6;
1137        let prompt = vec![1usize, 2, 3, 1, 2];
1138        let max_new = 3;
1139        let params = SamplingParams {
1140            temperature: 1.0,
1141            ..SamplingParams::default()
1142        };
1143        let seeds = 4_000u64;
1144
1145        let decoder = Decoder::new_random_small(cfg, 1, vocab);
1146        let mut speculator = PromptLookupSpeculator::new(2, 3);
1147        let exact = exact_marginals(&decoder, &prompt, &params, max_new, vocab);
1148
1149        let mut spec_counts = vec![vec![0usize; vocab]; max_new];
1150        for seed in 0..seeds {
1151            let mut kv = caches(&decoder);
1152            let out = speculative_decode_with(
1153                &decoder,
1154                &prompt,
1155                &mut kv,
1156                &mut speculator,
1157                &SpeculativeOptions {
1158                    max_new_tokens: max_new,
1159                    sampling: params.clone(),
1160                    seed,
1161                    ..SpeculativeOptions::default()
1162                },
1163            );
1164            for (i, &t) in out.generated_tokens.iter().enumerate() {
1165                spec_counts[i][t] += 1;
1166            }
1167        }
1168
1169        for i in 0..max_new {
1170            let tv: f64 = (0..vocab)
1171                .map(|t| (spec_counts[i][t] as f64 / seeds as f64 - exact[i][t]).abs())
1172                .sum::<f64>()
1173                / 2.0;
1174            assert!(
1175                tv < 0.03,
1176                "position {i}: speculative sampling drifted from the target's own \
1177                 distribution (total variation {tv:.4})\n  speculative = {:?}\n  exact = {:?}",
1178                spec_counts[i]
1179                    .iter()
1180                    .map(|&c| c as f64 / seeds as f64)
1181                    .collect::<Vec<_>>(),
1182                exact[i]
1183            );
1184        }
1185    }
1186
1187    #[test]
1188    fn speculative_decode_saves_real_calls_when_drafts_hit() {
1189        let cfg = tiny_test_config();
1190        let vocab = 8;
1191        let prompt = vec![1usize, 2, 3, 1, 2];
1192        let max_new = 8;
1193
1194        let decoder = Decoder::new_random_small(cfg, 2, vocab);
1195        let mut kv = caches(&decoder);
1196        let mut speculator = PromptLookupSpeculator::new(2, 4);
1197        let result = speculative_decode(&decoder, &prompt, max_new, &mut kv, &mut speculator);
1198
1199        assert_eq!(result.tokens_generated, max_new);
1200        // Plain sequential decode needs exactly `max_new` calls here:
1201        // one prefill plus one per token except the last, whose KV is
1202        // never needed. Speculation must never need more.
1203        assert!(
1204            result.forward_calls <= max_new,
1205            "speculative decode must never need MORE forward_batch calls than plain \
1206             sequential decode would (calls={}, tokens={})",
1207            result.forward_calls,
1208            max_new
1209        );
1210    }
1211
1212    #[test]
1213    fn speculative_decode_with_no_repeats_falls_back_to_one_token_per_call() {
1214        // A prompt with no internal repeats at all must still work
1215        // correctly, just without any speedup.
1216        let cfg = tiny_test_config();
1217        let vocab = 8;
1218        let prompt = vec![1usize, 2, 3];
1219        let max_new = 5;
1220
1221        let decoder = Decoder::new_random_small(cfg, 2, vocab);
1222        let mut kv = caches(&decoder);
1223        let mut speculator = PromptLookupSpeculator::new(10, 4); // ngram far longer than any possible history
1224        let result = speculative_decode(&decoder, &prompt, max_new, &mut kv, &mut speculator);
1225
1226        assert_eq!(result.tokens_generated, max_new);
1227        assert_eq!(
1228            result.forward_calls,
1229            1 + max_new - 1,
1230            "prefill (1 call) + one call per token, minus the last token, whose KV is \
1231             never needed because generation stopped"
1232        );
1233        assert_eq!(result.drafted_tokens, 0);
1234        assert_eq!(result.accept_rate(), None);
1235    }
1236
1237    // ---- drafter trait plumbing ----
1238
1239    #[test]
1240    fn the_drafter_is_asked_to_continue_the_anchor_token() {
1241        // The block the drafter proposes lands *after* the pending
1242        // token, so the history it sees must already contain it.
1243        // Drafting from a history that stopped one token short would
1244        // shift every proposal by one position and quietly halve the
1245        // accept rate without breaking any output-correctness test.
1246        let cfg = tiny_test_config();
1247        let decoder = Decoder::new_random_small(cfg, 2, 8);
1248        let mut kv = caches(&decoder);
1249        let prompt = vec![1usize, 2, 3];
1250        let mut drafter = FixedDrafter::new(DraftBlock::deterministic(vec![5, 6]));
1251
1252        let result = speculative_decode(&decoder, &prompt, 4, &mut kv, &mut drafter);
1253
1254        let seen = drafter.seen_history.borrow();
1255        assert!(!seen.is_empty(), "the drafter must actually be consulted");
1256        for (round, history) in seen.iter().enumerate() {
1257            assert_eq!(
1258                history.len(),
1259                prompt.len() + round + 1,
1260                "round {round}: history must grow by the committed tokens"
1261            );
1262            assert_eq!(
1263                history[..prompt.len()],
1264                prompt[..],
1265                "the prompt must stay at the front of the drafter's history"
1266            );
1267        }
1268        assert_eq!(seen[0][prompt.len()], result.generated_tokens[0]);
1269    }
1270
1271    #[test]
1272    fn the_drafter_receives_the_targets_hidden_state() {
1273        // The conditioning tensor dFlash/EAGLE need. It is already
1274        // computed by verification; the trait exists so it stops being
1275        // discarded.
1276        let cfg = tiny_test_config();
1277        let hidden_dim = cfg.hidden_dim;
1278        let decoder = Decoder::new_random_small(cfg, 2, 8);
1279        let mut kv = caches(&decoder);
1280        let mut drafter = FixedDrafter::new(DraftBlock::deterministic(vec![5, 6]));
1281
1282        speculative_decode(&decoder, &[1usize, 2, 3], 4, &mut kv, &mut drafter);
1283
1284        let lens = drafter.seen_hidden_len.borrow();
1285        assert!(!lens.is_empty());
1286        for len in lens.iter() {
1287            assert_eq!(
1288                *len, hidden_dim,
1289                "every round must pass a full target hidden state, not an empty slice"
1290            );
1291        }
1292    }
1293
1294    // ---- cache resume + rollback arithmetic ----
1295
1296    #[test]
1297    fn resuming_a_warm_cache_gives_the_same_tokens_as_one_fresh_run() {
1298        // The serving shape: a prefix cache hands the decode loop a
1299        // cache that already holds part of the context.
1300        let cfg = tiny_test_config();
1301        let vocab = 8;
1302        let decoder = Decoder::new_random_small(cfg, 2, vocab);
1303        let mut speculator = PromptLookupSpeculator::new(2, 3);
1304        let full_prompt = vec![1usize, 2, 3, 4, 1, 2];
1305        let max_new = 6;
1306
1307        let mut fresh = caches(&decoder);
1308        let cold = speculative_decode(&decoder, &full_prompt, max_new, &mut fresh, &mut speculator);
1309
1310        // Warm: feed the first 4 prompt tokens through the decoder
1311        // first, then resume speculative decoding from position 4.
1312        let split = 4;
1313        let mut warm = caches(&decoder);
1314        decoder.forward_batch(&full_prompt[..split], 0, &mut warm);
1315        let resumed = speculative_decode_with(
1316            &decoder,
1317            &full_prompt[split..],
1318            &mut warm,
1319            &mut speculator,
1320            &SpeculativeOptions {
1321                max_new_tokens: max_new,
1322                start_pos: split,
1323                ..SpeculativeOptions::default()
1324            },
1325        );
1326
1327        assert_eq!(
1328            resumed.generated_tokens, cold.generated_tokens,
1329            "resuming a warm cache must not change the output"
1330        );
1331    }
1332
1333    #[test]
1334    fn rolls_back_to_absolute_positions_on_a_warm_cache() {
1335        // Rollback lengths are absolute cache lengths, not offsets from
1336        // the start of this call. With a warm cache the two differ by
1337        // start_pos, and a rollback that used the offset would truncate
1338        // into the caller's context. Forced rejections every round make
1339        // the rollback path run every round.
1340        let cfg = tiny_test_config();
1341        let decoder = Decoder::new_random_small(cfg, 2, 8);
1342        // Token 7 is a fixed guess; whether it is accepted is up to the
1343        // model, but the invariant below holds either way.
1344        let mut drafter = FixedDrafter::new(DraftBlock::deterministic(vec![7, 7, 7]));
1345        let context = vec![1usize, 2, 3, 4];
1346        let prompt = vec![5usize, 6];
1347        let max_new = 6;
1348
1349        let mut kv = caches(&decoder);
1350        decoder.forward_batch(&context, 0, &mut kv);
1351        assert_eq!(kv[0].seq_len, context.len());
1352
1353        let result = speculative_decode_with(
1354            &decoder,
1355            &prompt,
1356            &mut kv,
1357            &mut drafter,
1358            &SpeculativeOptions {
1359                max_new_tokens: max_new,
1360                start_pos: context.len(),
1361                ..SpeculativeOptions::default()
1362            },
1363        );
1364
1365        assert_eq!(result.tokens_generated, max_new);
1366        // Exact invariant: the cache holds the context, the prompt and
1367        // every generated token except the last (whose KV is not
1368        // computed until it is fed).
1369        let expected = context.len() + prompt.len() + result.tokens_generated - 1;
1370        for cache in kv.iter() {
1371            assert_eq!(
1372                cache.seq_len,
1373                expected,
1374                "cache length must be absolute: context {} + prompt {} + generated {} - 1",
1375                context.len(),
1376                prompt.len(),
1377                result.tokens_generated
1378            );
1379        }
1380    }
1381
1382    #[test]
1383    fn a_resumed_run_continues_a_previous_one() {
1384        // Two back-to-back calls on the same caches must equal one long
1385        // call: this is what "not a demo" means for the serving path.
1386        let cfg = tiny_test_config();
1387        let decoder = Decoder::new_random_small(cfg, 2, 8);
1388        let mut speculator = PromptLookupSpeculator::new(2, 3);
1389        let prompt = vec![1usize, 2, 3, 4, 1, 2];
1390
1391        let mut one = caches(&decoder);
1392        let long = speculative_decode(&decoder, &prompt, 8, &mut one, &mut speculator);
1393
1394        let mut kv = caches(&decoder);
1395        let first = speculative_decode(&decoder, &prompt, 4, &mut kv, &mut speculator);
1396        // The last generated token's KV is not in the cache yet, so it
1397        // is the first token of the continuation's "prompt".
1398        let resume_prompt = vec![*first.generated_tokens.last().unwrap()];
1399        let start = prompt.len() + first.tokens_generated - 1;
1400        let second = speculative_decode_with(
1401            &decoder,
1402            &resume_prompt,
1403            &mut kv,
1404            &mut speculator,
1405            &SpeculativeOptions {
1406                max_new_tokens: 5,
1407                start_pos: start,
1408                ..SpeculativeOptions::default()
1409            },
1410        );
1411
1412        let mut stitched = first.generated_tokens.clone();
1413        stitched.pop(); // re-fed as the continuation's prompt
1414        stitched.extend_from_slice(&second.generated_tokens);
1415        assert_eq!(
1416            &stitched[..8],
1417            &long.generated_tokens[..],
1418            "a decode split across two calls must equal the same decode in one"
1419        );
1420    }
1421
1422    #[test]
1423    #[should_panic(expected = "start_pos must be the caches' current length")]
1424    fn a_mismatched_start_pos_is_refused_rather_than_silently_wrong() {
1425        let cfg = tiny_test_config();
1426        let decoder = Decoder::new_random_small(cfg, 2, 8);
1427        let mut kv = caches(&decoder);
1428        decoder.forward_batch(&[1usize, 2, 3], 0, &mut kv);
1429        let mut speculator = PromptLookupSpeculator::new(2, 2);
1430        speculative_decode(&decoder, &[4usize, 5], 2, &mut kv, &mut speculator);
1431    }
1432
1433    // ---- acceptance metrics ----
1434
1435    #[test]
1436    fn per_position_accept_rates_expose_suffix_decay() {
1437        // A drafter whose first guess is always right and whose later
1438        // guesses are always wrong has the same mean accept rate as one
1439        // that is uniformly mediocre. Only the per-position curve tells
1440        // them apart, which is the whole reason it exists.
1441        let mut result = SpeculativeDecodeResult::default();
1442        for _ in 0..100 {
1443            result.record_position(0, true);
1444            result.record_position(1, false);
1445        }
1446        result.verification_steps = 100;
1447        result.tokens_generated = 200;
1448
1449        assert_eq!(result.accept_rate(), Some(0.5));
1450        assert_eq!(result.accept_rate_per_position(), vec![1.0, 0.0]);
1451        assert_eq!(result.acceptance_length(), Some(2.0));
1452    }
1453
1454    #[test]
1455    fn positions_after_a_rejection_are_not_counted_as_drafted() {
1456        // A round that rejects at position 0 never evaluates positions
1457        // 1..k. Counting them would report an accept rate that falls
1458        // with the block size rather than with the drafter's accuracy.
1459        let cfg = tiny_test_config();
1460        let decoder = Decoder::new_random_small(cfg, 2, 8);
1461        let mut kv = caches(&decoder);
1462        // Token 7 against a random model: whatever happens, every
1463        // counted position must have been reachable.
1464        let mut drafter = FixedDrafter::new(DraftBlock::deterministic(vec![7, 7, 7, 7]));
1465        let result = speculative_decode(&decoder, &[1usize, 2, 3], 6, &mut kv, &mut drafter);
1466
1467        let evaluated = &result.evaluated_at_position;
1468        let accepted = &result.accepted_at_position;
1469        assert!(
1470            result.drafted_tokens > result.accepted_tokens,
1471            "the scenario is pointless unless something was actually rejected \
1472             (drafted {}, accepted {})",
1473            result.drafted_tokens,
1474            result.accepted_tokens
1475        );
1476        // The sharp invariant: position i+1 is only reached when
1477        // position i was accepted, so it can never have been evaluated
1478        // more often. Merely checking that the counts are
1479        // non-increasing is not enough -- crediting every position of
1480        // every proposed block, rejected or not, keeps them
1481        // non-increasing (it makes them equal) while reporting an
1482        // accept rate that decays with the block size rather than with
1483        // the drafter.
1484        for (i, &seen) in evaluated.iter().enumerate().skip(1) {
1485            assert!(
1486                seen <= accepted[i - 1],
1487                "position {i} was evaluated {seen} times but position {} was only \
1488                 accepted {} times: evaluated={evaluated:?} accepted={accepted:?}",
1489                i - 1,
1490                accepted[i - 1]
1491            );
1492        }
1493        assert_eq!(
1494            result.drafted_tokens,
1495            evaluated.iter().sum::<usize>(),
1496            "drafted_tokens must be the per-position counts' total"
1497        );
1498        assert_eq!(
1499            result.accepted_tokens,
1500            result.accepted_at_position.iter().sum::<usize>()
1501        );
1502        assert!(result.accepted_tokens <= result.drafted_tokens);
1503    }
1504
1505    #[test]
1506    fn acceptance_length_is_reported_per_verification_step_not_per_call() {
1507        // The published metric divides by verification steps; charging
1508        // the one-off prefill against it understates short runs.
1509        let cfg = tiny_test_config();
1510        let decoder = Decoder::new_random_small(cfg, 2, 8);
1511        let mut kv = caches(&decoder);
1512        let mut speculator = PromptLookupSpeculator::new(2, 3);
1513        let result =
1514            speculative_decode(&decoder, &[1usize, 2, 3, 1, 2], 6, &mut kv, &mut speculator);
1515
1516        assert_eq!(result.verification_steps, result.forward_calls - 1);
1517        let length = result.acceptance_length().unwrap();
1518        assert!(length >= 1.0, "every verification step commits >= 1 token");
1519        assert!(
1520            length > result.tokens_per_call(),
1521            "acceptance length must not be diluted by the prefill call"
1522        );
1523    }
1524
1525    #[test]
1526    fn an_empty_run_reports_no_acceptance_length_rather_than_zero() {
1527        let result = SpeculativeDecodeResult::default();
1528        assert_eq!(result.acceptance_length(), None);
1529        assert_eq!(result.accept_rate(), None);
1530        assert_eq!(result.tokens_per_call(), 0.0);
1531    }
1532
1533    /// The observer sees exactly the committed tokens, in order, and
1534    /// stopping through it truncates the result to the token that said
1535    /// so.
1536    ///
1537    /// This is what lets `ferrox run` stream and stop on an EOS without
1538    /// a second copy of the verification loop. A copy is how this
1539    /// project lost five model features from one duplicated decode
1540    /// path, and the rejection rule is the last code in the tree that
1541    /// should be duplicated: a subtly wrong copy still looks lossless.
1542    #[test]
1543    fn the_observer_sees_every_committed_token_and_can_end_the_run() {
1544        let cfg = tiny_test_config();
1545        let vocab = 8;
1546        let prompt = vec![1usize, 2, 3, 4, 1, 2];
1547
1548        let decoder = Decoder::new_random_small(cfg.clone(), 2, vocab);
1549        let mut kv = caches(&decoder);
1550        let mut spec = PromptLookupSpeculator::new(2, 3);
1551
1552        let mut seen = Vec::new();
1553        let result = speculative_decode_observed(
1554            &decoder,
1555            &prompt,
1556            &mut kv,
1557            &mut spec,
1558            &mut |t| {
1559                seen.push(t);
1560                true
1561            },
1562            &SpeculativeOptions {
1563                max_new_tokens: 6,
1564                start_pos: 0,
1565                sampling: SamplingParams::default(),
1566                seed: 0,
1567            },
1568        );
1569        assert_eq!(
1570            seen, result.generated_tokens,
1571            "the observer must see exactly what the run returns, in order"
1572        );
1573
1574        // Now stop after three tokens.
1575        let decoder = Decoder::new_random_small(cfg, 2, vocab);
1576        let mut kv = caches(&decoder);
1577        let mut spec = PromptLookupSpeculator::new(2, 3);
1578        let mut count = 0usize;
1579        let stopped = speculative_decode_observed(
1580            &decoder,
1581            &prompt,
1582            &mut kv,
1583            &mut spec,
1584            &mut |_| {
1585                count += 1;
1586                count < 3
1587            },
1588            &SpeculativeOptions {
1589                max_new_tokens: 6,
1590                start_pos: 0,
1591                sampling: SamplingParams::default(),
1592                seed: 0,
1593            },
1594        );
1595        assert_eq!(
1596            stopped.generated_tokens.len(),
1597            3,
1598            "the run must end at the token that said stop, not at the end of its block"
1599        );
1600        assert_eq!(
1601            stopped.generated_tokens,
1602            result.generated_tokens[..3],
1603            "and the tokens up to the stop must be the ones an unstopped run produced"
1604        );
1605    }
1606}