Speculative decoding I: exact speculative sampling
At small batch sizes decoding can be memory-bound, and verifying k tokens may cost close to generating one. Speculative decoding uses this opportunity: a cheap draft proposes and the larger model verifies in one pass. We prove exact target-distribution sampling, derive expected speedup from total variation, examine draft sources and implement real models; the documented measurement uses an RTX 3060.
After this lesson you can
- Prove speculative sampling produces exactly the target-model distribution.
- Relate acceptance to total variation and calculate expected speedup and optimal k.
- Implement draft and verification with KV cache rollback using two real models from the same family.
- Compare small-model drafts, prompt lookup and self-speculation by acceptance and cost.
- Explain why gain falls with large batches and decide when to disable speculation.
Before you start
A cheap proposal, an expensive verification
Autoregressive decoding produces one token at a time. For a single stream, each step rereads model weights and may be memory-bandwidth-bound. Under those conditions, evaluating several known positions in one pass can cost much less than separate calls. This opportunity depends on hardware, context length, and batch: it is not a universal transformer property.
In the draft-and-verify paradigm, a cheap mechanism proposes consecutive tokens and the target model computes their distributions in parallel conditioned on proposed prefixes. The causal mask prevents looking ahead at each position. Accepted output remains autoregressive: parallelism only anticipates work that may need discarding. For greedy decoding, compare each proposal with target argmax, retain the matching prefix, and replace the first disagreement with target argmax. If all agree, the next position’s argmax can also be emitted. Stern et al. studied blockwise parallel decoding.
For sampling, however, accepting only matches generally does not reproduce the target distribution. A rule is needed to correct draft bias. The next figure shows three distributions for a three-symbol vocabulary: change and observe overlap. The 1000 outputs use a reproducible seed; they are not language-model measurements.
Exact correction
Fix a prefix and finite vocabulary. Let and be normalized target and draft distributions after applying chosen sampling transformations such as temperature or truncation. For token drawn from , speculative sampling accepts with probability . The ratio is evaluated only where , since the draft cannot propose a zero-mass symbol.
On rejection, draw from residual , where . If , the distributions are equal and there is no rejection, so no residual need be defined. This construction relates to rejection sampling, but here missing mass is recovered with another distribution instead of proposing from again.
In the figure’s initial state, and . Accepted masses are and sum to . The unnormalized residual is with mass , so rejection draws from . The second symbol receives from acceptance and from correction: total , exactly its target mass. The same holds for other symbols. A finite histogram fluctuates around those probabilities and need not match exactly each run.
The proof is a probability identity for the distributions computed. On a real machine, evaluating the same prefix in differently shaped blocks or with different caches can slightly change logits due to operation order and precision. In one SmolLM2-1.7B, BF16, RTX 3060 check, TV between block-verification softmax and full recomputation was approximately 0.003, 0.003, and 0.037 for three positions of one example. In a separate CPU FP32 test with the same prompt but two other fixed proposals, TV was on the order of . These are bounded tests, not a general bound or proof of cause. Mathematical equality does not promise bitwise-identical output against another numerical path.
Proof
The accepted mass of is , also when by continuity of the final expression. Total rejection probability is . Thus correction contributes mass , and the sum is . If , the first mass is already .
∎The proof does not require ‘s support to be contained in ‘s. If and , the draft never proposes , but the residual can emit it. At the extreme and , the first proposal is always rejected and the second symbol always returned. At the opposite extreme , everything is accepted and each block returns tokens. Both cases also show high acceptance is a coupling property, not a speed guarantee: draft and verification still cost time.
The same proof applies at each position conditioned on the actually accepted prefix. At the first rejection, later tokens are ignored because their distributions were conditioned on a token no longer in the prefix. If all are accepted, draw one extra token from the target distribution computed after the block. Induction over prefixes proves sequence exactness, aside from implementation numerical differences. Leviathan et al. and Chen et al. justify this procedure.
Target distribution must also include constraints you want to preserve. If applying a repetition penalty or allowed vocabulary, apply it to the correct prefix before calculating each . Do not use a distribution for a prefix containing a rejected proposal for the corrected token. In greedy mode with deterministic tie-breaking, the target is a point mass: a proposal is accepted exactly when it matches the chosen argmax. In finite implementations, check that residual mass is positive after rejection and avoid dividing by a sum rounded to zero.
Acceptance and cost
Acceptance rate and speedup relate to total variation distance. For a fixed prefix,
The identity follows from and both masses summing to one. If all positions have constant conditional acceptance probability , the probability of reaching emission of token is . By the expectation tail-sum formula, tokens emitted per verification are
The initial one is the correction or extra token. This sum is for , and for . If one target pass costs one unit and each draft token costs units, without overhead or verification-cost variation with , ideal speedup is . Choose the maximum among allowed sizes, not a universal . In practice acceptance varies by position and context: the correct expression is .
The condition under which another proposal improves this model follows from comparing and . Multiplying by positive denominators and canceling terms gives
The left side measures marginal gain from reaching the new token, weighted by prior cost; the right is extra draft cost. Equality makes both sizes indifferent. In a real system evaluate as the nonspeculative option: if every candidate is slower than baseline, do not enable the mechanism. The chart searches through 16 to show shape, so its maximum alone does not decide whether speculation is worthwhile.
Map points come from one short RTX 3060 run with SmolLM2-1.7B as target and SmolLM2-135M as draft, seed 17, and the local cell’s prompt. That run’s speculative warm-up requested two tokens; code below requests eight to check more steps, consuming a different portion of the random sequence. At temperature 0.7, 17 of 25 verified tokens were accepted with and 21 of 31 with ; at temperature 1.0, 19 of 25 and 19 of 31. These are one-run rates, not precise estimates or measured speedups. They combine positions and contexts and do not prove constant acceptance: the map places them in the nearest row for orientation and calculates color from the idealized model. Proposals after rejection do not count as verified.
With , and , the sum is and ideal speedup is . This excludes cache, synchronization, kernels, and prefill time. Leviathan et al. reported 2 to 3 times speedup in their T5-XXL configuration; Chen et al. reported 2 to 2.5 times for Chinchilla 70B in their distributed setup. These are measurements of those systems, not predictions for your GPU.
Cache and proposal sources
The KV cache stores keys and values for the prefix. The target verifies proposed positions at once, but if position is rejected, KV entries from that position onward represent a discarded continuation. Crop cache to original prefix length plus the accepted tokens. Process the corrected token afterward to build its KV. Absolute positions and mask must match the retained prefix; draft cache must also return to a consistent state. In the figure is a deliberately constructed example, not a model run.
Work out indices before implementing. If the prefix has length , cache the first positions and pass the target the prefix’s last token followed by . The first logit row predicts ; the row after predicts , and the last predicts the extra token. Resulting cache has positions. If is rejected, keep positions and leave correction outside cache to process on the next call. If all are accepted, retain and leave the extra token pending. An offset mask or position can produce plausible logits conditioned on another sequence, so the lab compares against full recomputation and checks lengths after each crop.
Draft selection balances cost and closeness to . A small model from the same family can share a tokenizer and generate sequentially; a distilled one can learn to imitate the target better in contexts of interest. DistillSpec studies draft-generated data and task-adapted divergences to align both models. Prompt n-gram lookup proposes a previously seen continuation, useful for repetition without running another model. If no match is found, fall back to the target or another proposal. Self-speculation uses an early exit from the model itself; LayerSkip explicitly trains that ability and shares work between draft and verifier. None of these sources guarantees high acceptance on every task.
The batch tradeoff changes the decision. As batch grows, weight reads are amortized and the target may shift from memory-bound to compute-bound. Verifying more positions then costs more and the draft competes for resources. Measure both per-request latency and aggregate throughput with the same length distribution and generation options. Disable speculation if total cost per useful token rises or desired latency is missed. Latency measurement must exclude or disclose prefill, warm-up, and synchronization; the throughput-latency tradeoff matters more than one ratio.
Draft cost is not just parameter count: it includes retained cache, sequential calls, and verifier communication. A highly accurate draft almost as expensive as the target may lose to a less accurate one. A server can observe acceptance and time per token in recent windows and change , but must account for noise and prefill versus decode phases. Comparing configurations with different output lengths requires counting all actually emitted tokens and separating the first token from later per-token latency.
Temperature changes both distributions and can change their TV in either direction: there is no general monotonicity law. Measure acceptance and time at each temperature with the same logit processing in the proposal and ratio.
import numpy as np
def softmax_at(logits, temperature):
z = np.asarray(logits)/temperature
e = np.exp(z-z.max())
return e/e.sum()
def acceptance_at(a, b, temperature):
return np.minimum(softmax_at(a, temperature), softmax_at(b, temperature)).sum()
for a, b in [([2.06, -.51, -.29], [.46, -.95, -.37]), ([0,1,2], [0,2,1])]:
print('aceptación a T = 0.5, 1, 2:', [round(acceptance_at(a,b,t), 4) for t in (.5,1,2)])For the first pair acceptance falls from 0.5 to 1 then rises; for the second it rises at both steps. These are example logits, not model measurements. The very-high-temperature limit tends to make distributions uniform if all logits are finite and the same vocabulary is used, but that does not imply monotonicity along the whole path.
Lab: one position with character models
The next small corpus defines a bigram model for and trigram model for with additive smoothing. The experiment conditions on a fixed prefix, repeats correction, and compares frequency, acceptance, and a chi-square test. A test does not prove equality of distributions; the preceding proof does under its assumptions.
import numpy as np
from scipy.stats import chisquare
corpus = 'abracadabra abracadabra banana bandana ' * 30
alphabet = sorted(set(corpus))
index = {c: i for i, c in enumerate(alphabet)}
def probs(prefix, order):
counts = np.ones(len(alphabet), dtype=float)
for i in range(order - 1, len(corpus)):
if corpus[i-order+1:i] == prefix[-(order-1):]:
counts[index[corpus[i]]] += 1
return counts / counts.sum()
p, q = probs('ab', 3), probs('ab', 2)
alpha = np.minimum(p, q).sum()
r = np.maximum(p-q, 0)
if r.sum():
r /= r.sum()
generator = np.random.default_rng(2026)
n = 20000
draft = generator.choice(len(p), size=n, p=q)
accepted = generator.random(n) < np.minimum(1, p[draft]/q[draft])
output = draft.copy()
if (~accepted).sum():
output[~accepted] = generator.choice(len(p), size=(~accepted).sum(), p=r)
counts = np.bincount(output, minlength=len(p))
stat, pvalue = chisquare(counts, n*p)
print('alfabeto:', ''.join(alphabet))
print('aceptación medida y 1-TV:', round(accepted.mean(), 4), round(alpha, 4))
print('frecuencia:', np.round(counts/n, 4))
print('objetivo:', np.round(p, 4))
print('chi cuadrado y valor p:', round(stat, 3), round(pvalue, 4))Now propose full blocks. The count table is reused by context, but each distribution changes with the proposed prefix. At the first rejection later proposals are discarded. The first character’s distribution is checked with chi-square and observed acceptance compared with mean across actually verified contexts. Checking one position does not statistically prove the full-sequence distribution: the joint guarantee comes from the prior induction.
from functools import lru_cache
@lru_cache(maxsize=None)
def cached_probs(context, order):
return probs(context, order)
def block(prefix, k, random):
draft_prefix = prefix
proposal, draft_probs = [], []
for _ in range(k):
q = cached_probs(draft_prefix[-1:], 2)
x = random.choice(len(alphabet), p=q)
proposal.append(x); draft_probs.append(q)
draft_prefix += alphabet[x]
output, probabilities, flags = [], [], []
for x, q in zip(proposal, draft_probs):
p = cached_probs(prefix[-2:], 3)
probabilities.append(np.minimum(p,q).sum())
accepted = random.random() < min(1, p[x]/q[x])
flags.append(accepted)
if not accepted:
residual = np.maximum(p-q, 0)
residual /= residual.sum()
output.append(int(random.choice(len(alphabet), p=residual)))
return output, probabilities, flags
output.append(int(x))
prefix += alphabet[x]
p = cached_probs(prefix[-2:], 3)
output.append(int(random.choice(len(alphabet), p=p)))
return output, probabilities, flags
random = np.random.default_rng(17)
first, tested, predicted, lengths = [], [], [], []
for _ in range(1200):
result, expected, flags = block('ab', 3, random)
first.append(result[0]); tested.extend(flags); predicted.extend(expected); lengths.append(len(result))
counts = np.bincount(first, minlength=len(alphabet))
stat, pvalue = chisquare(counts, 1200*cached_probs('ab', 3))
print('primer carácter, chi cuadrado y valor p:', round(stat, 3), round(pvalue, 4))
print('aceptación observada y solapamiento medio:', round(np.mean(tested), 4), round(np.mean(predicted), 4))
print('tokens emitidos por bloque:', round(np.mean(lengths), 4))The preceding test observes only one character. To check a two-character event too, continue generation if the first block emitted only one. The theoretical probability of ra is the probability of r after ab times that of a after abr. Grouping into “ra” and “other” retains enough expected cases for this sample, but still does not turn a statistical test into a proof of equality for all events.
from scipy.stats import binomtest
random = np.random.default_rng(19)
hits = 0
for _ in range(1200):
prefix, generated = 'ab', ''
while len(generated) < 2:
result, _, _ = block(prefix, 3, random)
chars = ''.join(alphabet[i] for i in result)
generated += chars
prefix += chars
hits += generated[:2] == 'ra'
p_event = cached_probs('ab', 3)[index['r']]*cached_probs('br', 3)[index['a']]
print('frecuencia de ra:', round(hits/1200, 4), 'objetivo:', round(p_event, 4))
print('valor p binomial:', round(binomtest(hits, 1200, p_event).pvalue, 4))Local lab: two models and two caches
Use SmolLM2-1.7B as target and SmolLM2-135M as draft. PyTorch, Transformers, and space for both models are required; the first run may download them. Code was verified with Transformers 5.23.0, whose dynamic cache accepts crop(-n) to remove positions. Other versions may use another interface. It checks equal vocabularies, pins each model revision, and keeps separate caches.
At each block’s start both caches contain the whole prefix except its last token, pending processing. After proposing tokens, the target processes that last token plus the block in one pass. Both caches are then cropped to the original prefix plus accepted prefix; correction remains pending. When all are accepted, the draft must also process its last token so its cache reaches the correct length. Length checks seek rollback errors. TV comparison against full recomputation during warm-up shows numerical differences in this path, not a proven bound.
To expose mechanics, this code generates a fixed minimum length and ignores EOS. A final block may exceed the requested count. Time includes prompt prefill, draft cost, and verification; warm-up calls are excluded. Results vary with GPU load, prompt, and temperature. The Transformers comparison uses its own implementation and may stop at EOS, so it prints actual token count. Prompt lookup is tested with a repeated code snippet, not an editing benchmark.
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
torch.manual_seed(17)
torch.set_num_threads(4)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
target_id = 'HuggingFaceTB/SmolLM2-1.7B'
draft_id = 'HuggingFaceTB/SmolLM2-135M'
target_rev = 'effd688a12921b4cc83e3312b6feb579f70f9c71'
draft_rev = '93efa2f097d58c2a74874c7e644dbc9b0cee75a2'
tokenizer = AutoTokenizer.from_pretrained(target_id, revision=target_rev)
draft_tokenizer = AutoTokenizer.from_pretrained(draft_id, revision=draft_rev)
assert tokenizer.get_vocab() == draft_tokenizer.get_vocab()
dtype = torch.bfloat16 if device == 'cuda' and torch.cuda.is_bf16_supported() else torch.float32
target = AutoModelForCausalLM.from_pretrained(target_id, revision=target_rev, dtype=dtype).to(device).eval()
draft = AutoModelForCausalLM.from_pretrained(draft_id, revision=draft_rev, dtype=dtype).to(device).eval()
def distribution(logits, temperature):
return torch.softmax(logits.float() / temperature, dim=-1)
def crop_to(cache, length):
remove = cache.get_seq_length() - length
if remove < 0:
raise ValueError('la caché no alcanza el prefijo que se quiere conservar')
if remove:
cache.crop(-remove)
@torch.inference_mode()
def speculative(prompt, count=32, k=4, temperature=0.8, verify_cache=False):
ids = prompt.clone()
cache = target(ids[:, :-1], use_cache=True).past_key_values
draft_cache = draft(ids[:, :-1], use_cache=True).past_key_values
accepted_total = tested_total = calls = 0
while ids.shape[1] < prompt.shape[1] + count:
assert cache.get_seq_length() == ids.shape[1] - 1
assert draft_cache.get_seq_length() == ids.shape[1] - 1
proposals, qs = [], []
draft_input = ids[:, -1:]
full_draft = ids.clone()
for _ in range(k):
draft_out = draft(draft_input, past_key_values=draft_cache, use_cache=True)
draft_cache = draft_out.past_key_values
if verify_cache:
reference = draft(full_draft, use_cache=False).logits[0, -1]
tv = (distribution(draft_out.logits[0, -1], temperature)-distribution(reference, temperature)).abs().sum()/2
print('TV borrador caché frente a recálculo:', tv.item())
q = distribution(draft_out.logits[0, -1], temperature)
x = int(torch.multinomial(q, 1).item())
proposals.append(x); qs.append(q)
draft_input = torch.tensor([[x]], device=device)
full_draft = torch.cat((full_draft, draft_input), dim=1)
block = torch.tensor([[int(ids[0, -1]), *proposals]], device=device)
out = target(block, past_key_values=cache, use_cache=True)
cache = out.past_key_values
ps = distribution(out.logits[0], temperature)
if verify_cache:
full = torch.cat((ids, torch.tensor([proposals], device=device)), dim=1)
full_logits = target(full, use_cache=False).logits[0, -k-1:]
tv = (ps-distribution(full_logits, temperature)).abs().sum(dim=-1)/2
print('TV objetivo caché frente a recálculo:', tv.tolist())
emitted = []
for i, x in enumerate(proposals):
tested_total += 1
if torch.rand((), device=device) < torch.minimum(torch.ones((), device=device), ps[i, x]/qs[i][x]):
emitted.append(x); accepted_total += 1
else:
residual = torch.clamp(ps[i]-qs[i], min=0)
if residual.sum().item() <= 0:
raise FloatingPointError('residual nula tras un rechazo: revisa la precisión')
residual /= residual.sum()
emitted.append(int(torch.multinomial(residual, 1).item()))
break
else:
emitted.append(int(torch.multinomial(ps[k], 1).item()))
accepted_here = len(emitted)-1
crop_to(cache, ids.shape[1]+accepted_here)
if accepted_here == k:
draft_cache = draft(draft_input, past_key_values=draft_cache, use_cache=True).past_key_values
crop_to(draft_cache, ids.shape[1]+accepted_here)
ids = torch.cat((ids, torch.tensor([emitted], device=device)), dim=1)
calls += 1
return ids, accepted_total, tested_total, calls
@torch.inference_mode()
def baseline(prompt, count=32, temperature=0.8):
ids = prompt.clone()
cache = target(ids[:, :-1], use_cache=True).past_key_values
for _ in range(count):
out = target(ids[:, -1:], past_key_values=cache, use_cache=True)
cache = out.past_key_values
p = distribution(out.logits[0, -1], temperature)
ids = torch.cat((ids, torch.multinomial(p, 1).reshape(1, 1)), dim=1)
return ids
def measure(fn):
if device == 'cuda': torch.cuda.synchronize()
start = time.perf_counter()
result = fn()
if device == 'cuda': torch.cuda.synchronize()
return result, time.perf_counter()-start
prompt = tokenizer('Explain why a cache helps autoregressive generation:', return_tensors='pt').input_ids.to(device)
baseline(prompt, count=2)
speculative(prompt, count=8, k=2, verify_cache=True)
for temperature in (0.7, 1.0):
_, elapsed_base = measure(lambda: baseline(prompt, temperature=temperature))
print('temperatura', temperature, 'base tokens/s', 32/elapsed_base)
for k in (2, 4):
(ids, accepted, tested, calls), elapsed = measure(lambda: speculative(prompt, k=k, temperature=temperature))
generated = ids.shape[1]-prompt.shape[1]
print('k', k, 'tokens', generated, 'aceptados/verificados', accepted, tested,
'tokens por llamada', generated/calls, 'tokens/s', generated/elapsed,
'velocidad relativa', (generated/elapsed)/(32/elapsed_base))
draft.generation_config.num_assistant_tokens = 4
draft.generation_config.num_assistant_tokens_schedule = 'constant'
draft.generation_config.assistant_confidence_threshold = 0.0
@torch.inference_mode()
def builtin(ids, **kwargs):
output = target.generate(ids, max_new_tokens=32, do_sample=True, temperature=0.8,
pad_token_id=tokenizer.eos_token_id, **kwargs)
return output.shape[1]-ids.shape[1]
_, _ = measure(lambda: builtin(prompt))
n, elapsed = measure(lambda: builtin(prompt))
library_base = n/elapsed
print('Transformers base:', n, 'tokens, tokens/s', library_base)
_, _ = measure(lambda: builtin(prompt, assistant_model=draft))
n, elapsed = measure(lambda: builtin(prompt, assistant_model=draft))
print('Transformers con borrador:', n, 'tokens, tokens/s', n/elapsed, 'velocidad relativa', (n/elapsed)/library_base)
editing = tokenizer('def square(x):' + chr(10) + ' return x*x' + chr(10)*2 + 'def square(x):' + chr(10) + ' return', return_tensors='pt').input_ids.to(device)
for name, options in [('base', {}), ('prompt lookup', {'prompt_lookup_num_tokens':4, 'max_matching_ngram_size':2})]:
_, _ = measure(lambda: builtin(editing, **options))
n, elapsed = measure(lambda: builtin(editing, **options))
print(name, 'tokens', n, 'tokens/s', n/elapsed)npm run lab and open the connection link.Acceptance counts include only tokens examined up to each block’s first rejection. For a useful comparison, repeat measurements with multiple prompts and lengths, separate prefill from decoding, report batch, and measure aggregate throughput too. Library policies may change between versions; do not attribute a timing difference solely to draft quality.
In three short runs of the custom implementation on the shared RTX 3060, observed relative speeds for the four temperature and combinations ranged approximately from 0.13 to 0.94: slower than their respective baselines. These figures do not establish stable performance, and Python cost, synchronization, and load changes are part of measurement. In one code-prompt test, Transformers prompt lookup reached approximately 1.52 times its baseline speed; this is an observation on that repetitive example, not a general gain. The library is compared with its own baseline at temperature 0.8 and retains default generation options, which may include truncation and differ from the custom implementation. Self-speculation needs a model prepared for early exit and is explained here but was not measured.
Exercises
Step 1 of 2. What mass of symbol x is accepted?
Step 1 of 2. How is the minimum expressed?
speculative_step(p_probs, q_probs, draft_tokens, rng). Each row i of p and q is the distribution for the proposed prefix through i; p has an additional row for accepting all. Return the accepted prefix followed by a residual sample, or the extra sample. You receive tokens already proposed from q and a NumPy generator.import numpy as np
def speculative_step(p_probs, q_probs, draft_tokens, rng):
pass