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.positions(),
552            options.start_pos,
553            "start_pos must be the caches' current length: they hold exactly the \
554             context preceding the prompt"
555        );
556    }
557
558    let mut result = SpeculativeDecodeResult::default();
559    if options.max_new_tokens == 0 {
560        return result;
561    }
562
563    let mut rng = Sampler::new(options.seed);
564    let mut history: Vec<usize> = prompt_tokens.to_vec();
565    let mut generated: Vec<usize> = Vec::with_capacity(options.max_new_tokens);
566
567    // Prefill: one batched call over the whole prompt.
568    let (prefill_logits, prefill_hidden) =
569        decoder.forward_batch_with_hidden(prompt_tokens, options.start_pos, kv_caches);
570    result.forward_calls += 1;
571    let last = prefill_logits
572        .last()
573        .expect("prompt_tokens is non-empty, so forward_batch returns at least one logits vector");
574    let mut target_hidden = prefill_hidden.last().cloned().unwrap_or_default();
575
576    // `pending` is decided but its KV is not in the cache yet: it is
577    // fed as the anchor of the next batch, which is what lets one
578    // forward call both commit it and verify a block after it.
579    let mut pending = {
580        // Split ONE structure rather than pairing `history` with the
581        // separate `generated` vector: the two would then have to agree
582        // about every push, which is exactly the shape this fix exists
583        // to remove.
584        let (seen_prompt, seen_generated) = history.split_at(prompt_tokens.len());
585        let xtc_roll = rng.xtc_roll(&options.sampling);
586        let probs = sampling_distribution(
587            last,
588            &options.sampling,
589            PenaltyWindow::new(seen_prompt, seen_generated),
590            xtc_roll,
591        );
592        rng.sample_from(&probs)
593    };
594    let mut pos = options.start_pos + prompt_tokens.len();
595
596    // Set when the observer asks to stop. The current block still runs
597    // to completion so the caches end in the one state this function
598    // documents, and `generated` is cut back to this length afterwards.
599    let mut stop_at: Option<usize> = None;
600
601    loop {
602        generated.push(pending);
603        history.push(pending);
604        if !on_token(pending) {
605            stop_at = Some(generated.len());
606            break;
607        }
608        if generated.len() == options.max_new_tokens {
609            break;
610        }
611        // One short of the remaining budget on purpose: the last token
612        // of the run is always committed as an anchor at the top of the
613        // loop, never as an accepted draft. That keeps the cache in
614        // exactly one state on return (see the doc comment) instead of
615        // one state when the budget runs out on an anchor and another
616        // when it runs out mid-block -- and it costs nothing, because
617        // the drafted position it gives up is one whose KV would have
618        // had to be discarded anyway.
619        let draft_budget = options.max_new_tokens - generated.len() - 1;
620
621        // The drafter is asked to continue a history that *includes*
622        // `pending`, because the first drafted token lands at pos + 1.
623        let mut draft = drafter.propose(&history, &target_hidden, draft_budget);
624        draft.truncate(draft_budget);
625
626        let mut batch = Vec::with_capacity(1 + draft.len());
627        batch.push(pending);
628        batch.extend_from_slice(draft.tokens());
629
630        let (batch_logits, batch_hidden) =
631            decoder.forward_batch_with_hidden(&batch, pos, kv_caches);
632        result.forward_calls += 1;
633        result.verification_steps += 1;
634
635        // batch_logits[i] is the target's distribution for the position
636        // right after batch[i], i.e. the distribution draft token i
637        // should be judged against.
638        let mut accepted = 0usize;
639        let mut replacement: Option<usize> = None;
640        for (i, (&token, dist)) in draft.tokens().iter().zip(draft.dists()).enumerate() {
641            let (seen_prompt, seen_generated) = history.split_at(prompt_tokens.len());
642            let xtc_roll = rng.xtc_roll(&options.sampling);
643            let target = sampling_distribution(
644                &batch_logits[i],
645                &options.sampling,
646                PenaltyWindow::new(seen_prompt, seen_generated),
647                xtc_roll,
648            );
649            match accept_or_resample(&target, dist, token, &mut rng) {
650                None => {
651                    result.record_position(i, true);
652                    accepted += 1;
653                    history.push(token);
654                    generated.push(token);
655                    if stop_at.is_none() && !on_token(token) {
656                        // Keep verifying the rest of the block: the
657                        // loop below truncates the caches to exactly
658                        // what was committed, and leaving early here
659                        // would skip that.
660                        stop_at = Some(generated.len());
661                    }
662                }
663                Some(resampled) => {
664                    result.record_position(i, false);
665                    replacement = Some(resampled);
666                    break;
667                }
668            }
669        }
670
671        // Every position past `accepted` was computed from a token that
672        // is not going to be committed, so its KV is wrong. Lengths are
673        // absolute, which is what makes a warm cache work: `pos` is
674        // already offset by start_pos.
675        let committed_len = pos + 1 + accepted;
676        if accepted < draft.len() {
677            for cache in kv_caches.iter_mut() {
678                cache.truncate(committed_len);
679            }
680        }
681        // POSITIONS: `committed_len` is absolute, offset by start_pos.
682        debug_assert!(kv_caches.iter().all(|c| c.positions() == committed_len));
683
684        target_hidden = batch_hidden[accepted].clone();
685        pending = match replacement {
686            // A rejected position was resampled from the residual; that
687            // token is committed and becomes the next anchor.
688            Some(tok) => tok,
689            // Every draft token was accepted, so the last row of the
690            // batch predicts a genuinely new position -- the free bonus
691            // token that makes a fully-accepted block worth `k + 1`.
692            None => {
693                let (seen_prompt, seen_generated) = history.split_at(prompt_tokens.len());
694                let xtc_roll = rng.xtc_roll(&options.sampling);
695                let probs = sampling_distribution(
696                    &batch_logits[accepted],
697                    &options.sampling,
698                    PenaltyWindow::new(seen_prompt, seen_generated),
699                    xtc_roll,
700                );
701                rng.sample_from(&probs)
702            }
703        };
704        pos = committed_len;
705        if stop_at.is_some() {
706            break;
707        }
708        debug_assert!(generated.len() < options.max_new_tokens);
709    }
710
711    if let Some(len) = stop_at {
712        // The observer said stop at this token. Everything after it was
713        // produced by a block that had already been dispatched, and the
714        // caller never saw it.
715        generated.truncate(len);
716    } else {
717        debug_assert_eq!(generated.len(), options.max_new_tokens);
718    }
719    result.tokens_generated = generated.len();
720    result.generated_tokens = generated;
721    result
722}
723
724#[cfg(test)]
725mod tests {
726    use super::*;
727    use crate::config::glm_5_2;
728    use crate::ModelConfig;
729    use std::cell::RefCell;
730
731    fn tiny_test_config() -> ModelConfig {
732        let mut cfg = glm_5_2();
733        cfg.hidden_dim = 16;
734        cfg.n_heads = 4;
735        cfg.n_kv_heads = 2;
736        cfg.head_dim = 4;
737        cfg.moe.hidden_dim = 16;
738        cfg.moe.n_experts = 6;
739        cfg.moe.n_experts_active = 2;
740        cfg.moe.n_shared_experts = 1;
741        cfg.moe.expert_ffn_dim = 8;
742        cfg
743    }
744
745    fn caches(decoder: &Decoder) -> Vec<KvCache> {
746        (0..decoder.layers.len())
747            .map(|_| KvCache::new(decoder.config.n_kv_heads, decoder.config.head_dim))
748            .collect()
749    }
750
751    fn argmax(logits: &[f32]) -> usize {
752        logits
753            .iter()
754            .enumerate()
755            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
756            .map(|(i, _)| i)
757            .unwrap_or(0)
758    }
759
760    /// A drafter that always proposes the same block, with a
761    /// configurable draft distribution, and records the history it was
762    /// asked about.
763    struct FixedDrafter {
764        block: DraftBlock,
765        seen_history: RefCell<Vec<Vec<usize>>>,
766        seen_hidden_len: RefCell<Vec<usize>>,
767    }
768
769    impl FixedDrafter {
770        fn new(block: DraftBlock) -> Self {
771            FixedDrafter {
772                block,
773                seen_history: RefCell::new(Vec::new()),
774                seen_hidden_len: RefCell::new(Vec::new()),
775            }
776        }
777    }
778
779    impl Drafter for FixedDrafter {
780        fn propose(
781            &mut self,
782            history: &[usize],
783            target_hidden: &[f32],
784            max_len: usize,
785        ) -> DraftBlock {
786            self.seen_history.borrow_mut().push(history.to_vec());
787            self.seen_hidden_len.borrow_mut().push(target_hidden.len());
788            let mut block = self.block.clone();
789            block.truncate(max_len);
790            block
791        }
792    }
793
794    // ---- PromptLookupSpeculator tests ----
795
796    #[test]
797    fn proposes_the_continuation_after_a_real_repeat() {
798        let mut spec = PromptLookupSpeculator::new(2, 4);
799        // "...1 2 3 4 5 9 9 9 1 2" -> earlier "1 2" occurs at the very
800        // start (indices 0-1); the 4 tokens that followed it are
801        // "3 4 5 9" (capped at max_draft_len=4).
802        let history = vec![1, 2, 3, 4, 5, 9, 9, 9, 1, 2];
803        assert_eq!(spec.propose_tokens(&history), vec![3, 4, 5, 9]);
804        assert_eq!(
805            spec.propose(&history, &[], 8),
806            DraftBlock::deterministic(vec![3, 4, 5, 9])
807        );
808    }
809
810    #[test]
811    fn respects_max_draft_len() {
812        let spec = PromptLookupSpeculator::new(2, 2);
813        let history = vec![1, 2, 3, 4, 5, 6, 7, 1, 2];
814        assert_eq!(spec.propose_tokens(&history), vec![3, 4]);
815    }
816
817    #[test]
818    fn returns_empty_when_no_earlier_match_exists() {
819        let spec = PromptLookupSpeculator::new(2, 4);
820        let history = vec![1, 2, 3, 4, 5];
821        assert_eq!(spec.propose_tokens(&history), Vec::<usize>::new());
822    }
823
824    #[test]
825    fn returns_empty_when_history_too_short() {
826        let spec = PromptLookupSpeculator::new(3, 4);
827        let history = vec![1, 2, 3];
828        assert_eq!(spec.propose_tokens(&history), Vec::<usize>::new());
829    }
830
831    #[test]
832    fn finds_the_most_recent_match_when_several_exist() {
833        let spec = PromptLookupSpeculator::new(1, 3);
834        // needle = [9]. Earlier occurrences at index 0 (-> [8,7,6]) and
835        // index 4 (-> [5,4,9]); most recent (index 4) should win.
836        let history = vec![9, 8, 7, 6, 9, 5, 4, 9];
837        assert_eq!(spec.propose_tokens(&history), vec![5, 4, 9]);
838    }
839
840    #[test]
841    fn the_trait_caps_a_block_at_the_callers_budget() {
842        let mut spec = PromptLookupSpeculator::new(2, 4);
843        let history = vec![1, 2, 3, 4, 5, 9, 9, 9, 1, 2];
844        let block = spec.propose(&history, &[], 2);
845        assert_eq!(block.tokens(), &[3, 4]);
846        assert_eq!(block.dists().len(), 2);
847    }
848
849    // ---- the rejection rule ----
850
851    #[test]
852    fn a_draft_at_least_as_likely_under_the_target_is_always_accepted() {
853        let target = vec![0.6f32, 0.3, 0.1];
854        let draft = DraftDist::from_dense(&[0.5, 0.4, 0.1]);
855        let mut rng = Sampler::new(1);
856        for _ in 0..100 {
857            // p(0)=0.6 >= q(0)=0.5, so token 0 is never rejected.
858            assert_eq!(accept_or_resample(&target, &draft, 0, &mut rng), None);
859        }
860    }
861
862    #[test]
863    fn a_draft_the_target_rules_out_is_always_rejected() {
864        let target = vec![0.5f32, 0.5, 0.0];
865        let draft = DraftDist::deterministic(2);
866        let mut rng = Sampler::new(2);
867        for _ in 0..50 {
868            let replacement = accept_or_resample(&target, &draft, 2, &mut rng);
869            let tok = replacement.expect("p(2) = 0 means token 2 can never be accepted");
870            assert!(tok < 2, "residual must never resample the rejected token");
871        }
872    }
873
874    #[test]
875    fn resampling_reproduces_the_target_distribution() {
876        // THE invariant. Draw a token from the draft distribution, run
877        // it through the accept/reject rule, and the result must be
878        // distributed as the TARGET, no matter how bad the draft is.
879        //
880        // A test that only checked "it runs" would pass on the old
881        // argmax rule, which concentrates mass on the target's argmax
882        // and is not the target distribution at all.
883        let target = vec![0.30f32, 0.25, 0.20, 0.15, 0.07, 0.03];
884        let drafts = [
885            // A drafter that is simply wrong about which token is likely.
886            DraftDist::from_dense(&[0.02, 0.03, 0.05, 0.10, 0.30, 0.50]),
887            // A deterministic drafter, i.e. prompt lookup.
888            DraftDist::deterministic(3),
889            // A drafter whose support misses most of the target's.
890            DraftDist::from_support(vec![(0, 0.5), (5, 0.5)]),
891            // A perfect drafter.
892            DraftDist::from_dense(&target),
893        ];
894        let draws = 200_000;
895        for (d, draft) in drafts.iter().enumerate() {
896            let mut rng = Sampler::new(0xA11CE + d as u64);
897            let mut counts = vec![0usize; target.len()];
898            for _ in 0..draws {
899                // Sample the draft token from the draft distribution --
900                // the rule is only lossless when q is honest about
901                // where the token came from.
902                let dense = {
903                    let mut v = vec![0.0f32; target.len()];
904                    for &(t, p) in draft.support() {
905                        v[t] = p;
906                    }
907                    v
908                };
909                let x = rng.sample_from(&dense);
910                let out = accept_or_resample(&target, draft, x, &mut rng).unwrap_or(x);
911                counts[out] += 1;
912            }
913            let tv: f64 = counts
914                .iter()
915                .enumerate()
916                .map(|(i, &c)| (c as f64 / draws as f64 - target[i] as f64).abs())
917                .sum::<f64>()
918                / 2.0;
919            assert!(
920                tv < 0.01,
921                "draft {d}: speculative output distribution differs from the target \
922                 (total variation {tv:.4}); counts={counts:?}"
923            );
924        }
925    }
926
927    // ---- speculative_decode correctness tests ----
928
929    #[test]
930    fn speculative_decode_matches_greedy_token_for_token() {
931        // Quality-neutrality at temperature 0: token-for-token identity
932        // against a plain sequential forward_token loop on a
933        // separately constructed but identically-seeded decoder.
934        let cfg = tiny_test_config();
935        let vocab = 8;
936        let prompt = vec![1usize, 2, 3, 4, 1, 2];
937        let max_new = 6;
938
939        let decoder_a = Decoder::new_random_small(cfg.clone(), 2, vocab);
940        let mut caches_a = caches(&decoder_a);
941        let mut speculator = PromptLookupSpeculator::new(2, 3);
942        let result =
943            speculative_decode(&decoder_a, &prompt, max_new, &mut caches_a, &mut speculator);
944
945        let decoder_b = Decoder::new_random_small(cfg, 2, vocab);
946        let mut caches_b = caches(&decoder_b);
947        let mut pending = decoder_b
948            .forward_batch(&prompt, 0, &mut caches_b)
949            .pop()
950            .unwrap();
951        let mut greedy = Vec::with_capacity(max_new);
952        for pos in (prompt.len()..).take(max_new) {
953            let tok = argmax(&pending);
954            greedy.push(tok);
955            pending = decoder_b.forward_token(tok, pos, &mut caches_b);
956        }
957
958        assert_eq!(
959            result.generated_tokens, greedy,
960            "speculative decode must produce exactly the same tokens as plain greedy decode"
961        );
962    }
963
964    /// The exact per-position marginal distributions of plain
965    /// token-at-a-time sampling from `decoder`, by enumerating every
966    /// prefix rather than sampling them. Only tractable because the
967    /// test model has a 6-token vocabulary and the horizon is 3, but
968    /// worth it: the speculative sampler is then compared against the
969    /// truth, not against a second noisy estimate of it.
970    fn exact_marginals(
971        decoder: &Decoder,
972        prompt: &[usize],
973        params: &SamplingParams,
974        depth: usize,
975        vocab: usize,
976    ) -> Vec<Vec<f64>> {
977        #[allow(clippy::too_many_arguments)]
978        fn walk(
979            decoder: &Decoder,
980            kv: &[KvCache],
981            logits: &[f32],
982            history: &mut Vec<usize>,
983            weight: f64,
984            level: usize,
985            depth: usize,
986            pos: usize,
987            params: &SamplingParams,
988            marginals: &mut [Vec<f64>],
989        ) {
990            // `history` is already prompt-then-generated, and the
991            // window only ever reads the tail of the two halves
992            // together, so the whole sequence goes in the first one.
993            // This helper enumerates the exact marginal over every
994            // continuation, so it must not depend on a random draw:
995            // `None` is correct here and only here, because the params
996            // it is called with never enable XTC.
997            debug_assert!(
998                !params.xtc_can_fire(),
999                "the exact marginal is not defined under XTC"
1000            );
1001            let probs =
1002                sampling_distribution(logits, params, PenaltyWindow::new(history, &[]), None);
1003            for (token, &p) in probs.iter().enumerate() {
1004                if p <= 0.0 {
1005                    continue;
1006                }
1007                marginals[level][token] += weight * p as f64;
1008                if level + 1 == depth {
1009                    continue;
1010                }
1011                let mut branch: Vec<KvCache> = kv.to_vec();
1012                let next = decoder.forward_token(token, pos, &mut branch);
1013                history.push(token);
1014                walk(
1015                    decoder,
1016                    &branch,
1017                    &next,
1018                    history,
1019                    weight * p as f64,
1020                    level + 1,
1021                    depth,
1022                    pos + 1,
1023                    params,
1024                    marginals,
1025                );
1026                history.pop();
1027            }
1028        }
1029
1030        let mut marginals = vec![vec![0.0f64; vocab]; depth];
1031        let mut kv = caches(decoder);
1032        let logits = decoder.forward_batch(prompt, 0, &mut kv).pop().unwrap();
1033        let mut history = prompt.to_vec();
1034        walk(
1035            decoder,
1036            &kv,
1037            &logits,
1038            &mut history,
1039            1.0,
1040            0,
1041            depth,
1042            prompt.len(),
1043            params,
1044            &mut marginals,
1045        );
1046        marginals
1047    }
1048
1049    /// Speculation and plain token-at-a-time decoding must agree about
1050    /// WHICH tokens the penalties look back over, including the prompt.
1051    ///
1052    /// This is issue #55's other half. `SpeculativeOptions` used to
1053    /// carry a `penalty_history_start` knob whose only job was to let a
1054    /// caller line the two paths up by hand, which meant nothing failed
1055    /// when they drifted -- and `--model-draft` shipped setting it to
1056    /// `prompt.len()` because the plain loop penalised the generated
1057    /// tokens alone. Both now go through `PenaltyWindow`, and this test
1058    /// is what notices if one of them stops.
1059    ///
1060    /// Greedy on purpose: the assertion is token-for-token equality, so
1061    /// a one-token disagreement in the window is a hard failure rather
1062    /// than a shift in a sampled distribution. The prompt repeats
1063    /// tokens 1 and 2, so the penalty has something to bite on from the
1064    /// very first generated position.
1065    #[test]
1066    fn speculation_and_plain_decoding_penalise_the_same_window() {
1067        let cfg = tiny_test_config();
1068        let vocab = 6;
1069        let prompt = vec![0usize, 1, 2, 3, 1];
1070        let max_new = 6;
1071        let params = SamplingParams {
1072            temperature: 0.0,
1073            repetition_penalty: 3.0,
1074            penalty_last_n: 8,
1075            ..SamplingParams::default()
1076        };
1077
1078        let decoder = Decoder::new_random_small(cfg, 2, vocab);
1079
1080        // Plain token-at-a-time decoding, penalising over the same
1081        // window `Sampler::sample` would use on any decode loop.
1082        let mut kv = caches(&decoder);
1083        let mut pos = 0usize;
1084        let mut logits = Vec::new();
1085        for &tok in &prompt {
1086            logits = decoder.forward_token(tok, pos, &mut kv);
1087            pos += 1;
1088        }
1089        let mut sampler = Sampler::new(7);
1090        let mut plain: Vec<usize> = Vec::new();
1091        for _ in 0..max_new {
1092            let next = sampler.sample(&logits, &params, PenaltyWindow::new(&prompt, &plain));
1093            plain.push(next);
1094            logits = decoder.forward_token(next, pos, &mut kv);
1095            pos += 1;
1096        }
1097
1098        let mut speculator = PromptLookupSpeculator::new(2, 3);
1099        let mut spec_kv = caches(&decoder);
1100        let out = speculative_decode_with(
1101            &decoder,
1102            &prompt,
1103            &mut spec_kv,
1104            &mut speculator,
1105            &SpeculativeOptions {
1106                max_new_tokens: max_new,
1107                sampling: params.clone(),
1108                seed: 7,
1109                ..SpeculativeOptions::default()
1110            },
1111        );
1112        assert_eq!(
1113            out.generated_tokens, plain,
1114            "speculation changed the text at --repeat-penalty {}",
1115            params.repetition_penalty
1116        );
1117
1118        // And the penalty is doing something here, or the equality
1119        // above is satisfied by a window nobody reads.
1120        let mut off = params.clone();
1121        off.repetition_penalty = 1.0;
1122        let mut kv = caches(&decoder);
1123        let mut pos = 0usize;
1124        let mut logits = Vec::new();
1125        for &tok in &prompt {
1126            logits = decoder.forward_token(tok, pos, &mut kv);
1127            pos += 1;
1128        }
1129        let mut sampler = Sampler::new(7);
1130        let mut unpenalised: Vec<usize> = Vec::new();
1131        for _ in 0..max_new {
1132            let next = sampler.sample(&logits, &off, PenaltyWindow::new(&prompt, &unpenalised));
1133            unpenalised.push(next);
1134            logits = decoder.forward_token(next, pos, &mut kv);
1135            pos += 1;
1136        }
1137        assert_ne!(
1138            unpenalised, plain,
1139            "the penalty must change this generation, or the agreement above proves nothing"
1140        );
1141    }
1142
1143    #[test]
1144    fn speculative_decode_at_temperature_matches_plain_sampling() {
1145        // The end-to-end half of the losslessness claim, and the one
1146        // the old argmax accept test fails: at temperature > 0 the
1147        // per-position output distribution of speculative decoding must
1148        // equal that of plain token-at-a-time sampling from the same
1149        // target. Argmax matching passes every other test in this file
1150        // and fails this one, because accepting a draft only when it is
1151        // the target's most likely token pushes mass onto the argmax.
1152        let cfg = tiny_test_config();
1153        let vocab = 6;
1154        let prompt = vec![1usize, 2, 3, 1, 2];
1155        let max_new = 3;
1156        let params = SamplingParams {
1157            temperature: 1.0,
1158            ..SamplingParams::default()
1159        };
1160        let seeds = 4_000u64;
1161
1162        let decoder = Decoder::new_random_small(cfg, 1, vocab);
1163        let mut speculator = PromptLookupSpeculator::new(2, 3);
1164        let exact = exact_marginals(&decoder, &prompt, &params, max_new, vocab);
1165
1166        let mut spec_counts = vec![vec![0usize; vocab]; max_new];
1167        for seed in 0..seeds {
1168            let mut kv = caches(&decoder);
1169            let out = speculative_decode_with(
1170                &decoder,
1171                &prompt,
1172                &mut kv,
1173                &mut speculator,
1174                &SpeculativeOptions {
1175                    max_new_tokens: max_new,
1176                    sampling: params.clone(),
1177                    seed,
1178                    ..SpeculativeOptions::default()
1179                },
1180            );
1181            for (i, &t) in out.generated_tokens.iter().enumerate() {
1182                spec_counts[i][t] += 1;
1183            }
1184        }
1185
1186        for i in 0..max_new {
1187            let tv: f64 = (0..vocab)
1188                .map(|t| (spec_counts[i][t] as f64 / seeds as f64 - exact[i][t]).abs())
1189                .sum::<f64>()
1190                / 2.0;
1191            assert!(
1192                tv < 0.03,
1193                "position {i}: speculative sampling drifted from the target's own \
1194                 distribution (total variation {tv:.4})\n  speculative = {:?}\n  exact = {:?}",
1195                spec_counts[i]
1196                    .iter()
1197                    .map(|&c| c as f64 / seeds as f64)
1198                    .collect::<Vec<_>>(),
1199                exact[i]
1200            );
1201        }
1202    }
1203
1204    #[test]
1205    fn speculative_decode_saves_real_calls_when_drafts_hit() {
1206        let cfg = tiny_test_config();
1207        let vocab = 8;
1208        let prompt = vec![1usize, 2, 3, 1, 2];
1209        let max_new = 8;
1210
1211        let decoder = Decoder::new_random_small(cfg, 2, vocab);
1212        let mut kv = caches(&decoder);
1213        let mut speculator = PromptLookupSpeculator::new(2, 4);
1214        let result = speculative_decode(&decoder, &prompt, max_new, &mut kv, &mut speculator);
1215
1216        assert_eq!(result.tokens_generated, max_new);
1217        // Plain sequential decode needs exactly `max_new` calls here:
1218        // one prefill plus one per token except the last, whose KV is
1219        // never needed. Speculation must never need more.
1220        assert!(
1221            result.forward_calls <= max_new,
1222            "speculative decode must never need MORE forward_batch calls than plain \
1223             sequential decode would (calls={}, tokens={})",
1224            result.forward_calls,
1225            max_new
1226        );
1227    }
1228
1229    #[test]
1230    fn speculative_decode_with_no_repeats_falls_back_to_one_token_per_call() {
1231        // A prompt with no internal repeats at all must still work
1232        // correctly, just without any speedup.
1233        let cfg = tiny_test_config();
1234        let vocab = 8;
1235        let prompt = vec![1usize, 2, 3];
1236        let max_new = 5;
1237
1238        let decoder = Decoder::new_random_small(cfg, 2, vocab);
1239        let mut kv = caches(&decoder);
1240        let mut speculator = PromptLookupSpeculator::new(10, 4); // ngram far longer than any possible history
1241        let result = speculative_decode(&decoder, &prompt, max_new, &mut kv, &mut speculator);
1242
1243        assert_eq!(result.tokens_generated, max_new);
1244        assert_eq!(
1245            result.forward_calls,
1246            1 + max_new - 1,
1247            "prefill (1 call) + one call per token, minus the last token, whose KV is \
1248             never needed because generation stopped"
1249        );
1250        assert_eq!(result.drafted_tokens, 0);
1251        assert_eq!(result.accept_rate(), None);
1252    }
1253
1254    // ---- drafter trait plumbing ----
1255
1256    #[test]
1257    fn the_drafter_is_asked_to_continue_the_anchor_token() {
1258        // The block the drafter proposes lands *after* the pending
1259        // token, so the history it sees must already contain it.
1260        // Drafting from a history that stopped one token short would
1261        // shift every proposal by one position and quietly halve the
1262        // accept rate without breaking any output-correctness test.
1263        let cfg = tiny_test_config();
1264        let decoder = Decoder::new_random_small(cfg, 2, 8);
1265        let mut kv = caches(&decoder);
1266        let prompt = vec![1usize, 2, 3];
1267        let mut drafter = FixedDrafter::new(DraftBlock::deterministic(vec![5, 6]));
1268
1269        let result = speculative_decode(&decoder, &prompt, 4, &mut kv, &mut drafter);
1270
1271        let seen = drafter.seen_history.borrow();
1272        assert!(!seen.is_empty(), "the drafter must actually be consulted");
1273        for (round, history) in seen.iter().enumerate() {
1274            assert_eq!(
1275                history.len(),
1276                prompt.len() + round + 1,
1277                "round {round}: history must grow by the committed tokens"
1278            );
1279            assert_eq!(
1280                history[..prompt.len()],
1281                prompt[..],
1282                "the prompt must stay at the front of the drafter's history"
1283            );
1284        }
1285        assert_eq!(seen[0][prompt.len()], result.generated_tokens[0]);
1286    }
1287
1288    #[test]
1289    fn the_drafter_receives_the_targets_hidden_state() {
1290        // The conditioning tensor dFlash/EAGLE need. It is already
1291        // computed by verification; the trait exists so it stops being
1292        // discarded.
1293        let cfg = tiny_test_config();
1294        let hidden_dim = cfg.hidden_dim;
1295        let decoder = Decoder::new_random_small(cfg, 2, 8);
1296        let mut kv = caches(&decoder);
1297        let mut drafter = FixedDrafter::new(DraftBlock::deterministic(vec![5, 6]));
1298
1299        speculative_decode(&decoder, &[1usize, 2, 3], 4, &mut kv, &mut drafter);
1300
1301        let lens = drafter.seen_hidden_len.borrow();
1302        assert!(!lens.is_empty());
1303        for len in lens.iter() {
1304            assert_eq!(
1305                *len, hidden_dim,
1306                "every round must pass a full target hidden state, not an empty slice"
1307            );
1308        }
1309    }
1310
1311    // ---- cache resume + rollback arithmetic ----
1312
1313    #[test]
1314    fn resuming_a_warm_cache_gives_the_same_tokens_as_one_fresh_run() {
1315        // The serving shape: a prefix cache hands the decode loop a
1316        // cache that already holds part of the context.
1317        let cfg = tiny_test_config();
1318        let vocab = 8;
1319        let decoder = Decoder::new_random_small(cfg, 2, vocab);
1320        let mut speculator = PromptLookupSpeculator::new(2, 3);
1321        let full_prompt = vec![1usize, 2, 3, 4, 1, 2];
1322        let max_new = 6;
1323
1324        let mut fresh = caches(&decoder);
1325        let cold = speculative_decode(&decoder, &full_prompt, max_new, &mut fresh, &mut speculator);
1326
1327        // Warm: feed the first 4 prompt tokens through the decoder
1328        // first, then resume speculative decoding from position 4.
1329        let split = 4;
1330        let mut warm = caches(&decoder);
1331        decoder.forward_batch(&full_prompt[..split], 0, &mut warm);
1332        let resumed = speculative_decode_with(
1333            &decoder,
1334            &full_prompt[split..],
1335            &mut warm,
1336            &mut speculator,
1337            &SpeculativeOptions {
1338                max_new_tokens: max_new,
1339                start_pos: split,
1340                ..SpeculativeOptions::default()
1341            },
1342        );
1343
1344        assert_eq!(
1345            resumed.generated_tokens, cold.generated_tokens,
1346            "resuming a warm cache must not change the output"
1347        );
1348    }
1349
1350    #[test]
1351    fn rolls_back_to_absolute_positions_on_a_warm_cache() {
1352        // Rollback lengths are absolute cache lengths, not offsets from
1353        // the start of this call. With a warm cache the two differ by
1354        // start_pos, and a rollback that used the offset would truncate
1355        // into the caller's context. Forced rejections every round make
1356        // the rollback path run every round.
1357        let cfg = tiny_test_config();
1358        let decoder = Decoder::new_random_small(cfg, 2, 8);
1359        // Token 7 is a fixed guess; whether it is accepted is up to the
1360        // model, but the invariant below holds either way.
1361        let mut drafter = FixedDrafter::new(DraftBlock::deterministic(vec![7, 7, 7]));
1362        let context = vec![1usize, 2, 3, 4];
1363        let prompt = vec![5usize, 6];
1364        let max_new = 6;
1365
1366        let mut kv = caches(&decoder);
1367        decoder.forward_batch(&context, 0, &mut kv);
1368        assert_eq!(kv[0].positions(), context.len());
1369
1370        let result = speculative_decode_with(
1371            &decoder,
1372            &prompt,
1373            &mut kv,
1374            &mut drafter,
1375            &SpeculativeOptions {
1376                max_new_tokens: max_new,
1377                start_pos: context.len(),
1378                ..SpeculativeOptions::default()
1379            },
1380        );
1381
1382        assert_eq!(result.tokens_generated, max_new);
1383        // Exact invariant: the cache holds the context, the prompt and
1384        // every generated token except the last (whose KV is not
1385        // computed until it is fed).
1386        let expected = context.len() + prompt.len() + result.tokens_generated - 1;
1387        for cache in kv.iter() {
1388            assert_eq!(
1389                cache.positions(),
1390                expected,
1391                "cache length must be absolute: context {} + prompt {} + generated {} - 1",
1392                context.len(),
1393                prompt.len(),
1394                result.tokens_generated
1395            );
1396        }
1397    }
1398
1399    #[test]
1400    fn a_resumed_run_continues_a_previous_one() {
1401        // Two back-to-back calls on the same caches must equal one long
1402        // call: this is what "not a demo" means for the serving path.
1403        let cfg = tiny_test_config();
1404        let decoder = Decoder::new_random_small(cfg, 2, 8);
1405        let mut speculator = PromptLookupSpeculator::new(2, 3);
1406        let prompt = vec![1usize, 2, 3, 4, 1, 2];
1407
1408        let mut one = caches(&decoder);
1409        let long = speculative_decode(&decoder, &prompt, 8, &mut one, &mut speculator);
1410
1411        let mut kv = caches(&decoder);
1412        let first = speculative_decode(&decoder, &prompt, 4, &mut kv, &mut speculator);
1413        // The last generated token's KV is not in the cache yet, so it
1414        // is the first token of the continuation's "prompt".
1415        let resume_prompt = vec![*first.generated_tokens.last().unwrap()];
1416        let start = prompt.len() + first.tokens_generated - 1;
1417        let second = speculative_decode_with(
1418            &decoder,
1419            &resume_prompt,
1420            &mut kv,
1421            &mut speculator,
1422            &SpeculativeOptions {
1423                max_new_tokens: 5,
1424                start_pos: start,
1425                ..SpeculativeOptions::default()
1426            },
1427        );
1428
1429        let mut stitched = first.generated_tokens.clone();
1430        stitched.pop(); // re-fed as the continuation's prompt
1431        stitched.extend_from_slice(&second.generated_tokens);
1432        assert_eq!(
1433            &stitched[..8],
1434            &long.generated_tokens[..],
1435            "a decode split across two calls must equal the same decode in one"
1436        );
1437    }
1438
1439    #[test]
1440    #[should_panic(expected = "start_pos must be the caches' current length")]
1441    fn a_mismatched_start_pos_is_refused_rather_than_silently_wrong() {
1442        let cfg = tiny_test_config();
1443        let decoder = Decoder::new_random_small(cfg, 2, 8);
1444        let mut kv = caches(&decoder);
1445        decoder.forward_batch(&[1usize, 2, 3], 0, &mut kv);
1446        let mut speculator = PromptLookupSpeculator::new(2, 2);
1447        speculative_decode(&decoder, &[4usize, 5], 2, &mut kv, &mut speculator);
1448    }
1449
1450    // ---- acceptance metrics ----
1451
1452    #[test]
1453    fn per_position_accept_rates_expose_suffix_decay() {
1454        // A drafter whose first guess is always right and whose later
1455        // guesses are always wrong has the same mean accept rate as one
1456        // that is uniformly mediocre. Only the per-position curve tells
1457        // them apart, which is the whole reason it exists.
1458        let mut result = SpeculativeDecodeResult::default();
1459        for _ in 0..100 {
1460            result.record_position(0, true);
1461            result.record_position(1, false);
1462        }
1463        result.verification_steps = 100;
1464        result.tokens_generated = 200;
1465
1466        assert_eq!(result.accept_rate(), Some(0.5));
1467        assert_eq!(result.accept_rate_per_position(), vec![1.0, 0.0]);
1468        assert_eq!(result.acceptance_length(), Some(2.0));
1469    }
1470
1471    #[test]
1472    fn positions_after_a_rejection_are_not_counted_as_drafted() {
1473        // A round that rejects at position 0 never evaluates positions
1474        // 1..k. Counting them would report an accept rate that falls
1475        // with the block size rather than with the drafter's accuracy.
1476        let cfg = tiny_test_config();
1477        let decoder = Decoder::new_random_small(cfg, 2, 8);
1478        let mut kv = caches(&decoder);
1479        // Token 7 against a random model: whatever happens, every
1480        // counted position must have been reachable.
1481        let mut drafter = FixedDrafter::new(DraftBlock::deterministic(vec![7, 7, 7, 7]));
1482        let result = speculative_decode(&decoder, &[1usize, 2, 3], 6, &mut kv, &mut drafter);
1483
1484        let evaluated = &result.evaluated_at_position;
1485        let accepted = &result.accepted_at_position;
1486        assert!(
1487            result.drafted_tokens > result.accepted_tokens,
1488            "the scenario is pointless unless something was actually rejected \
1489             (drafted {}, accepted {})",
1490            result.drafted_tokens,
1491            result.accepted_tokens
1492        );
1493        // The sharp invariant: position i+1 is only reached when
1494        // position i was accepted, so it can never have been evaluated
1495        // more often. Merely checking that the counts are
1496        // non-increasing is not enough -- crediting every position of
1497        // every proposed block, rejected or not, keeps them
1498        // non-increasing (it makes them equal) while reporting an
1499        // accept rate that decays with the block size rather than with
1500        // the drafter.
1501        for (i, &seen) in evaluated.iter().enumerate().skip(1) {
1502            assert!(
1503                seen <= accepted[i - 1],
1504                "position {i} was evaluated {seen} times but position {} was only \
1505                 accepted {} times: evaluated={evaluated:?} accepted={accepted:?}",
1506                i - 1,
1507                accepted[i - 1]
1508            );
1509        }
1510        assert_eq!(
1511            result.drafted_tokens,
1512            evaluated.iter().sum::<usize>(),
1513            "drafted_tokens must be the per-position counts' total"
1514        );
1515        assert_eq!(
1516            result.accepted_tokens,
1517            result.accepted_at_position.iter().sum::<usize>()
1518        );
1519        assert!(result.accepted_tokens <= result.drafted_tokens);
1520    }
1521
1522    #[test]
1523    fn acceptance_length_is_reported_per_verification_step_not_per_call() {
1524        // The published metric divides by verification steps; charging
1525        // the one-off prefill against it understates short runs.
1526        let cfg = tiny_test_config();
1527        let decoder = Decoder::new_random_small(cfg, 2, 8);
1528        let mut kv = caches(&decoder);
1529        let mut speculator = PromptLookupSpeculator::new(2, 3);
1530        let result =
1531            speculative_decode(&decoder, &[1usize, 2, 3, 1, 2], 6, &mut kv, &mut speculator);
1532
1533        assert_eq!(result.verification_steps, result.forward_calls - 1);
1534        let length = result.acceptance_length().unwrap();
1535        assert!(length >= 1.0, "every verification step commits >= 1 token");
1536        assert!(
1537            length > result.tokens_per_call(),
1538            "acceptance length must not be diluted by the prefill call"
1539        );
1540    }
1541
1542    #[test]
1543    fn an_empty_run_reports_no_acceptance_length_rather_than_zero() {
1544        let result = SpeculativeDecodeResult::default();
1545        assert_eq!(result.acceptance_length(), None);
1546        assert_eq!(result.accept_rate(), None);
1547        assert_eq!(result.tokens_per_call(), 0.0);
1548    }
1549
1550    /// The observer sees exactly the committed tokens, in order, and
1551    /// stopping through it truncates the result to the token that said
1552    /// so.
1553    ///
1554    /// This is what lets `ferrox run` stream and stop on an EOS without
1555    /// a second copy of the verification loop. A copy is how this
1556    /// project lost five model features from one duplicated decode
1557    /// path, and the rejection rule is the last code in the tree that
1558    /// should be duplicated: a subtly wrong copy still looks lossless.
1559    #[test]
1560    fn the_observer_sees_every_committed_token_and_can_end_the_run() {
1561        let cfg = tiny_test_config();
1562        let vocab = 8;
1563        let prompt = vec![1usize, 2, 3, 4, 1, 2];
1564
1565        let decoder = Decoder::new_random_small(cfg.clone(), 2, vocab);
1566        let mut kv = caches(&decoder);
1567        let mut spec = PromptLookupSpeculator::new(2, 3);
1568
1569        let mut seen = Vec::new();
1570        let result = speculative_decode_observed(
1571            &decoder,
1572            &prompt,
1573            &mut kv,
1574            &mut spec,
1575            &mut |t| {
1576                seen.push(t);
1577                true
1578            },
1579            &SpeculativeOptions {
1580                max_new_tokens: 6,
1581                start_pos: 0,
1582                sampling: SamplingParams::default(),
1583                seed: 0,
1584            },
1585        );
1586        assert_eq!(
1587            seen, result.generated_tokens,
1588            "the observer must see exactly what the run returns, in order"
1589        );
1590
1591        // Now stop after three tokens.
1592        let decoder = Decoder::new_random_small(cfg, 2, vocab);
1593        let mut kv = caches(&decoder);
1594        let mut spec = PromptLookupSpeculator::new(2, 3);
1595        let mut count = 0usize;
1596        let stopped = speculative_decode_observed(
1597            &decoder,
1598            &prompt,
1599            &mut kv,
1600            &mut spec,
1601            &mut |_| {
1602                count += 1;
1603                count < 3
1604            },
1605            &SpeculativeOptions {
1606                max_new_tokens: 6,
1607                start_pos: 0,
1608                sampling: SamplingParams::default(),
1609                seed: 0,
1610            },
1611        );
1612        assert_eq!(
1613            stopped.generated_tokens.len(),
1614            3,
1615            "the run must end at the token that said stop, not at the end of its block"
1616        );
1617        assert_eq!(
1618            stopped.generated_tokens,
1619            result.generated_tokens[..3],
1620            "and the tokens up to the stop must be the ones an unstopped run produced"
1621        );
1622    }
1623}