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 in past (past=None starts an empty cache). Entry logits[j] contains vocabulary scores predicting the token immediately after input_ids[j], and past returns the updated cache including input_ids. When picking a greedy argmax token from a score row, break ties in favor of the smallest vocabulary index.
  • past = model.truncate_cache(past, valid_length) trims past so only the first valid_length cached 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

  1. autoregressive_decode: Prefill input_ids once, then greedily append one argmax token per step using the KV cache until eos_token_id is generated (keep eos_token_id in the returned list) or max_new_tokens new tokens have been produced. Return only the newly generated tokens (excluding input_ids).
  2. speculative_decode: Repeat speculative rounds until eos_token_id is committed or max_new_tokens tokens are generated:
    • Have draft_model greedily propose K candidate tokens (1 <= K <= min(gamma, remaining_budget)), stopping early if draft_model predicts eos_token_id.
    • Run one target_model.forward pass over any uncached committed prefix tokens followed by the K draft tokens.
    • Accept the longest leading prefix drafts[:num_accepted] where each draft token equals target_model's greedy argmax at that position.
    • Unless an accepted draft already equals eos_token_id or max_new_tokens has already been reached, also append target_model's argmax at position num_accepted (acting as the ground-truth replacement on a mismatch, or as one free bonus token when all K drafts matched).
    • Truncate both models' KV caches back to the confirmed prefix so rejected draft states never pollute subsequent rounds.
    • Return (generated_tokens, acceptance_rate), where generated_tokens matches autoregressive_decode(target_model, ...) and acceptance_rate = total_accepted_drafts / total_proposed_drafts.
  3. benchmark_decoding: Validate len(prompts) >= 1 and num_runs >= 1 (raising ValueError otherwise). Execute warmup_runs untimed passes over prompts for both decoders, then num_runs timed passes (synchronizing CUDA before and after timing when torch is 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": mean acceptance_rate across 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": True if speculative and autoregressive token lists matched on every timed call, else False.

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) <= 2048
  • 1 <= gamma <= 16
  • 1 <= max_new_tokens <= 512
  • 0 <= warmup_runs <= 10 and 1 <= num_runs <= 20
  • Do not require PyTorch to be installed in CPU-only environments.

Step-by-step walkthrough

  1. 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 1 must stream every model weight from GPU memory just to predict one token. For example, a 7-billion-parameter model stored in 16-bit floats occupies 14 GB; on a GPU with 2 TB/s of memory bandwidth, simply reading the weights once takes 14 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 same 14 GB of weights once and also takes roughly 7 ms!

    Speculative decoding turns that spare parallel compute into wall-clock speedup: a tiny, fast draft model guesses K <= gamma candidate tokens sequentially, and the large target model verifies all K guesses 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 in past (past=None starts empty). Row logits[j] scores every vocabulary token for the position immediately after input_ids[j].
    • past = model.truncate_cache(past, valid_length) trims the key-value (KV) cache to keep only the first valid_length cached positions and returns the trimmed cache.
    • Both decoders return only the newly generated tokens (keeping eos_token_id if emitted), and acceptance_rate = total_accepted_drafts / total_proposed_drafts (target corrections and bonus tokens are not counted as accepted drafts).
  2. Build the autoregressive baseline with a KV cache

    Standard greedy decoding has two phases:

    1. Prefill: Feed the full input_ids prompt once with past_key_values=None so the KV cache records every prompt token's key and value vectors, and inspect logits[-1] to pick the first generated token.
    2. Decode loop: Feed [next_token] one token at a time alongside past until either eos_token_id is emitted or max_new_tokens tokens have been generated.

    Writing a shared _argmax helper 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 N tokens this way always requires exactly N target forward passes.

  3. Key idea: align target inputs with verification logit rows

    In each speculative round, suppose the draft model proposes K tokens [d0, d1, ..., d(K-1)]. We feed target_inputs = uncached_committed + drafts into one target_model.forward call. Look at which token each row of logits predicts:

    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) - 1 is simply the index of the last committed token inside target_inputs:

    • We walk i = 0, 1, ... while drafts[i] == _argmax(logits[first_verify_row + i]). Let num_accepted be 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 after drafts[: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 after d(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 commits 1 true target token!

  4. 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 (and target_cached) recording how many leading tokens of sequence are already inside that model's KV cache. Whenever a model runs, the missing prefix tokens it needs to catch up on are simply sequence[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] (1 token). - After an all-accepted round with a bonus token, the draft model never fed its own final draft d(K-1) back in and never saw bonus_token, so sequence[draft_cached:] automatically feeds [d(K-1), bonus_token] (2 tokens)!

    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 predicts eos_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_cached
    
  5. Verify drafts, claim the extra token, and roll back both KV caches

    After the target forward pass, target_past contains committed_len + len(drafts) positions — including any rejected draft tokens starting at drafts[num_accepted]. If we left rejected drafts inside target_past or draft_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 already eos_token_id (generation has ended). 2. All K drafts were accepted and generated_so_far + K == max_new_tokens (the token budget is already full).

  6. Trace Example 1 across two rounds

    Let's trace Example 1 from statement.md: vocabulary 0..7, target_model predicts (last + 2) % 8, draft_model predicts (last + 2) % 8 except after 3 where it predicts 7, with input_ids = [1], gamma = 2, max_new_tokens = 4, and eos_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-alarm 7 (eos_token_id) in Round 1 did not end generation because target_model rejected it and substituted 5 — and emitting [3, 5, 7] took 2 target passes instead of 3!

  7. Measure wall-clock latency accurately in the benchmark harness

    Benchmarking GPU inference accurately requires avoiding three classic measurement bugs:

    1. 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.
    2. Accelerator synchronization (torch.cuda.synchronize()): CUDA kernel launches are asynchronous — Python returns immediately after placing work in the GPU queue. Synchronizing right before starting time.perf_counter() and right before stopping it ensures we time actual GPU execution. Checking sys.modules.get("torch") avoids importing PyTorch when running lightweight CPU tests.
    3. Interleaved runs: Alternating autoregressive_decode and speculative_decode on 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
    
  8. 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)) and N. Every verification round commits at least 1 token (when drafts[0] is rejected and replaced by the target's correction) and at most gamma + 1 tokens (when all gamma drafts match plus 1 bonus token), compared to always N passes in standard autoregressive decoding. If each draft token is accepted with probability alpha independently, a full gamma-draft round yields (1 - alpha^(gamma + 1)) / (1 - alpha) expected tokens — for example, alpha = 0.8 and gamma = 4 produce (1 - 0.8^5) / 0.2 = 3.36 tokens per target pass.
  • Draft model forward passes: at most gamma per round (<= N * gamma total). Each proposed draft token takes one tiny forward pass over 1 token (except round 1's prefill, meaning the initial pass over the full prompt, and 2 tokens right after an all-accepted round).
  • Host-side verification work: O((K + 1) * V) per round. Scanning K + 1 vocabulary rows of length V with _argmax takes linear time in V per checked row (or a single vectorized logits.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 length L, temporarily holding up to gamma unconfirmed draft positions during verification before truncate_cache rolls them back.

Edge cases

  • max_new_tokens = 1 or remaining budget smaller than gamma: Capping draft_budget = min(gamma, max_new_tokens - generated_so_far) ensures we never draft unnecessary tokens or overshoot max_new_tokens.
  • All K drafts accepted right at the budget limit (generated_so_far + K == max_new_tokens): Skip appending the bonus token so the output length never hits max_new_tokens + 1.
  • Draft model predicts eos_token_id: _propose_draft_tokens stops drafting immediately because nothing follows end-of-sequence — however, if the target model rejects that draft eos_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_id is kept at the end of the output list and speculative_decode returns immediately.
  • Draft cache length after a fully accepted round: Because drafts[-1] was emitted as output and never fed back into draft_model.forward, draft_cached equals committed_len + K - 1 (1 less than valid_prefix_len = committed_len + K). Using min(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 _argmax when two top logits differ by 1e-7. Reporting outputs_match in benchmark_decoding surfaces this without crashing real-hardware benchmarks.

Common mistakes

  • Off-by-one alignment between drafts and logits: 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 at drafts[0]'s own position (which predicts drafts[1]).
  • Discarding the correction or bonus token: Returning only drafts[:num_accepted] produces 0 tokens whenever drafts[0] is wrong, causing an infinite loop!
  • Forgetting to truncate KV caches after verification: Leaving rejected draft tokens in target_past or draft_past pollutes future attention keys and values, silently changing generated text.
  • Re-feeding the entire sequence every round instead of sequence[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, unsynchronized time.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: Inflates acceptance_rate above the true fraction of accepted draft guesses (and can even push total_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 gamma tokens 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 gamma scheduling: Increase gamma when recent rounds accepted every draft (high local predictability) and shrink gamma right 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) and p(x) via softmax(logits / T) (applying identical top-k/top-p filtering), sample each draft token x ~ q, and accept x with probability min(1, p(x) / q(x)). At the first rejection, sample the replacement token from the normalized residual distribution p'(x) = max(0, p(x) - q(x)) / sum_v max(0, p(v) - q(v)) (and if all K drafts are accepted, sample the bonus token directly from p); algebraically P(accept x) + P(reject) * p'(x) = min(p(x), q(x)) + max(0, p(x) - q(x)) = p(x), guaranteeing the exact target distribution p at 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_target be the latency ratio of one draft step to one target step, and assume a memory-bound target verification pass over gamma + 1 tokens still costs ~1 target-step unit. One round costs gamma * c + 1 target-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 (for gamma = 1, this simplifies cleanly to alpha < c). For gamma = 4, alpha = 0.8 with c = 0.05 yields 3.36 / 1.20 = 2.80x speedup, whereas alpha = 0.2 with c = 0.20 yields 1.25 / 1.80 = 0.69x (a 31% slowdown); large serving batch sizes can also erase speedups because the target pass becomes compute-bound and verifying gamma + 1 tokens per request costs close to gamma + 1 steps.
  • How does speculative verification generalize from a single chain of gamma tokens 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 equals committed_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 k predicts k + 1 steps 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

Similar questions

More Spacex interview questions

All 5 Spacex questions →