AI Logic

Model Compression

Speculative Decoding

Updated:

The speed of speculative decoding. The left side compares the timelines of ordinary decoding (one token per call to the target model) and speculative decoding, which drafts 3 tokens with the approximation model and then verifies them with the target model. The right side is a graph, drawn from the formula, of the speedup for draft counts γ = 1, 3, 5, 7 (c = 0.05) against the acceptance rate α on the horizontal axis.

Background and Overview

Speculative decoding is a method that speeds up generation without changing the output distribution by having a small, fast "approximation model" draft several tokens ahead and then verifying them all in a single pass of the large "target model". It was published in 2022 by Leviathan, Kalman, and Matias at Google Research (ICML 2023). On the 11-billion-parameter T5-XXL, it achieves a 2 to 3× speedup without changing the output at all.

Autoregressive models such as the Transformer need to run the model KK times in sequence to generate KK tokens. Moreover, inference with large models is often bound by memory bandwidth and communication rather than by the amount of computation, leaving compute resources to spare. The idea of this method is therefore to use the spare compute by increasing the number of tokens verified at once.

It is based on "speculative execution" in processors. As in branch prediction, work that may be needed is carried out ahead of time; if it turns out to be needed, the result is used, and otherwise it is discarded. The paper extends this to the probabilistic setting. As an analogy, it is like a veteran editor (the large model) reading several lines drafted by a newcomer (the small model) all at once, adopting them up to the point where they are correct, and fixing only the first mistake personally.

The rule for accepting or rejecting drafts (speculative sampling) is the same as speculative sampling, published independently at around the same time by Chen et al. (2023) at DeepMind. This article covers what the paper by Leviathan et al. puts at its center: the analysis that estimates speed and compute from the acceptance rate, and how to choose the approximation model. Note that the two papers use opposite notation; this article follows Leviathan et al. and writes the target model as pp and the approximation model as qq.

Theory (One Loop and the Acceptance Rate)

Let MpM_p be the target model with next-token distribution p(xt∣x<t)p(x_t \mid x_{<t}), and MqM_q the approximation model with distribution q(xt∣x<t)q(x_t \mid x_{<t}). Any sampling method, including Top-k, Nucleus, temperature, and greedy decoding (argmax), can be rewritten as "ordinary sampling from an adjusted distribution", so pp and qq denote the distributions after that adjustment (Section 2.2 of the paper).

One loop (Algorithm 1 in the paper) goes as follows.

  1. Use MqM_q to sample γ\gamma tokens x1,…,xγx_1, \dots, x_\gamma in sequence.
  2. Run MpM_p in parallel on the γ+1\gamma + 1 inputs prefix, prefix +[x1]+ [x_1], …, prefix +[x1,…,xγ]+ [x_1, \dots, x_\gamma] to obtain p1(x),…,pγ+1(x)p_1(x), \dots, p_{\gamma+1}(x).
  3. Going through the drafts from left to right, decide whether to accept each one using the speculative sampling rule. If q(x)≤p(x)q(x) \le p(x), always accept; if q(x)>p(x)q(x) > p(x), reject with probability 1−p(x)/q(x)1 - p(x)/q(x).
  4. At the first rejected position, resample a token from norm(max⁡(0,p(x)−q(x)))\mathrm{norm}(\max(0, p(x) - q(x))) and discard the remaining drafts. If all are accepted, draw one more token from pγ+1(x)p_{\gamma+1}(x).

With only one run of MpM_p per loop, at least 1 and at most γ+1\gamma + 1 tokens are determined. Even in the worst case, the number of calls to MpM_p is no greater than with ordinary decoding. The distribution of the generated text is exactly the same as when generating with MpM_p alone (the proof is in the speculative sampling article).

Acceptance rate: Let β\beta be the probability that the approximation model's draft is accepted in a given context. The paper defines DLKD_{LK}, a measure of the difference between two distributions, and shows that β\beta is determined by it (Theorem 3.5).

DLK(p,q)=∑x∣p(x)−p(x)+q(x)2∣=1−∑xmin⁡(p(x),q(x)),β=1−DLK(p,q)D_{LK}(p, q) = \sum_x \left| p(x) - \frac{p(x) + q(x)}{2} \right| = 1 - \sum_x \min\left(p(x), q(x)\right), \qquad \beta = 1 - D_{LK}(p, q)

The mean of β\beta, α=E(β)=E(∑xmin⁡(p(x),q(x)))\alpha = E(\beta) = E\left(\sum_x \min(p(x), q(x))\right), is used as a measure of how good the approximation model is. If pp and qq are identical, α=1\alpha = 1; if they do not overlap at all, α=0\alpha = 0.

Assuming that β\beta is independent and identically distributed at every position, the number of tokens generated per loop follows a geometric distribution capped at γ+1\gamma + 1. Its expected value is the following (Eq. (1) in the paper).

E(#tokens)=1−αγ+11−αE(\#\text{tokens}) = \frac{1 - \alpha^{\gamma + 1}}{1 - \alpha}

For example, with α=0.8\alpha = 0.8 and γ=5\gamma = 5, each loop advances about 3.7 tokens on average.

Speedup Analysis (Acceptance Rate and Speed)

Walltime improvement

Let cc be the ratio of the time for one run of the approximation model to the time for one run of the target model (the cost coefficient). While α\alpha is determined by the models and the task, cc is determined by the hardware and the implementation. Assuming that computing γ+1\gamma + 1 positions in parallel takes no extra time, and letting TT be the time of one run of MpM_p, one loop takes Tcγ+TT c \gamma + T. Dividing this by the expected number of tokens per loop gives the walltime improvement (Theorem 3.8).

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

The right of the top figure plots this formula with c=0.05c = 0.05. The formula shows the following.

  • The larger α\alpha, the faster. The more the approximation model resembles the target model, the more tokens advance per loop.
  • There is an optimal γ\gamma. Increasing γ\gamma increases the drafting time γc\gamma c, and later drafts are less likely to be accepted. The larger α\alpha is, the larger the optimal γ\gamma (Figure 3 in the paper).
  • If α>c\alpha > c, a speedup is always possible. In that case, even with γ=1\gamma = 1, the improvement is at least 1+α1+c\frac{1 + \alpha}{1 + c} (Corollary 3.9).
  • If the approximation model's time is nearly 0 (c≈0c \approx 0), the improvement is 1−αγ+11−α\frac{1 - \alpha^{\gamma+1}}{1 - \alpha}, and it never exceeds 11−α\frac{1}{1 - \alpha} no matter how large γ\gamma becomes.

Compute and memory reads

In exchange for the speedup, the total amount of computation can increase. Letting c^\hat{c} be the ratio of per-token computation of the approximation model to that of the target model, the total computation is multiplied by the following factor (Theorem 3.11).

Compute factor=(1−α)(γc^+γ+1)1−αγ+1\text{Compute factor} = \frac{(1 - \alpha)(\gamma \hat{c} + \gamma + 1)}{1 - \alpha^{\gamma + 1}}

Computation for rejected drafts and the positions after them is thrown away, so the lower α\alpha, the more waste. On the other hand, the target model's weights and KV cache are read only once per loop, so the number of memory reads drops by a factor of 1−αγ+11−α\frac{1 - \alpha^{\gamma+1}}{1 - \alpha}. This is why large models bound by memory reads become faster.

Table 1 of the paper shows the relationship between speed and compute under the assumption c=c^=0c = \hat{c} = 0.

α\alphaγ\gammaComputeSpeed
0.621.53×1.96×
0.731.58×2.53×
0.821.23×2.44×
0.851.63×3.69×
0.921.11×2.71×
0.9101.60×6.86×

Even with the same α\alpha, a larger γ\gamma is faster but also increases compute. Choose γ\gamma according to how much compute is to spare.

Since β\beta varies with context, there is room for further speedup by not fixing γ\gamma, and instead predicting β\beta and changing γ\gamma each loop. The paper estimates that, as an upper bound with ideal prediction, the improvement could be up to about 60% higher than with a fixed γ\gamma (implementation is left for future work).

Choosing the Approximation Model

Speculative sampling guarantees that the output distribution is unchanged no matter which approximation model is used. The choice of approximation model affects only speed (Section 3.6 of the paper).

  • A smaller model with the same architecture: In the paper's experiments, a model about two orders of magnitude smaller than the target model often gave the best balance between α\alpha and cc and the best results. Approximation models of this size had α\alpha of 0.5 to 0.9.
  • An n-gram model: Since it only requires a table lookup, c≈0c \approx 0. For T5-XXL English-German translation, even a very simple bigram model gave α≈0.2\alpha \approx 0.2 and a 1.25× speedup with γ=3\gamma = 3.
  • A model that just copies from the context: The paper notes that in settings where long spans tend to repeat, such as summarization or chats that repeatedly rewrite text or code, even a model that merely copies matching spans from the context can be expected to achieve a high α\alpha.
  • A non-autoregressive model: Instead of the drafting loop in Algorithm 1, a model that outputs multiple tokens in one step can be used.

In the paper's measurements, for every model, the sharper the adjusted distribution (the lower the temperature), the higher α\alpha was. Greedy decoding (temperature 0) tends to be faster than sampling at temperature 1.

Experimental Results

The paper uses T5-XXL (11B) from T5 v1.1 as the target model and compares actual wall-clock time against the standard T5X implementation on English-German translation (WMT EnDe) and summarization (CNN/DM), on a single TPU-v4 with batch size 1 (excerpt from Table 2).

TaskApproximation modelTemperatureγ\gammaα\alphaSpeed
EnDe translationT5-small (77M)070.753.4×
EnDe translationT5-base (250M)070.802.8×
EnDe translationT5-large (800M)070.821.7×
EnDe translationT5-small (77M)170.622.6×
SummarizationT5-small (77M)050.653.1×
SummarizationT5-small (77M)150.532.3×
  • The smallest model, T5-small, gave the largest speedup. Larger approximation models raise α\alpha, but cc also grows.
  • The results agreed well with the theoretical predictions. Despite some variation due to implementation details, the speeds were close to the estimates of Theorem 3.8.

Table 3 also measures α\alpha for other models.

Target modelApproximation modelTemperature 0Temperature 1
GPT-like (97M)GPT-like (6M)0.880.89
GPT-like (97M)Bigram0.050.05
LaMDA (137B)LaMDA (100M)0.610.57
LaMDA (137B)LaMDA (8B)0.750.74

After the paper was published, Chen et al. reported a 2 to 2.5× speedup on Chinchilla 70B with an independent implementation.

Practical Considerations

  • Spare compute is a prerequisite. The method assumes that computing γ+1\gamma + 1 positions in parallel takes no extra time. With large batch sizes, where computation is already the bottleneck, it may not speed things up. The paper's experiments also use batch size 1.
  • Measure cc empirically. Since cc varies with hardware and implementation, measure the times of the approximation and target models in your environment and choose γ\gamma together with α\alpha. In the paper's experiments, cc was always below 0.05.
  • The approximation model must output probabilities over the same vocabulary. The paper tested models with the same architecture as the target model whose probabilities were adjusted in the same way.
  • The models' training and architecture are unchanged. Trained models can be used as they are, and the method can be combined with other speedups such as knowledge distillation, quantization, and multi-query attention.

What improves is latency; the total amount of computation can actually increase (about 1.63× with α=0.8\alpha = 0.8, γ=5\gamma = 5). It is not suited to reducing power or compute costs. In addition, Theorem 3.8 assumes that β\beta is independent and identically distributed and that sufficiently long text is generated, so short outputs do not get as fast as estimated.

Comparison with Other Methods

The following table compares methods for speeding up inference of large language models from the same viewpoints.

MethodOutput distributionRetraining or model changesTotal compute
Speculative decodingSame as the target modelNot requiredMay increase
Knowledge distillation, quantizationChanges slightlyRequired (distillation), sometimes not required (quantization)Decreases
Adaptive computation (e.g., early exit)ChangesRequiredDecreases
Blockwise Parallel DecodingAims to preserve downstream quality (not necessarily identical)Required (a dedicated model)−
Shallow Aggressive DecodingDoes not support stochastic samplingNot required (just copies the input)−

Blockwise Parallel Decoding (Stern et al. 2018) also verifies multiple tokens in parallel, but it works only with greedy decoding and requires training a dedicated model. Shallow Aggressive Decoding can only use drafts that copy the input as is, limiting it to tasks whose inputs and outputs are similar, such as grammatical error correction. Speculative decoding differs in that it works with any approximation model and with stochastic sampling, without changing the output distribution.

  • To shorten response latency without changing a large model's output at all, speculative decoding is well suited.
  • To reduce the computational cost itself, make the model lighter with knowledge distillation or quantization. The two can be combined.

The speculative sampling article explains the accept/reject rule and why it leaves the distribution unchanged, using concrete numerical examples.

PyTorch example

Show code
python
import torch

# One loop of speculative decoding (Algorithm 1 in the paper) and speed estimates (Theorems 3.8 and 3.11).
# target(ids) and draft(ids) are functions that take a token sequence (1, L) and return next-token probabilities (1, L, V) at each position
# (probabilities after adjustments such as temperature and Top-k). Put models in model.eval() and use them inside torch.no_grad().

@torch.no_grad()
def speculative_decoding_step(target, draft, prefix, gamma=5):
    # 1. Sample γ tokens in sequence with the approximation model M_q
    ids, qs = prefix, []
    for _ in range(gamma):
        q = draft(ids)[:, -1]                          # (1, V)
        x = torch.multinomial(q, 1)
        qs.append(q)
        ids = torch.cat([ids, x], dim=1)
    drafts = ids[:, prefix.shape[1]:]                  # (1, γ)

    # 2. Run the target model M_p only once to get distributions for γ + 1 positions in parallel
    ps = target(ids)[:, prefix.shape[1] - 1:]          # (1, γ + 1, V)

    # 3. Decide acceptance from left to right: reject if r > p(x)/q(x) (always accept if q(x) ≤ p(x))
    n = gamma
    for i in range(gamma):
        x = drafts[0, i]
        if torch.rand(()) > ps[0, i, x] / qs[i][0, x]:
            n = i
            break

    # 4. At the rejected position draw from norm(max(0, p − q)); if all accepted, draw one from p_{γ+1}
    p_next = ps[:, n]
    if n < gamma:
        p_next = torch.clamp(p_next - qs[n], min=0)
        p_next = p_next / p_next.sum(dim=-1, keepdim=True)
    t = torch.multinomial(p_next, 1)
    return torch.cat([prefix, drafts[:, :n], t], dim=1)   # advances 1 to γ + 1 tokens


def expected_tokens(alpha, gamma):
    """Expected number of tokens advanced per loop (Eq. (1))"""
    return (1 - alpha ** (gamma + 1)) / (1 - alpha)


def walltime_improvement(alpha, gamma, c):
    """Walltime improvement (Theorem 3.8)"""
    return expected_tokens(alpha, gamma) / (gamma * c + 1)


def ops_increase(alpha, gamma, c_hat):
    """Factor of increase in total compute (Theorem 3.11)"""
    return (gamma * c_hat + gamma + 1) / expected_tokens(alpha, gamma)


def best_gamma(alpha, c, max_gamma=30):
    return max(range(1, max_gamma + 1), key=lambda g: walltime_improvement(alpha, g, c))


# Reproduce one row of Table 1 in the paper (α = 0.8, γ = 5, c = ĉ = 0)
print(round(walltime_improvement(0.8, 5, 0), 2), round(ops_increase(0.8, 5, 0), 2))   # 3.69 1.63
print("Optimal γ at c = 0.05:", best_gamma(0.8, 0.05))


# Toy models for a quick check (vocabulary of 8, fixed distributions that ignore context)
V = 8
p_fixed = torch.softmax(torch.randn(V), dim=0)
q_fixed = torch.softmax(p_fixed.log() + 0.3 * torch.randn(V), dim=0)
target = lambda ids: p_fixed.expand(1, ids.shape[1], V)
draft = lambda ids: q_fixed.expand(1, ids.shape[1], V)
out = speculative_decoding_step(target, draft, torch.zeros(1, 3, dtype=torch.long), gamma=4)
print("Tokens advanced:", out.shape[1] - 3)

FAQ

Q. Are speculative decoding and [speculative sampling](/decoding/speculative-sampling) different things?
A.

The accept/reject rule is the same; they were published independently by two groups at about the same time. Leviathan et al. call the overall method "speculative decoding" and the accept/reject rule within it "speculative sampling", and they give a detailed analysis that estimates speed and compute from the acceptance rate. Chen et al. at DeepMind call the whole method "speculative sampling" and demonstrated its effect on Chinchilla 70B. Note that the two papers swap the symbols pp and qq for the target and approximation models.

Q. How many drafts $\gamma$ should be used?
A.

From the acceptance rate α\alpha and the cost coefficient cc, choose the integer that maximizes the walltime improvement 1−αγ+1(1−α)(γc+1)\frac{1 - \alpha^{\gamma+1}}{(1 - \alpha)(\gamma c + 1)}. The higher α\alpha is, the more a larger γ\gamma pays off. The paper's T5-XXL experiments used 3, 5, and 7. Keep in mind, however, that a larger γ\gamma also increases total compute, so consider how much compute is to spare.

Q. Does a poor approximation model lower output quality?
A.

No. Thanks to the accept/reject rule, the output distribution is the same as when generating with the target model alone. The quality of the approximation model affects only the acceptance rate α\alpha, that is, only the speed. As an extreme example, the paper notes that even an approximation model that picks tokens at random yields correct output and a very slight speedup.

References

  1. Y. Leviathan, M. Kalman, and Y. Matias, "Fast Inference from Transformers via Speculative Decoding," Proceedings of the 40th International Conference on Machine Learning (ICML), PMLR 202, 2023, arXiv:2211.17192.
  2. 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.