Greedy Speculative Decoding and Latency Benchmark
Medium · Machine Learning · Research Scientist · Technical Screen
Problem Statement
Generating tokens one by one with a large language model is typically bottlenecked by reading model weights from accelerator memory rather than by arithmetic compute. Speculative decoding speeds up single-sequence generation without altering outputs: a lightweight draft model proposes up to gamma lookahead tokens sequentially, and the target model checks all proposed tokens in a single parallel forward call.
Both target_model and draft_model expose the same incremental key-value (KV) cache interface:
logits, past = model.forward(input_ids, use_cache=True, past_key_values=past)accepts the list of token IDs not yet stored inpast(past=Nonestarts an empty cache). Entrylogits[j]contains vocabulary scores predicting the token immediately afterinput_ids[j], andpastreturns the updated cache includinginput_ids. When picking a greedyargmaxtoken from a score row, break ties in favor of the smallest vocabulary index.past = model.truncate_cache(past, valid_length)trimspastso only the firstvalid_lengthcached token positions remain and returns the trimmed cache.
Implement three functions:
from typing import Any, Dict, List, Tuple
def autoregressive_decode(
model,
input_ids: List[int],
max_new_tokens: int,
eos_token_id: int,
) -> List[int]: ...
def speculative_decode(
target_model,
draft_model,
input_ids: List[int],
max_new_tokens: int,
gamma: int,
eos_token_id: int,
) -> Tuple[List[int], float]: ...
def benchmark_decoding(
target_model,
draft_model,
prompts: List[List[int]],
max_new_tokens: int,
gamma: int,
eos_token_id: int,
warmup_runs: int = 2,
num_runs: int = 5,
) -> Dict[str, Any]: ...
Decoding & Verification Rules
autoregressive_decode: Prefillinput_idsonce, then greedily append oneargmaxtoken per step using the KV cache untileos_token_idis generated (keepeos_token_idin the returned list) ormax_new_tokensnew tokens have been produced. Return only the newly generated tokens (excludinginput_ids).speculative_decode: Repeat speculative rounds untileos_token_idis committed ormax_new_tokenstokens are generated:- Have
draft_modelgreedily proposeKcandidate tokens (1 <= K <= min(gamma, remaining_budget)), stopping early ifdraft_modelpredictseos_token_id. - Run one
target_model.forwardpass over any uncached committed prefix tokens followed by theKdraft tokens. - Accept the longest leading prefix
drafts[:num_accepted]where each draft token equalstarget_model's greedyargmaxat that position. - Unless an accepted draft already equals
eos_token_idormax_new_tokenshas already been reached, also appendtarget_model'sargmaxat positionnum_accepted(acting as the ground-truth replacement on a mismatch, or as one free bonus token when allKdrafts matched). - Truncate both models' KV caches back to the confirmed prefix so rejected draft states never pollute subsequent rounds.
- Return
(generated_tokens, acceptance_rate), wheregenerated_tokensmatchesautoregressive_decode(target_model, ...)andacceptance_rate = total_accepted_drafts / total_proposed_drafts.
- Have
benchmark_decoding: Validatelen(prompts) >= 1andnum_runs >= 1(raisingValueErrorotherwise). Executewarmup_runsuntimed passes overpromptsfor both decoders, thennum_runstimed passes (synchronizing CUDA before and after timing whentorchis loaded and CUDA is available). Return a dictionary with:"mean_latency_speculative"and"mean_latency_autoregressive": mean wall-clock seconds per decode call (num_runs * len(prompts)calls each),"speedup":mean_latency_autoregressive / mean_latency_speculative,"mean_acceptance_rate": meanacceptance_rateacross timed speculative calls,"tokens_per_second_speculative"and"tokens_per_second_autoregressive": total generated tokens divided by total elapsed seconds for each decoder,"outputs_match":Trueif speculative and autoregressive token lists matched on every timed call, elseFalse.
Examples
Example 1
Input:
# Vocabulary 0..7; input_ids = [1], max_new_tokens = 4, gamma = 2, eos_token_id = 7
# target_model rule: next_token = (last_token + 2) % 8
# draft_model rule: next_token = 7 if last_token == 3 else (last_token + 2) % 8
tokens, rate = speculative_decode(target_model, draft_model, [1], 4, 2, 7)
Output:
([3, 5, 7], 0.6666666666666666)
Walk-through:
- Round 1: From [1], draft_model proposes 3, then after 3 predicts 7 (eos_token_id) and stops early (drafts = [3, 7]). target_model scores [1, 3, 7] in one pass, predicting 3 after 1 (matches drafts[0]) and 5 after 3 (rejects drafts[1] = 7). The round commits [3, 5] and truncates both KV caches back to [1, 3]. Because draft 7 was rejected, generation continues.
- Round 2: From [1, 3, 5], draft_model feeds [5], predicts 7 (eos_token_id), and stops (drafts = [7]). target_model confirms 7 after 5. Generation halts at eos_token_id = 7, returning [3, 5, 7] with acceptance_rate = (1 + 1) / (2 + 1) = 2 / 3.
Example 2
Input:
# Vocabulary 0..9; input_ids = [2, 0], max_new_tokens = 5, gamma = 2, eos_token_id = 99
# Both target_model and draft_model predict (last_token + 3) % 10
tokens, rate = speculative_decode(target_model, draft_model, [2, 0], 5, 2, 99)
Output:
([3, 6, 9, 2, 5], 1.0)
Walk-through: Round 1 drafts [3, 6]; target_model accepts both and appends bonus token 9 ([3, 6, 9]). Round 2 drafts [2, 5]; target_model accepts both, and since 3 + 2 == 5 == max_new_tokens, the bonus token is omitted. All 4 proposed drafts were accepted (rate = 4 / 4 = 1.0) using only 2 target forward passes instead of 5.
Constraints
1 <= len(input_ids) <= 20481 <= gamma <= 161 <= max_new_tokens <= 5120 <= warmup_runs <= 10and1 <= num_runs <= 20- Do not require PyTorch to be installed in CPU-only environments.
Step-by-step walkthrough
Understand why single-token LLM decoding is memory-bound
When a large language model generates text one token at a time (autoregressive decoding), each forward pass at batch size
1must stream every model weight from GPU memory just to predict one token. For example, a 7-billion-parameter model stored in 16-bit floats occupies14 GB; on a GPU with2 TB/sof memory bandwidth, simply reading the weights once takes14 GB / (2 TB/s) = 7 ms. Because the GPU's math units sit mostly idle waiting on memory reads, scoring 5 tokens in parallel reads the exact same14 GBof weights once and also takes roughly7 ms!Speculative decoding turns that spare parallel compute into wall-clock speedup: a tiny, fast draft model guesses
K <= gammacandidate tokens sequentially, and the large target model verifies allKguesses in one parallel forward pass while guaranteeing the exact same output sequence as running the target model alone.Let's pin down the model interface from
starter.py:logits, past = model.forward(input_ids, use_cache=True, past_key_values=past)takes only the tokens not yet stored inpast(past=Nonestarts empty). Rowlogits[j]scores every vocabulary token for the position immediately afterinput_ids[j].past = model.truncate_cache(past, valid_length)trims the key-value (KV) cache to keep only the firstvalid_lengthcached positions and returns the trimmed cache.- Both decoders return only the newly generated tokens (keeping
eos_token_idif emitted), andacceptance_rate = total_accepted_drafts / total_proposed_drafts(target corrections and bonus tokens are not counted as accepted drafts).
Build the autoregressive baseline with a KV cache
Standard greedy decoding has two phases:
- Prefill: Feed the full
input_idsprompt once withpast_key_values=Noneso the KV cache records every prompt token's key and value vectors, and inspectlogits[-1]to pick the first generated token. - Decode loop: Feed
[next_token]one token at a time alongsidepastuntil eithereos_token_idis emitted ormax_new_tokenstokens have been generated.
Writing a shared
_argmaxhelper with strict>ensures ties always pick the lowest token index in both decoders:from typing import List def _argmax(scores_row) -> int: """Return the vocabulary index with the largest score (first index wins ties).""" best_idx = 0 for idx in range(1, len(scores_row)): if scores_row[idx] > scores_row[best_idx]: best_idx = idx return best_idx def autoregressive_decode( model, input_ids: List[int], max_new_tokens: int, eos_token_id: int ) -> List[int]: """Standard greedy decoding with a KV cache: one forward pass per generated token.""" logits, past = model.forward(list(input_ids), use_cache=True, past_key_values=None) generated: List[int] = [] while True: next_token = _argmax(logits[-1]) generated.append(next_token) if next_token == eos_token_id or len(generated) == max_new_tokens: return generated logits, past = model.forward([next_token], use_cache=True, past_key_values=past)Generating
Ntokens this way always requires exactlyNtarget forward passes.- Prefill: Feed the full
Key idea: align target inputs with verification logit rows
In each speculative round, suppose the draft model proposes
Ktokens[d0, d1, ..., d(K-1)]. We feedtarget_inputs = uncached_committed + draftsinto onetarget_model.forwardcall. Look at which token each row oflogitspredicts:target_inputs: [ ... uncached_committed ..., d0, d1, ..., d(K-1) ] ^ ^ ^ ^ | | | | index in target_inputs: first first+1 first+2 first+K | | | | what that logits row predicts: next after next next next committed after d0 after d1 after d(K-1) | | | | what we use it for: check == d0 check == d1 check == d2 BONUS token!Here
first_verify_row = len(uncached_committed) - 1is simply the index of the last committed token insidetarget_inputs:- We walk
i = 0, 1, ...whiledrafts[i] == _argmax(logits[first_verify_row + i]). Letnum_acceptedbe the number of matching drafts. - If a draft mismatches (
num_accepted < K):_argmax(logits[first_verify_row + num_accepted])is already the exact token greedy target decoding would have chosen afterdrafts[:num_accepted]! We append it as a correction token. - If every draft matches (
num_accepted == K):_argmax(logits[first_verify_row + K])is the target's prediction afterd(K-1)— a bonus token for free!
That is why speculative decoding never stalls: even when
num_accepted == 0(the very first draft is wrong), the round still commits1true target token!- We walk
Generate up to K candidate tokens with the draft model
To avoid off-by-one bugs in KV-cache bookkeeping, we track an integer
draft_cached(andtarget_cached) recording how many leading tokens ofsequenceare already inside that model's KV cache. Whenever a model runs, the missing prefix tokens it needs to catch up on are simplysequence[cached:]!Why is that slice
sequence[draft_cached:]so helpful? - On round 1 (draft_cached = 0),sequence[0:]feeds the whole prompt. - After a rejected round,sequence[draft_cached:]is[correction_token](1token). - After an all-accepted round with a bonus token, the draft model never fed its own final draftd(K-1)back in and never sawbonus_token, sosequence[draft_cached:]automatically feeds[d(K-1), bonus_token](2tokens)!We cap
draft_budget = min(gamma, max_new_tokens - generated_so_far)so drafts never exceed the token budget, and stop early if the draft model predictseos_token_id:from typing import Any, List, Tuple def _propose_draft_tokens( draft_model, sequence: List[int], draft_past: Any, draft_cached: int, max_drafts: int, eos_token_id: int, ) -> Tuple[List[int], Any, int]: """Greedily draft up to `max_drafts` candidate tokens after `sequence`, stopping at `eos_token_id`.""" uncached_inputs = sequence[draft_cached:] drafts: List[int] = [] while len(drafts) < max_drafts: logits, draft_past = draft_model.forward( uncached_inputs, use_cache=True, past_key_values=draft_past ) draft_cached += len(uncached_inputs) draft_token = _argmax(logits[-1]) drafts.append(draft_token) if draft_token == eos_token_id: break uncached_inputs = [draft_token] return drafts, draft_past, draft_cachedVerify drafts, claim the extra token, and roll back both KV caches
After the target forward pass,
target_pastcontainscommitted_len + len(drafts)positions — including any rejected draft tokens starting atdrafts[num_accepted]. If we left rejected drafts insidetarget_pastordraft_past, future tokens would attend to phantom tokens that were never part of the generated text!Look at what each cache holds before and after rollback to
valid_prefix_len = committed_len + num_accepted:Example A: K = 3 drafts [d0, d1, d2], mismatch at d1 (num_accepted = 1, correction = c1) Confirmed sequence becomes: [...committed..., d0, c1] target_past before rollback: [...committed..., d0, d1(BAD), d2(BAD)] -> truncate to valid_prefix_len -> [...committed..., d0] draft_past before rollback: [...committed..., d0, d1(BAD)] -> truncate to valid_prefix_len -> [...committed..., d0] Next round feeds `c1` into both models! Example B: K = 3 drafts [d0, d1, d2], all 3 match (num_accepted = 3, bonus = b) Confirmed sequence becomes: [...committed..., d0, d1, d2, b] target_past before rollback: [...committed..., d0, d1, d2] (len = valid_prefix_len) -> keep all draft_past before rollback: [...committed..., d0, d1] (len = valid_prefix_len - 1) -> min() keeps valid_prefix_len - 1 Next round feeds `[b]` to target_model and `[d2, b]` to draft_model!Also note the two cases where we skip appending the extra correction/bonus token: 1. An accepted draft in
drafts[:num_accepted]was alreadyeos_token_id(generation has ended). 2. AllKdrafts were accepted andgenerated_so_far + K == max_new_tokens(the token budget is already full).Trace Example 1 across two rounds
Let's trace Example 1 from
statement.md: vocabulary0..7,target_modelpredicts(last + 2) % 8,draft_modelpredicts(last + 2) % 8except after3where it predicts7, withinput_ids = [1],gamma = 2,max_new_tokens = 4, andeos_token_id = 7:Round 1: sequence = [1] (committed_len = 1, generated = 0, draft_budget = min(2, 4) = 2) 1. Draft: feeds [1] -> 3; feeds [3] -> 7 (== eos, stops early!) -> drafts = [3, 7], draft_cached = 2 ([1, 3]) 2. Target: feeds [1] + [3, 7] = [1, 3, 7]; first_verify_row = 0 logits[0] -> 3, logits[1] -> 5, logits[2] -> 1 3. Verify: i=0: drafts[0]=3 == 3 (accept); i=1: drafts[1]=7 != 5 (reject!) -> num_accepted = 1 4. Extra: append correction logits[1] -> 5; sequence becomes [1, 3, 5] 5. Rollback: valid_prefix_len = 1 + 1 = 2 -> target_past=[1, 3], draft_past=[1, 3] Round 2: sequence = [1, 3, 5] (committed_len = 3, generated = 2, draft_budget = min(2, 4 - 2) = 2) 1. Draft: feeds [5] -> 7 (== eos, stops after 1 token!) -> drafts = [7], draft_cached = 3 ([1, 3, 5]) 2. Target: feeds [5] + [7] = [5, 7]; first_verify_row = 0 logits[0] -> 7, logits[1] -> 1 3. Verify: drafts[0]=7 == 7 -> num_accepted = 1 (round_tokens = [7]) 4. Extra: eos_token_id (7) is in round_tokens -> skip bonus token! 5. Stop: returns ([3, 5, 7], acceptance_rate = (1 + 1) / (2 + 1) = 2 / 3)Notice that
draft_model's false-alarm7(eos_token_id) in Round 1 did not end generation becausetarget_modelrejected it and substituted5— and emitting[3, 5, 7]took2target passes instead of3!Measure wall-clock latency accurately in the benchmark harness
Benchmarking GPU inference accurately requires avoiding three classic measurement bugs:
- Warm-up passes (
warmup_runs): The first GPU calls pay one-time setup overhead (CUDA context creation, memory-pool allocation, kernel selection). Running untimed warm-up iterations keeps those one-time costs out of the timed numbers. - Accelerator synchronization (
torch.cuda.synchronize()): CUDA kernel launches are asynchronous — Python returns immediately after placing work in the GPU queue. Synchronizing right before startingtime.perf_counter()and right before stopping it ensures we time actual GPU execution. Checkingsys.modules.get("torch")avoids importing PyTorch when running lightweight CPU tests. - Interleaved runs: Alternating
autoregressive_decodeandspeculative_decodeon each prompt inside each timed pass spreads clock throttling or background machine noise evenly across both methods.
from typing import Any, Tuple import sys import time def _synchronize() -> None: """Block until queued CUDA kernels finish so wall-clock timers measure execution, not kernel launch.""" torch = sys.modules.get("torch") if torch is not None and torch.cuda.is_available(): torch.cuda.synchronize() def _timed(fn, *args) -> Tuple[Any, float]: """Execute `fn(*args)` with accelerator synchronization before and after timing.""" _synchronize() start_time = time.perf_counter() result = fn(*args) _synchronize() elapsed_seconds = time.perf_counter() - start_time return result, elapsed_seconds- Warm-up passes (
Complete solution
from typing import Any, Dict, List, Tuple import sys import time # Model contract shared by target_model and draft_model: # logits, past = model.forward(input_ids, use_cache=True, past_key_values=past) # input_ids: list[int] of tokens NOT yet stored in `past` (`past=None` starts empty). # logits[j]: vocabulary score vector predicting the token immediately AFTER input_ids[j]. # past: updated KV cache now containing the previous cache plus `input_ids`. # past = model.truncate_cache(past, valid_length) # retains only the first `valid_length` cached token positions and returns the trimmed cache. def _argmax(scores_row) -> int: """Return the vocabulary index with the largest score (first index wins ties).""" best_idx = 0 for idx in range(1, len(scores_row)): # Strict `>` keeps the earliest token ID when two vocabulary scores tie. if scores_row[idx] > scores_row[best_idx]: best_idx = idx return best_idx def autoregressive_decode( model, input_ids: List[int], max_new_tokens: int, eos_token_id: int ) -> List[int]: """Standard greedy decoding with a KV cache: one forward pass per generated token.""" # Phase 1 (Prefill): Feed the entire prompt once so `past` caches all prompt positions. logits, past = model.forward(list(input_ids), use_cache=True, past_key_values=None) # generated: list[int] of newly emitted token IDs (excluding the prompt). generated: List[int] = [] while True: # `logits[-1]` predicts the token immediately following the latest input token. next_token = _argmax(logits[-1]) generated.append(next_token) if next_token == eos_token_id or len(generated) == max_new_tokens: return generated # Phase 2 (Decode step): Feed only the single new token; prior positions stay in `past`. logits, past = model.forward([next_token], use_cache=True, past_key_values=past) def _propose_draft_tokens( draft_model, sequence: List[int], draft_past: Any, draft_cached: int, max_drafts: int, eos_token_id: int, ) -> Tuple[List[int], Any, int]: """Greedily draft up to `max_drafts` candidate tokens after `sequence`, stopping at `eos_token_id`.""" # Feed every committed token not yet present in `draft_past` (full prompt on round 1, # 1 token after a rejection round, or 2 tokens after an all-accepted round with a bonus token). uncached_inputs = sequence[draft_cached:] drafts: List[int] = [] while len(drafts) < max_drafts: logits, draft_past = draft_model.forward( uncached_inputs, use_cache=True, past_key_values=draft_past ) draft_cached += len(uncached_inputs) draft_token = _argmax(logits[-1]) drafts.append(draft_token) # Stop drafting early if the draft model predicts end-of-sequence; nothing follows EOS. if draft_token == eos_token_id: break uncached_inputs = [draft_token] # Note: `drafts[-1]` was predicted as output and never fed back into `draft_model.forward`, # so `draft_past` now holds `sequence + drafts[:-1]` (`draft_cached == len(sequence) + len(drafts) - 1`). return drafts, draft_past, draft_cached def speculative_decode( target_model, draft_model, input_ids: List[int], max_new_tokens: int, gamma: int, eos_token_id: int, ) -> Tuple[List[int], float]: """Greedy speculative decoding producing exact target-model greedy output plus acceptance rate.""" # sequence: list[int] holding prompt + all confirmed output tokens so far. sequence: List[int] = list(input_ids) prompt_len = len(sequence) # target_cached / draft_cached: number of leading tokens of `sequence` currently stored in each KV cache. target_past, target_cached = None, 0 draft_past, draft_cached = None, 0 total_proposed = 0 total_accepted = 0 while True: committed_len = len(sequence) generated_so_far = committed_len - prompt_len # Never draft more tokens than the remaining generation budget allows. draft_budget = min(gamma, max_new_tokens - generated_so_far) # Phase 1 (Draft): Cheaply generate K <= draft_budget candidate tokens with draft_model. drafts, draft_past, draft_cached = _propose_draft_tokens( draft_model, sequence, draft_past, draft_cached, draft_budget, eos_token_id ) # Phase 2 (Parallel verification pass): Score uncached committed tokens + all drafts at once. uncached_committed = sequence[target_cached:] target_inputs = uncached_committed + drafts logits, target_past = target_model.forward( target_inputs, use_cache=True, past_key_values=target_past ) target_cached += len(target_inputs) # `uncached_committed[-1]` sits at index `len(uncached_committed) - 1` inside `target_inputs`, # so that row of `logits` predicts `drafts[0]`, and row `first_verify_row + i` predicts `drafts[i]`. first_verify_row = len(uncached_committed) - 1 # Phase 3 (Greedy check): Accept drafts left-to-right until the first mismatch with target argmax. num_accepted = 0 while num_accepted < len(drafts): target_choice = _argmax(logits[first_verify_row + num_accepted]) if drafts[num_accepted] != target_choice: break num_accepted += 1 total_proposed += len(drafts) total_accepted += num_accepted # Phase 4 (Free extra token): Row `first_verify_row + num_accepted` already holds either # the target's ground-truth correction (on mismatch) or a bonus next token (when all K matched). round_tokens = drafts[:num_accepted] has_eos = eos_token_id in round_tokens has_budget_for_one_more = (generated_so_far + len(round_tokens)) < max_new_tokens if not has_eos and has_budget_for_one_more: extra_token = _argmax(logits[first_verify_row + num_accepted]) round_tokens.append(extra_token) sequence.extend(round_tokens) # Phase 5 (KV-cache rollback): Trim rejected draft states so future attention sees only valid text. # Note that `extra_token` was predicted as output and not yet fed in, so valid cached length is # `committed_len + num_accepted`. For `draft_past`, `min()` handles the all-accepted case where # `drafts[-1]` was never fed into `draft_model` (`draft_cached == valid_prefix_len - 1`). valid_prefix_len = committed_len + num_accepted target_cached = valid_prefix_len target_past = target_model.truncate_cache(target_past, target_cached) draft_cached = min(draft_cached, valid_prefix_len) draft_past = draft_model.truncate_cache(draft_past, draft_cached) # Phase 6 (Stopping check): Return once EOS is committed or `max_new_tokens` is reached. total_generated = len(sequence) - prompt_len if eos_token_id in round_tokens or total_generated >= max_new_tokens: acceptance_rate = total_accepted / total_proposed return sequence[prompt_len:], acceptance_rate def _synchronize() -> None: """Block until queued CUDA kernels finish so wall-clock timers measure execution, not kernel launch.""" # Check sys.modules so CPU-only environments work without requiring PyTorch to be installed. torch = sys.modules.get("torch") if torch is not None and torch.cuda.is_available(): torch.cuda.synchronize() def _timed(fn, *args) -> Tuple[Any, float]: """Execute `fn(*args)` with accelerator synchronization before and after timing.""" _synchronize() start_time = time.perf_counter() result = fn(*args) _synchronize() elapsed_seconds = time.perf_counter() - start_time return result, elapsed_seconds def benchmark_decoding( target_model, draft_model, prompts: List[List[int]], max_new_tokens: int, gamma: int, eos_token_id: int, warmup_runs: int = 2, num_runs: int = 5, ) -> Dict[str, Any]: """Benchmark speculative decoding against standard autoregressive decoding across `prompts`.""" if not prompts or num_runs < 1: raise ValueError("need at least one prompt and one timed run") # Phase 1 (Warm-up): Absorb one-time CUDA context setup, allocator growth, and kernel compilation. for _ in range(warmup_runs): for prompt in prompts: autoregressive_decode(target_model, prompt, max_new_tokens, eos_token_id) speculative_decode(target_model, draft_model, prompt, max_new_tokens, gamma, eos_token_id) # Phase 2 (Timed runs): Interleave both decoders on each prompt so thermal throttling affects both equally. ar_total_seconds = 0.0 spec_total_seconds = 0.0 ar_total_tokens = 0 spec_total_tokens = 0 acceptance_rates: List[float] = [] outputs_match = True for _ in range(num_runs): for prompt in prompts: ar_tokens, ar_elapsed = _timed( autoregressive_decode, target_model, prompt, max_new_tokens, eos_token_id ) ar_total_seconds += ar_elapsed ar_total_tokens += len(ar_tokens) spec_result, spec_elapsed = _timed( speculative_decode, target_model, draft_model, prompt, max_new_tokens, gamma, eos_token_id, ) spec_tokens, rate = spec_result spec_total_seconds += spec_elapsed spec_total_tokens += len(spec_tokens) acceptance_rates.append(rate) if spec_tokens != ar_tokens: outputs_match = False # Phase 3 (Aggregate metrics): Compute per-call mean latencies, speedup ratio, and token throughputs. total_calls = num_runs * len(prompts) mean_ar_latency = ar_total_seconds / total_calls mean_spec_latency = spec_total_seconds / total_calls return { "mean_latency_speculative": mean_spec_latency, "mean_latency_autoregressive": mean_ar_latency, "speedup": mean_ar_latency / mean_spec_latency, "mean_acceptance_rate": sum(acceptance_rates) / len(acceptance_rates), "tokens_per_second_speculative": spec_total_tokens / spec_total_seconds, "tokens_per_second_autoregressive": ar_total_tokens / ar_total_seconds, "outputs_match": outputs_match, }✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a busy senior editor working with a fast junior assistant: instead of typing an article one word at a time, the assistant quickly types gamma draft words, and the senior editor scans all gamma words in a single glance — keeping the prefix they agree with and immediately writing the right word at the first disagreement (or writing one bonus word at the end if every draft word was spot-on). In LLM inference, autoregressive decoding (generating tokens one after another, where each token depends on all earlier ones) is memory-bandwidth bound (limited by the time needed to read gigabytes of model weights from GPU memory rather than by math operations). Because reading the target model's weights once can score gamma + 1 positions in parallel in nearly the same time as scoring 1 position, checking a short draft batch turns wasted GPU math capacity into extra confirmed tokens per pass while maintaining a KV cache (stored attention key and value tensors for already-processed tokens so earlier context is never recomputed).
Why does plain greedy decoding fall short, and why would naive batching without cache rollback break? Standard decoding runs N heavy target forward passes to produce N tokens, paying the full weight-loading latency N times. On the other hand, if you feed draft tokens into the target model without rolling back the KV cache on a mismatch, rejected draft tokens remain inside the attention state and corrupt every future prediction, breaking the guarantee that speculative decoding produces the exact same sequence of logits (unnormalized vocabulary scores) and argmax (highest-scoring token ID) choices as the target model alone.
Let's walk through a 1-round example starting from prompt [10] with gamma = 3, where the draft model proposes [20, 30, 99] and the target model's parallel pass on [10, 20, 30, 99] predicts [20, 30, 40, 50]:
target_inputs: [ 10, 20, 30, 99 ] (1 committed token + 3 drafts)
target argmax: [ 20, 30, 40, 50 ] (each entry predicts the NEXT token)
compare drafts: ==20 ==30 !=99 (ignored)
OK OK REJECT -> use 40 as target's ground-truth correction!
Confirmed tokens added this round: [20, 30, 40] (3 tokens from just 1 target pass; rate = 2/3)
KV caches rolled back to length 3 ([10, 20, 30]) so rejected token 99 is erased; 40 feeds in next round.
Complexity
Let N be the number of generated tokens (N <= max_new_tokens), L be the total sequence length (len(input_ids) + N), V be the vocabulary size, and gamma be the maximum draft length per round.
- Target model forward passes: between
ceil(N / (gamma + 1))andN. Every verification round commits at least1token (whendrafts[0]is rejected and replaced by the target's correction) and at mostgamma + 1tokens (when allgammadrafts match plus1bonus token), compared to alwaysNpasses in standard autoregressive decoding. If each draft token is accepted with probabilityalphaindependently, a fullgamma-draft round yields(1 - alpha^(gamma + 1)) / (1 - alpha)expected tokens — for example,alpha = 0.8andgamma = 4produce(1 - 0.8^5) / 0.2 = 3.36tokens per target pass. - Draft model forward passes: at most
gammaper round (<= N * gammatotal). Each proposed draft token takes one tiny forward pass over1token (except round 1's prefill, meaning the initial pass over the full prompt, and2tokens right after an all-accepted round). - Host-side verification work:
O((K + 1) * V)per round. ScanningK + 1vocabulary rows of lengthVwith_argmaxtakes linear time inVper checked row (or a single vectorizedlogits.argmax(dim=-1)kernel on GPU). - Space:
O(L + gamma)KV-cache positions per model. Each model maintains one KV cache scaling linearly with context lengthL, temporarily holding up togammaunconfirmed draft positions during verification beforetruncate_cacherolls them back.
Edge cases
max_new_tokens = 1or remaining budget smaller thangamma: Cappingdraft_budget = min(gamma, max_new_tokens - generated_so_far)ensures we never draft unnecessary tokens or overshootmax_new_tokens.- All
Kdrafts accepted right at the budget limit (generated_so_far + K == max_new_tokens): Skip appending the bonus token so the output length never hitsmax_new_tokens + 1. - Draft model predicts
eos_token_id:_propose_draft_tokensstops drafting immediately because nothing follows end-of-sequence — however, if the target model rejects that drafteos_token_id, generation continues seamlessly with the target's correction token. - Target model emits
eos_token_id(via accepted draft, correction, or bonus token):eos_token_idis kept at the end of the output list andspeculative_decodereturns immediately. - Draft cache length after a fully accepted round: Because
drafts[-1]was emitted as output and never fed back intodraft_model.forward,draft_cachedequalscommitted_len + K - 1(1less thanvalid_prefix_len = committed_len + K). Usingmin(draft_cached, valid_prefix_len)avoids claiming a cache slot the draft model never computed, and the next round feeds[drafts[-1], bonus_token]cleanly. - Floating-point near-ties on GPU hardware: Batched matrix-matrix multiplication (verification) and single-row matrix-vector multiplication (autoregressive decoding) group floating-point additions differently, which can flip
_argmaxwhen two top logits differ by1e-7. Reportingoutputs_matchinbenchmark_decodingsurfaces this without crashing real-hardware benchmarks.
Common mistakes
- Off-by-one alignment between
draftsandlogits:drafts[0]is predicted by the logit row of the last committed token (first_verify_row = len(uncached_committed) - 1), not by the logit row atdrafts[0]'s own position (which predictsdrafts[1]). - Discarding the correction or bonus token: Returning only
drafts[:num_accepted]produces0tokens wheneverdrafts[0]is wrong, causing an infinite loop! - Forgetting to truncate KV caches after verification: Leaving rejected draft tokens in
target_pastordraft_pastpollutes future attention keys and values, silently changing generated text. - Re-feeding the entire
sequenceevery round instead ofsequence[cached:]: Produces the right tokens on toy tests, but turns every round into a full prefill (O(L^2)total work) and destroys the real-world speedup. - Timing CUDA code without
torch.cuda.synchronize()or warm-up runs: Because GPU kernels execute asynchronously, unsynchronizedtime.perf_counter()calls only time Python kernel launches (microseconds) rather than GPU completion (milliseconds), while skipping warm-up pollutes runs with one-time compilation and allocator costs. - Counting target corrections or bonus tokens in
total_accepted: Inflatesacceptance_rateabove the true fraction of accepted draft guesses (and can even pushtotal_accepted / total_proposed > 1.0!).
Alternative approaches
- Prompt-lookup (ngram) speculative decoding: Instead of running a neural draft model, search the prompt and recent output for matching token n-grams and propose the following
gammatokens as drafts — near-zero draft cost and very high acceptance on summarization, RAG, and code editing tasks. - Self-speculative / layer-skipping decoding: Run a subset of the target model's own layers as the draft model, eliminating the need to train, store, or tokenizer-align a separate draft checkpoint.
- Dynamic
gammascheduling: Increasegammawhen recent rounds accepted every draft (high local predictability) and shrinkgammaright after early rejections so draft compute is never wasted on hard-to-predict tokens.
Follow-up questions
- How do you generalize greedy verification to non-zero temperature sampling while preserving the exact target token distribution? Convert both the draft logits and target logits into probability distributions
q(x)andp(x)viasoftmax(logits / T)(applying identical top-k/top-p filtering), sample each draft tokenx ~ q, and acceptxwith probabilitymin(1, p(x) / q(x)). At the first rejection, sample the replacement token from the normalized residual distributionp'(x) = max(0, p(x) - q(x)) / sum_v max(0, p(v) - q(v))(and if allKdrafts are accepted, sample the bonus token directly fromp); algebraicallyP(accept x) + P(reject) * p'(x) = min(p(x), q(x)) + max(0, p(x) - q(x)) = p(x), guaranteeing the exact target distributionpat every step!
text
Worked 3-token vocabulary trace:
Target p = [0.6, 0.3, 0.1], Draft q = [0.2, 0.7, 0.1]
Accept rules: x=0 -> min(1, 0.6/0.2) = 1; x=1 -> min(1, 0.3/0.7) = 3/7; x=2 -> min(1, 0.1/0.1) = 1
P(reject) = 0.2*(0) + 0.7*(4/7) + 0.1*(0) = 0.4
Residual max(0, p - q) = [0.4, 0.0, 0.0] -> normalized p' = [1.0, 0.0, 0.0]
Final output probs: P(0) = 0.2*1 + 0.4*1.0 = 0.6; P(1) = 0.7*(3/7) = 0.3; P(2) = 0.1*1 = 0.1 (exact match to p!)
- At what combination of per-token acceptance probability and draft-to-target step-latency ratio does speculation hurt overall latency? Let
c = T_draft / T_targetbe the latency ratio of one draft step to one target step, and assume a memory-bound target verification pass overgamma + 1tokens still costs~1target-step unit. One round costsgamma * c + 1target-step units and produces(1 - alpha^(gamma + 1)) / (1 - alpha)expected tokens, so speculative decoding slows down whenever(1 - alpha^(gamma + 1)) / ((1 - alpha) * (gamma * c + 1)) < 1(forgamma = 1, this simplifies cleanly toalpha < c). Forgamma = 4,alpha = 0.8withc = 0.05yields3.36 / 1.20 = 2.80xspeedup, whereasalpha = 0.2withc = 0.20yields1.25 / 1.80 = 0.69x(a31%slowdown); large serving batch sizes can also erase speedups because the target pass becomes compute-bound and verifyinggamma + 1tokens per request costs close togamma + 1steps. - How does speculative verification generalize from a single chain of
gammatokens to branching draft trees? Arrange multiple candidate continuations (such as top-2 or top-3 choices at each depth) into a prefix tree, flatten all tree nodes into a single input sequence where each node's positional embedding index equalscommitted_len + depth, and pass a custom tree attention mask so every candidate node attends only to the committed prefix and its own ancestor chain. A single target pass scores every root-to-leaf branch simultaneously, letting you accept the longest matching branch plus one extra target token — then gather (compact) the KV-cache slots of the winning branch's nodes into contiguous positions rather than merely truncating the tail. Architectures like Medusa predict these tree candidates using lightweight extra linear heads atop the target model's last hidden state (head kpredictsk + 1steps ahead), while Speculative Streaming folds multi-step lookahead streams directly into the target model so drafting and tree verification happen inside one forward pass without a separate draft model.
Follow-up questions
- How do you generalize greedy verification to non-zero temperature sampling while preserving the exact target token distribution?
- At what combination of per-token acceptance probability and draft-to-target step-latency ratio does speculation hurt overall latency?
- How does speculative verification generalize from a single chain of `gamma` tokens to branching draft trees?
Similar questions
- Diagnosing Live Recall Drops and Training-Serving Skew in Telemetry ML
- Stream Alignment and Versioned Reconciliation for Late Telemetry
- Fix a Broken Python Multiprocessing Batch Pipeline
- Incremental Island Counts
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision