Autoregressive decoding normally asks the target model for one token at a time. This is inefficient when each step reads a large set of weights but performs little parallel work. Speculative decoding uses a cheaper process to propose several tokens, then asks the target model to verify them together. Verification is the essential step. Greedy speculative decoding returns the same tokens as ordinary greedy decoding. Sampling-based speculative decoding uses an acceptance and correction rule that preserves the target model’s output distribution. A draft token is never accepted merely because the draft model prefers it. In this post, you will learn about: How a draft model proposes tokens for target-model verification How sampling-based speculation preserves the target distribution How acceptance rate and verification cost determine speedup Let’s get started. Overview This post is divided into six parts; they are: Draft and Verify Sampling-Based Speculative Decoding Assisted Generation with a Draft Model Measuring Acceptance and Speedup Other Ways to Draft Tokens When Speculation Helps Draft and Verify Speculative decoding involves two models: a draft model (usually a smaller model that is faster to run) and a target model (usually a larger model that is more accurate). The draft model proposes tokens, and the target model verifies them. Let the draft model propose $n$ tokens. The target model evaluates the prompt followed by those candidates in one forward pass. Because causal attention produces a prediction at every candidate position, this pass checks several next-token decisions in parallel. For greedy decoding, verification proceeds from left to right: The draft proposes $n$ tokens. The target computes its preferred token at each candidate position. Matching candidates are accepted up to the first mismatch. At the first mismatch, the target token is emitted instead. Unverified draft state after the mismatch is discarded. Suppose the draft proposes “the cat sat down”, while the target would choose “the cat slept still”. The first two draft tokens are accepted, “sat” is rejected, and “slept” is emitted. The remaining draft token, “down”, and the target prediction “still” are discarded because both were conditioned on a rejected history. The target still performs work over the candidate positions. The benefit comes from verifying them as a short sequence rather than launching one target-model decode step for each token. The draft model must be much cheaper than the target, and enough candidates must be accepted to offset its cost. Both models need KV caches. The draft cache advances while candidates are proposed. When the target rejects a candidate, the runtime rolls back or ignores the draft state for the rejected suffix. This cache bookkeeping is part of the implementation cost. Sampling-Based Speculative Decoding The previous section described greedy speculative decoding. Sampling-based speculative decoding is a different algorithm because there is no single target token to match at each position. Its verifier must preserve the target model’s probability distribution rather than reproduce one greedy sequence. Greedy verification can compare each candidate with the target argmax. The sampling-based algorithm cannot rely on this simple match; it instead uses acceptance and correction probabilities. Let $p(x)$ be the target probability and $q(x)$ the draft probability for candidate token $x$. A candidate sampled from $q$ is accepted with probability $\min(1, p(x)/q(x))$. If the candidate is rejected, the replacement token is sampled from a corrected distribution proportional to $\max(0, p(x)-q(x))$. This correction matters. Accepting candidates based only on agreement or a confidence threshold would generally change the target distribution. A correct sampling implementation also uses the same temperature and filtering semantics when it constructs the target and draft distributions. For greedy decoding, lossless means the token sequence is unchanged. For sampling, it means the probability distribution is unchanged; two independent runs can still produce different samples. Assisted Generation with a Draft Model The transformers library exposes speculative decoding as assisted generation. The following example compares ordinary greedy generation with a smaller assistant model. Both checkpoints use the same tokenizer family. 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 import timeimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizertarget_name = "HuggingFaceTB/SmolLM-1.7B"assistant_name = "HuggingFaceTB/SmolLM-135M"device = "cuda" if torch.cuda.is_available() else "cpu"dtype = torch.float16 if device == "cuda" else torch.float32tokenizer = AutoTokenizer.from_pretrained(target_name)target = AutoModelForCausalLM.from_pretrained(target_name, dtype=dtype).to(device)assistant = AutoModelForCausalLM.from_pretrained(assistant_name, dtype=dtype).to(device)target.eval()assistant.eval()inputs = tokenizer( "Efficient language model inference requires", return_tensors="pt",).to(device)def synchronize(): if device == "cuda": torch.cuda.synchronize()@torch.inference_mode()def timed_generate(**kwargs): synchronize() start = time.perf_counter() output = target.generate( **inputs, max_new_tokens=64, do_sample=False, **kwargs, ) synchronize() return output, time.perf_counter() - start# Warm up both paths before measuring them.timed_generate()timed_generate(assistant_model=assistant)baseline_ids, baseline_seconds = timed_generate()assisted_ids, assisted_seconds = timed_generate(assistant_model=assistant)assert torch.equal(baseline_ids, assisted_ids)print(tokenizer.decode(assisted_ids[0], skip_special_tokens=True))print(f"ordinary greedy: {baseline_seconds:.3f} seconds")print(f"assisted greedy: {assisted_seconds:.3f} seconds") The equality check is appropriate because both calls use greedy decoding. For sampling, compare the output distribution or task quality across many requests rather than requiring token-for-token equality. The smaller model still consumes memory and execution time. The current transformers implementation of assisted generation is most useful for single-request latency experiments; check the documentation before assuming that it supports a particular batching mode. A production engine may implement different proposers and batching rules. Measuring Acceptance and Speedup Acceptance rate is the fraction of proposed draft tokens accepted by the target: $$ r = \frac{N_{\text{accepted}}}{N_{\text{drafted}}} $$ Also measure the number of accepted tokens per target verification pass. This quantity connects acceptance to the expensive operation that speculation is intended to reduce. Depending on the algorithm, a pass may emit accepted draft tokens plus one token selected by the target. def speculation_metrics(drafted, accepted, target_passes, wall_seconds): assert drafted >= 0 assert 0 0 assert wall_seconds > 0 return { "acceptance_rate": accepted / max(1, drafted), "accepted_per_target_pass": accepted / target_passes, "drafted_tokens_per_wall_second": drafted / wall_seconds, }print(speculation_metrics( drafted=100, accepted=75, target_passes=25, wall_seconds=2.0)) Acceptance rate alone does not determine speedup. You should also measure: Draft model runtime Target model verification time Candidate construction and rejection overhead Tokens emitted per target pass Time to first token and time per output token Peak memory for both models and caches Throughput at the intended batch size A larger speculation length $\gamma$ offers more possible accepted tokens, but it also requires more drafting work and asks the target to verify a longer sequence. If acceptance falls with position, the last candidates are often wasted. Dynamic lookahead can stop drafting early when the proposer is uncertain. For planning, assume each draft token has the same independent acceptance probability $a$. A verification pass emits an expected $\sum_{i=0}^{\gamma}a^i$ tokens when the implementation also emits the target’s correction or bonus token. This simple model ignores position-dependent acceptance, cache overhead, and batch effects: def estimated_speedup(lookahead, acceptance, draft_step_ms, verify_ms, target_step_ms): assert lookahead >= 1 assert 0 <= acceptance <= 1 expected_emitted = sum(acceptance**i for i in range(lookahead + 1)) speculative_ms = lookahead * draft_step_ms + verify_ms ordinary_ms = expected_emitted * target_step_ms return expected_emitted, ordinary_ms / speculative_msfor lookahead in (2, 4, 8): emitted, speedup = estimated_speedup( lookahead, acceptance=0.75, draft_step_ms=0.3, verify_ms=2.0, target_step_ms=1.5, ) print(lookahead, round(emitted, 2), round(speedup, 2)) You should replace these illustrative timings with measurements from your hardware. You can compare observed tokens emitted per verification pass with this estimate before trusting the projected speedup. You should compare speculative decoding with a baseline that uses the same target model, prompts, decoding settings, and workload. Speculation that improves one-request latency may reduce server throughput if the draft model consumes memory needed for a larger target batch. Other Ways to Draft Tokens A separate autoregressive draft model is only one source of candidates. Current inference libraries also support other proposers, but their applicability varies. N-gram or prompt lookup: Reuse token sequences that already appear in the prompt or recent output. vLLM and transformers support this lightweight method. It is most useful when the answer copies from its input, such as in summarization or translation. EAGLE-style drafting: Predict future target-model features with a lightweight draft module, then turn those features into token candidates. vLLM and TensorRT-LLM support EAGLE, but it requires a compatible draft checkpoint. Medusa-style heads: Add several trained prediction heads to a model so it can propose a tree of future tokens. Optimized runtimes support Medusa, but the need for a modified checkpoint makes it more specialized than prompt lookup or a general draft model. Self-speculation: Use intermediate layers or an early-exit head to draft before the remaining layers verify the candidates. The transformers library supports this method for models trained with suitable early-exit logits, so it is limited to compatible checkpoints. These methods trade draft quality, extra memory, training cost, and implementation complexity. N-gram proposals are cheap but workload-dependent. A separate draft model is easy to understand but duplicates weights and caches. Trained heads or feature predictors can share more target state but require compatible checkpoints and runtime kernels. The verifier, not the proposer, preserves correctness. A faster proposer is useful only if the runtime can verify its candidate structure efficiently. When Speculation Helps Speculative decoding is most promising when ordinary decode is memory-bandwidth bound, the target is much more expensive than the proposer, and candidate acceptance is high. It often improves latency at low to medium batch sizes more than throughput at a saturated, high batch size. It can hurt when: The draft model is too large or runs on an inefficient kernel. The target and draft disagree frequently. Outputs are so short that setup and warmup dominate. A large batch already uses the target hardware efficiently. The extra draft weights reduce KV cache capacity or maximum batch size. Tokenizer conversion, candidate trees, or cache rollback add too much overhead. Sampling settings influence agreement. Higher temperature and aggressive filtering can lower candidate acceptance, depending on the models and verification implementation. Tokenizer compatibility also matters. Some runtimes support conversion between different tokenizers, but it adds alignment work and should be measured rather than assumed free. Further Reading Below are some resources you may find useful: Yaniv Leviathan, Matan Kalman, Yossi Matias (2022). Fast Inference from Transformers via Speculative Decoding. This paper derives speculative sampling that preserves the target distribution. Charlie Chen et al. (2023). Accelerating Large Language Model Decoding with Speculative Sampling. This paper presents a closely related draft-and-verify method. Hugging Face Transformers documentation. Assisted decoding. This guide covers assistant models, prompt lookup, and self-speculative decoding. vLLM documentation. Speculative Decoding. This guide compares supported proposers, including draft models, EAGLE, and n-gram lookup. Tianle Cai et al. (2024). Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads. This paper uses multiple heads and tree attention to propose future tokens. Yuhui Li et al. (2024). EAGLE: Speculative Sampling Requires Rethinking Feature Uncertainty. This paper drafts using predicted target-model features. Summary In this post, you learned how speculative decoding replaces several sequential target decode steps with cheap drafting and parallel target verification. Greedy verification preserves the exact target sequence, while sampling-based verification uses acceptance and correction probabilities to preserve the target distribution. Speedup depends on more than acceptance rate. Draft cost, verification kernels, cache bookkeeping, batch size, output length, and memory capacity all matter. No comments yet.
Speculative Decoding
Full Article
Original Source
Read the full article at Machinelearningmastery →KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.