Skip to content
AILinkDeepTech
Go back
Deep Learning Advanced

Speculative Decoding: Mathematical Foundations, Rejection Sampling Proofs, Tree Attention (Medusa & EAGLE), and Production PyTorch Serving

Abstract

Master Speculative Decoding: memory-bandwidth bottlenecks, modified rejection sampling proof of exact distributional equivalence, expected speedup dynamics, tree-based verification (Medusa & EAGLE), and production PyTorch serving implementations.

The Memory-Bound Inference Bottleneck in Autoregressive LLMs

Modern Large Language Models (LLMs)—including LLaMA-3, DeepSeek, Mistral, and GPT-4—generate text through autoregressive sequence stepping: predicting the next token conditioned on all historical tokens .

While the initial prompt ingestion (Prefill Phase) is highly parallel and compute-dense, the subsequent sequential token generation (Decode Phase) is severely memory-bandwidth bound.

flowchart LR subgraph Prefill["1. Prefill Phase (Compute-Bound)"] direction TB P_IN["Prompt Sequence (L Tokens)"] --> P_GEMM["High Operational Intensity Matmul<br/>Massive Parallel FLOP Utilization"] P_GEMM --> P_OUT["Prefill Output & Initial KV Cache"] end subgraph Decode["2. Autoregressive Decode (Memory-Bound)"] direction TB D_IN["Single Token Generation (Step t)"] --> D_IO["Low Operational Intensity<br/>Stream Entire Model Weights from HBM"] D_IO --> D_OUT["Single Token Emitted<br/>GPU Compute Underutilized (&lt;1%)"] end

The Arithmetic Intensity Wall:

Arithmetic intensity is defined as the ratio of floating-point operations (FLOPs) performed to bytes of high-bandwidth memory (HBM) transferred:

  1. For a Model of Parameters: Generating a single token requires moving all weights (e.g., bytes in FP16/BF16) from GPU HBM into on-chip SRAM registers to perform approximately FLOPs of matrix-vector multiplication.
  2. Resulting Intensity: .
  3. Hardware Capacity Mismatch: An NVIDIA H100 GPU delivers up to of FP16 Tensor Core compute, supported by of HBM3 bandwidth. The saturation threshold is:

Because , an H100 executing single-token generation at batch size operates at less than of its theoretical compute capacity. Generation latency is governed entirely by memory bandwidth:

For a 70B parameter model in FP16 (), generating token takes roughly:

Crucially, validating candidate tokens simultaneously requires nearly the exact same memory bandwidth and wall-clock time as evaluating a single token, because the model weights are loaded once from HBM and reused across all tokens.


Architectural & Theoretical Paradigm Comparison

Inference Acceleration ParadigmDraft MechanismDistribution InvarianceTraining CostWall-Clock SpeedupPrimary Failure Mode
Standard AutoregressiveNone (Sequential)Baseline ()None (Pretrained) (Baseline)Memory-bandwidth idle
Vanilla Speculative (Leviathan)Independent Small Draft ModelStrictly LosslessSmall (Train draft)Model size & KV mismatch
Self-Speculative (Early Exit)Skip Upper Transformer LayersApproximate / LosslessLow / NoneLayer alignment drift
Medusa (Cai et al.)Parallel Non-Autoregressive HeadsStrictly LosslessLight (Train heads)Inter-token correlation loss
EAGLE / EAGLE-2 (Li et al.)Auto-regressive Feature TransformerStrictly LosslessModerate (Feature head)High draft compute overhead
Lossy Speculative (Greedy)Small Model + Argmax MatchingLossy ()NoneSemantic degradation & drift

The Speculative Decoding Paradigm

Speculative Decoding (Leviathan et al., 2023; Chen et al., 2023) breaks this memory-bandwidth bottleneck by decoupling token generation into two coordinated components:

  1. The Draft Model (): A compact, high-speed model with distribution . It rapidly proposes a sequence of speculative candidate tokens: sequentially in time, where .
  2. The Target Model (): The original large foundation model with distribution . It verifies all speculative candidates in a single forward pass by evaluating the full sequence in parallel, computing candidate probabilities .
flowchart LR subgraph Step_1["1. Draft Phase (Fast Sequential)"] direction LR DRAFT_M["Draft Model M_q<br/>Small & Low Latency"] --> PROP["Propose K Speculative Tokens<br/>(x̃₁, x̃₂, ..., x̃_K)"] end subgraph Step_2["2. Verification Phase (Parallel Single-Pass)"] direction LR TARGET_M["Target Model M_p<br/>Large Foundation Model"] --> VERIFY["Parallel Verification<br/>Evaluate All K Tokens Simultaneously"] end subgraph Step_3["3. Rejection Sampling (Lossless Filtering)"] direction LR SAMPLE["Modified Rejection Sampler<br/>Accept valid prefix (x̃₁...x̃_m)<br/>Resample recovery token x_{m+1}"] end Step_1 --> Step_2 Step_2 --> Step_3

Rigorous Mathematical Proof: The Modified Rejection Sampling Scheme

A widespread misconception is that speculative decoding introduces approximation errors or degrades output quality. In reality, speculative decoding is strictly mathematically lossless: the marginal probability distribution of generated tokens is identical to sampling directly from the target model .

1. The Acceptance Criterion and Resampling Distribution

Let be the draft model probability distribution for token , and be the target model probability distribution over vocabulary .

Acceptance Probability:

The proposed token is accepted with probability:

Rejection & Recovery Sampling:

If candidate token is rejected (which occurs with probability ), speculative decoding terminates verification of all subsequent speculative tokens in the chain, and samples a new replacement token strictly from the normalized residual distribution:

where is the total acceptance probability, and .

flowchart LR CAND["Draft Token: x̃ ~ q(x)"] --> CHECK{"Acceptance Check<br/>Rand(0, 1) < min(1, p/q)?"} CHECK -- "Yes (Accept)" --> ACC["Accept x̃ into Final Output<br/>Proceed to Verify x̃_{k+1}"] CHECK -- "No (Reject)" --> REJ["Halt Verification<br/>Sample x_new ~ (p(x) - q(x))⁺ / (1 - β)"]

2. Analytical Proof of Exact Distributional Equivalence

We prove that under this rejection sampling scheme, the marginal probability of emitting any token is identically equal to :

Step-by-Step Proof:

By the law of total probability, emitting token occurs under two mutually exclusive events:

  1. Candidate is proposed by the draft model and accepted.
  2. An arbitrary proposed candidate is rejected, and token is drawn from the adjusted residual distribution .

Evaluating the First Term:

The probability that candidate is proposed and accepted:

Evaluating the Rejection Probability:

Summing the acceptance probabilities over the entire vocabulary:

Consequently:

Evaluating the Second Term:

Using the definition of the residual distribution :

Combining the Terms:

Adding the accepted and resampled probabilities:

Applying the fundamental algebraic identity :

This completes the proof. Sampling with speculative decoding guarantees zero statistical divergence from target model generation:


Expected Speedup and Acceptance Rate Dynamics

In each speculative decoding iteration with draft lookahead length :

  • The draft model proposes candidate tokens.
  • The target model verifies all tokens simultaneously, emitting between and valid tokens in that single round.

1. Expected Accepted Tokens per Round

Let represent the average single-token acceptance rate. Assuming token acceptance events are independent identically distributed (i.i.d.):

  • When (Poor draft quality): . The target model rejects the first proposal and emits recovery token, matching standard autoregressive throughput.
  • When (High alignment): . All draft tokens are accepted, plus an extra free bonus token sampled from the target model’s final forward pass.
flowchart LR B_LOW["Low Acceptance Rate (β = 0.4)<br/>E[N] ≈ 1.6 Tokens/Round<br/>Wall Speedup: ~1.2x"] --> B_MED["Moderate Acceptance (β = 0.7)<br/>E[N] ≈ 3.1 Tokens/Round<br/>Wall Speedup: ~2.0x"] B_MED --> B_HIGH["High Acceptance (β = 0.85)<br/>E[N] ≈ 4.8 Tokens/Round<br/>Wall Speedup: ~3.0x"]

2. Wall-Clock Speedup Ratio

Let:

  • : Latency of one forward evaluation on target model .
  • : Latency of one forward evaluation on draft model .
  • : Number of speculative tokens per round.

The wall-clock speedup factor is:

Key Engineering Takeaways:

  1. The Cost Ratio Threshold: Speedup occurs if and only if: For large target models (e.g., LLaMA-70B where ), high speedups () are readily attainable even with modest acceptance rates ().
  2. Diminishing Returns with Large : As scales, consumes significant draft latency, while decays exponentially. The optimal lookahead typically lies between and .

Architectural Evolution: Tree-Based Speculative Decoding (Medusa & EAGLE)

While vanilla speculative decoding verifies a single linear candidate trajectory, modern frameworks explore a tree of candidate hypotheses simultaneously.

flowchart LR subgraph Linear["Vanilla Linear Speculation (K = 3)"] direction LR L1["x̃₁"] --> L2["x̃₂"] --> L3["x̃₃"] end subgraph Tree["Tree Attention Speculation (Medusa / EAGLE)"] direction LR T1["Root (x)"] --> T2_1["Top-1 (x̃₁a)"] T1 --> T2_2["Top-2 (x̃₁b)"] T2_1 --> T3_1["Branch (x̃₂a)"] T2_1 --> T3_2["Branch (x̃₂b)"] T2_2 --> T3_3["Branch (x̃₂c)"] end

1. Medusa: Multi-Head Speculation without a Draft Model

Proposed by Cai et al. (2024), Medusa eliminates the separate draft model entirely. Instead, it attaches lightweight MLP prediction heads to the top layer of the target foundation model:

During generation, Head predicts the token distribution at offset directly from the final hidden state . Top- candidates from each head are combined into a tree of speculative paths.

2. EAGLE & EAGLE-2: Context-Aware Autoregressive Feature Heads

While Medusa heads predict tokens independently (ignoring causal inter-token dependencies), EAGLE (Li et al., 2024) feeds the target model’s continuous feature representations into an autoregressive single-layer decoder. This preserves token context, raising the average acceptance rate from to over across complex reasoning datasets.

3. Tree Attention Masks (Non-Causal Tree Verification)

To verify multi-branch candidate trees in a single forward pass without causal leakage across unshared branches, modern serving engines construct a custom 2D Tree Attention Mask.

Tree Topology:
       Token 0 (Root)
       ├── Token 1 ── Token 3
       └── Token 2 ── Token 4

Corresponding Tree Attention Mask Matrix:
               Token 0   Token 1   Token 2   Token 3   Token 4
   Token 0 [     1         0         0         0         0     ]
   Token 1 [     1         1         0         0         0     ]
   Token 2 [     1         0         1         0         0     ]
   Token 3 [     1         1         0         1         0     ]  <-- Attends to 0 and 1
   Token 4 [     1         0         1         0         1     ]  <-- Attends to 0 and 2

This 2D attention mask ensures Token 3 can attend to Token 1 and Root 0, but is completely masked from Token 2 and Token 4. The target model verifies all candidate branches simultaneously in a single forward evaluation.


Production PyTorch Implementation

Below is a complete, modular, and self-contained PyTorch implementation featuring:

  1. The Modified Rejection Sampling Engine with exact distribution matching.
  2. The Tree Attention Mask Generator for parallel verification.
  3. The end-to-end Speculative Decoding Execution Loop.
from __future__ import annotations

import torch
import torch.nn.functional as F


class SpeculativeSampler:
    """
    Exact Modified Rejection Sampler for Speculative Decoding.
    Guarantees strict distribution invariance: P(X = x) == p(x).
    """

    def __init__(self, temperature: float = 1.0) -> None:
        self.temperature = max(1e-5, temperature)

    @torch.no_grad()
    def sample_token(self, logits: torch.Tensor) -> torch.Tensor:
        """Samples a discrete token index from logits with temperature."""
        probs = F.softmax(logits / self.temperature, dim=-1)
        return torch.multinomial(probs, num_samples=1).squeeze(-1)

    @torch.no_grad()
    def verify_tokens(
        self,
        draft_tokens: torch.Tensor,
        draft_probs: torch.Tensor,
        target_probs: torch.Tensor,
    ) -> tuple[torch.Tensor, int]:
        """
        Executes modified rejection sampling over speculative candidate chain.

        Args:
            draft_tokens: Proposed token IDs of shape (K,)
            draft_probs: Draft model probabilities q(x_k) of shape (K, V)
            target_probs: Target model probabilities p(x_k) of shape (K + 1, V)

        Returns:
            accepted_tokens: Accepted tokens plus recovery token of shape (M,)
            num_accepted: Count of verified candidate tokens accepted (0 to K)
        """
        k = draft_tokens.shape[0]
        accepted_tokens = []
        num_accepted = 0

        for i in range(k):
            token_id = draft_tokens[i].item()
            q_val = draft_probs[i, token_id].item()
            p_val = target_probs[i, token_id].item()

            # 1. Acceptance ratio: min(1, p / q)
            alpha = min(1.0, p_val / max(1e-8, q_val))
            rand_val = torch.rand(1).item()

            if rand_val < alpha:
                # Accept candidate token
                accepted_tokens.append(token_id)
                num_accepted += 1
            else:
                # Reject candidate: sample recovery token from normalized residual distribution
                p_dist = target_probs[i]
                q_dist = draft_probs[i]
                residual = torch.clamp(p_dist - q_dist, min=0.0)
                residual_sum = residual.sum()

                if residual_sum > 1e-8:
                    recovery_probs = residual / residual_sum
                else:
                    recovery_probs = p_dist

                recovery_token = torch.multinomial(recovery_probs, num_samples=1).item()
                accepted_tokens.append(recovery_token)
                return torch.tensor(accepted_tokens, device=draft_tokens.device), num_accepted

        # If all K draft tokens are accepted, draw free bonus token from final target distribution
        bonus_probs = target_probs[k]
        bonus_token = torch.multinomial(bonus_probs, num_samples=1).item()
        accepted_tokens.append(bonus_token)

        return torch.tensor(accepted_tokens, device=draft_tokens.device), num_accepted
from __future__ import annotations

import torch
import torch.nn as nn
import torch.nn.functional as F


def build_tree_attention_mask(
    parent_indices: list[int],
    device: torch.device,
) -> torch.Tensor:
    """
    Constructs a 2D causal tree attention mask from parent lineage indices.

    Args:
        parent_indices: List where parent_indices[i] is the parent node index of node i.
                        Root node has parent index -1.
    Returns:
        mask: Boolean attention mask of shape (N, N) where mask[i, j] is True if j is an ancestor of i.
    """
    n = len(parent_indices)
    mask = torch.zeros(n, n, dtype=torch.bool, device=device)

    for i in range(n):
        curr = i
        while curr != -1:
            mask[i, curr] = True
            curr = parent_indices[curr]

    return mask


class SpeculativeInferenceEngine:
    """
    End-to-end Speculative Decoding Coordinator.
    Manages draft generation, target parallel evaluation, and KV cache synchronizations.
    """

    def __init__(
        self,
        target_model: nn.Module,
        draft_model: nn.Module,
        sampler: SpeculativeSampler,
        lookahead_k: int = 4,
    ) -> None:
        self.target_model = target_model
        self.draft_model = draft_model
        self.sampler = sampler
        self.k = lookahead_k

    @torch.no_grad()
    def generate_step(
        self,
        prefix_ids: torch.Tensor,
    ) -> tuple[torch.Tensor, int]:
        """
        Executes one speculative decoding round.

        Args:
            prefix_ids: Current context token tensor of shape (1, seq_len)
        Returns:
            emitted_ids: Newly accepted tokens for this round
            accepted_count: Number of proposed tokens verified
        """
        device = prefix_ids.device
        current_seq = prefix_ids.clone()

        # Step 1: Draft Model sequentially proposes K tokens
        draft_tokens = []
        draft_prob_list = []

        for _ in range(self.k):
            draft_logits = self.draft_model(current_seq)[:, -1, :]
            draft_token = self.sampler.sample_token(draft_logits)
            draft_prob = F.softmax(draft_logits / self.sampler.temperature, dim=-1)

            draft_tokens.append(draft_token)
            draft_prob_list.append(draft_prob)
            current_seq = torch.cat([current_seq, draft_token.unsqueeze(0)], dim=-1)

        draft_tokens = torch.cat(draft_tokens, dim=0)  # Shape: (K,)
        draft_probs = torch.cat(draft_prob_list, dim=0)  # Shape: (K, V)

        # Step 2: Target Model verifies full candidate sequence in one parallel pass
        full_candidate_seq = torch.cat([prefix_ids, draft_tokens.unsqueeze(0)], dim=-1)
        target_logits = self.target_model(full_candidate_seq)[0]  # Shape: (seq_len + K, V)

        # Slice target logits corresponding to candidate positions
        start_idx = prefix_ids.shape[-1] - 1
        relevant_target_logits = target_logits[start_idx : start_idx + self.k + 1]
        target_probs = F.softmax(relevant_target_logits / self.sampler.temperature, dim=-1)

        # Step 3: Rejection sampling verification
        emitted_tokens, accepted_count = self.sampler.verify_tokens(
            draft_tokens, draft_probs, target_probs
        )

        return emitted_tokens, accepted_count

Empirical Benchmark Evaluation

Quantitative performance benchmarking comparing Standard Autoregressive Decoding, Vanilla Speculative Decoding, Medusa, and EAGLE-2 across diverse workloads on an NVIDIA H100 GPU:

1. Generation Speedup Across Task Domains (Target: LLaMA-3 70B Instruct)

Speculative MethodDraft ConfigurationCode Generation (HumanEval)Mathematical Reasoning (GSM8K)General Chat (MT-Bench)Creative Writing
Autoregressive (Baseline)None () () () ()
Vanilla SpeculativeLLaMA-3 8B Draft () () () () ()
Medusa-14 Non-Autoregressive Heads () () () ()
EAGLE-2Autoregressive Feature Head () () () ()

2. Analysis of Domain-Specific Acceptance Rates:

  • Code & Formal Syntax (): High structural predictability (keywords, indentation, standard library signatures) enables high draft acceptance rates, yielding over wall-clock speedup.
  • Creative Writing (): High semantic entropy and diverse vocabulary reduce draft alignment, lowering speedup to approximately .

Troubleshooting Common Speculative Decoding Faults in Serving Systems

1. KV Cache Rollback and Invalidation

  • Symptom: Generated text degenerates into garbled repetitions or hallucinations after the first rejected speculative token.
  • Root Cause: When the target model evaluates candidate tokens in parallel, its KV cache stores activations for all tokens. When candidate is rejected, remaining positions are invalid. Failing to truncate the KV cache length back to position corrupts future attention operations.
  • Remedy: Always maintain a sequential sequence length pointer; reset the KV cache sequence length explicitly:
    # Truncate KV Cache to exact verified prefix length
    kv_cache.truncate(new_seq_len=valid_prefix_len)

2. High Batch Size Performance Saturation

  • Symptom: Speculative decoding provides a speedup at batch_size = 1, but drops to (slower than baseline) when batch_size > 16.
  • Root Cause: At high batch sizes, the target model transitions from memory-bandwidth bound to compute-bound. Speculative candidate verification increases total FLOPs by , inducing compute saturation.
  • Remedy: Implement Dynamic Speculation Gating: dynamically bypass speculative decoding and revert to pure autoregressive decoding whenever server request concurrency exceeds the GPU arithmetic intensity saturation threshold.

3. Temperature Zero (Greedy Decoding) Branch Inefficiency

  • Symptom: Running modified rejection sampling with temperature = 0 triggers divide-by-zero or non-deterministic resampling errors.
  • Root Cause: Rejection sampling is defined over stochastic distributions. At zero temperature, distributions collapse to Dirac delta functions ().
  • Remedy: For greedy decoding, replace rejection sampling with exact token matching:
    # Greedy Speculative Acceptance
    accepted = (draft_tokens == target_tokens)

References

  1. Leviathan, Y., Kalman, M., & Matias, Y. (2023). Fast Inference from Transformers via Speculative Decoding. International Conference on Machine Learning (ICML 2023).
  2. Chen, C., Borgeaud, S., Irving, G., Lespiau, J. B., Sifre, L., & Jumper, J. (2023). Accelerating Large Language Model Decoding with Speculative Sampling. arXiv:2302.01318.
  3. Cai, T., Li, Y., Geng, Z., Peng, B., Lee, J. D., & Chen, T. (2024). Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads. arXiv:2401.10774.
  4. Li, Y., Wei, F., Zhang, C., & Zhang, H. (2024). EAGLE: Speculative Sampling Requires Rethinking Feature Uncertainty. International Conference on Machine Learning (ICML 2024).
  5. Miao, X., Oliaro, G., Zhang, Z., Wang, X., Wang, Z., Zhu, R., … & Jia, Z. (2024). SpecInfer: Accelerating Generative LLM Serving with Tree-based Speculative Inference and Verification. ASPLOS 2024.


Cite this Explanation

@article{ailinkdeeptech2026speculativedecoding,
  title={Speculative Decoding: Mathematical Foundations, Rejection Sampling Proofs, Tree Attention (Medusa & EAGLE), and Production PyTorch Serving},
  author={AILinkDeepTech},
  journal={AILinkDeepTech Algorithm Explanations},
  year={2026},
  url={https://ailinkdeeptech.com/research/speculative_decoding/}
}

Related Explanations