AI Logic

Decoding

Speculative Sampling

Updated:

The flow of speculative sampling and an example of the decision. The top shows one loop with K = 3: the draft model p generates "sunny, and, hot" in turn, the target model q computes the probabilities at 4 positions in one pass, "sunny" and "and" are accepted, and "hot" is rejected and resampled as "cold". The bottom shows a single position after "Today is": on the left, bars of q and p for each word with the acceptance probability min(1, q/p) (sunny 0.75, hot 0.67, others 1); on the right, the distribution (q − p)+ resampled from on rejection (rainy and Sunday 0.33, cold 0.20, etc.)

What is speculative sampling?

Speculative sampling is a method that speeds up text generation with a large model by having a small, fast "draft model" write several tokens ahead, checking them all at once with the large "target model" in a single computation, and deciding which to accept with a special accept/reject rule. Because the acceptance rule is carefully designed, the probability distribution of the generated text is exactly the same (up to numerical error) as when the large model alone generates one token at a time. The name was coined by Chen et al. (2023) at DeepMind, who made generation with the 70-billion-parameter Chinchilla 2–2.5 times faster.

Generation with large language models is slow because every token requires reading all of the model's weights from memory, so time is bound by memory bandwidth rather than computation. On the other hand, computing the probabilities at each position of a few existing continuation tokens in parallel, all at once, takes about as long as generating a single token. Speculative sampling exploits this gap.

This article focuses on the probabilistic rule of which tokens to accept and what to resample on rejection (the decoding part). Around the same time, Leviathan et al. (2023) at Google independently published the same idea as "speculative decoding," and the analysis of the speedup and implementation techniques are covered in the speculative decoding article. Chen et al. also state that the core idea is the same.

Procedure

Following the notation of Chen et al., let qq be the probabilities of the target model (large) and pp those of the draft model (small). Given the context x1,…,xnx_1, \dots, x_n, one loop does the following (Algorithm 2 in the paper).

  1. With the draft model, sample KK tokens x~1,…,x~K\tilde{x}_1, \dots, \tilde{x}_K one at a time in sequence.
  2. Feed the context followed by the draft into the target model just once, and compute the probabilities at K+1K + 1 positions, q(x∣x1:n)q(x \mid x_{1:n}), q(x∣x1:n,x~1)q(x \mid x_{1:n}, \tilde{x}_1), …, q(x∣x1:n,x~1:K)q(x \mid x_{1:n}, \tilde{x}_{1:K}), in parallel.
  3. Going from left to right, accept each draft token with the following probability (qq and pp are the probabilities in the context at that position).
min⁡(1,q(x~t)p(x~t))\min\left(1, \frac{q(\tilde{x}_t)}{p(\tilde{x}_t)}\right)
  1. If accepted, move on to the next token. If rejected, resample the token at that position from the following distribution, discard the rest of the draft, and end the loop.
x∼(q(x)−p(x))+,(f(x))+=max⁡(0,f(x))∑x′max⁡(0,f(x′))x \sim \left(q(x) - p(x)\right)_+, \qquad \left(f(x)\right)_+ = \frac{\max\left(0, f(x)\right)}{\sum_{x'} \max\left(0, f(x')\right)}
  1. If all KK tokens are accepted, sample one more token from qq at the (K+1)(K + 1)-th position, already computed in step 2.

In one loop, a single call to the target model determines at least 1 and at most K+1K + 1 tokens. Even if the first draft token is rejected, the resampled token always remains.

Example: the token after "Today is"

The lower part of the figure at the top of the article shows an example of the decision at the first position. The target model's probabilities qq are the same values for what follows "Today is" used in articles such as top-k sampling, and the draft model's probabilities pp are illustrative values.

WordTarget qqDraft ppAcceptance probability min⁡(1,q/p)\min(1, q/p)Resampling distribution (q−p)+(q - p)_+
sunny0.300.400.750
rainy0.200.1510.05 / 0.15 = 0.33
Sunday0.150.1010.05 / 0.15 = 0.33
hot0.100.150.670
cold0.080.0510.03 / 0.15 = 0.20
Monday0.060.0510.01 / 0.15 = 0.07
the0.030.0210.01 / 0.15 = 0.07
nice, cat, of0.05, 0.02, 0.010.05, 0.02, 0.0110
  • When the draft model outputs "sunny," it overestimates by 0.10 relative to the target model, so the token is accepted with probability 0.75 and rejected with probability 0.25.
  • When the draft model outputs "rainy," the target model gives it a higher estimate, so it is always accepted.
  • On rejection, the token is resampled from the amount by which the target model's estimate exceeded the draft's, (q−p)+(q - p)_+. Words the draft rarely produces, such as "rainy" and "Sunday," are made up for here.

For example, the probability that "rainy" is finally chosen is the sum of "the draft outputs rainy and it is accepted," 0.15×1=0.150.15 \times 1 = 0.15, and "something is rejected and resampling yields rainy," 0.15×0.33=0.050.15 \times 0.33 = 0.05, for a total of 0.200.20, which matches the target model's probability q(rainy)=0.20q(\text{rainy}) = 0.20. The probability of a rejection, 0.150.15, is 1−∑xmin⁡(q(x),p(x))=1−0.851 - \sum_x \min(q(x), p(x)) = 1 - 0.85.

The upper part of the figure shows a full loop with K=3K = 3. Of the draft "sunny, and, hot," "sunny" and "and" are accepted, "hot" is rejected, and "cold" is resampled, so a single call to the target model advances 3 tokens.

Why the distribution matches the target model

Theorem 1 in the paper's appendix shows that the distribution of the result XX of choosing one token with this accept/reject rule is exactly the same as the target model's distribution qq. X=xX = x happens either when "the draft outputs xx and it is accepted" or when "something is rejected and resampling yields xx."

When accepted: Multiply the probability p(x)p(x) that the draft outputs xx by the acceptance probability.

p(x)min⁡(1,q(x)p(x))=min⁡(p(x),q(x))p(x) \min\left(1, \frac{q(x)}{p(x)}\right) = \min\left(p(x), q(x)\right)

When rejected: The probability of a rejection is 1 minus the total probability of acceptance.

1−∑x′min⁡(p(x′),q(x′))=∑x′max⁡(0,q(x′)−p(x′))1 - \sum_{x'} \min\left(p(x'), q(x')\right) = \sum_{x'} \max\left(0, q(x') - p(x')\right)

This is exactly the denominator of the resampling distribution (q−p)+(q - p)_+. Therefore, the probability that "a rejection occurs and resampling yields xx" is max⁡(0,q(x)−p(x))\max(0, q(x) - p(x)).

Total: Adding the two gives min⁡(p,q)+max⁡(0,q−p)=q\min(p, q) + \max(0, q - p) = q, so P(X=x)=q(x)P(X = x) = q(x).

Intuitively, words the draft outputs too often (p>qp > q) are trimmed by rejecting them in proportion to the excess, and words the draft outputs too rarely (p<qp < q) have the shortfall made up by resampling on rejection. Thanks to this property, no matter how inaccurate the draft model is, the quality of the text is the same as with the target model. The quality of the draft affects only the speed.

The total acceptance probability ∑xmin⁡(q(x),p(x))\sum_x \min(q(x), p(x)) is the area where the two distributions overlap. The more the draft model resembles the target model, the closer it gets to 1, and the more tokens each loop can advance.

Experimental results

Chen et al. used the 70-billion-parameter Chinchilla as the target model and a 4-billion-parameter draft model trained with the same tokenizer and data (with only 8 layers but greater width). Both ran on 16 TPU v4 chips, with per-token generation times of 14.1 ms for Chinchilla and 1.8 ms for the draft model. Results with batch size 1 and K=4K = 4 are as follows (Table 1).

TaskDecodingMetricStandard generationSpeculative samplingTime per tokenSpeedup
XSum (summarization)Nucleus (p=0.8p = 0.8)ROUGE-20.1120.11414.1 ms → 7.52 ms1.92×
XSum (summarization)GreedyROUGE-20.1570.15614.1 ms → 7.00 ms2.01×
HumanEval (code generation)Nucleus (p=0.95p = 0.95, temperature 0.8)Accuracy45.1%47.0%14.1 ms → 5.73 ms2.46×
  • Quality is unchanged: The metric values are almost the same as with standard generation. The theorem guarantees that the distribution is the same, and the experiments confirm it. Because random number handling and the order of computation differ, the output texts themselves do not match.
  • Speed differs by task: The paper suggests that HumanEval was faster because code contains many fixed patterns such as for i in range(len(arr)): that even the draft model can predict well.
  • A larger KK is not always better: Increasing KK increases drafting time, and later tokens are less likely to be accepted, so the speedup plateaus or even declines. For nucleus sampling on XSum, K=3K = 3 was fastest, and the larger KK was, the more the generation time varied (Figure 1).

Caveats

This is a method for reducing latency, and the total amount of computation can increase. Chen et al. present it as a method for latency-critical applications, and their experiments use batch size 1. Computation for rejected draft tokens and the positions after them is discarded, so a low acceptance rate means more wasted computation (Section 3.4 of Leviathan et al.). It assumes there is enough spare compute to process K+1K + 1 positions in parallel.

  • Choosing the draft model: A model with the same tokenizer (vocabulary) that can output probabilities (logits) is required. The paper notes that a smaller version of the target model is a convenient choice. For large models run in a distributed setting, a draft model with fewer layers and greater width reduces communication overhead and is faster.
  • Can be combined with top-k, nucleus, and temperature: Transform the probabilities of both the target and the draft with top-k, nucleus, or temperature first, then apply this rule. The paper reports that the acceptance rate is not much affected by these parameters.
  • No changes to the model are needed: The training and architecture of the target model are left untouched, so it can be used together with other speedups such as quantization and multi-query attention.

Comparison with other decoding methods

Speculative sampling has a different goal from earlier decoding methods. Methods such as top-k and nucleus change "which distribution to choose from" to change the quality of the text, whereas speculative sampling "draws the same result faster from a given distribution." It can therefore be combined with other methods.

MethodGoalDistribution of generated textCalls to the large model
Standard sampling (one token at a time)−Target model's distributionOnce per token
Top-k, nucleus, typicalImprove text qualityTruncated and changedOnce per token
Beam searchFind high-probability sentences(No sampling)BB beams' worth per token
Speculative sampling (this article)Speed upSame as the target model'sOnce per up to K+1K + 1 tokens
Knowledge distillation, quantizationFaster and lighterSlightly different from the original modelOnce per token (the model itself is lighter)

Guidelines for choosing:

  • Faster responses without changing the large model's output quality at all: speculative sampling. A small model with similar behavior is required.
  • The model itself may be made lighter: knowledge distillation or quantization. The output changes slightly, but the total computation also decreases.
  • Changing the diversity or naturalness of the text: set the distribution with top-k, nucleus, etc., and then combine it with speculative sampling to speed things up.

PyTorch example

Show code
python
import torch


def speculative_accept(q_probs, p_probs, draft_tokens, generator=None):
    """Accept/reject for one loop (Algorithm 2 of Chen et al. 2023).
    q_probs: target model probabilities [K + 1, vocab] (K + 1 positions computed at once)
    p_probs: draft model probabilities [K, vocab]
    draft_tokens: draft tokens [K]
    Returns: list of tokens finalized in this loop (1 to K + 1 tokens)"""
    out = []
    K = draft_tokens.numel()
    for t in range(K):
        x = draft_tokens[t]
        q, p = q_probs[t, x], p_probs[t, x]
        r = torch.rand((), generator=generator)
        if r < torch.clamp(q / p, max=1.0):          # accept with probability min(1, q/p)
            out.append(x.item())
        else:                                          # reject: resample from (q − p)+ and stop
            resid = torch.clamp(q_probs[t] - p_probs[t], min=0.0)
            resid = resid / resid.sum()
            out.append(torch.multinomial(resid, 1, generator=generator).item())
            return out
    # if all K are accepted, draw one more from q at position K + 1
    out.append(torch.multinomial(q_probs[K], 1, generator=generator).item())
    return out


# Check with the example in the figure at the top of the article that the distribution at the first position matches q
words = ["sunny", "rainy", "Sunday", "hot", "cold", "Monday", "nice", "the", "cat", "of"]
q = torch.tensor([0.30, 0.20, 0.15, 0.10, 0.08, 0.06, 0.05, 0.03, 0.02, 0.01])  # target model
p = torch.tensor([0.40, 0.15, 0.10, 0.15, 0.05, 0.05, 0.05, 0.02, 0.02, 0.01])  # draft model
print("acceptance rate:", torch.minimum(q, p).sum().item())  # 0.85

g = torch.Generator().manual_seed(0)
counts = torch.zeros(10)
for _ in range(100000):
    draft = torch.multinomial(p, 1, generator=g)                    # the draft model outputs one token (K = 1)
    first = speculative_accept(torch.stack([q, q]), p[None], draft, g)[0]
    counts[first] += 1
print([round(c, 3) for c in (counts / counts.sum()).tolist()])
# nearly matches the target q (0.30, 0.20, 0.15, ...)


# Usage with real models (batch size 1; model(ids) is assumed to return logits of shape [1, length, vocab])
@torch.no_grad()
def speculative_generate(target, draft, input_ids, max_new_tokens=64, K=4):
    target.eval(); draft.eval()
    goal = input_ids.shape[1] + max_new_tokens
    while input_ids.shape[1] < goal:
        ids, p_list = input_ids, []
        for _ in range(K):                                              # 1. draft K tokens
            p_t = torch.softmax(draft(ids)[0, -1], dim=-1)
            p_list.append(p_t)
            ids = torch.cat([ids, torch.multinomial(p_t, 1)[None]], dim=-1)
        drafts = ids[0, input_ids.shape[1]:]
        q_all = torch.softmax(target(ids)[0, -(K + 1):], dim=-1)        # 2. call the target model only once
        new = speculative_accept(q_all, torch.stack(p_list), drafts)    # 3-5. accept/reject
        input_ids = torch.cat([input_ids, torch.tensor([new])], dim=-1)
    return input_ids

FAQ

Q. Does an inaccurate draft model lower text quality?
A.

No. Because of the accept/reject and resampling rules, the distribution of the generated tokens is mathematically identical to that of the target model (Theorem 1 in the paper). An inaccurate draft model increases rejections and reduces the number of tokens each loop advances, so only the speed drops.

Q. What value should K (the draft length) take?
A.

The paper ran its main experiments with K=4K = 4, and for nucleus sampling on XSum, K=3K = 3 was fastest. Increasing KK increases drafting time and makes later tokens less likely to be accepted, so the speedup plateaus and the generation time varies more. Try a few values, matched to the task and the draft model.

Q. Are speculative sampling and speculative decoding the same thing?
A.

The core idea is the same. Chen et al. (2023) at DeepMind published it as "speculative sampling" and Leviathan et al. (2023) at Google as "speculative decoding," independently and around the same time. Leviathan et al. also call the accept/reject rule itself "speculative sampling." The analysis of the speedup and implementation techniques are covered in the speculative decoding article.

References

  1. C. Chen, S. Borgeaud, G. Irving, J.-B. Lespiau, L. Sifre, and J. Jumper, "Accelerating Large Language Model Decoding with Speculative Sampling," arXiv:2302.01318, 2023.
  2. Y. Leviathan, M. Kalman, and Y. Matias, "Fast Inference from Transformers via Speculative Decoding," ICML, 2023.