Algorithm Search⌘K

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.

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
Properties
randomizedexactonlineiterative
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 pp, with fewer sequential calls of it. A small draft model qq proposes γ\gamma tokens one by one. The target then scores all γ+1\gamma + 1 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 xx is accepted with probability min⁡(1,p(x)/q(x))\min(1, p(x) / q(x)); at the first rejection, a token is drawn from the normalized residual max⁡(0,p−q)\max(0, p - q) and the step ends; if all are accepted, one more token comes from pp for free. This is a form of rejection sampling, and the page proves that the output has exactly the distribution of sampling from pp. 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 yy, distributions p(⋅∣y)p(\cdot \mid y) and q(⋅∣y)q(\cdot \mid y) over a vocabulary VV that contains </s>. The task is to draw an output yy with P(y)=∏tp(yt∣y<t)P(y) = \prod_t p(y_t \mid y_{<t}), exactly the law of ancestral sampling from pp, with as few sequential calls of pp as possible. A call of pp 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 pp and qq for the two distributions of the next token. The acceptance rate is

α=∑x∈Vmin⁡(p(x),q(x))=1−TV(p,q),\alpha = \sum_{x \in V} \min(p(x), q(x)) = 1 - \mathrm{TV}(p, q),

where TV is the total variation distance. It is the probability that a draft token is accepted.

The algorithm

One step, from a prefix yy:

  1. SPECULATIVE-STEP(y, p, q, γ)
  2. 1for i ← 1 to γ do ▷ stop early after "</s>"
  3. 2x_i ~ q(· | y x_1 .. x_{i-1})
  4. 3compute p(· | y x_1 .. x_{i-1}) for i = 1 .. γ + 1 in one call of the target
  5. 4for i ← 1 to γ do
  6. 5draw r uniform on [0, 1)
  7. 6if r · q(x_i | ·) < p(x_i | ·) then accept x_i and continue ▷ probability min(1, p/q)
  8. 7else return x_1 .. x_{i-1} and a token drawn from norm(max(0, p(· | ·) - q(· | ·)))
  9. 8if x_γ = "</s>" then return x_1 .. x_γ
  10. 9return 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 q(x)=0q(x) = 0 is never drafted. If p=qp = q, the residual has mass 0, but then no rejection happens.

Example

The target pp is the model M1 of greedy decoding. At the empty prefix the two models are

token a b </s>
pp 0.5 0.4 0.1
qq 0.7 0.2 0.1
min⁡(p,q)\min(p, q) 0.5 0.2 0.1
max⁡(0,p−q)\max(0, p - q) 0 0.2 0

So α=0.8\alpha = 0.8, 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 0.5/0.70.5 / 0.7, so it is output with probability 0.5;
  • b is drafted with probability 0.2 and always accepted, and every rejection (probability 1−α=0.21 - \alpha = 0.2) 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 pp. 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 α=0.8\alpha = 0.8 independently, a step with γ=4\gamma = 4 would yield (1−0.85)/(1−0.8)=3.3616(1 - 0.8^5) / (1 - 0.8) = 3.3616 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 γ=3\gamma = 3.

Correctness

The proof is in proofs/correctness.md. The core is one line: the probability that a step emits xx at a given position is

q(x)min⁡(1,p(x)q(x))+(1−α)max⁡(0,p(x)−q(x))1−α=min⁡(p(x),q(x))+max⁡(0,p(x)−q(x))=p(x).q(x) \min\Big(1, \frac{p(x)}{q(x)}\Big) + (1 - \alpha) \frac{\max(0, p(x) - q(x))}{1 - \alpha} = \min(p(x), q(x)) + \max(0, p(x) - q(x)) = p(x).

The proof then shows by induction over the positions that each emitted token, given every token before it, has the law p(⋅∣prefix)p(\cdot \mid \text{prefix}), 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 pp. 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 γ=0\gamma = 0 to 3, and the frequencies of 20000 sampled outputs agree with it.

The same proof gives the mean number of tokens per step, (1−αγ+1)/(1−α)(1 - \alpha^{\gamma + 1}) / (1 - \alpha), under the assumption that each draft token is accepted with probability α\alpha independently; the test checks the exact mean against this formula for γ=0\gamma = 0 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 yy, py=p(⋅∣y)p_y = p(\cdot \mid y) and qy=q(⋅∣y)q_y = q(\cdot \mid y) are distributions over VV, which contains </s>. The decoder has a length limit nn; the target law is the law of ancestral sampling from pp stopped at </s> or after nn tokens. We assume exact arithmetic and an exact uniform generator.

Lemma 1 (one position). Let pp and qq be distributions on VV and α=∑xmin⁡(p(x),q(x))\alpha = \sum_x \min(p(x), q(x)). Draw X∼qX \sim q and RR uniform on [0,1)[0, 1). If R q(X)<p(X)R \, q(X) < p(X), output XX and call the draw accepted; otherwise output a draw from r=max⁡(0,p−q)/(1−α)r = \max(0, p - q) / (1 - \alpha). Then the output has law pp, and the draw is accepted with probability α\alpha.

Proof. XX is drafted only when q(X)>0q(X) > 0, and then P(R q(X)<p(X))=min⁡(1,p(X)/q(X))P(R \, q(X) < p(X)) = \min(1, p(X) / q(X)). So xx is output by acceptance with probability q(x)min⁡(1,p(x)/q(x))=min⁡(p(x),q(x))q(x) \min(1, p(x) / q(x)) = \min(p(x), q(x)), and the acceptance probability is α\alpha. If α<1\alpha < 1, a rejection happens with probability 1−α1 - \alpha, and since ∑xmax⁡(0,p(x)−q(x))=∑x(p(x)−min⁡(p(x),q(x)))=1−α\sum_x \max(0, p(x) - q(x)) = \sum_x (p(x) - \min(p(x), q(x))) = 1 - \alpha, the residual rr is a distribution. The output is xx with probability min⁡(p(x),q(x))+(1−α)r(x)=min⁡(p(x),q(x))+max⁡(0,p(x)−q(x))=p(x)\min(p(x), q(x)) + (1 - \alpha) r(x) = \min(p(x), q(x)) + \max(0, p(x) - q(x)) = p(x). If α=1\alpha = 1 then p=qp = q, no rejection happens, and the output law is q=pq = p. □\square

The emitted stream. Run the decoder and list the tokens it emits in order, z1,z2,…z_1, z_2, \ldots. Each ztz_t is produced by one of three mechanisms:

  1. an accepted draft at line L6, or a residual draw at line L7, at some position ii of a step: this is one run of Lemma 1 with p=pz<tp = p_{z_{<t}} and q=qz<tq = q_{z_{<t}}, because the draft token xix_i was drawn from qq at the prefix yx1…xi−1y x_1 \ldots x_{i-1}, and x1…xi−1x_1 \ldots x_{i-1} were accepted, so that prefix is z<tz_{<t};
  2. the bonus draw of line L9, from pz<tp_{z_{<t}} directly;
  3. 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 y=z<ty = z_{<t}.

Let Ft−1\mathcal{F}_{t-1} be everything drawn before the mechanism that produces ztz_t starts: all earlier uniforms, drafts and residual draws. Which mechanism produces ztz_t, and with which γ\gamma, is a function of Ft−1\mathcal{F}_{t-1} (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 xix_i and the uniform RR at position ii are drawn after Ft−1\mathcal{F}_{t-1} is fixed. One subtle point: the drafts xi+1,…,xγx_{i+1}, \ldots, x_\gamma of the same step are drawn before the test at position ii. Each xjx_{j} is drawn from qq at the prefix yx1…xj−1y x_1 \ldots x_{j-1}, and the test at position ii uses only xix_i, RR and the two distributions at position ii. So drawing xi+1,…,xγx_{i+1}, \ldots, x_\gamma lazily, after the test at position ii, gives the same joint law of all draws, and we may assume that order. Then xi+1x_{i+1} is the fresh draft of case 1 at the next position.

Lemma 2 (the conditional law). For every tt, given Ft−1\mathcal{F}_{t-1}, the token ztz_t has law pz<tp_{z_{<t}}.

Proof. In case 2 this is the definition of the bonus draw. In cases 1 and 3, the draft xx at the position has law qz<tq_{z_{<t}} given Ft−1\mathcal{F}_{t-1}, the uniform RR and the residual draw are independent of Ft−1\mathcal{F}_{t-1}, and Lemma 1 applies with p=pz<tp = p_{z_{<t}} and q=qz<tq = q_{z_{<t}}. The prefix z<tz_{<t} is a function of Ft−1\mathcal{F}_{t-1}, so the conditional law is pz<tp_{z_{<t}}. □\square

Theorem 3 (exactness). The output of SPECULATIVE-DECODE has the target law: for every sequence y=y1…ymy = y_1 \ldots y_m that ends with </s> (with no earlier </s>) and has m≤nm \le n, or that has m=nm = n tokens and no </s>, P(output=y)=∏t=1mp(yt∣y<t)P(\text{output} = y) = \prod_{t=1}^{m} p(y_t \mid y_{<t}).

Proof. The decoder stops exactly when the emitted stream ends with </s> or reaches nn 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 nn tokens. So the output is z1…zmz_1 \ldots z_m with the same stopping rule as ancestral sampling. By Lemma 2 and the tower rule, P(z1=y1,…,zm=ym)=∏tp(yt∣y<t)P(z_1 = y_1, \ldots, z_m = y_m) = \prod_t p(y_t \mid y_{<t}), by induction on mm: the event {z<t=y<t}\{z_{<t} = y_{<t}\} is a union of events in Ft−1\mathcal{F}_{t-1}, and on each of them P(zt=yt∣Ft−1)=p(yt∣y<t)P(z_t = y_t \mid \mathcal{F}_{t-1}) = p(y_t \mid y_{<t}). □\square

Theorem 4 (tokens per step). Suppose that at every position the draft token is accepted with probability α\alpha, independently of everything before it, and that no </s> and no length limit interrupts the step. Then a step emits (1−αγ+1)/(1−α)(1 - \alpha^{\gamma + 1}) / (1 - \alpha) tokens on average, and γ+1\gamma + 1 if α=1\alpha = 1.

Proof. Let KK be the number of accepted drafts. Then P(K≥i)=αiP(K \ge i) = \alpha^i for 0≤i≤γ0 \le i \le \gamma. The step emits K+1K + 1 tokens: the KK accepted drafts and either the residual draw (if K<γK < \gamma) or the bonus draw (if K=γK = \gamma). So the mean is 1+E[K]=1+∑i=1γP(K≥i)=∑i=0γαi1 + E[K] = 1 + \sum_{i=1}^{\gamma} P(K \ge i) = \sum_{i=0}^{\gamma} \alpha^i. □\square

The independence assumption holds in the test model, where both models give the same rows at every prefix. It fails for real models, where α\alpha 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 γ\gamma draft calls, one target call, and O(γ∣V∣)O(\gamma |V|) work for the tests and the residual. In the worst case every step emits one token, so nn tokens take nn target calls, no fewer than plain sampling, plus the draft work. With independent acceptances at rate α\alpha, a step emits (1−αγ+1)/(1−α)(1 - \alpha^{\gamma + 1}) / (1 - \alpha) tokens on average, so the expected number of target calls is about n(1−α)/(1−αγ+1)n (1 - \alpha) / (1 - \alpha^{\gamma + 1}).

If one draft call costs cc times one target call, a step costs γc+1\gamma c + 1 target calls of time, and the expected speed up in wall time over plain sampling is

1−αγ+1(1−α)(γc+1),\frac{1 - \alpha^{\gamma + 1}}{(1 - \alpha)(\gamma c + 1)},

under the same assumptions, and assuming that the parallel call on γ+1\gamma + 1 prefixes takes the time of one call. It grows with α\alpha and has a best γ\gamma for each α\alpha and cc. 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 γ+1\gamma + 1 target distributions and the γ\gamma draft distributions of one step, O(γ∣V∣)O(\gamma |V|), 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 γ\gamma and any acceptance rate.
  • Never wrong, sometimes slow. A bad draft only lowers α\alpha; it never biases the output.
  • At least one token per target call. Every step emits between 1 and γ+1\gamma + 1 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 pp and qq 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 α\alpha), 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 γ\gamma. 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 α\alpha on your data before choosing γ\gamma.

Pitfalls

  • Testing the wrong distributions. The test must use the same processed distributions (temperature, top-k, penalties) for pp and qq that the sampler uses. Using raw pp with a filtered qq 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 max⁡(0,p−q)\max(0, p - q) of two nearly equal distributions is tiny and noisy. If it sums to 0 after rounding, fall back to pp, as the code does.
  • Speed ups are not universal. They depend on α\alpha, γ\gamma, cc, 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 q(x)=0q(x) = 0 are only produced by the residual, which lowers α\alpha.

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 γ+1\gamma + 1 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.

speculative_decoding.pyI0RawGitHub
# 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

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example