Example

Reject every draft token and still match the target

Trace a speculative round where the draft is wrong, count the rejected proposals, and verify that greedy output is unchanged.

Speculative decoding spends extra compute on a cheap draft model to reduce the number of target-model passes. The draft proposes several tokens; the target checks them. The correctness claim is not that the draft is good. It is that the final output matches what the target alone would have produced under the same decoding rule.

This example runs two cases. In the agreed case, draft and target choose the same next token, and five proposals are accepted. In the mismatched case, the draft proposes a token the target rejects every time: accepted: 0, rejected: 6. The generated tokens still equal the baseline. Rejection costs work; it does not change the greedy answer. That separation is the mechanism worth learning.

Run it

From the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch17/speculative.py --json

Python 3.11 or later, standard library only. No model, network, GPU or credentials. It finishes immediately.

Implementation

The draft proposes up to k tokens. The target verifies each proposed token against the target’s own greedy choice for that prefix. On a mismatch it appends the target’s token and stops the round; if all proposals are accepted, the target generates one more token.

def greedy_speculative(draft: LogitsFn, target: LogitsFn, prompt: int, k: int, max_tokens: int) -> SpecResult:
    if k < 1:
        raise ValueError("k must be positive")
    tokens = [prompt]
    proposed = 0
    accepted = 0
    rejected = 0
    while len(tokens) - 1 < max_tokens:
        # Draft proposes up to k tokens.
        draft_tokens = []
        cur = tokens[-1]
        for _ in range(k):
            logits = draft(cur)
            nxt = max(range(len(logits)), key=lambda i: (logits[i], -i))
            draft_tokens.append(nxt)
            cur = nxt
            proposed += 1
            if len(tokens) - 1 + len(draft_tokens) >= max_tokens:
                break
        # Target verifies.
        # Compute target logits for each prefix.
        accepted_this_round = 0
        for i, dt in enumerate(draft_tokens):
            t_logits = target(tokens[-1] if i == 0 else draft_tokens[i - 1])
            t_next = max(range(len(t_logits)), key=lambda j: (t_logits[j], -j))
            if t_next == dt:
                tokens.append(dt)
                accepted += 1
                accepted_this_round += 1
                if len(tokens) - 1 >= max_tokens:
                    break
            else:
                # Reject: use target's token.
                tokens.append(t_next)
                rejected += 1
                break
        else:
            # All proposed accepted; target generates one more.
            if len(tokens) - 1 < max_tokens:
                t_logits = target(tokens[-1])
                t_next = max(range(len(t_logits)), key=lambda j: (t_logits[j], -j))
                tokens.append(t_next)
    generated = tokens[1:]
    generated = generated[:max_tokens]
    return SpecResult(
        tokens=generated,
        proposed=proposed,
        accepted=accepted,
        rejected=rejected,
        metadata={"k": k, "max_tokens": max_tokens},
    )

Expected outcome

Observed with the command above (exit 0):

{
  "agreed_tokens": [
    1,
    2,
    3,
    4,
    0,
    1
  ],
  "baseline_tokens": [
    1,
    2,
    3,
    4,
    0,
    1
  ],
  "agreed_proposed": 5,
  "agreed_accepted": 5,
  "mismatched_tokens": [
    1,
    2,
    3,
    4,
    0,
    1
  ],
  "mismatched_accepted": 0,
  "mismatched_rejected": 6
}

The mismatched draft was wrong about every proposal, so none were accepted and six were rejected. The output is still the baseline sequence. The agreed case proposed five tokens, not six, because after all proposals in a round are accepted the target generates the next token directly; the run stops at max_tokens=6.

Mechanism and limitations

Documented: greedy_target is the trusted baseline. greedy_speculative counts proposals, acceptances and rejections, and falls back to the target’s token on a mismatch. The demo uses a vocabulary of five and a deterministic draft/target function. The tests check that accepted output equals the baseline, that a mismatched draft is rejected, that k must be positive, and that the result serialises.

Observed: the command exited 0 with the counts and tokens above. The targeted tests.test_ch17_speculative is part of the canonical suite; no independent test count is claimed here.

Not shown: a speedup, a real draft model, sampling acceptance, KV-cache rollback, or a production verification kernel. The repository also contains speculative_lab.py for the measured experiment; this page uses the small deterministic module. Greedy acceptance is easier to verify than stochastic acceptance and does not demonstrate the distributional proof required for sampling.

Challenge this result

Run the same fixture with k=1 and k=5. Predict how proposed, accepted and rejected change, and whether the generated tokens can change at all while the target stays fixed. Then make the target prefer a different token and confirm that both the baseline and the speculative output change together. Explain why a mismatch counter alone is not a quality metric: a draft can be wrong often and still save target passes if its proposals are cheap and occasionally accepted.

Source and verification

Canonical source: examples/ch17/speculative.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch17_speculative.py . Chapter: Speculative Decoding . The run above is a fresh local execution on Windows 11 with Python 3.13.15; it uses a toy draft and target, not a language model.

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.