Speculative Decoding
Letting a small model guess and a large one check: the acceptance rules that keep the output exact, what the guesses are worth on real text, and where the arithmetic says it should and should not pay.
On the same NVIDIA RTX 2060, with the same 3.21-billion-parameter target model, speculative decoding ranged from 0.77× to 1.51× the speed of plain greedy decoding in the tested prompt categories and draft lengths. With six proposed tokens per iteration, repetitive or structured text ran 1.51× as fast; prose ran at 0.77×, meaning it delivered about 23% less throughput. The output type mattered as much as the algorithm setting. These are medians from short, batch-one runs on one model pair, not general throughput claims.
Speculative decoding tries to reduce the number of sequential target-model calls, rather than the cost of each individual call. A smaller draft model proposes a continuation; the larger target scores the proposed tokens together and decides how much to keep. Picture one iteration with four proposals. If the target agrees with the first three and disagrees at the fourth, the iteration keeps those three and takes the target’s own choice in place of the fourth: four tokens for one target call, where plain decoding would have needed four. If the target disagrees at the very first proposal, the iteration yields only the target’s one token, and the draft’s work was wasted.
Whether this is faster overall therefore depends on three measured quantities: how often proposals are accepted, what a draft step costs, and what a verification pass costs. The draft’s parameter count, on its own, predicts none of these sufficiently well.
Correctness has two different meanings here. For greedy decoding, the acceptance rule produces the target’s greedy continuation in exact arithmetic; finite-precision changes in execution shape can still change a near-tied arg-max. For sampling, the acceptance-and-residual rule is designed to reproduce the target’s probability distribution, not the same token sequence under the same random seed. This chapter implements the rules, tests their consequences, and reports where the real-model greedy experiment diverged.
Where this sits
Autoregressive Generation made generation a sequence of forward passes and contrasted token generation with scoring known tokens. Prefill and Decode measured the per-step cost of decoding, where launch and weight traffic often dominate at batch one. Key-Value Caching established the cache-state requirements; Memory Bandwidth and Compute Bottlenecks supplied a cost model for checking whether a wider pass is actually cheap. Speculation combines those ideas: spend comparatively inexpensive draft work to avoid serial target calls, while preserving the accepted target prefix and rolling back rejected state. The claim that a multi-token check is inexpensive is tested below for one specific shape and GPU.
The Inference Lab increment is examples/ch17/speculative_lab.py: draft and target execution with separate DynamicCache objects, crop-based rollback, greedy and residual-based sampling acceptance, a simple acceptance/cost model, and correctness and timing probes. It remains separate from Continuous Batching’s continuous scheduler. A serving implementation would additionally need variable numbers of emitted tokens per iteration, batching of unequal proposal lengths, bounded KV allocations, correct stop-token handling, and latency accounting for draft and target work.
For the Pi series, the useful design question is whether an agent’s next tokens are predictable by its draft model. Repeated syntax in JSON, code and tool arguments may create stretches of high acceptance, but this chapter measured only three small code prompts and three repetitive or structured prompts. It did not test actual tool-call traces or agent workloads. The engineering lesson is to measure acceptance and cost by output class before deciding whether speculation belongs on a service path.
The idea, and how cheap checking is
Plain autoregressive decoding asks the target for the next-token distribution once per generated token. Speculation depends on the target being able to score several proposed tokens in one pass for much less than the cost of scoring them one at a time. Why might that be possible? At batch one, a short target pass may spend much of its time launching kernels and reading weights rather than performing extra arithmetic for each additional position; if so, scoring more positions in the same pass adds little. That makes simultaneous verification plausible, but not free by definition. So the first thing to measure is the pass itself. On the Llama-3.2-3B-Instruct target in fp16, with a cached context of about 69 tokens, the Lab measured these forward-pass times:
| New tokens in the pass | 1 | 2 | 3 | 5 | 9 |
|---|---|---|---|---|---|
| Target pass time | 33.7 ms | 31.6 ms | 32.1 ms | 31.9 ms | 32.5 ms |
Within this timing run, scoring between one and nine new positions took approximately 32–34 ms: the nine-position pass was not measurably slower than the one-position pass. These are medians from 45 observations per point, in one operating state of a desktop-shared GPU. They do not establish equal cost at larger batches, longer contexts, different attention backends or other GPUs. A verification call also needs the right cache contents and logit alignment; the timing comparison alone does not prove the speculative loop correct.
The draft is a second model that proposes token IDs the target can interpret in the same way. In this experiment the target was Llama-3.2-3B-Instruct (3.21 billion parameters, 28 layers) and the draft Llama-3.2-1B-Instruct (1.24 billion parameters, 16 layers), both in fp16. The runtime compared get_vocab() and found identical token-to-ID mappings. That is stronger than equal vocabulary size, but a deployable pair must also agree on any relevant special-token IDs, prompt formatting, token handling and stopping rules. The measured loop operates on explicit token IDs and does not establish compatibility for arbitrary chat templates.
One iteration
With \(k\) guesses, an iteration has four steps:
- Propose. The draft produces up to \(k\) tokens autoregressively. In sampling mode it also retains the actual proposal distribution \(q_i\) used for each drawn token.
- Verify. The target processes the proposals together with any preceding output token not yet entered into its cache. From the correctly aligned logits it obtains the target distribution for each proposal and, if all are accepted, one extra distribution for a bonus token.
- Accept or reject in order. The greedy rule compares each proposal with the target arg-max. The sampling rule accepts probabilistically; on the first rejection it samples a replacement from the residual distribution. Later proposals in that iteration are discarded. If all pass, the target supplies a bonus token.
- Commit and roll back. Append the accepted proposals and one target-supplied token, discard speculative state beyond the committed prefix, then bring both model caches into alignment for the next iteration.
Here is an illustrative greedy trace with \(k=4\) (made-up tokens, not from the recorded runs). The committed text ends “…the cache”. The draft proposes, one token at a time, " is", " read", " once", " per". The target scores all four positions in one pass, plus one more position after " per". At each position it computes its own arg-max: " is", " read", " twice". The first two agree, so they are accepted. The third disagrees, so the iteration stops checking there: " once" and " per" are discarded, and the target’s " twice" is committed in place of " once". The iteration commits three tokens (" is", " read", " twice") for one target call. Had all four agreed, the target’s arg-max at the extra fifth position would have been committed as a bonus token, for five tokens in total.
So an iteration commits between one and \(k+1\) output tokens while calling the target once. The implementation makes approximately \(k\) draft invocations, including feeding any not-yet-cached continuation into the draft at the start of the iteration.
One detail of the implementation matters for the measurements later. The last iteration still proposes and verifies a full batch even if fewer than \(k+1\) tokens remain before max_new; the returned token list is truncated afterwards. Its measured draft work and accepted-proposal counters can therefore include unused final-iteration work. The simple cost model below is an approximation to that actual loop, especially for short generations.
Rolling back the cache
The target and draft maintain independent key/value states, and after verification neither is in the right state for the next iteration. The target cache now contains entries for every proposal the target just evaluated; after an early rejection, some of those tokens will never appear in the output. In the trace above, the target cache holds entries for " once" and " per", which were discarded.
The implementation crops the target’s DynamicCache to len(tokens) - 1, leaving the final target-supplied token (" twice" in the trace) to be processed at the start of the next pass. It also crops the draft cache to the last position it actually evaluated: when all proposals were accepted, the draft may not yet have processed its own final proposal. At the next iteration tokens[n_d:] supplies that missing continuation. These off-by-one details are essential, because a misplaced cache position silently changes later predictions.
CPU tests on small random Llama models compare greedy output with a plain loop over several prompts and \(k\) values. The recorded rollback bookkeeping took roughly 0.1–0.23 ms per iteration in the speed run, but that timing does not by itself prove cache correctness under every stopping, rejection or batching pattern.
Greedy acceptance
In greedy mode, the proposed token at position \(i\) is retained exactly when the target would choose it by arg-max, given the accepted prefix. The helper receives correctly aligned target logits, including one extra row for the possible bonus token:
def accept_greedy(proposals, target_logits):
for i, x in enumerate(proposals):
best = int(torch.argmax(target_logits[i]))
if best != x:
return i, best # accepted i proposals; the target supplies `best`
return len(proposals), int(torch.argmax(target_logits[len(proposals)]))
target_logits[i] predicts proposals[i]; the last row predicts the bonus token if all \(k\) proposals are accepted.
Why does this reproduce target-only greedy decoding? Argue one committed token at a time. Every accepted proposal is, by the test above, the token the target itself would have picked at that position, given a prefix that is already the target’s own. The first rejected position is replaced by the target’s own pick. So each committed token is the one target-only decoding would have produced, and by induction on the committed prefix the whole continuation is the same, when both calculations use identical mathematical logits and the same tie-breaking rule. The function itself is a small, testable acceptance rule; the full decoding loop additionally has to supply correctly positioned logits and valid cache state.
The condition in bold is where real execution departs from the proof. The real implementation uses fp16, where mathematically equivalent calls may execute different kernels or reduction orders. The acceptance proof does not guarantee that their bit patterns, or their arg-max choices at very small margins, will be identical.
Identical, up to arithmetic
The speed experiment used 12 prompts: six book paragraphs, three Python snippets and three repetitive or structured examples. It generated 64 tokens per prompt and repeated the experiment for three rounds. Plain greedy output matched itself on 24 of 24 repeat comparisons. Speculative output matched plain greedy in 36 of 36 runs at \(k=1\) and \(k=2\), but in 30 of 36 at each of \(k=3,4,6\). The six disagreements were the same two prose prompts, repeated across three rounds; their first differing output positions were zero-based indices 8 and 26 (the ninth and twenty-seventh generated tokens). These are observations on this fp16 model pair and backend, not an assertion that larger \(k\) inherently changes greedy answers.
What caused the two divergences? A diagnostic found next-token decisions separated by very small fp16 logit margins, but it does not fully identify the cause. At one divergence, plain decoding emitted " pattern" and speculation emitted " latency". Recomputing logits from the resulting context in three fresh arrangements favoured " latency" by 0.0078125, even though the original plain run had selected " pattern". At the other, plain emitted " parallel" and speculation " model"; the three recomputations favoured " parallel" by 0.0078125–0.015625. These differences are roughly one or two fp16 representable steps at logits near 12–15.
The diagnostic supports a numerical near-tie explanation; it does not isolate the exact kernel, cache history or reduction order that changed the original decision. The five-token diagnostic and full-prefill recomputations are observations, not a reproduction of every intermediate from the original runs.
The practical distinction is between a mathematical guarantee and an operational reproducibility contract. Changing which positions are evaluated together can change floating-point rounding, especially when two logits are almost tied. Here, fixed target weights and fixed prompts did not imply token-for-token equality between plain and speculative fp16 execution at every \(k\). A deployment requiring byte-identical output must test that property for its actual kernel, dtype, cache implementation and decoding settings, and fail or fall back when it cannot be guaranteed. When bitwise identity is not the requirement, greedy speculation can still be evaluated for quality and speed, but a tiny logit margin does not by itself quantify the eventual difference in generated text.
Sampling acceptance
For sampling, equality means equality in distribution, not equality to a reference random-number trace. The question is how to use a draft’s proposals while still producing each token with exactly the target’s probabilities.
At a candidate position, let \(p\) be the target distribution after all sampling transforms, and let \(q\) be the draft distribution that actually produced proposal \(x\sim q\). The acceptance rule given by Leviathan, Kalman and Matias (ICML 2023) and Chen et al. (2023) is:
- Accept proposal \(x\) with probability \(a(x)=\min\left(1,\dfrac{p(x)}{q(x)}\right)\). The ratio is well defined for a proposal drawn from a positive-probability entry of \(q\).
- On the first rejection, discard that proposal and draw the replacement from the normalised positive residual:
The intuition: where the draft over-proposes a token (\(q\) above \(p\)), some of those proposals are rejected to bring that token down to its target probability; where the draft under-proposes, the residual tops it up. A three-token example makes this concrete. Let the target be \(p = (0.5, 0.3, 0.2)\) over tokens A, B, C, and the draft \(q = (0.2, 0.6, 0.2)\).
- If the draft proposes A (probability 0.2), it is always accepted, since \(p > q\) for A. If it proposes B (probability 0.6), it is accepted with probability \(0.3/0.6 = 0.5\). If it proposes C (probability 0.2), it is always accepted.
- The accepted mass per token is therefore 0.2 for A, 0.3 for B and 0.2 for C, a total of 0.7. Rejection happens with the remaining probability, 0.3, and only ever after B was proposed.
- The positive residual \(\max(0, p - q)\) is \((0.3, 0, 0)\), so the replacement after a rejection is always A.
- Output probabilities: A gets \(0.2 + 0.3 = 0.5\), B gets 0.3, C gets 0.2. That is exactly \(p\).
The general argument is the same bookkeeping. The probability that this procedure outputs a particular token \(y\) is the probability that the draft proposed it and it was accepted, plus the probability that something was rejected and the residual produced \(y\):
Two natural simplifications break this, and the chapter tests both:
- Resample from the full target \(p\) after rejection rather than the residual. This double-counts mass already supplied by accepted proposals and generally biases the output. In the example, rejected B proposals would sometimes be replaced by B again, pushing B above 0.3.
- Always keep the draft token. This samples \(q\), not \(p\), except where the two distributions happen to coincide.
Both are useful negative controls: a test that only compares cases with \(p\approx q\) may fail to detect either error.
Crucially, \(p\) and \(q\) in the proof are the actual categorical distributions used to sample. Temperature, top-\(k\), top-\(p\), repetition penalties and token masks can change those distributions; the draft’s stored \(q_i\) must match its proposal draw and the target’s \(p_i\) must match verification. Identical transforms need not produce identical distributions, because the logits differ, but each model must be internally consistent. This Lab applies temperature in accept_sample; it does not implement or qualify top-\(k\), top-\(p\), stop-token handling or other logit processors. In production, probabilities near zero also require numerical safeguards without silently changing the acceptance rule.
Testing it
The proof supplies the invariant; statistical tests check whether code plausibly implements it. Passing a statistical test does not establish exactness, but testing at three levels catches mistakes that an acceptance-function unit test alone can miss:
- Known six-token distributions. The unit tests compare 20,000 samples under the correct and two deliberately incorrect rules. The correct rule falls below the chosen chi-square rejection threshold; both incorrect rules are detected. A separate test confirms that, when \(p=q\), all proposals are accepted.
- Autoregressive loop with caches. On small random models with an eight-token vocabulary, 6,000 two-token continuations are compared with the target’s calculated joint distribution. This exercises cache alignment, rejection, resampling and truncation together. It is still a statistical test of one small configuration.
- Real next-token distributions. At the 12 measured prompt contexts, the 3B and 1B models provide \(p\) and \(q\). Each rule generates 200,000 draws per context; chi-square compares the 60 most probable target tokens plus a pooled remainder across three seeds. This experiment samples from already computed distributions: it does not time the full real-model speculative loop in sampling mode.
The real-model result, over 12 contexts and 3 seeds (36 tests for the correct rule):
| Rule | Tests with \(p < 0.01\) | Total variation distance to \(p\), prose contexts, seed 0 |
|---|---|---|
| Speculative sampling (min, residual) | 1 of 36 | 0.017 to 0.038 |
| Resample from the target | 10 of 12 on every seed | 0.14 to 0.18 |
| Keep the draft’s token | 10 of 12 on every seed | 0.31 to 0.44 |
For the correct rule, just one of 36 real-model chi-square tests had \(p<0.01\), with a value of 0.007; the same context returned 0.54 and 0.76 under the other seeds. Under a correctly specified null, a threshold of 0.01 would on average flag 0.36 of 36 tests, so one is possible by chance. The test series is consistent with the sampling rule, but it is not a proof of the implementation.
The two columns of the table answer different questions. The total-variation values reported for the correct rule are over the entire large vocabulary, where many extremely rare tokens are sparsely observed; the chi-square test instead pools all but the top 60. A calibrated evaluation should report both the binning rule and the expected sampling-noise floor.
The incorrect rules were not rejected in two of the 12 contexts, where draft and target next-token distributions were nearly the same and proposal acceptance was close to one. That is a low-power comparison, not supporting evidence for the wrong rule; it is the \(p\approx q\) case warned about above. To distinguish implementations, select contexts with meaningful \(\operatorname{TV}(p,q)\), keep the holdout independent of rule tuning, and report confidence intervals or repeated tests rather than treating a single \(p\)-value as certification.
The real-model experiment checks only the first sampled token at each of twelve contexts. The two-token joint test exercises the complete loop, but on toy models. Neither result establishes real-model end-to-end sampling fidelity for long continuations, nor the correctness of sampling transforms this implementation does not support. The mathematical proof explains what a correct implementation should produce; these experiments provide bounded evidence that particular components do so.
What a guess is worth
How many tokens does one iteration commit on average? The cost model begins with a simplifying assumption: each candidate has the same conditional acceptance probability \(\alpha\), independent of earlier candidate outcomes. An iteration always emits one target-supplied token, plus however many proposals survive consecutively. The \(j\)-th proposal survives only if all of the first \(j\) are accepted, which under the assumption has probability \(\alpha^j\). Adding up the probabilities of accepting at least \(j\) proposals, for \(j=0,\ldots,k\):
In real decoding, acceptance varies with token position, prior acceptances and output class. The Lab estimates \(\hat\alpha\) as accepted proposals / proposals considered: the first rejected proposal counts as considered, while later guesses in that same iteration do not. This estimator characterises the observed prefix checks, not necessarily an independent probability for every future proposal.
The acceptance experiment used the 12 prompts and 64 requested output tokens, with \(k\in\{1,2,4,8\}\). It counted accepted proposals, checked proposals and target iterations. The resulting tokens per target pass metric is (accepted + iterations) / iterations: a count of tokens committed before final-output truncation. Because speculative_generate can overrun the 64-token limit in its final iteration and return only the requested prefix, the metric can modestly overstate useful emitted tokens per verification call for short requests.
| Kind of text | \(\hat\alpha\) at \(k=4\) | Tokens per target pass |
|---|---|---|
| Prose (six paragraphs of this book) | 0.74 | 2.95 |
| Python code | 0.95 | 4.56 |
| Repetitive or structured text | 0.98 | 4.88 |
Across the 12 prompts, \(\hat\alpha\) was approximately 0.85, 0.84, 0.85 and 0.85 for \(k=1,2,4,8\). The observed committed-token counts per target pass were 1.85, 2.54, 3.63 and 4.87; the independent-\(\alpha\) formula gives 1.85, 2.54, 3.68 and 5.09. The two agree closely at small \(k\) and the gap widens at \(k=8\). Correlated acceptance is a plausible explanation, especially for prompts that alternate between easy and difficult spans, but the measurements also include final-iteration truncation effects and sampling variability. The four nearly equal pooled \(\hat\alpha\) values do not prove that acceptance is invariant to \(k\).
The acceptance-length distribution shows why an average alone is inadequate. Among 133 prose iterations at \(k=4\), 37 accepted none, 55 accepted one to three, and 41 accepted all four proposals. Code accepted all four in 35 of 43 iterations; structured text did so in 37 of 40. For prose, 37 iterations gained nothing from the draft while 41 gained everything it offered; categories with similar averages could still have very different patterns, and one pooled \(\hat\alpha\) hides very different workloads. For a more predictive model, measure \(P(A\ge j)\) for each proposal position \(j\), then estimate \(E[\text{tokens}] = 1+\sum_{j=1}^{k}P(A\ge j)\) directly. That identity does not require independence, though the observed counts still need correction for request boundaries.
What a pass costs
Tokens per iteration is only half of the speed calculation; the other half is what an iteration costs. The simplest throughput prediction divides expected useful tokens by expected iteration time. Approximating every iteration as \(k\) draft calls plus one target verification call, and comparing with \(E[\text{tokens}]\) ordinary target steps, gives
This formula intentionally omits extra model-input preparation, synchronisation, rollback, allocation, stop handling, and the final iteration’s discarded work. Those costs can matter when \(k\) is large or the requested continuation is short. Because the draft cost enters directly, the empirical draft-to-target cost ratio is more useful than the ratio of parameter counts:
| Target (3B) | Draft (1B) | Ratio | |
|---|---|---|---|
| Parameters | 3.21 B | 1.24 B | 0.38 |
| Weights in fp16 | 5.98 GiB | 2.30 GiB | 0.38 |
| Layers | 28 | 16 | 0.57 |
| One decoding step (healthy run) | 33.7 ms | 18.3 ms | 0.54 |
| One decoding step (mean over the speed run) | 44.7 ms | 24.8 ms | 0.56 |
The 1B draft held 38% of the target’s fp16 weight bytes but took 54–56% of its measured time per single-token step. Its 16 layers are 57% of the target’s 28, so layer-count-related launch overhead is a plausible contributor. That resemblance is not a causal measurement: the models differ in hidden dimensions and kernel shapes as well as depth, and memory traffic remains relevant. A matched-depth comparison or profiler trace would be needed to distinguish these mechanisms. What the present experiment establishes is the performance ratio: a 2.6× smaller draft was only about 1.8× faster per step on this machine.
Using a target step of 44.7 ms, draft step of 24.8 ms, and target verification cost of about 33–42 ms depending on the pass width, the model predicts the following relative speeds. These step times are averages of measurements taken before and after the speed experiment; the two sets drifted markedly, so the table is a planning calculation, not a stable hardware characteristic.
| \(\alpha\) | \(k=1\) | \(k=2\) | \(k=3\) | \(k=4\) | \(k=6\) | \(k=8\) | Best \(k\) |
|---|---|---|---|---|---|---|---|
| 0.50 | 1.01 | 0.86 | 0.72 | 0.61 | 0.49 | 0.38 | 1 |
| 0.74 | 1.17 | 1.13 | 1.04 | 0.95 | 0.83 | 0.69 | 1 |
| 0.85 | 1.24 | 1.27 | 1.23 | 1.17 | 1.11 | 0.99 | 2 |
| 0.95 | 1.31 | 1.40 | 1.43 | 1.43 | 1.48 | 1.43 | 6 |
The entries are predictions, not measured speed-ups. Each row assumes independent proposal acceptance with the stated \(\alpha\); each column uses the recorded verification time for its corresponding width. In particular, a model that predicts \(S>1\) for a workload does not guarantee that a fully instrumented implementation will beat its baseline under the same queueing or memory conditions.
Reading across a row of this predicted table shows the trade-off. At low acceptance the best choice is the smallest \(k\), because extra proposals are mostly rejected but always paid for; only at high acceptance do longer proposal runs repay their draft steps. At the measured cost assumptions, the break-even acceptance probabilities were approximately 0.49 for \(k=1\), 0.63 for \(k=2\), 0.77 for \(k=4\), and 0.81 for \(k=6\). Increasing \(k\) purchases more possible accepted tokens but charges another draft step for every proposal, including proposals after the first rejected one that will never be used.
To illustrate cost sensitivity rather than predict a new implementation, suppose the draft step fell to 0.38 of the target step and verification equalled one target step: at \(\alpha=0.85,k=4\), the formula gives about 1.47×, rather than roughly 1.15× with a 0.56 draft ratio. No such faster draft was benchmarked. A deployable decision should use measured verification latency by width and an acceptance distribution by workload, not just a headline \(\hat\alpha\).
Measured speed
For speed, each of the 12 prompts was decoded for 64 tokens across three rounds, once plainly and at \(k=1,2,3,4,6\), with the order rotated for each prompt and round. Every speculative throughput was divided by the plain throughput for the same prompt and round; the table reports both the median of those 36 ratios and the ratio of pooled token rates. They are not the same statistic.
The machine was not stable during this experiment, and the design had to account for that. The RTX 2060 display GPU was shared with the desktop, and its target-step timing moved from 33.2 to 56.2 ms during this experiment (draft: 17.3 to 32.4 ms). An earlier, non-interleaved comparison suggested up to 1.8× only because machine speed changed between method groups; it was discarded. The retained plain runs averaged 24.8 output tokens/s, including per-request work timed by the harness. Interleaving mitigates drift; it does not eliminate all order or host-load effects.
| \(k\) | Speed-up, median of per-run ratios | Pooled | Predicted | \(\hat\alpha\) | Tokens per target pass | Output identical to plain |
|---|---|---|---|---|---|---|
| 1 | 1.24 | 1.25 | 1.24 | 0.85 | 1.85 | 36 / 36 |
| 2 | 1.20 | 1.27 | 1.25 | 0.84 | 2.54 | 36 / 36 |
| 3 | 1.17 | 1.25 | 1.21 | 0.84 | 3.09 | 30 / 36 |
| 4 | 1.11 | 1.17 | 1.16 | 0.85 | 3.63 | 30 / 36 |
| 6 | 0.98 | 1.00 | 1.10 | 0.85 | 4.32 | 30 / 36 |
Tokens per target pass rises steadily with \(k\), but speed does not follow it. Through \(k=4\), the model’s prediction and pooled measured ratio differ by about 0.05 or less; at \(k=6\), prediction is 1.10× versus pooled measurement of 1.00×. The median paired-run ratios tell a slightly less favourable story: 1.24×, 1.20×, 1.17×, 1.11× and 0.98× as \(k\) grows. Both views support using a short draft for this mixed, 12-prompt workload, rather than assuming that more proposals always help. Neither statistic establishes a best \(k\) for long-running services or a different mix of requests.
The pooled result averages together prose, code and repetitive text. The following rows use median paired-run speed-ups within each prompt category, three rounds per prompt; they expose the variation hidden by the aggregate:
| Kind of text | \(k=2\) | \(k=4\) | \(k=6\) |
|---|---|---|---|
| Prose | 1.09 | 0.94 | 0.77 |
| Code | 1.29 | 1.31 | 1.22 |
| Repetitive or structured | 1.44 | 1.49 | 1.51 |
At \(k=6\), prose reached 0.77×, or about 23% less throughput than plain decoding, while structured text reached 1.51×. At \(k=4\), the measured prose result (0.94×) is close to the \(\alpha=0.74\) cost-model prediction (0.95×). The code cases are less well explained: with \(\alpha\approx0.95\), predictions of 1.43× at \(k=4\) and 1.48× at \(k=6\) exceed measured medians of 1.31× and 1.22×. The acceptance data for these categories were collected in the separate \(k=4\) experiment, not recorded by category for every \(k\) in the speed runs. Additional work is required before attributing this gap to acceptance changes, synchronisation overhead or another cause.
Where did the time go inside an iteration? At \(k=4\), the speed run charged an average of about 84 ms per iteration to drafting, 38 ms to target verification, and 0.18 ms to rollback bookkeeping. In this implementation, most iteration time is spent obtaining proposals rather than verifying them. Verification is comparatively cheap, not free; for this measured case, reducing draft cost is the most promising lever. These component times span the same drifting host conditions as the overall benchmark and are not a profile of isolated GPU kernels.
When it loses
The experiments found one way to lose, and the arithmetic suggests others:
- Low or uneven acceptance. At a given \(k\), a long tail of early rejections can make the draft’s serial work more expensive than the target calls saved. Prose at \(k\ge4\) lost throughput here. Adaptively selecting \(k\) from recent acceptance is a plausible mitigation, not a feature this Lab has implemented.
- A draft that is not cheap enough. The measured draft step cost 0.56 target steps. As it grows, the break-even \(\alpha\) rises. Even a nearly perfect draft may not repay an expensive sequence of proposal calls.
- Memory pressure. The two fp16 weight tensors account for approximately 5.98 GiB (target) and 2.30 GiB (draft), before their KV caches, temporary allocations and framework overhead. The GPU’s measured allocator state during one run was about 8.30 GiB, not a promise about physical residency in all conditions.
- Verification that scales with work. These timings are for batch-one verification of short proposal runs. At higher batch, longer context, or different kernels, scoring extra positions can consume appreciable arithmetic and memory traffic. Batched speculation was not measured.
- Short-output waste and service integration. The current loop still drafts and checks a complete final iteration before truncating output to
max_new. It does not stop on EOS, share speculative KV reservations with Continuous Batching’s scheduler, or record per-request queueing latency.
A measurement that was not about the technique
One discarded experiment illustrates how badly GPU memory pressure can corrupt a speed comparison. An earlier draft step took 285–560 ms, against roughly 18 ms when the machine later ran normally. Diagnostics showed around 4 GB associated with leftover processes and reported no free device memory after the target was loaded. Once that pressure cleared, draft latency returned to its expected range.
The suggestion that some weights had been serviced from system memory over PCIe is an inference, not a measured transfer trace: 2.3 GiB at 8 GB/s would take about 290 ms, compatible with the slowest observed regime, but not proof of the path used. Those runs were discarded. The reproducibility requirement is to record physical free/resident memory, active processes, driver state and host load alongside timing, and to reject comparisons collected during unexplained resource contention.
Other ways to propose
A separate autoregressive draft model is only one way to propose a continuation. Medusa, by Cai et al. (ICML 2024, not merely an unpublished preprint), adds prediction heads to the target model and verifies a tree of candidate continuations. Its published proceedings abstract reports over 2.2× speed-up for Medusa-1 and 2.3–2.8× for Medusa-2 in the authors’ experiments. These are not results reproduced by the Lab, and adding heads introduces training, compatibility and manifest requirements absent from draft-model speculation. DeepSeek’s DeepInfer README separately describes a draft-token and confidence-scheduled-verification feature; that repository description is vendor documentation, not a benchmark or a specification of its internal acceptance rule. These approaches share the idea of proposing ahead, but their exactness conditions, training costs, memory use and service integration differ.
Inference Lab increment
The Lab now has:
speculative_generate: the draft/target generation loop withDynamicCache.crop, greedy or sampled acceptance, and counters for proposals, accepted/considered tokens and component times; it currently truncates the last iteration’s output tomax_new.plain_greedy: the target-only baseline and step timers, used for token comparison and paired throughput measurements.accept_greedyandaccept_sample: separate acceptance helpers whose inputs must be position-aligned target logits and, for sampling, the draft’s actual proposal probabilities.expected_tokens_per_iteration,predicted_speedupandbreak_even_alpha: planning calculations under constant independent acceptance and constant draft-step cost.chi_squareand thetiming,acceptance,speed,divergence,distributioncommands;distribution --seed Nsupports repeated real-model first-token checks.
The new rule is: measure acceptance, draft cost, verification cost and output equivalence separately. Under the mathematical min/residual rule, speculative sampling preserves the target distribution; under exact greedy arithmetic, acceptance preserves the target’s arg-max continuation. Neither statement makes float16 output bit-identical in every kernel arrangement, nor guarantees a speed-up. The speed claim is an empirical property of the particular model pair, workload, hardware and generated length, and a final report should include both paired-run ratios and delivered-token throughput.
Limits of this chapter’s evidence
Set-up.
- One model pair and one GPU. The Llama-3.2-3B/1B-Instruct pair ran in fp16 at batch one on a desktop-shared RTX 2060. Model widths, kernels, memory residency and acceptance rates will differ elsewhere.
- Short, selected prompts. Twelve prompts (six from this book, three code, three structured), 64 generated tokens, three speed rounds. This is not a representative agent, chat or serving trace.
Measurements.
- Host drift and suspected paging. Some runs were discarded; even the retained paired measurements were taken across substantially changing step times.
- Sampling speed unmeasured. The real-model distribution tests use one-token distributions; the end-to-end sampling path was statistically checked only on small random CPU models.
- Numerical equivalence, not universal token identity. The greedy loop diverged on two prose prompts for some proposal lengths; the near-tie hypothesis is supported but not isolated by profiler evidence.
Model.
- A simplified independent-acceptance cost model. Proposal acceptance is correlated and changes by output class. Final-iteration output truncation also makes the recorded committed tokens-per-pass larger than useful delivered tokens-per-pass in some cases.
- The code-specific prediction gap is unresolved. The cost model overestimates speed at \(k=4\) and \(k=6\) for the three code prompts.
Scope.
- No full stopping and serving protocol. There is no EOS termination, dynamic \(k\), live scheduler, batched verification, tree drafting, queueing SLO or request cancellation.
What you should now be able to do
- Trace one speculative iteration, including the alignment of verifier logits with proposals and the target-supplied token that has not yet entered the cache.
- Derive the min/residual sampling rule and distinguish distributional correctness from identical seeded token traces.
- Explain why fp16 execution can change near-tied greedy choices even when the acceptance algorithm is mathematically exact.
- Test both a one-step categorical sampler and a two-token autoregressive loop with an independent target distribution.
- Estimate \(E[\text{tokens}]\) from a constant \(\alpha\), then replace that assumption with measured accepted-prefix lengths.
- Compute break-even \(\alpha\) and compare a model prediction with paired real timings, including final-iteration overrun.
- Identify conditions in which speculation loses: low acceptance, costly drafting, larger verification batches, or memory pressure.
- Distinguish an author-reported acceleration from one reproduced locally, and document the precision and hardware used.
Speculation changes the number and width of target calls. The speculative and plain paths here both use eager execution despite those different call shapes. Every draft and target call in this chapter was an ordinary eager PyTorch call through the library model; none was compiled or captured. Compilation and Execution Graphs looks at the other side of the cost: what changes when the operations of a decode step are captured once and replayed.
Key terms
- Draft model: the lower-cost proposer whose token probabilities may differ from the target’s.
- Target model: the model defining the desired greedy choices or sampled output distribution.
- Proposal: a token advanced by the draft before verification.
- Acceptance rate (\(\alpha\)): a conditional probability of retaining a checked proposal; \(\hat\alpha\) is estimated from accepted and considered proposals.
- Bonus token: an additional target-supplied token emitted when all proposals pass.
- Residual distribution: the normalised positive part of \(p-q\), sampled on rejection to recover the target distribution.
- Cache rollback: truncation of speculative KV state to the committed target/draft prefix.
- Break-even acceptance rate: the acceptance level at which the chosen cost model predicts speculation and target-only decoding take equal time.
- Near-tie: competing logits with a margin small enough that execution-dependent rounding may change their order.
- Final-iteration overrun: useful output stops at a requested limit although the loop may have computed more speculative tokens.
Reader exercises
- Implement adaptive \(k\) from a trailing window of acceptance counts. Compare delivered-token speed with the best fixed \(k\) separately on prose and code, including adaptation overhead.
- Use an int8 or packed-4-bit draft from Quantization and Numerical Precision, if a suitable kernel exists. Measure both \(t_d\) and \(\hat\alpha\); explain why saving bytes alone need not help.
- Run the full sampling loop on the real pair at temperatures 0.7 and 1.0. Check output distributions over multiple positions and measure wall-clock speed; include an explicit target-only sampler.
- Record accepted-prefix histograms separately for each category and \(k\). Does \(1+\sum_{j=1}^{k}P(A\ge j)\) improve speed prediction on code?
- Stop speculative work at an exact output limit, handling the bonus token, EOS and cache cropping. Which cost and acceptance counters change?
- Implement prompt-lookup drafting using tokens following a repeated n-gram; measure proposal-hit cases and fallback overhead.
- Extend verification to a batch of four unequal prefixes and proposed lengths. Report cache memory reservations, correctness and TTFT/TPOT effects as well as tokens/s.
- Recreate the near-tie divergence under controlled fp32/fp16 and fixed kernels; capture actual comparison logits at the divergence, rather than relying solely on fresh recomputations.
- Force a memory-pressure condition in a safe bounded test and record free GPU memory and transfers, without assuming PCIe paging from latency alone.
References
- Fast Inference from Transformers via Speculative Decoding — Leviathan, Kalman and Matias, ICML 2023. Original distribution-preserving speculative-decoding analysis; the paper reports 2–3× acceleration on T5-XXL against its stated baseline, not on the models in this chapter.
- Accelerating Large Language Model Decoding with Speculative Sampling — Chen et al., 2023 preprint. Independent speculative-sampling formulation and 2–2.5× results on a 70B Chinchilla model in a distributed setup; the authors qualify distribution preservation by hardware numerics.
- Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads — Cai et al., ICML 2024. Multi-head proposals and tree verification; the published proceedings abstract reports over 2.2× for Medusa-1 and 2.3–2.8× for Medusa-2 on the authors’ configurations.
- DeepSeek DeepInfer repository — vendor documentation mentioning draft-token and confidence-scheduled verification. Used only to identify a described feature, not as evidence of speed or distributional equivalence.
- Local experiment evidence:
research/ch17/results.json,research/ch17/sources.mdandexamples/ch17/speculative_lab.pyprovide the recorded observations, implementation and run assumptions.
Evidence in this chapter
| Claim | Category |
|---|---|
| Min/residual speculative sampling preserves the target conditional distribution when the correct \(p_i,q_i\) and committed prefix are used | Established mathematical result (Leviathan et al.; Chen et al.) |
| Greedy speculative acceptance preserves target-only greedy output with identical mathematical logits and tie breaking | Mathematical result; fp16 execution is not guaranteed bit-identical |
| Target verification over 1–9 positions took 31.6–33.7 ms on one short-context, batch-one timing run | Book result; 45 observations per width, single GPU |
| Full greedy runs matched plain output 36/36 at \(k=1,2\) and 30/36 at \(k=3,4,6\) | Book result; two prompts diverged at near-tied fp16 logits, original mechanism not isolated |
| Acceptance estimates: prose 0.74, code 0.95, structured 0.98 at \(k=4\); pooled approximately 0.85 across tested \(k\) | Book result; 12 selected prompts and final-iteration counters |
| Target step 33.7 ms vs draft 18.3 ms in one stable run; about 44.7 vs 24.8 ms averaged across a drifting speed run | Book results; cause of the layer-count resemblance untested |
| Pooled measured speed 1.25× at \(k=1\), 1.17× at \(k=4\), 1.00× at \(k=6\) | Book result; paired method order, short outputs, host drift |
| At \(k=6\), prose median 0.77× and structured median 1.51× | Book result; only six prose, three structured prompts across three rounds |
| Independence-based speed prediction matches pooled figures near \(k\le4\) and overpredicts at \(k=6\) | Derived model compared with measurements; approximation, not calibration proof |
| Correct one-step sampler rejected by chi-square in 1/36 tests at threshold 0.01; incorrect rules rejected in most contexts | Book result; 200,000 draws/context, first-token distributions only |
| Multi-token sampling loop matches the target’s two-token joint distribution on random small models | CPU statistical test; not full-length real-model proof |
| Under GPU contention, earlier draft-step time rose to 285–560 ms; PCIe/system-memory paging was suspected | Discarded run, documented inference without transfer trace |
| Medusa’s published 2.2×+ and 2.3–2.8×; vendor DeepInfer proposal feature | External reported claims, not reproduced |
| EOS handling, adaptive \(k\), batched sampling, tree drafts, real task traces, long-output speed and memory-transfer attribution | Not measured / not implemented |