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

0.0 tokens/s0.0 s

Qwen3-4B with a small helper model

0.0 tokens/s0.0 s

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
True

Identical, token for token.

  1. 1Where does the speed come from?
  2. 2How is the output identical?
  3. 3Why is some text faster?

By the end of this talk

Prashant Anand

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

Every[id]
morning[id]
I[id]
brew[id]
a[id]
cup[id]
of[id]
coffee[id]
with[id]
a[id]
V[id]
60[id]

LLMs write one token per pass

Every morning I

pass 1
big model
brewwakemake
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
Memory8 GB of weightsComputewaitingtoken 1

Checking 8 tokens costs about the same as 1

ms per pass02505007501000124816tokens in one passQwen3-4B bf16 on an Apple M5, 300-token context.if each token cost a full pass69.370.383.7

One pass predicts the next token at every position

morning
I
brew
a
cup
of
coffee
EverymorningIbrewacupof
big model

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 position

Questions

  1. Where does the speed come from?

    Partly. Each pass reads the whole model, so checking 8 tokens costs about the same as writing 1.

  2. How is the output identical?

  3. 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

small model

0 small passes

Like autocomplete in your editor: nothing is committed yet.

Step 2: the big model checks every guess in one pass

cupofcoffeewith…
EverymorningIbrewacupofcoffeein big model

1 big pass, a prediction for every guess

Step 3: keep guesses up to the first mismatch

cupofcoffeewith…
EverymorningIbrewacupofcoffeein big model

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

aV60andapaper
EverymorningIbrewacupofcoffeewithaV60anda big model

1 big pass → 5 tokens

The big model decides every token

Questions

  1. Where does the speed come from?

    Each pass reads the whole model, so checking k guesses costs about one pass.

  2. How is the output identical?

    Partly. With greedy decoding, the big model decides every token.

  3. 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

to_probs, finish, sample
helpers
LM
a model with a memory you can rewind
generate
the plain loop from slide 8
verify
keep or reject
speculative_generate
guess, check, keep, rewind

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

EverymorningIbrewa
read up to here
cupofcoffeein

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), accepted

The loop: guess, check, keep, rewind

  1. 1. Draft
  2. 2. Check
  3. 3. Keep
  4. 4. Rewind
cupofcoffeewithEverymorningIbrewaread up to herecupofcoffeein

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

cup
q
cup
p

p/q = 1/1: always keep

Guess differs

inwith
q
inwith
p

p/q = 0/1: always reject

Rejected

inwith
max(p − q, 0)

only the pick is left

All kept

paper
p

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 4

Expected

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

  1. Where does the speed come from?

    Each pass reads the whole model, so checking k guesses costs about one pass.

  2. How is the output identical?

    Partly. With greedy decoding, the big model decides every token. Seen live: same text.

  3. 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

0.50
V60
0.25
Chemex
0.15
AeroPress
0.10
machine
  1. run 1
    …with a V60
  2. run 2
    …with a Chemex
  3. run 3
    …with a AeroPress

The two models disagree about the odds

0.50
V60
0.25
Chemex
0.15
AeroPress
0.10
machine
  • 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():
0.50
0.30
V60

p/q = 0.50 / 0.30, more than 1.
Always accept.

0.10
0.40
machine

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)
V60
Chemex
AeroPress
machine
  • p, big model
  • q, small model
  • leftover, 0.30 in total

Kept plus leftover equals the big model’s odds

p = 0.50
V60
p = 0.25
Chemex
p = 0.15
AeroPress
p = 0.10
machine
  • 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

V60
Chemex
AeroPress
machine

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.
19.125
19.0
allowsindex

Logits for the next token. Axis starts at 18.5.

Questions

  1. Where does the speed come from?

    Each pass reads the whole model, so checking k guesses costs about one pass.

  2. 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.

  3. 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.

accepted guessbig model’s own token“guessed”: share of tokens that were accepted guesses[placeholder data]
accepted guessrejected guessbig model’s own token[placeholder trace]

Qwen3-4B

0.0 tokens/s0.0 s
0 big passes1 token per pass

Qwen3-4B with a small helper model

0.0 tokens/s0.0 s
0 big passes

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.

slower1×2×3×4×123468k, guesses per roundCounting, best k = 6Python code, best k = 4Explanation, best k = 4Surreal story, best k = 2

[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 − α)

[figure: 03_expected_tokens_vs_gamma.png]

When is it worth it?

speed-up = tokens per pass ÷ (k·c + 1)

[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)

[figure: 01_accept_reject_geometry.png]

The wrong versions drift away from p

[figure: 01_exactness_montecarlo.png]

The cheap check depends on hardware

At large batch sizes the gain shrinks

Other ways to guess

What rewind hides