Algorithmresearch
Speculative decoding
Also called speculative sampling.
A small draft model proposes several tokens. The large model checks them in one pass and accepts each by a rule that keeps its exact distribution.
- Solves
- Autoregressive decoding
- Time
- O(n (P + k Q + k V)) worstO(n (1 - a) / (1 - a^(k + 1)) (P + k Q + k V)) expected
- Space
- O(k V) extra
- Where
- P = the cost of one parallel call of the target; Q = the cost of one call of the draft; V = the vocabulary size |V|; a = the acceptance rate (alpha on the page); k = the number of draft tokens per step (gamma on the page); n = the number of output tokens
- Model
- Real RAM
- Properties
- randomizedexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Yaniv Leviathan, Matan Kalman, Yossi Matias, Charlie Chen, Sebastian Borgeaud, Geoffrey Irving, Jean Baptiste Lespiau, Laurent Sifre, John Jumper, 2023
Speculative decoding samples from a large autoregressive model, the target , with fewer sequential calls of it. A small draft model proposes tokens one by one. The target then scores all prefixes in one parallel pass, which on a GPU takes about as long as one ordinary step, because a decoding step of a large transformer is limited by reading the weights from memory, not by arithmetic. Each draft token is accepted with probability ; at the first rejection, a token is drawn from the normalized residual and the step ends; if all are accepted, one more token comes from for free. This is a form of rejection sampling, and the page proves that the output has exactly the distribution of sampling from . The speed up depends on how often the draft agrees with the target, and is a measurement.
In plain words
A big model writes well but slowly, one word at a time. A small model writes fast but worse. Let the small model guess the next few words. Then ask the big model about all of them at once, which costs about as much as asking for one word. Keep the guessed words while the big model agrees with them, by a random rule that is fair to the big model. At the first word it does not accept, the big model picks a replacement, and you start again from there. The text you get is a text the big model could have written by itself, with the same chances, but you asked it fewer times.
The problem
The target and the draft give, for every prefix , distributions and over a vocabulary that contains </s>. The task is to draw an output with , exactly the law of ancestral sampling from , with as few sequential calls of as possible. A call of on several prefixes of the same sequence counts as one call, because a transformer with a key-value cache scores them in one forward pass.
For one position, write and for the two distributions of the next token. The acceptance rate is
where TV is the total variation distance. It is the probability that a draft token is accepted.
The algorithm
One step, from a prefix :
SPECULATIVE-STEP(y, p, q, γ)- 1
for i ← 1 to γ do ▷ stop early after "</s>" - 2
x_i ~ q(· | y x_1 .. x_{i-1}) - 3
compute p(· | y x_1 .. x_{i-1}) for i = 1 .. γ + 1 in one call of the target - 4
for i ← 1 to γ do - 5
draw r uniform on [0, 1) - 6
if r · q(x_i | ·) < p(x_i | ·) then accept x_i and continue ▷ probability min(1, p/q) - 7
else return x_1 .. x_{i-1} and a token drawn from norm(max(0, p(· | ·) - q(· | ·))) - 8
if x_γ = "</s>" then return x_1 .. x_γ - 9
return x_1 .. x_γ and a token drawn from p(· | y x_1 .. x_γ)
The decoder repeats steps from the growing output until it ends with </s> or reaches the length limit; near the limit, the step drafts fewer tokens so that it never overshoots. The test in line L6 is written without a division, so a draft probability of 0 needs no special case: a token with is never drafted. If , the residual has mass 0, but then no rejection happens.
Example
The target is the model M1 of greedy decoding. At the empty prefix the two models are
| token | a | b | </s> |
|---|---|---|---|
| 0.5 | 0.4 | 0.1 | |
| 0.7 | 0.2 | 0.1 | |
| 0.5 | 0.2 | 0.1 | |
| 0 | 0.2 | 0 |
So , and the residual puts all its mass on b. Check the law of the first token:
- a is drafted with probability 0.7 and accepted with probability , so it is output with probability 0.5;
- b is drafted with probability 0.2 and always accepted, and every rejection (probability ) outputs b too, so b comes out with probability 0.4;
</s>is drafted with probability 0.1 and always accepted: 0.1.
That is . The draft offers too much a and too little b, and the rejection step moves exactly the excess of a to b.
If every draft token were accepted with probability independently, a step with would yield tokens per call of the target on average. The test runs 10000 steps on a pair of models that give the rows of the table at every position, with a third token c in place of </s>, so that the rate is 0.8 at every position and the acceptances are independent. It measures an acceptance rate near 0.8 and about 3.36 tokens per call. When the two models are equal, every draft token is accepted, and 400 tokens take 100 target calls with .
Correctness
The proof is in proofs/correctness.md. The core is one line: the probability that a step emits at a given position is
The proof then shows by induction over the positions that each emitted token, given every token before it, has the law , whether it came from an accepted draft, a rejection or the bonus draw of line L9. By the chain rule the output has the law of sampling from . This is a theorem, and the test checks it twice: the exact law of the output, computed with fractions over every path of the algorithm, equals the target law for to 3, and the frequencies of 20000 sampled outputs agree with it.
The same proof gives the mean number of tokens per step, , under the assumption that each draft token is accepted with probability independently; the test checks the exact mean against this formula for to 5. On real models the rate varies from position to position, so the formula is a model of the speed, not a theorem about it.
Proof: Speculative decoding samples exactly from the targetfull
We use the notation of the page. For a prefix , and are distributions over , which contains </s>. The decoder has a length limit ; the target law is the law of ancestral sampling from stopped at </s> or after tokens. We assume exact arithmetic and an exact uniform generator.
Lemma 1 (one position). Let and be distributions on and . Draw and uniform on . If , output and call the draw accepted; otherwise output a draw from . Then the output has law , and the draw is accepted with probability .
Proof. is drafted only when , and then . So is output by acceptance with probability , and the acceptance probability is . If , a rejection happens with probability , and since , the residual is a distribution. The output is with probability . If then , no rejection happens, and the output law is .
The emitted stream. Run the decoder and list the tokens it emits in order, . Each is produced by one of three mechanisms:
- an accepted draft at line L6, or a residual draw at line L7, at some position of a step: this is one run of Lemma 1 with and , because the draft token was drawn from at the prefix , and were accepted, so that prefix is ;
- the bonus draw of line L9, from directly;
- a residual or bonus draw at the start of a new step, which is the same as case 1 or 2 with the step's prefix .
Let be everything drawn before the mechanism that produces starts: all earlier uniforms, drafts and residual draws. Which mechanism produces , and with which , is a function of (whether the previous position was accepted, how many drafts the step has left, how much room is left). The draws of the mechanism itself are fresh: the draft and the uniform at position are drawn after is fixed. One subtle point: the drafts of the same step are drawn before the test at position . Each is drawn from at the prefix , and the test at position uses only , and the two distributions at position . So drawing lazily, after the test at position , gives the same joint law of all draws, and we may assume that order. Then is the fresh draft of case 1 at the next position.
Lemma 2 (the conditional law). For every , given , the token has law .
Proof. In case 2 this is the definition of the bonus draw. In cases 1 and 3, the draft at the position has law given , the uniform and the residual draw are independent of , and Lemma 1 applies with and . The prefix is a function of , so the conditional law is .
Theorem 3 (exactness). The output of SPECULATIVE-DECODE has the target law: for every sequence that ends with </s> (with no earlier </s>) and has , or that has tokens and no </s>, .
Proof. The decoder stops exactly when the emitted stream ends with </s> or reaches tokens: line L8 returns after an accepted </s> draft without a bonus, line L1 stops drafting after </s>, and the room argument keeps every step within tokens. So the output is with the same stopping rule as ancestral sampling. By Lemma 2 and the tower rule, , by induction on : the event is a union of events in , and on each of them .
Theorem 4 (tokens per step). Suppose that at every position the draft token is accepted with probability , independently of everything before it, and that no </s> and no length limit interrupts the step. Then a step emits tokens on average, and if .
Proof. Let be the number of accepted drafts. Then for . The step emits tokens: the accepted drafts and either the residual draw (if ) or the bonus draw (if ). So the mean is .
The independence assumption holds in the test model, where both models give the same rows at every prefix. It fails for real models, where depends on the prefix; then Theorem 4 is a model of the speed, while Theorem 3 still holds exactly.
Complexity
A step makes at most draft calls, one target call, and work for the tests and the residual. In the worst case every step emits one token, so tokens take target calls, no fewer than plain sampling, plus the draft work. With independent acceptances at rate , a step emits tokens on average, so the expected number of target calls is about .
If one draft call costs times one target call, a step costs target calls of time, and the expected speed up in wall time over plain sampling is
under the same assumptions, and assuming that the parallel call on prefixes takes the time of one call. It grows with and has a best for each and . Leviathan et al. measured speed ups of 2 to 3 times on T5-XXL against the standard implementation, a measurement on their hardware. The total arithmetic grows, because rejected draft tokens are scored and thrown away; the method trades arithmetic for fewer sequential steps, which pays when the target is limited by memory bandwidth (see the roofline model).
The extra space is the target distributions and the draft distributions of one step, , plus the key-value caches of both models.
Properties
- Exact (a theorem). The output has the law of sampling from the target, for any draft model, any and any acceptance rate.
- Never wrong, sometimes slow. A bad draft only lowers ; it never biases the output.
- At least one token per target call. Every step emits between 1 and tokens.
- Greedy mode. With temperature 0, accept a draft token when it equals the argmax of the target and otherwise emit the argmax. The output is then the output of greedy decoding of the target.
- Works with any sampler that changes the distribution per position, such as temperature sampling, as long as and in the test are the distributions after that change.
Variants and improvements
- Draft choices. A smaller model of the same family, a model trained by knowledge distillation to match the target (which raises ), extra prediction heads on the target itself, or n-gram matches from the prompt.
- Draft trees. Propose a tree of continuations and verify all its branches in one pass with a tree-shaped attention mask, to raise the expected accepted length.
- Adaptive . Stop drafting when the draft model's confidence drops, since a token it is unsure of is likely to be rejected.
- Blockwise parallel decoding. An earlier greedy scheme (Stern, Shazeer and Uszkoreit 2018) predicted several future tokens with extra heads and kept the longest prefix that the model's greedy choices confirmed.
- Non-autoregressive generation. Non-autoregressive translation drops the sequential dependency instead, and changes the output distribution; speculative decoding keeps it.
When to use it
Use speculative decoding to cut the latency of a large model at batch size 1 or small batches, where each step is limited by memory bandwidth, and when a cheap draft with a high acceptance rate exists. At large batch sizes the hardware is already busy with arithmetic, and the extra work of rejected drafts can make the total slower. Measure on your data before choosing .
Pitfalls
- Testing the wrong distributions. The test must use the same processed distributions (temperature, top-k, penalties) for and that the sampler uses. Using raw with a filtered breaks exactness.
- A drifting key-value cache. After a rejection, the caches of both models hold entries for draft tokens that were thrown away. Truncate them to the accepted length.
- Floating-point ties. The residual of two nearly equal distributions is tiny and noisy. If it sums to 0 after rounding, fall back to , as the code does.
- Speed ups are not universal. They depend on , , , the batch size and the hardware. Report them as measurements.
- The draft must cover the target's support. It need not, for exactness, but tokens with are only produced by the residual, which lowers .
Implementations
The code takes the next-token distributions of the target and the draft as given, as functions of the prefix, and implements the drafting, the acceptance test and the residual sampling; it does not run or train a network. One call of the target on prefixes stands for one parallel forward pass and is counted as one call.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/speculative-decoding/. The authors are listed in prov/K824EJ.jsonl.
"""Speculative decoding (Leviathan, Kalman and Matias 2023; Chen et al. 2023).
The target model p and the draft model q are functions that take a prefix
(a tuple of strings) and return a dict from each token to its probability.
The end token is the string "</s>". The code takes these distributions as
given; it does not run or train a network. One call of the target on
gamma + 1 prefixes stands for the one parallel forward pass of a real
system, and is counted as one target call.
"""
import random
from typing import Callable, Dict, List, Optional, Tuple
EOS = "</s>"
Dist = Dict[str, float]
Model = Callable[[Tuple[str, ...]], Dist]
def sample(dist: Dist, rng: random.Random) -> str:
"""Draw a token from dist (weights that need not sum to 1), by the cumulative sum."""
total = sum(dist.values())
u = rng.random() * total
acc = 0.0
last = None
for w, pw in dist.items():
if pw <= 0:
continue
acc += pw
last = w
if u < acc:
return w
if last is None:
raise ValueError("every weight is zero")
return last
def residual(p: Dist, q: Dist) -> Dist:
"""Return max(0, p - q), normalized. If p and q are equal, return p."""
r = {w: max(0, p[w] - q.get(w, 0)) for w in p}
total = sum(r.values())
if total == 0:
return dict(p)
return {w: v / total for w, v in r.items()}
def speculative_step(
prefix: Tuple[str, ...],
target: Model,
draft: Model,
gamma: int,
rng: random.Random,
room: int,
stats: Optional[Dict[str, int]] = None,
) -> List[str]:
"""Return the 1 to gamma + 1 tokens that one step appends to prefix.
At most room tokens are returned. The draft proposes up to
min(gamma, room - 1) tokens and stops after "</s>".
"""
g = min(gamma, room - 1)
xs: List[str] = []
qs: List[Dist] = []
for _ in range(g): # @line L1
q = draft(prefix + tuple(xs))
x = sample(q, rng) # @line L2
xs.append(x)
qs.append(q)
if x == EOS:
break
ended = bool(xs) and xs[-1] == EOS
ps = [target(prefix + tuple(xs[:i])) for i in range(len(xs) + (0 if ended else 1))] # @line L3
if stats is not None:
stats["target_calls"] = stats.get("target_calls", 0) + 1
stats["draft_calls"] = stats.get("draft_calls", 0) + len(xs)
stats["drafted"] = stats.get("drafted", 0) + len(xs)
for i, x in enumerate(xs): # @line L4
r = rng.random() # @line L5
if stats is not None:
stats["tried"] = stats.get("tried", 0) + 1
if r * qs[i][x] < ps[i].get(x, 0): # @line L6
if stats is not None:
stats["accepted"] = stats.get("accepted", 0) + 1
continue
return xs[:i] + [sample(residual(ps[i], qs[i]), rng)] # @line L7
if ended: # @line L8
return xs
return xs + [sample(ps[len(xs)], rng)] # @line L9
def speculative_decode(
target: Model,
draft: Model,
gamma: int,
max_len: int,
rng: random.Random,
stats: Optional[Dict[str, int]] = None,
) -> List[str]:
"""Return an output of at most max_len tokens, distributed as a sample of the target."""
if gamma < 0 or max_len < 1:
raise ValueError("gamma must be at least 0 and max_len at least 1")
y: List[str] = []
while len(y) < max_len and (not y or y[-1] != EOS):
y += speculative_step(tuple(y), target, draft, gamma, rng, max_len - len(y), stats)
return y
def expected_tokens_per_step(alpha: float, gamma: int) -> float:
"""Return (1 - alpha^(gamma + 1)) / (1 - alpha), the mean tokens per target call.
This holds when every draft token is accepted with the same probability
alpha, independently of the others.
"""
if alpha == 1:
return gamma + 1
return (1 - alpha ** (gamma + 1)) / (1 - alpha)
def acceptance_rate(p: Dist, q: Dist) -> float:
"""Return alpha = sum over w of min(p(w), q(w))."""
return sum(min(p[w], q.get(w, 0)) for w in p)
test_speculative_decoding.py 197 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/speculative-decoding/. The authors are listed in prov/K824EJ.jsonl.
import math
import random
from collections import Counter, defaultdict
from fractions import Fraction as F
from speculative_decoding import (
EOS,
acceptance_rate,
expected_tokens_per_step,
residual,
sample,
speculative_decode,
speculative_step,
)
P_ROWS = {
(): {"a": F(1, 2), "b": F(2, 5), EOS: F(1, 10)},
("a",): {"a": F(2, 5), "b": F(3, 10), EOS: F(3, 10)},
("b",): {"a": F(1, 20), "b": F(1, 20), EOS: F(9, 10)},
}
Q_ROWS = {
(): {"a": F(7, 10), "b": F(1, 5), EOS: F(1, 10)},
("a",): {"a": F(1, 5), "b": F(1, 2), EOS: F(3, 10)},
("b",): {"a": F(3, 10), "b": F(3, 10), EOS: F(2, 5)},
}
END = {"a": F(0), "b": F(0), EOS: F(1)}
def p_exact(prefix):
return P_ROWS.get(tuple(prefix), END)
def q_exact(prefix):
return Q_ROWS.get(tuple(prefix), END)
def as_float(model):
cache = {}
def m(prefix):
if prefix not in cache:
cache[prefix] = {w: float(v) for w, v in model(prefix).items()}
return cache[prefix]
return m
def step_law(prefix, target, draft, gamma, room):
"""The exact law of one step, in Fractions, enumerated over the draft and the coin flips."""
g = min(gamma, room - 1)
out = defaultdict(F)
def rec(xs, prob):
p = target(prefix + tuple(xs))
if xs and xs[-1] == EOS:
out[tuple(xs)] += prob
return
if len(xs) == g:
for t, pt in p.items():
if pt:
out[tuple(xs) + (t,)] += prob * pt
return
q = draft(prefix + tuple(xs))
res = residual(p, q)
for x, qx in q.items():
if qx == 0:
continue
acc = min(F(1), p.get(x, F(0)) / qx)
if acc:
rec(xs + [x], prob * qx * acc)
if acc < 1:
for t, rt in res.items():
if rt:
out[tuple(xs) + (t,)] += prob * qx * (1 - acc) * rt
rec([], F(1))
return out
def output_law(target, draft, gamma, max_len, prefix=()):
if len(prefix) == max_len or (prefix and prefix[-1] == EOS):
return {prefix: F(1)}
out = defaultdict(F)
for block, pr in step_law(prefix, target, draft, gamma, max_len - len(prefix)).items():
for seq, pr2 in output_law(target, draft, gamma, max_len, prefix + block).items():
out[seq] += pr * pr2
return out
def target_law(target, max_len, prefix=()):
if len(prefix) == max_len or (prefix and prefix[-1] == EOS):
return {prefix: F(1)}
out = defaultdict(F)
for t, pt in target(prefix).items():
if pt:
for seq, pr in target_law(target, max_len, prefix + (t,)).items():
out[seq] += pt * pr
return out
def random_rows(seed, vocab, n):
def model(prefix):
if len(prefix) >= n - 1:
return {w: F(int(w == EOS)) for w in vocab}
rng = random.Random(f"{seed}|{' '.join(prefix)}")
ws = [rng.randrange(0, 6) for _ in vocab]
ws[-1] += 1
return {w: F(x, sum(ws)) for w, x in zip(vocab, ws)}
return model
def test_example_numbers() -> None:
p, q = P_ROWS[()], Q_ROWS[()]
assert acceptance_rate(p, q) == F(4, 5)
assert residual(p, q) == {"a": 0, "b": 1, EOS: 0}
assert math.isclose(expected_tokens_per_step(0.8, 4), 3.3616)
assert expected_tokens_per_step(1, 4) == 5
def test_one_step_has_the_target_law() -> None:
# With gamma = 1 the first token of the step is distributed as p.
law = step_law((), p_exact, q_exact, 1, 3)
first = defaultdict(F)
for block, pr in law.items():
first[block[0]] += pr
assert dict(first) == P_ROWS[()]
assert sum(law.values()) == 1
def test_exact_output_law_equals_the_target() -> None:
want = target_law(p_exact, 3)
for gamma in range(0, 4):
assert output_law(p_exact, q_exact, gamma, 3) == want
vocab = ["a", "b", EOS]
for seed in range(8):
target = random_rows(seed, vocab, 4)
draft = random_rows(seed + 100, vocab, 4)
want = target_law(target, 4)
for gamma in (1, 2, 3):
assert output_law(target, draft, gamma, 4) == want
def test_sample_frequencies() -> None:
rng = random.Random(1)
target, draft = as_float(p_exact), as_float(q_exact)
want = target_law(p_exact, 3)
draws = 20000
counts = Counter(tuple(speculative_decode(target, draft, 3, 3, rng)) for _ in range(draws))
assert set(counts) <= set(want)
for seq, pr in want.items():
assert abs(counts[seq] / draws - float(pr)) < 0.01
def test_acceptance_rate_and_tokens_per_call() -> None:
p = {"a": 0.5, "b": 0.4, "c": 0.1}
q = {"a": 0.7, "b": 0.2, "c": 0.1}
target = lambda prefix: p # noqa: E731
draft = lambda prefix: q # noqa: E731
rng = random.Random(2)
stats = {}
steps = 10000
tokens = sum(len(speculative_step((), target, draft, 4, rng, 100, stats)) for _ in range(steps))
assert stats["target_calls"] == steps
assert abs(stats["accepted"] / stats["tried"] - 0.8) < 0.01
assert abs(tokens / steps - 3.3616) < 0.05
y = speculative_decode(target, draft, 4, 50, rng)
assert len(y) == 50
def test_exact_mean_tokens_per_step() -> None:
p = {"a": F(1, 2), "b": F(2, 5), "c": F(1, 10)}
q = {"a": F(7, 10), "b": F(1, 5), "c": F(1, 10)}
alpha = acceptance_rate(p, q)
for gamma in range(0, 6):
law = step_law((), lambda s: p, lambda s: q, gamma, 100)
mean = sum(len(block) * pr for block, pr in law.items())
assert mean == (1 - alpha ** (gamma + 1)) / (1 - alpha)
def test_equal_models_accept_everything() -> None:
p = {"a": 0.25, "b": 0.75}
rng = random.Random(3)
stats = {}
speculative_decode(lambda s: p, lambda s: p, 3, 400, rng, stats)
assert stats["accepted"] == stats["drafted"]
assert stats["target_calls"] == 100
def test_sample_helper() -> None:
rng = random.Random(4)
counts = Counter(sample({"x": 1, "y": 3, "z": 0}, rng) for _ in range(20000))
assert counts["z"] == 0
assert abs(counts["y"] / 20000 - 0.75) < 0.01
History
Leviathan, Kalman and Matias, and Chen, Borgeaud, Irving, Lespiau, Sifre and Jumper found the same acceptance rule independently: the first posted in November 2022 and published at ICML 2023, and the second posted in February 2023. Both prove that the rule keeps the target's distribution. Earlier work on blockwise parallel decoding had used a similar draft and verify loop for greedy decoding only. The method is now a standard part of large model serving.
References
- Yaniv Leviathan, Matan Kalman and Yossi Matias, Fast inference from transformers via speculative decoding, ICML 2023, PMLR 202, pages 19274 to 19286, Algorithm 1 (one step of speculative decoding), Section 3 (the acceptance rate and Equation (1) for the expected number of tokens per run of the target), and Appendix A.1 (the proof that the output follows the target)
- Charlie Chen, Sebastian Borgeaud, Geoffrey Irving, Jean-Baptiste Lespiau, Laurent Sifre and John Jumper, Accelerating large language model decoding with speculative sampling, arXiv 2302.01318, 2023, the modified rejection sampling scheme and its proof
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag K824EJ Edit this page History Report an error Markdown