Python · cell 1
Speculative decoding makes a large language model produce several tokens per forward pass without changing what it writes. A small, fast model guesses the next few tokens. The large model checks all the guesses in one pass, keeps the ones it agrees with, and adds one token of its own. When the guesses are good, each expensive pass yields three or four tokens instead of one. The text that comes out has exactly the distribution the large model would have produced on its own.
Two names hold for the whole section. The large model whose output we want is the target. The small model that guesses is the draft. The target is fixed, and the draft is ours to choose.
The trick works because checking a few tokens costs about as much as writing one. To write a token, a model must read every one of its weights from the GPU's memory. On a GPU that reading takes far longer than the arithmetic the token needs (§20.1). Here is how lopsided it is for a real model.
Two questions decide whether this is worth anything. First, how can the target accept guesses without changing what it would have written, even when it samples at a temperature instead of always taking its top token? Second, how often must the guesses be right, and how cheap must the guesser be, for the scheme to pay? This section answers both exactly. Then it follows the idea into a busy server, where checking stops being free, into trees of guesses, and through the kinds of guessers that frontier serving systems use in 2026. The proof of exactness and the speedup formula are both standard interview questions on inference.
Every speedup in this section is measured against the cost model of a decode step built in §20.1, so we restate it here. A decode step does two kinds of work. It reads bytes from the GPU's memory, and it does arithmetic. The GPU overlaps the two, so the step takes as long as the larger of them.
The bytes come in two kinds. The weights are read once per step, however many sequences share the step. Each sequence also reads its own KV cache, the stored keys and values of its earlier tokens, kept so that they are not recomputed (§6.5). The arithmetic is about two FLOPs per weight for every token processed, plus the attention of that token over its cache.
In symbols, a decode step for sequences whose mean context, the number of tokens already cached, is takes
Each term is a time.
As in §20.1, and always mean these two hardware numbers in this chapter. Their ratio is the ridge point, the number of FLOPs a kernel must do per byte it reads before arithmetic becomes the bottleneck. For an H100 in bfloat16 it is FLOPs per byte.
Now feed the model new tokens per sequence in one pass instead of one. This is the chunked forward pass of §6.5. Each new token attends to the whole cache and to the new tokens before it, through the causal mask of §4.4 aligned to its bottom-right corner. Every new token does a full token's arithmetic. The weights and the caches are still read once. So the pass takes
In plain words, checking tokens per sequence costs one decode step as long as the extra arithmetic still hides under the memory time, that is, while . The pass also writes new cache entries, kilobytes against gigabytes, which we drop as §20.1 did.
For one sequence with a short context, the condition reads . In bfloat16, , so that is about 295 tokens. §20.1 met the same number as the knee, the batch size at which plain decoding turns compute-bound. Both count the tokens processed per read of the weights. A weight read from memory does not care whether those tokens come from 295 different sequences or from one sequence checking 295 guesses.
In this model a pass over 256 tokens of one sequence costs exactly one decode step, for both models. Only at 512 does the arithmetic exceed the memory traffic.
Real kernels are less generous. A matrix multiply works in tiles of 64 or 128 rows, so a few extra tokens can cost a whole extra tile. Engines also record each step as a CUDA graph, a replayable sequence of kernel launches, for only a few fixed shapes, and pad every pass up to the next shape. So the cost of a verification pass that vLLM measures at startup is a staircase set by those shapes, not a smooth roofline (vLLM Team 2026). In practice the free range of a few hundred tokens is never the limit. Guesses far down a draft are rarely right, as the speedup formula below shows, so deployed chains check from 1 to about 16 tokens and trees of guesses have a few dozen nodes.
On several GPUs there is one more cost, the all-reduces of tensor parallelism (§20.1), which sum each layer's partial results across the GPUs. Their cost does not grow with either. Each carries the activations of a handful of tokens, so its time is set by the latency of a message, not by bytes. Chen et al. (2023) list exactly these three reasons why scoring a short continuation costs about as much as scoring one token. The linear layers are memory-bound at small batch. The attention cost is dominated by reading the cache, which does not grow with . And the all-reduces are latency-bound.
An interviewer will ask why a forward pass over five tokens costs about the same as a pass over one. The answer is this box. At small batch the step is set by bytes read, and checking more tokens adds arithmetic, not bytes.
Two symbols run through the rest of the section. Given the tokens so far, , the target assigns a probability to every possible next token . That list of probabilities is its next-token distribution . The draft has its own next-token distribution, written .
Start with a target that decodes greedily, always taking its most likely token, . This case needs no probability, and the whole idea is already visible in it. The draft guesses a few tokens. The target scores all of them in one pass and says, at every position, what it would have picked there. We keep the guesses up to the first disagreement and take the target's own pick at that position.
The example took four steps. The draft made its guesses. One target pass returned the target's own pick after every guess. The guesses were kept up to the first disagreement. Then the target's pick at that position was added. Written for any prefix and any number of guesses, these are the four steps of a round.
The bonus token is why a round where every guess is right emits tokens, one more than the draft wrote. The target pass computed its pick after the last guess anyway, so that token costs nothing extra. The question that remains is whether the output is still the target's own. It is, by a short induction over the positions of a round.
Let be the target's greedy continuation of . We show by induction that the round emits . For , assume . Then is the target's argmax after , which is by definition. Also by the definition of , so . The last emitted token is , the target's argmax after , which is . The next round starts from , and the same argument applies. The round emits tokens with . ∎
In plain words, keep the drafts for as long as they agree with what the target would have chosen anyway, and take one token from the target at the first disagreement. A round never emits fewer tokens per target pass than plain decoding, since it always emits at least the target's own next token. It can still cost more time, because the draft steps are not free, which the speedup formula below accounts for.
The guarantee holds in exact arithmetic. On a GPU, a pass over tokens runs kernels of different shapes from one-token passes. Kernels of different shapes add numbers in different orders, and floating-point addition is not associative, so the logits can differ in their last bits. At a near-tie that can flip an argmax. This is the batch-invariance problem of §6.4. So greedy speculation reproduces the greedy output of the same engine with the same verification kernels. At rare near-ties it can differ from a run without speculation, which matters if you test it by comparing strings.
Implement greedy_speculative_generate(target_logits, draft_next, prompt, n_new, gamma), greedy speculative decoding that also counts how many times it calls the target.
The two models are plain functions over a vocabulary of V tokens.
target_logits(tokens) runs the target once on a list of tokens. It returns an array of shape (len(tokens), V) whose row i scores the token that comes after tokens[:i+1].draft_next(tokens) returns the draft's logits for the token after tokens, an array of shape (V,).Each round does three things. It drafts gamma tokens greedily, one draft_next call each. It makes exactly one target call, on the current tokens followed by the drafts. It keeps the longest prefix of drafts that match the target's argmaxes and appends the target's own argmax after that prefix.
Return two things, the prompt followed by exactly n_new new tokens, and the number of target calls you made. The tokens must equal plain greedy decoding with the target. The setup provides make_models(seed, noise), which returns a target, a draft, and a dict counting the calls to each, and plain_greedy for comparison.
Most deployed models sample, and then agreement with the target's top token is the wrong test. The target does not have one right answer at each position, only a distribution . From here on, and mean the distributions each model really samples from, after temperature, truncation such as top-, and penalties have been applied (§6.4). We need a rule that turns a draft sampled from into a token distributed exactly as , and that keeps the draft as often as possible.
There is an easy exact rule, and it is poor. Sample from the verification pass, and keep the draft only if . The output is always , so it is distributed exactly as . But two independent samples agree only with probability . That is small whenever the distributions are spread out, even when they are identical. Take and over three tokens . They agree with probability .
The good rule treats the draft's tokens unequally. Where the draft proposes a token less often than the target wants it, keep every such proposal. Where it proposes a token too often, keep only the fraction of those proposals. When a draft is rejected, draw a replacement from the probability that the draft under-covers. That is the residual , normalized to sum to 1.
Is 0.7 good, or could a cleverer rule keep the draft more often? To answer, we need a way to measure how far apart two distributions are.
In plain words, total variation is the largest difference in probability that the two distributions can give to any event, and one minus it is how much their histograms overlap. In the example, and the overlap is 0.7.
Since , summing over gives . For the maximum, let be the set of tokens with . Both distributions sum to 1, so , and the positive and negative parts of have the same total. Hence . Any other set can only lose positive terms or add negative ones, so , and by symmetry the same bound holds for . ∎
Training usually measures distance with the KL divergence of §0.5, not with total variation. The two are tied together by Pinsker's inequality, with the KL in nats (Cover & Thomas 2006, Lemma 11.6.1, which we use without proof). So a draft close to the target in KL is close in total variation. That is why distilling the target into the draft, training the draft to match the target's distributions, raises acceptance.
Proof. The output is in one of two disjoint ways. Either was drafted and accepted, with probability , or the draft was rejected and the residual produced . Summing the first over gives the acceptance probability . The rejection probability is therefore . That is exactly the residual's normalizer, so the second way has probability . The total is , because for any two numbers. A token with is never drafted, so its ratio is never needed. When every draft is accepted and the residual is never needed either. ∎
In plain words, the probability thrown away by rejecting over-proposed tokens is exactly the probability that the draft under-covers elsewhere, and the residual hands it back there. §0.4 met this rule as a variant of rejection sampling, with the same acceptance rate . Unlike plain rejection sampling, a rejection is never wasted, because one exact sample comes out either way. In an interview, this proof is the core of the topic. Expect to give it on a whiteboard in under five minutes.
So is the 0.7 of the example the best possible? Yes. No exact rule can keep a single draft more often than .
Proof. For every token , the event that and is contained both in the event and in the event , so its probability is at most . Summing over gives the bound. The speculative rule emits exactly when it accepts, which has probability , and its is distributed as by the previous theorem. ∎
In plain words, two random tokens with distributions and can agree at most as often as their histograms overlap. A joint distribution of two random variables with given distributions is called a coupling. One that makes them equal as often as possible is a maximal coupling, and speculative sampling is a maximal coupling of the draft and the target.
What this changes in practice is where to look for more speed. The verification rule cannot be improved, so higher acceptance from a single draft needs a draft closer to the target. The other route is several drafts per position, the token trees below. Sun et al. (2023) analyze that case as an optimal transport problem, the problem of moving one distribution onto another at least cost.
Three special cases are worth knowing by heart.
Temperature matters, and here both models sample at the same temperature . As goes to 0, both approach their argmax. So tends to 1 where their argmaxes agree and to 0 where they do not. As grows, both spread toward the uniform distribution, and tends to 1 again. In between, can move either way, and on real models it is usually highest near 0. Leviathan et al. (2023) drafted for T5-XXL (11B parameters) with T5-small (77M) on English to German translation. They measured under argmax sampling and at temperature 1. With LaMDA 100M drafting for LaMDA 137B on dialog, they measured and . An interviewer may ask whether speculation helps more at temperature 0 or 1. Usually at 0, and these numbers are why.
Implement two functions.
tv(p, q) returns the total variation distance between distributions stored along the last axis of two arrays of shape (..., V). It returns one value per row.acceptance_rate(p_logits, q_logits, tau) returns the acceptance probability , one value per row, when both models sample at temperature tau from the given logits. That is, is the softmax of p_logits / tau, and is the softmax of q_logits / tau. Treat tau = 0 as greedy decoding on both sides.Then try logits of your own and watch how moves with the temperature. It need not move in one direction.
A real round drafts tokens in a row and verifies all of them in one target pass. It applies the one-token rule to the drafts from left to right and stops at the first rejection. The target pass supplies the target's distribution at every drafted position at once, each conditioned on the drafts before it.
This is Algorithm 1 of Leviathan et al. (2023). It was found independently at DeepMind, where it is Algorithm 2 of Chen et al. (2023). Chen et al. call the target and the draft , the reverse of our letters, which is worth knowing when you read both papers.
By the chain rule it is enough to show that each emitted token, given everything that happened before it was produced, has the target's conditional distribution given the tokens emitted so far. Look at the moment the procedure produces a token at some position of some round, with emitted prefix . Two cases are possible.
If the round has accepted every earlier draft and this position holds a draft, then was sampled from given the past, is a fresh uniform independent of the past, and . The token emitted here is if accepted and a residual sample otherwise. That is the single-token rule applied to and , so the token is distributed as by the theorem above.
If instead , the bonus token is drawn from directly.
A round ends after its first token that is not an accepted draft, and the next round starts from the emitted prefix with fresh randomness, so these two cases cover every token. The drafts after a rejected position were sampled conditioned on the rejected token and are discarded, so they never enter the output. ∎
In plain words, each position of a round is a fresh use of the one-token rule, and the round stops at the first position where the rule did not keep the draft.
The proof relies on one requirement that deserves a name now, because the schemes later in this section that choose how much to verify must respect it. The decision whether to verify position at all may depend on the tokens emitted before . It must never depend on the drafted token itself, or on anything computed from it, such as the drafts after it. A rule with this property is called non-anticipating. The proof used it without saying so, when it treated the token at position as a plain application of the one-token rule.
Implement speculative_verify(p, q, drafts, rng), the verification step of one round. Its inputs are the following.
p has shape (gamma + 1, V). Row i is the target's distribution after the prefix and the first i drafts.q has shape (gamma, V). Row i is the distribution that draft i was sampled from.drafts holds the gamma drafted token ids.Return the emitted tokens as a list of ints, the accepted drafts followed by one more token.
Use the random generator the way an engine does. Call rng.random() once per verified position, and accept when the result is below . Call rng.choice(V, p=...) once for the extra token. It comes from the normalized residual after a rejection, or from p[gamma] when every draft is accepted. The tests pass in a generator that records its calls.
The simulation below checks the theorem on small models we can solve exactly. Both are bigram models over six tokens, models whose next-token distribution depends only on the previous token . The target is , and the draft is a perturbed copy of it. Every drafted position conditions on the drafts before it, as in a real model.
We generate the first two tokens of 3,000 sequences and compare their joint frequencies with the exact target probabilities. We do it twice. The first run uses the correct residual. The second has the most common bug, resampling from after a rejection.
A round that accepts drafts emits tokens, the accepted drafts plus the target's correction or bonus token. Start with a tiny case. Let the draft guess tokens, each accepted with probability 0.8 if the one before it was.
The expected count is . The same number comes out as , one token always, plus the chance of reaching each draft. That second way of counting is the general rule. Write for the survival probability of position , the probability that the first drafts are all accepted.
, because counts the positions . Taking expectations gives . Under the i.i.d. model, surviving to position means independent acceptances, so . Then for , and . The geometric sum is . ∎
In plain words, each position contributes the probability of being reached, and the leading 1 is the token the target always adds. With and , a round emits tokens on average.
The first formula is exact for any draft. The second is a model. In a real model the acceptance probability of position is , and it changes with the context. Leviathan et al. call this per-position value , define as its expectation, and assume the values are i.i.d. to get the closed form. In real drafts acceptance usually decays along the block. So the survival form is the one to use, and the schedulers later in this section work with it directly.
Now put a price on a round. Let be the time of one draft step divided by the time of one target step, so a draft step costs target steps. Let the verification pass cost one target step, which the first part of this section showed is true at small batch.
Rounds are independent and identically distributed under the model, so by the law of large numbers the long-run tokens per unit time is the expected tokens per round over the expected time per round. That is in units of target steps, against 1 token per target step without speculation. Item 1 substitutes and , and exactly when . Item 2 bounds the geometric sum by its infinite version. Item 3 replaces the draft cost by . For item 4, a round does target-token units of arithmetic and emits tokens. These are Theorems 3.8 and 3.11 and Corollary 3.9 of Leviathan et al. (2023). ∎
In plain words, speculation trades arithmetic for fewer trips through memory. Every rejected draft is arithmetic thrown away. That costs nothing while the GPU is waiting on memory anyway, and real time once it is not. The best is found by trying integers. It is finite whenever , because never exceeds while the cost grows linearly in .
Implement three functions.
expected_tokens(alpha, gamma) returns , the expected number of tokens a round emits.speedup(alpha, gamma, c, parallel=False, v=0.0) returns divided by the cost of a round in target steps.best_gamma(alpha, c, max_gamma, parallel=False, v=0.0) returns the gamma in 1..max_gamma with the largest speedup, and the smallest such gamma on ties.alpha is either one number, the i.i.d. acceptance probability, or an array with at least gamma entries (max_gamma for best_gamma). In the array, entry i is the probability that draft i + 1 is accepted, given that the drafts before it were.
A round costs three things, in target steps. The draft costs gamma * c, or just c for a parallel drafter that proposes the whole block in one pass. The verification pass costs 1. And each verified draft adds v, the extra target cost per token once verification is no longer free, so gamma * v in all.
The closed form assumed i.i.d. acceptance. For the bigram models of the simulation we can compute the survival probabilities exactly and see how far off that assumption is. Let be the acceptance matrix with entries , the probability of drafting after and accepting it. Every sequence of the simulation starts from token 0, so let be the one-hot vector of token 0. Entry of the row vector is the probability of accepting the first drafts and ending at token . So the survival probability is the sum of that row.
Measured and exact agree, 2.932 against 2.938. The i.i.d. formula, with set to the first position's acceptance, gives 2.911. It is off by about 1%, because acceptance here depends on which token was accepted before. On real models the gap is larger, since acceptance decays along the draft. So check published speedups against measured survival curves, not a single .
Everything so far assumed that verifying tokens costs one decode step. That holds while the GPU waits on memory, and a busy server changes that. It decodes sequences together, so that one read of the weights serves all of them (§20.1). The batch already uses up some of the spare arithmetic.
With speculation, each round runs draft steps and then one target pass over tokens, which costs . Plain decoding costs per token per sequence. Here is the scale. For a dense model with short contexts, plain decoding turns compute-bound near on an H100. Checking 4 tokens per sequence puts tokens through each weight read, so it reaches the same point near . Past that point the extra tokens of a verification pass are no longer free.
Cases 1 to 3 substitute the branches of the maximum into . In case 1 both passes take . In case 2 both take their compute branch, and . In case 3 the baseline takes and verification takes , and the ratio falls as grows.
For the last part, for all if , since . Otherwise it fails for large , first at . Multiplying by gives . Collecting the terms in , with , gives the condition. ∎
In plain words, long contexts keep speculation alive. Each sequence's cache is read once per pass, however many of its tokens are checked. When contexts are long, the pass is dominated by bytes that verification does not multiply, and the extra arithmetic stays hidden at any batch. §20.1 called the same threshold the critical context, the context beyond which decode is memory-bound at every batch. Here it is computed with queries per sequence instead of one. Sadhukhan et al. (2024) made this argument, and their MagicDec system showed that speculation pays at batch 32 to 256 once sequences are long enough.
The cell puts numbers on it for Llama 3.1 8B on one H100. The drafter is one Transformer layer of 0.5B parameters, about the size of the drafters that read the target's features, described later. It costs about 6% of a target step at batch 1. The cell also checks the same quantities for latent attention and for a mixture of experts.
Three regimes show up.
Only 119 sequences of 4,096 tokens fit in one H100's 80 GB, so the right end of that curve needs more GPUs. The ratios do not depend on how many GPUs share the work. What this changes in practice is the default. Speculation is not only a low-load trick, and whether it pays at high load depends on the context length, the attention design, and whether the model is a mixture of experts.
The figure redraws the cell's curve for any context length and draft length, starting at 64 tokens of context. Slide the context up and watch the drop move to larger batches, until past 1,755 tokens verification is free at every batch. Hover over the curve to read the speedup at any batch.
A fixed is right for one load and wrong for every other. When the GPU is memory-bound, a long, risky draft is free. When it is compute-bound, each verified token displaces real work for other requests. So in 2026 engines began choosing, at every step, how many drafted tokens of each request to verify. This is called adaptive verification.
It needs an estimate of how likely each draft is to survive. Cheng et al. (2026) give their drafter, DSpark, a small confidence head, an extra output that predicts, for each drafted position, the probability that the token is accepted given that the positions before it were. The running product of these confidences along request is that request's survival curve, .
Now count the gain and the cost. Suppose the step verifies drafts of request . Then it emits tokens in expectation, and it costs a target pass over tokens. Each survival curve decreases, so the best way to spend draft slots is on the largest survivals over all requests. Those automatically form a prefix of each request's draft. The engine tries every and keeps the one with the most expected tokens per second, using a table of step costs it measured at startup (vLLM Team 2026). The cell runs that rule against our step model for a parallel drafter of 7 tokens, at three loads, with 512 tokens of context. It leaves out the drafter's own cost. That cost is the same for every , so it does not change the choice, but it makes the gain over no speculation look slightly larger than it is.
With 8 requests the pass is memory-bound, and the rule verifies all seven drafts. With 64 it already trims the unlikely tails, verifying 4.75 drafts per request on average. With 256 it verifies 1.35. At that load, always verifying all seven is slower than not speculating at all, 22,980 against 25,800 tokens per second. The adaptive rule reaches 51,209.
Real deployments behave the same way. vLLM ran adaptive verification for DeepSeek-V4-Pro on eight B300 GPUs, drafting 7 tokens per pass, from 1 to 256 concurrent requests (vLLM Team 2026). At every load it sat on the Pareto frontier of throughput against interactivity, the tokens per second each user sees. That means no fixed draft length was better on both at once. It acted like a long fixed draft at low load and a short one at high load. In that deployment the last of the 7 drafted tokens survived less than 10% of the time, and the first more than 70%.
In DeepSeek's own production serving, the earlier one-token draft verified 2 tokens per request, the draft and the bonus position. The scheduler expanded that to roughly 4 to 6 tokens per request under the moderate loads that dominate their traffic (Cheng et al. 2026).
There is a catch, and it is the non-anticipating requirement from the whole-round proof. DSpark's confidence for position reads the token drafted at position . Suppose a search looks at all the survivals at once and then decides how far to verify. Then whether position is verified can depend on , through the confidences after it, and the drafted tokens influence their own verification.
The paper avoids this in two ways. Its scheduler admits the draft slots one at a time, in order of survival, and stops at the first slot that lowers the expected throughput. So the decision about a slot never looks at the slots after it. The production versions choose the number of slots from older confidences, two steps old in DeepSeek's serving and one step old in vLLM, which cannot depend on the current drafts. Then they fill those slots in order of the current survivals. Our cell is safe for a simpler reason, since its survivals are random numbers that do not depend on any draft. An interviewer who asks about adaptive verification wants to hear this requirement.
Verifying always and verifying never are both exact. Verifying depending on the drafted token is not, and the cell prints the same as the hand count.
A chain of drafts dies at its first wrong guess. When the draft is unsure between two continuations, it can propose both, and the target can check both in the same pass. Say the prefix is "The cat" and the draft cannot decide between "sat" and "is". It proposes both, and after "sat" it adds "on". The target scores the three guesses in one pass. If it would have written "is", the round still accepts one draft, where a chain of "sat on" would have accepted none.
A token tree holds several candidate continuations that share prefixes, like this one. Verifying it costs one pass over all its nodes, so a tree of nodes is free in the same sense as a chain of tokens.
The pass needs two changes from an ordinary chunked pass. Each node must attend only to the prefix and to the nodes on its own branch, never to a rival guess. In the example, "on" may see "sat" but not "is". And each node must get the position id it would have in its own branch, the index fed to the position encoding (§5.4). Both "sat" and "is" are the third token of their sentence, so both get the same position id.
Here is a small tree. Its parents are . Nodes 0 and 1 are two guesses for the first token, nodes 2 and 3 continue the first guess, node 4 continues the second, and node 5 continues node 2. The node-to-node block of the mask and the depths are
and the prefix block is all ones. One pass returns the target's distribution after every node, conditioned on exactly that node's branch.
The figure starts from this tree, with "The cat" as the prefix. Click a node to see its row of the mask. Pick what the target would write to see which branch a greedy target keeps, by the walk described after the exercise.
Implement tree_attention_mask(parents, prefix_len). The tree is given as a parent array, with -1 for nodes that follow the prefix directly, and parents are listed before their children. Return two arrays.
(n_nodes, prefix_len + n_nodes). In row i, node i sees every prefix position, itself, and its ancestors, and nothing else.prefix_len + depth.Tree-based speculative decoders build exactly this mask before the verification pass.
Verifying a tree under greedy decoding is a walk. Start at the prefix and move to the child that equals the target's choice there. Repeat from that child. Stop at the first node with no such child, and emit the target's choice there as the extra token.
Under sampling, a node has several children to try, and the one-token rule extends to them. Try the children one at a time. Each rejection removes from the target what that child's draft distribution covered, and the next child is tested against what is left.
Show by backward induction on that the procedure started at try with target outputs a token distributed as . Started at try , it samples from directly. Started at try , it draws a fresh and accepts it with probability , and otherwise continues from try . By the induction hypothesis that continuation outputs a token distributed as , the residual of and . That is the single-token rule with target and residual , so the output is distributed as . Taking gives .
Try is accepted with probability given that it is reached, and the tries are independent given the targets, which gives the product. (If some , try is accepted with certainty and is never needed.) ∎
This is the multi-step speculative sampling of Miao et al. (2024), whose SpecInfer system introduced token trees with this mask. SpecInfer reported 1.5 to 2.8 times over existing serving systems for distributed inference. After a child is accepted, verification moves to that child's own children, drafted from conditioned on the branch. The argument for a chain applies level by level, so the whole tree is exact.
Chen et al. (2024), in their Sequoia method, draw a node's children without replacement instead. They zero each rejected token in and renormalize before the next try, so the same wrong token is never proposed twice. That matters at low temperature, where an i.i.d. draft keeps repeating its favorite.
The cell checks the theorem at one node over five tokens. It runs 100,000 trials for 1, 2, 4, and 8 children, and compares the output frequencies with and the chance of accepting some child with the formula.
The output stays at for every . The chance that some child survives climbs from 0.55 with one child to 0.86 with eight. It climbs slowly, because i.i.d. children keep re-proposing the draft's favorite token, which the target likes less than the draft does.
How the tree is shaped is where the methods differ.
After a tree is verified, the cache holds entries for every node, but only the accepted branch is kept. Its entries are scattered among discarded siblings, so they must be gathered into consecutive slots before the next round.
Every method in this section uses the same verifier. They differ only in where the guesses come from. The guesser sets both the acceptance rate and the relative cost , so it sets the speedup. Exactness always comes from the verifier, never from the drafter. Here are the families, from the oldest to the newest.
A smaller model of the same family. This is the original setting of Leviathan et al. (2023) and Chen et al. (2023). The draft must share the target's tokenizer, so that a drafted token id means the same string to both. Leviathan et al. found that drafts about two orders of magnitude smaller than the target worked best, with between 0.5 and 0.9.
Since , the natural way to improve a draft is to distill the target into it, training the draft to match the target's outputs (§20.4). Zhou et al. (2024) found that two choices matter most. One is training on the draft's own generations, which is called on-policy data. The other is choosing the divergence to match the decoding strategy. Their method, DistillSpec, reported 10 to 45% speedups over speculative decoding with an undistilled draft.
Extra heads on the target. Cai et al. (2024) add small output heads on top of the target. Each reads the target's last hidden state , the vector that the output layer turns into next-token logits. In their method, Medusa, head predicts the token at position as
written in this book's input-by-output layout. starts at zero, and starts as a copy of the target's output head. So each head begins as the ordinary next-token predictor. Each head guesses its position from alone, so the guesses for different positions are independent of each other. That is why Medusa verifies a Cartesian product tree.
Medusa comes in two versions. Medusa-1 trains only the heads on a frozen target, and it is exact with the rejection rule, at over 2.2 times. Medusa-2 also fine-tunes the target, at 2.3 to 2.8 times, which changes the model being served. Medusa also proposed typical acceptance. It keeps a candidate when the target gives it probability above a threshold that depends on the entropy of the target's distribution. It is faster at high temperature, and it is not exact.
DeepSeek-V3's multi-token prediction module (§8.1) is the same idea built into pretraining. Unlike a Medusa head, it also reads the token just emitted. So the module is a one-token draft that ships with the model.
Drafting from the target's features. The EAGLE drafter of Li et al. (2024) is one Transformer layer. It reads the target's features, the hidden states that enter the target's output head, together with the token sequence shifted one step ahead. It predicts the next feature and turns it into a token with the target's own output head. Features are more regular than tokens. Feeding in the sampled token tells the drafter which of several possible continuations the feature should follow. For a 70B target the drafter has under 1B trainable parameters and trains in one to two days on four A100 GPUs. It gave 2.7 to 3.5 times on LLaMA2-Chat 70B.
EAGLE-3 (Li et al. 2025) dropped the loss on predicting the next feature. It predicts tokens directly, from a fusion of low, middle, and high layers of the target. It is trained with training-time test, which means the drafter is trained on inputs that include its own earlier predictions, exactly as it will see them at inference. With those changes, the speedup kept improving as the training data grew. EAGLE-3 reached 3.0 to 6.5 times over plain decoding, 20 to 40% faster than EAGLE-2.
The target drafting for itself. Elhoushi et al. (2024) train with layer dropout and an early-exit loss, so that the first layers alone make usable predictions. Their method, LayerSkip, then drafts with the early layers and verifies with the rest, reusing the early layers' computation. It reported up to 2.16 times on CNN/DM summarization.
MagicDec (Sadhukhan et al. 2024) keeps the whole model as the draft but lets it read only a sparse window of its cache, the recent tokens plus a few initial ones. That is in the spirit of sliding-window attention with sinks. It is what long-context, large-batch serving needs, since the draft's cost no longer grows with the context.
No draft model at all. When the output copies the input, as in summarizing, editing code, or answering from retrieved documents, the context itself is a draft. Prompt lookup decoding (Saxena 2023) and LLMA (Yang et al. 2023) find an earlier occurrence of the last few tokens and propose what followed it. LLMA reported over 2 times speedups with outputs identical to greedy decoding.
Lookahead decoding (Fu et al. 2024) builds its own pool of n-grams with Jacobi iteration. That method guesses all future positions at once, runs the model on them in parallel, replaces each guess with the model's prediction, and repeats. Lookahead does this in the same pass as verification and is exact. It reported up to 1.8 times on MT-Bench and 4 times with several GPUs on code completion.
Implement ngram_draft(context, n, k), the drafter of prompt lookup decoding. context is a list of tokens, strings or ints.
n tokens of context, the suffix. Find its most recent earlier occurrence. That occurrence must start before the suffix itself does, so that the suffix never matches itself.k of them.n - 1 tokens, then n - 2, down to 1. Return an empty list if nothing matches.For example, take a b c X a b c Y a b c with n = 3 and k = 2. The suffix a b c last occurred earlier starting at the second a. It was followed by Y a, so that is the proposal. The setup's tok splits code-like text into tokens for the tests.
Drafting a whole block in one pass. An autoregressive drafter, one that guesses a token at a time, pays per round, which forces it to be shallow. A drafter that proposes the whole block in one pass pays once, so it can afford to be deeper. Chen, Liang & Liu (2026) built such a drafter, DFlash, from a small block diffusion model, one that fills all the masked positions of a block in a single forward pass. It is conditioned on hidden features of the target, injected into the keys and values of every draft layer. Their five-layer drafter proposing 16 tokens took less time to draft, and had more drafts accepted, than EAGLE-3's one-layer drafter proposing 8. They reported over 6 times lossless acceleration and up to 2.5 times the speedup of EAGLE-3.
Parallel drafting has one weakness. Positions predicted in parallel do not see the tokens sampled at each other, so acceptance decays quickly along the block. Cheng et al. (2026) call this suffix decay. Their drafter, DSpark, keeps the parallel backbone and adds a light sequential step. To position 's logits it adds a bias . Here is looked up at the token just sampled at position , and . Together they form a rank-256 table of which token tends to follow which. DSpark also adds the confidence head that drives adaptive verification.
Its reported results are these.
| Drafter | Guesses from | Extra weights | Training | Exact with the rule | Reported speedup |
|---|---|---|---|---|---|
| Small model of the same family | its own forward passes | a separate model | pretraining, ideally distillation | yes | 1.9 to 3.4 times (T5-XXL, Chinchilla) |
| Medusa heads | the target's last hidden state | one layer per head | heads only (Medusa-1) or joint (Medusa-2) | Medusa-1 yes, typical acceptance no | 2.2 to 2.8 times |
| Multi-token prediction (MTP) module | the target's last state and the token just emitted | one block | during pretraining | yes | 1.8 times at (DeepSeek-V3) |
| EAGLE 1 to 3 | the target's features and the shifted tokens | one layer, under 1B | one to two days on four A100s (EAGLE, 70B) | yes | 2.7 to 6.5 times |
| Early exit (LayerSkip) | the target's first layers | none | layer dropout and early-exit loss | yes | up to 2.16 times |
| Prompt lookup, LLMA, lookahead | the context or a Jacobi n-gram pool | none | none | yes | up to 1.8 times on chat (lookahead), over 2 times on copy-heavy tasks (LLMA) |
| Parallel block (DFlash, DSpark) | a one-pass block drafter on target features | a few layers, up to 5B (Kimi K3) | on target hidden states, at scale | yes | over 6 times (DFlash), 60 to 85% over MTP in production (DSpark) |
Every "yes" holds only with the rejection rule of this section, and up to floating-point differences between kernels. Every speedup is a batch-1 or low-load number on the paper's own hardware and tasks, so compare them with care. An interviewer who asks which drafter to use wants to hear that the answer depends on the batch, the context length, and whether you can train a drafter on the target's features.
The verification pass computed keys and values for every drafted position, so after a round the target's cache holds entries for all of them. After acceptances, the entries of the accepted drafts are correct, because they were computed on the right prefix. The entries of the rejected positions must be discarded. The correction or bonus token has no entry yet, and the next round computes it as the first token of its verification pass.
How rollback works depends on the cache layout.
Recurrent layers are harder. A state space or linear-attention layer folds every token into one fixed-size state, so a rejected token cannot be removed by truncation. The engine must save the state after each verified position or recompute from the last accepted one. That is a real cost for the hybrid models that mix attention with recurrent layers, which are becoming common.
Engines verify the whole batch at once, with no Python loop over sequences. The block below does it with gather, a cumulative product for the accepted prefix, and one multinomial call for the extra token. A row of zeros appended to makes the bonus case fall out of the residual formula, since . The check draws drafts from for 200,000 sequences and compares the first two emitted tokens with the target rows.
Both marginals match the target rows to within 0.001. The mean accepted length matches , the survival formula with the three positions' own acceptance rates.
In practice you call an engine. Hugging Face generate takes a draft model as assistant_model, or drafts from the prompt with prompt_lookup_num_tokens. vLLM takes a speculative_config. Here the draft shares the target's tokenizer, so a drafted token id means the same string to both.