Code Lab / Challenge 19

Speculative Decoding: Draft, Verify, Accept

HardDraft-and-verify with the exact rejection-sampling rule

The problem, as an interviewer would set it

A small draft model proposes gamma tokens, the large target model verifies all
of them in one forward pass, and the accept/reject rule keeps the output
distribution exactly equal to the target's. Implement it, then prove by test
that it is lossless. Both models here are seeded probability tables, so the
tests are deterministic:
    draft_probs_fn(prefix) -> array (V,), one sequential step
    target_probs_fn(prefix, continuation) -> array (len(continuation) + 1, V),
        ONE forward pass scoring every position at once: row i is the target's
        distribution for the token following prefix + continuation[:i]

Implement:

    draft_tokens(draft_probs_fn, prefix, gamma, rng) -> (tokens, q_probs)
        sample gamma tokens autoregressively from the draft, returning the
        tokens and the distribution used at each position (keep them:
        re-running the draft to recover q defeats the point)

    speculative_step(target_probs_fn, draft_probs_fn, prefix, gamma, rng)
        -> (accepted_tokens, n_target_calls)
        - draft gamma tokens, then call the target exactly once
        - accept each drafted x_i, in order, with prob min(1, p_i(x_i)/q_i(x_i))
        - on the first rejection emit one token from the residual
          norm(max(p_i - q_i, 0)) and stop, discarding the rest of the draft
        - if all gamma are accepted, emit a bonus token from p_gamma, which
          that same forward pass already paid for
        - output length is n_accepted + 1, always in [1, gamma + 1], and
          n_target_calls is 1 for any gamma, gamma = 0 included (that case
          degenerates to plain autoregressive sampling)

    residual_distribution(p, q) -> array (V,)
        max(p - q, 0) renormalised, falling back to p if the residual mass is
        zero (unreachable after a real rejection, but do not divide by zero)
What interviewers look for

Why it is lossless, why accept-if-argmax-matches is not, why it is a bandwidth win not a FLOPs win

A strong solution demonstrates:
- WHY it is lossless, in one line. P(emit t at the drafted position)
  = q(t) * min(1, p(t)/q(t)) + P(reject) * residual(t) = min(p(t), q(t))
  + (p(t) - q(t))+ = p(t), since P(reject) is exactly sum_t (p(t) - q(t))+,
  the normaliser the residual divides by. No approximation, no quality knob.
- WHY it is a memory-bandwidth win, not a FLOPs win. Batch-1 decoding streams
  every weight from HBM to produce one token, roughly one multiply-accumulate
  per weight loaded, so the arithmetic units idle while memory works. Verifying
  gamma + 1 positions in one pass reads those weights once and does gamma + 1
  times the arithmetic on them: total FLOPs go UP (rejected drafts are wasted
  work), wall-clock latency goes down.
- The crossover where it stops paying. With i.i.d. acceptance rate a, expected
  output per step is (1 - a^(gamma+1)) / (1 - a), saturating in gamma while
  draft cost stays linear in it, so there is an optimal gamma per model pair.
  Raising the batch size makes the target pass compute-bound, the spare
  arithmetic disappears and the wasted work becomes real time: a latency
  optimisation for small-batch serving that can cut throughput on a saturated
  server. The exception is long context, where KV-cache reads keep even large
  batches memory-bound and speculation can pay again. Too big a draft pays its
  own latency gamma times per step; too weak a draft drives a towards zero.
  Serving engines therefore tune gamma per workload or adapt it at runtime.
Common mistakes: resampling from p rather than the residual after a rejection
(nothing crashes, output silently drifts towards what the draft over-proposes);
accepting on argmax agreement, defensible only at temperature 0 and still
biased once you sample; forgetting the bonus token; not rolling back BOTH KV
caches past the rejected position; measuring the win in FLOPs.
Follow-ups: tree or multi-candidate drafting; n-gram or prompt-lookup drafting
with no draft model at all; self-speculation via early-exit layers; draft
heads on the target's own hidden states (Medusa, EAGLE) and multi-token
prediction heads trained with the model (DeepSeek-V3), both of which often
replace a separate draft model in production; lenient acceptance
thresholds that buy speed by giving up exactness; ragged batching when
sequences accept different numbers of tokens. References: Leviathan et
al., 2023, "Fast Inference from Transformers via Speculative Decoding"; Chen
et al., 2023, "Accelerating Large Language Model Decoding with Speculative
Sampling".

Write your own version first. The reference solution and its tests are one click away when you are ready.