Search

Search papers and lessons

Fast Inference from Transformers via Speculative Decoding

Yaniv Leviathan, Matan Kalman, Yossi Matias · 2022

Leviathan, Kalman and Matias (2022) let a cheap model draft tokens that a large model checks in parallel, with a sampling rule that leaves the output distribution unchanged, for 2 to 3 times faster decoding of T5-XXL.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Neural network basics
  • Linear algebra
  • Architectures
  • Discrete math
  • Sign in to see your progress

TL;DR

Decoding a Transformer is slow for a simple reason: producing KK tokens takes KK serial calls to a large model, and each call is limited by reading the weights from memory, not by arithmetic. Leviathan, Kalman and Matias noticed that many tokens are easy to guess. A small model drafts several tokens, the large model scores all of them in one parallel pass, and a sampling rule accepts the drafts that are consistent with the large model's distribution. The output has exactly the same distribution as the large model alone. On T5-XXL, the method gave 2 to 3 times lower latency than the standard T5X implementation, with identical outputs.

Where you'll see it: the "assisted generation" and draft-model options in production inference servers, which run a small model next to a large one to speed up chat and translation without changing answers.

The problem

Large autoregressive models such as GPT-3, LaMDA, PaLM and Parti are much more capable than small ones, but a single decode step of a large model is much slower. The steps also run one after another, because each token depends on the one before. The paper's introduction gives the cost directly: decoding KK tokens takes KK serial runs of the model.

Earlier speedups fell into two groups. Methods that reduce cost for all inputs, such as distillation, quantisation and architecture changes, usually need retraining and change the outputs. Adaptive computation methods spend less work on easy steps, but they too usually change the architecture or training and do not keep outputs identical. The paper's observation is that inference from large models is often limited by memory bandwidth and communication, not by arithmetic. That leaves spare compute, and spare compute can buy concurrency.

Key idea

The idea borrows from speculative execution in processors. A CPU guesses the outcome of a branch and starts the next instructions before the check finishes. If the guess is right, time is saved. If not, the work is thrown away and the correct path runs.

The paper extends this to stochastic outputs. Here a guess is a token sampled from a cheap model MqM_q, the approximation model. The large model MpM_p, the target, scores the guess in parallel with the others. A new rule, speculative sampling, decides which guesses to keep. The rule guarantees that the final tokens are distributed exactly as if MpM_p had sampled them alone.

Here is the loop in words. The draft model proposes γ\gamma tokens. The target model runs once on the prefix and on each prefix extended by drafts, which gives γ+1\gamma + 1 target distributions at the price of one parallel call. The drafts are checked left to right. The first rejected draft is replaced by a corrected token, and the rest are discarded. If every draft is accepted, the target distribution at the last position supplies one bonus token. Each round therefore produces between 1 and γ+1\gamma + 1 tokens, and never fewer than one, so the target is never called more often than ordinary decoding.

Figure 1 of the paper shows a 38-token sentence generated with only 9 serial runs of the 97-million-parameter target, using a 6-million-parameter draft. In the first line of the figure, the target runs once and 5 tokens come out.

The method

The sampling rule

Let p(x)p(x) be the target's distribution for the next token given a prefix, and q(x)q(x) the draft's. To sample from pp, draw x∼qx \sim q and keep it with probability min⁡(1,p(x)/q(x))\min(1, p(x)/q(x)). If it is rejected, draw again from the adjusted distribution

p′(x)=max⁡(0, p(x)−q(x))∑x′max⁡(0, p(x′)−q(x′)).p'(x)=\frac{\max(0,\,p(x)-q(x))}{\sum_{x'}\max(0,\,p(x')-q(x'))}.

The paper calls this norm(max(0, p - q)). The proof is short. The accepted probability for a value x′x' is min⁡(q(x′),p(x′))\min(q(x'), p(x')). The rejected mass is (1−β) p′(x′)(1-\beta)\,p'(x'), where β\beta is the overall acceptance probability. Adding the two gives p(x′)p(x') exactly, for any draft distribution qq at all. The draft affects only the speed, never the output.

The paper's Algorithm 1 generalises this to γ\gamma drafts. It draws x1,…,xγx_1, \dots, x_\gamma from MqM_q, runs MpM_p on all prefixes in one batch, draws one uniform random number rir_i per draft, and accepts the first nn drafts with ri≤pi(x)/qi(x)r_i \le p_i(x)/q_i(x). If n<γn < \gamma, the next token comes from p′p' built at position n+1n+1. If n=γn = \gamma, it comes from pγ+1p_{\gamma+1}.

Acceptance rate

The paper names the key quantity β\beta, the acceptance probability of one draft given its prefix. It shows that β=1−DLK(p,q)\beta = 1 - D_{LK}(p, q), where DLK(p,q)=∑x∣p(x)−q(x)∣/2D_{LK}(p,q) = \sum_x |p(x) - q(x)|/2 is the total-variation distance between the two distributions (the paper's Lemma 3.3 shows DLK(p,q)=1−∑xmin⁡(p(x),q(x))D_{LK}(p,q) = 1 - \sum_x \min(p(x), q(x))). In words, the more the draft and target distributions overlap, the more drafts survive.

Averaged over prefixes and assuming the β\beta values are independent with a common mean α\alpha, the expected number of tokens from one round is

E[tokens per round]=1−αγ+11−α.\mathbb{E}[\text{tokens per round}]=\frac{1-\alpha^{\gamma+1}}{1-\alpha}.

This is a capped geometric count. Figure 2 of the paper plots it against α\alpha for several γ\gamma. The formula is the paper's Equation 1.

Walltime

Let cc be the time for one draft call divided by the time for one target call. The paper assumes the target can run γ+1\gamma + 1 positions in parallel at the cost of one call. A round then costs γc+1\gamma c + 1 target units, and the expected speedup over ordinary decoding is

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

Corollary 3.9 gives a clean condition. If α>c\alpha > c, some γ\gamma yields a gain, and at γ=1\gamma = 1 the gain is at least (1+α)/(1+c)(1+\alpha)/(1+c). The paper reports that the draft cost cc was always below 0.05 in its experiments, and often close to zero.

Operations and memory

Speedup costs arithmetic. The target runs on γ+1\gamma+1 positions per round, and rejected positions are wasted. Theorem 3.11 gives the expected increase in total operations. Table 1 shows that with γ=2\gamma = 2 and α=0.9\alpha = 0.9, speed rises to 2.71 times while operations rise only to 1.11 times, but with γ=10\gamma = 10 the speed reaches 6.86 times and the operations rise to 1.60 times.

Memory traffic can fall. The target's weights and key-value cache are read once per round, not once per token, so the number of such reads shrinks by the same factor as the token count. The paper argues that this is why the method helps when memory bandwidth is the bottleneck.

Choosing gamma

Given α\alpha and cc, the best γ\gamma maximises SS. Because γ\gamma is an integer, it is found by trying values. Figure 3 gives the optimum for several cc. The paper also estimates that letting γ\gamma vary during decoding could add up to about 60 percent more speedup, which it leaves for future work.

00.20.40.60.82468alphaexpected tokens per round
  • gamma = 3
  • gamma = 7
Expected tokens per round against the acceptance rate alpha, from the paper's Equation 1. A longer draft helps more as alpha rises.

Results

Walltime on T5-XXL

The target is T5-XXL with 11 billion parameters. The drafts are T5-large (800 million), T5-base (250 million) and T5-small (77 million). Tasks are English to German translation on WMT and news summarisation on CNN/DailyMail. The test used a batch size of 1 on one TPU-v4, with argmax sampling (temperature 0) and standard sampling (temperature 1).

TaskDraftTempγ\gammaα\alphaSpeed
EnDeT5-small070.753.4X
EnDeT5-base070.802.8X
EnDeT5-small170.622.6X
CNNDMT5-small050.653.1X
CNNDMT5-small150.532.3X

T5-small gave the best balance of cost and acceptance. Larger drafts had higher α\alpha but cost more, so T5-large was slower overall (1.7X on translation at temperature 0). Argmax sampling gave higher α\alpha and larger speedups than standard sampling. The paper says the empirical results match the theory, with differences due to implementation details.

Acceptance rates across models

Table 3 covers more pairs. A 6-million-parameter GPT-like draft gives α\alpha of about 0.88 to 0.89 for a 97-million-parameter GPT-like target on the lm1b benchmark. On LaMDA 137B, drafts of 100 million, 2 billion and 8 billion parameters give α\alpha between 0.57 and 0.75. Unigram and bigram models, which cost almost nothing, reach only 0.03 to 0.23. Even so, the paper reports that a bigram draft on English to German translation gives a 1.25X speedup with γ=3\gamma = 3, because cc is zero.

The paper's broad finding is that drafts two orders of magnitude smaller than the target usually have α\alpha between 0.5 and 0.9.

Theory against measurement

Table 4 of the appendix compares the predicted speedup from Theorem 3.8 with the measured one. For T5-small on translation at temperature 0, the prediction is 3.2 and the measurement 3.4. For T5-large at temperature 1, the prediction is 2.0 and the measurement 1.4. The paper attributes the gaps to differences in optimisation against the baseline and to the i.i.d. assumption on β\beta.

The appendix also covers two extensions. A lenience factor ll multiplies the draft probability before the comparison. This relaxes the exact guarantee, but it still bounds how much more likely any token can become, at most 1/l1/l times the target probability. With l=0.1l = 0.1 on translation, the paper reports α\alpha rising from 0.62 to 0.84 for T5-small (temperature 1), and the improvement factor rising from 2.5X to 5X as ll falls from 1 to 0.1. Beam search can also be sped up, with a cost in compute, but the paper leaves its analysis for future work.

Why it mattered

The paper gave a way to speed up existing models without retraining, changing the architecture or changing the output distribution. Those three properties are why the method could be deployed as a drop-in change. The authors also note its limit: it trades extra arithmetic for lower latency, so it helps only when spare compute exists, which is common when memory bandwidth is the bottleneck.

The paper notes that Chen et al. (2023), an independent implementation, reported 2X to 2.5X speedups on Chinchilla 70B. The paper's central claim, that the output distribution is unchanged, is what separates it from the adaptive methods it compares against.

Reading guide

Read the paper in this order, using these prerequisite lessons:

  1. Section 1, Introduction. Needs Language Model for the idea of decoding one token at a time, and Transformer for the models named. The analogy to speculative execution in processors needs no further prerequisite.
  2. Section 2.1 and 2.2, Overview and standardised sampling. Needs Softmax Temperature for how argmax, top-k and temperature all become one adjusted distribution. Needs Conditional Probability for the notation p(xt∣x<t)p(x_t \mid x_{<t}).
  3. Section 2.3 and Algorithm 1. Needs Rejection Sampling for the accept-or-resample idea and Speculative Decoding for the overall loop. Read the proof in Appendix A.1 next to this section.
  4. Section 3.1 and 3.2, acceptance rate. Needs Expected Value for the average over prefixes, and Kullback–Leibler Divergence or total variation for DLKD_{LK}.
  5. Section 3.3, walltime. Needs only the algebra of the geometric sum. Work through γ=1\gamma = 1 first, since Corollary 3.9 reduces to it.
  6. Section 3.6, approximation models. Needs Knowledge Distillation to see why a distilled draft would raise α\alpha, a point the paper raises as future work.
  7. Section 4, experiments. Needs Softmax for the argmax and temperature settings.
  8. Appendix A.4, beam search. Needs Beam Search.
  9. Appendix A.5, lenience. Needs Importance Sampling only as a comparison: the lenience bound is a loose analogue of a bounded weight.

Check yourself

QuestionIn one round with γ=4\gamma = 4, the first three drafts are accepted and the fourth is rejected. How many tokens does the round produce, and which model supplies each one?Show answer

Four tokens. The three accepted drafts come from the draft model. The fourth position is rejected, so the replacement token is drawn from the adjusted distribution p′p', built from the target's distribution at that position. The target therefore supplies one token and the draft supplies three. That is one serial target call for four tokens, instead of four calls.

QuestionWith α=0.8\alpha = 0.8 and γ=3\gamma = 3, compute the expected tokens per round and the expected speedup when the draft costs c=0.05c = 0.05.Show answer

Expected tokens: (1−0.84)/(1−0.8)=(1−0.4096)/0.2=2.952(1 - 0.8^4)/(1 - 0.8) = (1 - 0.4096)/0.2 = 2.952. Cost per round: γc+1=3(0.05)+1=1.15\gamma c + 1 = 3(0.05) + 1 = 1.15 target units. Speedup: 2.952/1.15≈2.572.952 / 1.15 \approx 2.57. The round produces about 2.95 tokens for about 1.15 target-call units, so each token costs about 0.39 of an ordinary target call.

QuestionWhy does the paper's proof hold for any draft distribution q, even a bad one?Show answer

The accepted mass for each value x′x' is min⁡(q(x′),p(x′))\min(q(x'), p(x')), and the rejected mass is the remainder of p(x′)p(x') spread over p′p'. The two parts sum to p(x′)p(x') whatever qq is. A bad draft lowers α\alpha, so it wastes more target calls, but the output distribution is still exactly pp. The draft controls speed, and the rule controls correctness.

QuestionOn English to German translation a unigram draft gives α\alpha of about 0.07 and a bigram draft about 0.19 (temperature 1). Why can a trivial draft still be worth using?Show answer

With cc near zero, the speedup is (1−αγ+1)/(1−α)(1-\alpha^{\gamma+1})/(1-\alpha) with no cost term. At α=0.07\alpha = 0.07 this is only about 1.07 tokens per round, so a unigram draft barely helps by itself. The bigram draft at α=0.2\alpha = 0.2 gives about 1.25 times with γ=3\gamma = 3, which the paper calls surprisingly high for so simple a model. Trivial drafts help only when cc is essentially zero and α\alpha is not tiny.

QuestionWhy does the method leave the output distribution unchanged, but lenience does not?Show answer

Exact speculative sampling accepts x∼qx \sim q with probability min⁡(1,p/q)\min(1, p/q) and resamples the rest, which makes the output exactly pp. Lenience multiplies qq by ll before the comparison, so accepted tokens follow a different distribution. The paper's guarantee is weaker: no token can become more than 1/l1/l times as likely as under pp. That buys a higher α\alpha and more speed, at the price of exactness.

Sources

Read the full paper

Yaniv Leviathan, Matan Kalman, Yossi Matias, 2022. arXiv:2211.17192