Speculative Decoding in 100 Lines of Python
Prashant Anand
PyCon Mini Tokyo 2026
anandprashant.com/talks
Write a Python function is_palindrome(s) with a docstring and three doctests.
Qwen3-4B
Qwen3-4B with a small helper model
2.5× faster
[placeholder trace]
The two outputs are identical
Qwen3-4B
Qwen3-4B with a small helper model
def is_palindrome(s):=def is_palindrome(s): """Return True if s reads the same forwards and backwards.= """Return True if s reads the same forwards and backwards. = Case and non-alphanumeric characters are ignored.= Case and non-alphanumeric characters are ignored. = >>> is_palindrome("A man, a plan, a canal: Panama")= >>> is_palindrome("A man, a plan, a canal: Panama") True= True >>> is_palindrome("hello")= >>> is_palindrome("hello") False= False >>> is_palindrome("")= >>> is_palindrome("") True= True """= """ cleaned = [c.lower() for c in s if c.isalnum()]= cleaned = [c.lower() for c in s if c.isalnum()] return cleaned == cleaned[::-1]= return cleaned == cleaned[::-1]0 of 14 lines compared, 0 differences
>>> left == right
TrueIdentical, token for token.
- 1Where does the speed come from?
- 2How is the output identical?
- 3Why is some text faster?
By the end of this talk
- You’ll know why LLMs are slow, and why that leaves room for this trick.
- You’ll know why the output can’t change.
- We’ll write it in about 100 lines of Python and run it live.

Prashant Anand
- Founder, Orthonormal Labs
- Author, Agentic Coding Weekly
- Previously ML Engineer at Mercari for 6 years
- Specialty coffee nerdspecialtycoffee.tokyo
Slides and code
anandprashant.com/talks
Models read and write tokens
LLMs write one token per pass
Every morning I
def generate(model, prompt, max_tokens, temperature=0.0, eos=None): """Plain autoregressive decoding: one full forward pass of the model per token.""" lm, tokens = LM(model, temperature), list(prompt) while len(tokens) - len(prompt) < max_tokens and tokens[-1] != eos: tokens.append(sample(lm.probs(tokens)[-1])) return finish(tokens[len(prompt):], max_tokens, eos)Every token reads all 8 GB of weights
- Qwen3-4B in bf16: about 8 GB of weights
- Each token reads all 8 GB from memory
- M5 memory bandwidth: about 153 GB/s
- 153 ÷ 8 ≈ 19 tokens/s at most
- Measured: 14 tokens/s
Checking 8 tokens costs about the same as 1
One pass predicts the next token at every position
One pass gives a prediction at every position.
logits = self.model(mx.array(tokens[self.seen():])[None], cache=self.cache)[0]# shape: (tokens fed in, vocabulary size), one next-token prediction per positionQuestions
Where does the speed come from?
Partly. Each pass reads the whole model, so checking 8 tokens costs about the same as writing 1.
How is the output identical?
Why is some text faster?
So far
- LLMs write one token per pass, and each pass reads the whole model from memory.
- Feeding in 8 tokens costs about the same as 1, and gives a prediction at every position.
Some text is easy to guess
I can’t start my day without a cup of ______
My favorite specialty coffee shop in Tokyo is ______
[photo of the shop]
A big model and a small one
Big model: Qwen3-4B
8 GB (bf16), about 69 ms per pass
The one whose answer we want.
Also called the target model.
Small model: Qwen3-0.6B
0.4 GB (4-bit), about 5 ms per pass
A fast guesser.
Also called the draft model.
Same family, same tokenizer. That’s the one hard requirement.
Step 1: the small model guesses k tokens
Every morning I brew a
0 small passes
Like autocomplete in your editor: nothing is committed yet.
Step 2: the big model checks every guess in one pass
1 big pass, a prediction for every guess
Step 3: keep guesses up to the first mismatch
1 big pass → 4 tokens
- small model’s guess, kept
- rejected guess
- big model’s own token
From the opening race
def is_palindrome(:s) ": """Return True if the s same reads the same forwards and backwards.
If every guess is kept, we get one more token
1 big pass → 5 tokens
The big model decides every token
- Every kept token is exactly what the big model would have picked.
- Every replaced token is the big model’s own pick.
- So the output is the big model’s output.
The small model decides how fast, never what.
Questions
Where does the speed come from?
Each pass reads the whole model, so checking k guesses costs about one pass.
How is the output identical?
Partly. With greedy decoding, the big model decides every token.
Why is some text faster?
So far
- LLMs write one token per pass, and each pass reads the whole model from memory.
- Feeding in 8 tokens costs about the same as 1, and gives a prediction at every position.
- The small model guesses k tokens. The big model checks them in one pass. Keep the matching ones, plus one token from the big model.
- The big model decides every token. The small model only decides the speed.
The whole thing is 64 lines of code
120 lines, 64 of them code. Two libraries: mlx and mlx-lm.
A model with a memory you can rewind
class LM: """A language model plus its KV cache (its memory of tokens already read).""" def __init__(self, model, temperature: float): self.model = model self.temperature = temperature self.cache = make_prompt_cache(model) def seen(self) -> int: """How many tokens are in the cache.""" return self.cache[0].offset def probs(self, tokens: list[int]) -> mx.array: """Read the tokens not seen yet; return one next-token distribution per token read.""" logits = self.model(mx.array(tokens[self.seen() :])[None], cache=self.cache)[0] return to_probs(logits, self.temperature) def rewind(self, n: int) -> None: """Forget everything after the first n tokens (used to drop rejected guesses).""" if self.seen() > n: trim_prompt_cache(self.cache, self.seen() - n)A model with a memory you can rewind
In greedy mode, the top token gets probability 1
def to_probs(logits: mx.array, temperature: float) -> mx.array: """Turn logits into next-token probabilities. Temperature 0 means greedy.""" if temperature == 0: best = mx.argmax(logits, axis=-1, keepdims=True) return (mx.arange(logits.shape[-1]) == best).astype(mx.float32) # one-hot return mx.softmax(logits.astype(mx.float32) / temperature, axis=-1)def sample(probs: mx.array) -> int: """Draw one token id from a probability distribution.""" return mx.random.categorical(mx.log(probs)).item()The loop: guess, check, keep, rewind
def speculative_generate(target_model, draft_model, prompt, max_tokens, k=4, temperature=0.0, eos=None): target, draft = LM(target_model, temperature), LM(draft_model, temperature) tokens, accepted = list(prompt), [] while len(tokens) - len(prompt) < max_tokens and eos not in tokens[len(prompt):]: # 1. Draft: the small model guesses k tokens, one at a time. guesses, q = [], [] for _ in range(k): q.append(draft.probs(tokens + guesses)[-1]) guesses.append(sample(q[-1])) # 2. Check: the big model scores every guess in ONE forward pass. p = target.probs(tokens + guesses)[-(k + 1):] # 3. Keep the guesses it agrees with, plus one token of its own. new_tokens = verify(guesses, mx.stack(q), p) tokens += new_tokens accepted.append(len(new_tokens) - 1) # 4. Both models forget the rejected guesses. target.rewind(len(tokens) - 1) draft.rewind(len(tokens) - 1) return finish(tokens[len(prompt):], max_tokens, eos), acceptedThe loop: guess, check, keep, rewind
- 1. Draft
- 2. Check
- 3. Keep
- 4. Rewind
Same loop, more tokens per pass
generate: one pass, one token
while len(tokens) - len(prompt) < max_tokens and tokens[-1] != eos: tokens.append(sample(lm.probs(tokens)[-1]))speculative_generate: one pass, up to k + 1 tokens
while len(tokens) - len(prompt) < max_tokens and eos not in tokens[len(prompt):]: # 1. Draft: the small model guesses k tokens, one at a time. guesses, q = [], [] for _ in range(k): q.append(draft.probs(tokens + guesses)[-1]) guesses.append(sample(q[-1])) # 2. Check: the big model scores every guess in ONE forward pass. p = target.probs(tokens + guesses)[-(k + 1):] # 3. Keep the guesses it agrees with, plus one token of its own. new_tokens = verify(guesses, mx.stack(q), p) tokens += new_tokens accepted.append(len(new_tokens) - 1) # 4. Both models forget the rejected guesses. target.rewind(len(tokens) - 1) draft.rewind(len(tokens) - 1)verify keeps or rejects each guess
def verify(guesses: list[int], q: mx.array, p: mx.array) -> list[int]: kept = [] for i, guess in enumerate(guesses): # Accept with probability min(1, p/q) if mx.random.uniform().item() < (p[i, guess] / q[i, guess]).item(): kept.append(guess) else: # Rejected: resample from the probability mass the draft under-predicted. residual = mx.maximum(p[i] - q[i], 0) return kept + [sample(residual / residual.sum())] return kept + [sample(p[-1])] # All guesses accepted: a bonus token for free.Guess matches
p/q = 1/1: always keep
Guess differs
p/q = 0/1: always reject
Rejected
only the pick is left
All kept
p[-1]: the extra token
Running it on this laptop
uv run bench.py --target mlx-community/Qwen3-4B-bf16 \ --draft mlx-community/Qwen3-0.6B-4bit --k 4Expected
prompt k tokens base tok/s spec tok/s speedup accepted tok/round same? counting 4 ... 14.3 ... ...x ... ... True code 4 ... 14.2 36.0 2.53x 53% 3.12 True explain 4 ... 14.8 29.8 2.02x 43% 2.74 True story 4 ... 14.5 ... ...x ... ... True
Questions
Where does the speed come from?
Each pass reads the whole model, so checking k guesses costs about one pass.
How is the output identical?
Partly. With greedy decoding, the big model decides every token. Seen live: same text.
Why is some text faster?
So far
- LLMs write one token per pass, and each pass reads the whole model from memory.
- Feeding in 8 tokens costs about the same as 1, and gives a prediction at every position.
- The small model guesses k tokens. The big model checks them in one pass. Keep the matching ones, plus one token from the big model.
- The big model decides every token. The small model only decides the speed.
- It fits in about 64 lines of Python: LM with rewind, the four-step loop, and verify.
- Live: same text, about 2.5× faster.
Chat models sample from probabilities
Next token after “Every morning I brew a cup of coffee with a”, temperature 0.7
- run 1
…with a V60 - run 2
…with a Chemex - run 3
…with a AeroPress
The two models disagree about the odds
- p, big model
- q, small model
Accept a guess with probability min(1, p/q)
min(1, p / q)
if mx.random.uniform().item() < (p[i, guess] / q[i, guess]).item():p/q = 0.50 / 0.30, more than 1.
Always accept.
p/q = 0.10 / 0.40 = 0.25.
Accept 1 time in 4.
On rejection, sample from the leftover
Rejected? Sample from max(p − q, 0): where the big model wanted more than the small model gave.
residual = mx.maximum(p[i] - q[i], 0)- p, big model
- q, small model
- leftover, 0.30 in total
Kept plus leftover equals the big model’s odds
- p, big model
- kept guesses, 0.70 in total: how often a guess is accepted
- leftover, 0.30 in total: how often it’s rejected
Not an approximation. Any small model gives exactly the big model’s odds.
verify already does all of this
def verify(guesses: list[int], q: mx.array, p: mx.array) -> list[int]: kept = [] for i, guess in enumerate(guesses): # Accept with probability min(1, p/q) if mx.random.uniform().item() < (p[i, guess] / q[i, guess]).item(): kept.append(guess) else: # Rejected: resample from the probability mass the draft under-predicted. residual = mx.maximum(p[i] - q[i], 0) return kept + [sample(residual / residual.sum())] return kept + [sample(p[-1])] # All guesses accepted: a bonus token for free.min(1, p/q)
leftover
extra token
Greedy: every bar is 0 or 1
- p, big model
- q, small model
Exact in math, nearly exact in floating point
- “allows” 19.125, “index” 19.0: one bf16 rounding step apart.
- Scoring 5 tokens at once uses different GPU kernels than scoring 1, so a near-tie can flip.
- Still a valid output of the big model, just not always the identical sequence.
Logits for the next token. Axis starts at 18.5.
Questions
Where does the speed come from?
Each pass reads the whole model, so checking k guesses costs about one pass.
How is the output identical?
Accept with min(1, p/q), fill rejections from the leftover. The result has exactly the big model’s odds.
Why is some text faster?
So far
- LLMs write one token per pass, and each pass reads the whole model from memory.
- Feeding in 8 tokens costs about the same as 1, and gives a prediction at every position.
- The small model guesses k tokens. The big model checks them in one pass. Keep the matching ones, plus one token from the big model.
- The big model decides every token. The small model only decides the speed.
- It fits in about 64 lines of Python: LM with rewind, the four-step loop, and verify.
- Live: same text, about 2.5× faster.
- With sampling, accept with min(1, p/q). On rejection, sample from max(p − q, 0).
- Kept plus leftover equals the big model’s odds, for any small model.
Predictable text gets more guesses accepted
Counting
Count from 1 to 60
4.18×
97% accepted, 6.84 per pass
Python code
is_palindrome with doctests
2.53×
53% accepted, 3.12 per pass
Explanation
Explain a hash table
2.02×
43% accepted, 2.74 per pass
Surreal story
A lighthouse keeper who collects sounds
1.57×
41% accepted, 1.80 per pass
1×
Greedy, 200 tokens, best k. With sampling (temperature 0.7, k = 4): 3.12×, 1.97×, 1.66×, 1.29×.
Code is mostly guessed, stories mostly aren’t
Code: 88% guessed
def is_palindrome(s): """Return True if s reads the same forwards and backwards. >>> is_palindrome("racecar") True >>> is_palindrome("hello") False """ cleaned = [c.lower() for c in s if c.isalnum()] return cleaned == cleaned[::-1]
Story: 32% guessed
The lighthouse keeper kept every sound in glass jars: the hush of fog, a gull's complaint, the creak of the stairs at midnight. On stormy nights he opened one and let it fill the lamp room.
Qwen3-4B
Qwen3-4B with a small helper model
2.5× faster
More guesses can make it slower
Qwen3-8B-4bit as the big model, greedy
Story, k = 2: 1.34× faster
Story, k = 6: 0.53×, slower than not using it at all
On hard text most long guesses get thrown away, and you still pay for the small model and the bigger check.
Small k (2–4) for hard text, larger k (4–8) for predictable text.
[placeholder data]
It’s built into tools you already use
- llama.cpp
llama-server -m big.gguf -md small.gguf--spec-draft-n-max sets k
- MLX-LM
mlx_lm.generate --model … --draft-model … --num-draft-tokens 3- LM Studio
The “Speculative Decoding” setting, then pick a draft model
- vLLM, SGLang
--speculative-config …draft model, n-gram, EAGLE, MTP
- Gemma 4
An official small draft model for every size, “up to 3× faster”
Invented at Google (Leviathan, Kalman, Matias, 2022) and DeepMind (Chen et al., 2023). Google says it speeds up AI Overviews in Search.
Guess with a small model. Check with the big one.
Where does the speed come from?
LLMs are limited by memory reads, so checking k guesses costs about one pass.
How is the output identical?
The big model approves every token. Accept with min(1, p/q) and fill rejections from the leftover, which gives exactly the big model’s odds.
Why is some text faster?
Predictable text, like code and lists, gets more guesses accepted.
Try it: a small model from the same family, k around 3–4, measured on your own text.
[QR code to LinkedIn]
Slides and code
anandprashant.com/talks
Prashant Anand
Orthonormal Labs
Agentic Coding Weekly
How many tokens per pass?
(1 − αᵏ⁺¹) / (1 − α)
- Expected tokens per big pass, where α is the acceptance rate.
- The ceiling is 1 / (1 − α).
- Checked with sampling, gpt2 guessing for gpt2-large: measured 2.90, formula 2.83.
[figure: 03_expected_tokens_vs_gamma.png]
When is it worth it?
speed-up = tokens per pass ÷ (k·c + 1)
- c is the small model’s cost per pass, relative to the big model’s.
- Some k helps if and only if α > c.
- For our pair, c ≈ 4.7 / 69 ≈ 0.07.
[figure: 03_speedup_vs_gamma_c.png]
Why it’s exact, in two lines of algebra
P(x) = min(p(x), q(x)) + (1 − α)·r(x) = p(x)
- r is the normalized leftover, and α = Σ min(p, q).
- Leviathan et al., appendix A.1.
[figure: 01_accept_reject_geometry.png]
The wrong versions drift away from p
- Distance from p (total variation), correct rule: 0.0011, noise level.
- On rejection, sample from p again: 0.124.
- Accept with probability p(x): 0.378.
- Always accept: 0.25, the same as sampling the small model.
[figure: 01_exactness_montecarlo.png]
The cheap check depends on hardware
- Time per pass, 1 → 16 tokens fed in:
- Qwen3-0.6B bf16: 13.0 → 16.4 ms
- Qwen3-4B bf16: 69.3 → 83.7 ms
- Qwen3-0.6B 4-bit: 4.7 → 12.0 ms
- Qwen3-8B 4-bit: 37.7 → 120.4 ms
- 4-bit kernels on MLX don’t stay flat: use a bf16 big model or a small k.
At large batch sizes the gain shrinks
- At batch size 1, compute sits idle, so it’s a big win.
- At large batch sizes compute is already busy. vLLM has reported slowdowns under high load.
- It trades extra compute for lower latency. It doesn’t save compute.
Other ways to guess
- Medusa heads: extra heads on the big model guess ahead.
- EAGLE 1–3: a small head that reads the big model’s features.
- MTP heads: Gemma 4 draft models, DeepSeek.
- n-gram or prompt lookup: copies from the prompt, good for code edits.
- SpecInfer: checks a tree of guesses at once.
What rewind hides
- Rolling back the KV cache after a rejection.
- Sliding-window caches can’t always be trimmed.
- Sanity check: use the big model as its own small model. Acceptance should be exactly 1.0, which catches off-by-one bugs.