Sub topic 18
Speculative decoding for lower latency
This chapter assumes you have read the chapters on prefill and decode, the KV cache, continuous batching, and vllm serve. You should also be comfortable with the Python LLM class and with reading /metrics output.
Why decode is slow for one user
Decode produces one token per forward pass. Each pass reads all of the model's weights from GPU memory, and it does very little arithmetic per byte read. At small batch sizes the GPU is waiting on memory bandwidth, not on compute. A single request therefore leaves most of the GPU's arithmetic capacity idle.
Speculative decoding uses that idle capacity. A cheap mechanism guesses the next several tokens. The full model, called the target model, then checks all the guesses in one forward pass. Checking k guessed tokens costs about the same as generating one token, because the pass is memory-bound either way. Every guess the target accepts is a token you did not have to pay a full pass for.
The output distribution does not change. vLLM uses rejection sampling to accept or reject each guess, so the final text comes from the same distribution the target model would have produced alone. The method trades spare compute for lower latency and does not trade away quality.
The propose, verify, accept loop
- The proposer drafts k tokens, for example k = 5.
- The target model runs once over the current context plus the k drafted tokens. It computes its own probability for every position.
- Starting at the first drafted token, vLLM accepts each token that agrees with the target (under sampling, via rejection sampling) and stops at the first rejection.
- At the rejection point, the target's own token is used instead. If all k drafts are accepted, the target also yields one bonus token.
- The loop repeats from the new end of the sequence.
Each step therefore emits between 1 and k + 1 tokens. The worst case is one token per step, the same as normal decoding, plus the wasted cost of the draft.
How much speedup to expect
The key quantity is the acceptance rate α, the probability that a drafted token is accepted. If acceptances were independent with rate α, the expected number of tokens per target pass with k drafts would be (1 − α^(k+1)) / (1 − α).
| Acceptance rate α | Expected tokens per target pass (k = 5) |
|---|---|
| 0.5 | 1.97 |
| 0.7 | 2.94 |
| 0.8 | 3.69 |
Real acceptances are correlated, so treat these numbers as a rough guide. They are also an upper bound on speedup, because the proposer itself costs time. A draft model that takes 20% of a target pass per token spends k × 0.2 = 1.0 target-pass equivalents drafting five tokens. That erases much of the gain at α = 0.5. A good proposer is both accurate and much cheaper than the target.
Proposer options in vLLM
| Method | How it guesses | Strengths | Weaknesses |
|---|---|---|---|
| N-gram (prompt lookup) | Finds the most recent match of the last few tokens earlier in the prompt or output and copies what followed | No extra model, no extra memory | Only helps when output repeats the input |
| Draft model | A small model from the same family and tokenizer | General purpose | Uses GPU memory and compute, needs a matching tokenizer |
| Head-based (EAGLE, Medusa, MTP) | Small extra heads that reuse the target's hidden states | High acceptance rates | Needs trained heads for your specific target model |
Support for each method differs between vLLM versions, so check the release docs for yours. The configuration key has also changed over time. Current versions take a single speculative_config object. Older versions used flags such as speculative_model and num_speculative_tokens, so match the syntax to your installed version.
Example: n-gram speculation offline
N-gram speculation is the easiest to try because it needs nothing beyond the target model. This task suits it well: the model must repeat a passage with small edits.
from vllm import LLM, SamplingParams
def main():
llm = LLM(
model="Qwen/Qwen2.5-1.5B-Instruct",
max_model_len=4096,
gpu_memory_utilization=0.85,
speculative_config={
"method": "ngram",
"num_speculative_tokens": 5,
"prompt_lookup_max": 4,
},
)
document = (
"The scheduler admits waiting requests whenever enough KV cache "
"blocks are free. The scheduler preempts requests when blocks run out."
)
messages = [
{
"role": "user",
"content": "Repeat this text exactly, then add one sentence:\n" + document,
}
]
params = SamplingParams(temperature=0.0, max_tokens=128)
outputs = llm.chat(messages, params)
print(outputs[0].outputs[0].text)
if __name__ == "__main__":
main()Here prompt_lookup_max is the longest token sequence the proposer tries to match against earlier text. Copy-heavy tasks like this one give high acceptance. Free-form writing gives few matches, so n-gram speculation adds overhead and little benefit.
Example: a draft model on the server
For a larger target, pair it with a small model that shares its tokenizer. The Qwen2.5 family uses one tokenizer across sizes, so the 0.5B model can draft for the 32B model.
vllm serve Qwen/Qwen2.5-32B-Instruct \
--tensor-parallel-size 4 \
--max-model-len 8192 \
--speculative-config '{"model": "Qwen/Qwen2.5-0.5B-Instruct", "num_speculative_tokens": 5}'The draft model occupies GPU memory, so it shrinks the KV cache budget. If you tuned gpu_memory_utilization tightly, re-check the number of cache blocks in the startup log after adding a draft model.
When speculation helps and when it hurts
Speculation helps most when a request is latency-sensitive and the GPU is lightly loaded. Interactive chat with few concurrent users is the classic case. It also helps on predictable output, such as code edits, summaries that quote the source, and structured JSON.
It helps less, and can hurt, in these situations:
- High concurrency. Continuous batching already fills the memory-bound gap by adding more sequences to each pass. Once the batch is large, the pass is compute-bound. Verifying rejected draft tokens then wastes real compute and lowers throughput.
- Low acceptance. High-temperature creative output diverges from any cheap guess. Every rejected draft is wasted work.
- Tight memory. A draft model or extra heads take space from the KV cache, which reduces how many sequences fit.
Speculation is mainly a latency tool. If your goal is total tokens per second across many clients, benchmark with and without it before you commit.
Monitoring acceptance
The acceptance rate tells you whether the proposer is paying for itself. A speculative run exposes counters for drafted and accepted tokens on the same /metrics endpoint you used before. Metric names vary by version, so search for them instead of guessing:
curl -s http://localhost:8000/metrics | grep 'spec_decode'Divide the accepted-token counter by the drafted-token counter to get α. If α stays below roughly 0.5 on your real traffic, reduce num_speculative_tokens or switch proposers. Fewer drafted tokens per step means less wasted work when the guesses are poor.
Tuning checklist
- Establish a baseline: latency and throughput without speculation.
- Start with
num_speculative_tokensbetween 3 and 5. Higher values pay off only when α is high. - Test on traffic that looks like production, not on synthetic prompts that happen to repeat.
- Check the acceptance rate in the metrics.
- Re-measure at your peak concurrency and confirm throughput did not regress.
- Confirm the KV cache still has enough blocks for your
max_model_lenandmax_num_seqs.
Exercise
A service runs with k = 5 speculative tokens and measures an acceptance rate α = 0.7. Using the formula (1 − α^(k+1)) / (1 − α), how many tokens does each target pass produce on average? The draft proposer costs 0.5 of a target pass in total per step. Is a net speedup plausible? Then explain why the same setting might lower throughput under heavy load.
Show answer
The expected tokens per pass is (1 − 0.7^6) / 0.3 = (1 − 0.1176) / 0.3 ≈ 2.94. Each step costs about 1 target pass plus 0.5 for drafting, which is 1.5 pass-equivalents. That yields 2.94 / 1.5 ≈ 1.96 tokens per pass-equivalent versus 1.0 without speculation, so a net speedup of about 2x is plausible. Under heavy load, continuous batching already makes each pass compute-bound, so verifying draft tokens that get rejected consumes compute that other requests could have used. Throughput can then fall even though per-request latency at low load improved.