# 10. Deep Dive into LLM Speculative Sampling (Part 1)

> This article provides an in-depth look at Speculative Sampling, a powerful acceleration technique for LLM inference and deployment. It reviews classic deterministic sampling methods (Greedy, Beam Search), probabilistic approaches (Top-k, Top-p), and truncation sampling, then reveals the key insight that LLM output distributions are the sum of the true distribution and a smoothed distribution, along with an entropy-based dynamic truncation formula.

- Source: https://www.waytoagi.com/en/kb/learning-path/llm-speculative-sampling-part1
- Original (Feishu, Chinese): https://waytoagi.feishu.cn/wiki/U1BywrrxTibXOAkqF5Yc2uWynRh
- Updated: 2026-10-25

---

> 🔗 Original Link: [https://zhuanlan.zhihu.com/p/701465...](https://zhuanlan.zhihu.com/p/701465989)

> ⏰ Publication Time: 2024-06-04 09:21:17 (UTC+8)

> Due to formatting difficulties with the equations, it is recommended to visit the Zhihu link above for the full version.


## Update History

| Update Time | Update Content |
| --- | --- |
| 2024.06.04 | First edition of the official version completed |


## Introduction

Hello everyone, I’m Xiao A. In the previous two chapters, we covered quantization-related knowledge in LLM deployment. Starting from this chapter, we will introduce another important deployment acceleration technique: **Speculative Sampling**. This topic will also be divided into two parts:

- **Part 1 (this article)**: Introduces basic sampling strategies, including deterministic sampling, random sampling, and truncated sampling. It then provides a detailed explanation of the naive version of speculative sampling and its mathematical principles, followed by two representative optimization approaches.
- **Part 2**: We will explore the principles of self-speculative sampling, including the widely discussed Medusa sampling. Finally, we will introduce the Jacobi decoding algorithm and related improvement ideas.

Today we will cover Part 1. Buckle up and let’s get started~

PS: Long-read warning — this article is approximately 10,000 words. Liking, following, and reading on a computer will provide a much better experience~ (^_^)

## Common Sampling Strategies

We know that the output of an LLM is a probability distribution over the vocabulary. The sampling strategy directly determines the kind of output we obtain. Sometimes we want completely deterministic results, while other times we want richer and more interesting outputs. Below we introduce two major categories of sampling methods: **deterministic sampling** and **probabilistic sampling**. We will also focus on **truncation sampling**, which offers deep insights within probabilistic sampling.

### Deterministic Sampling

As the name suggests, deterministic sampling produces fixed, reproducible outputs. It is essentially a search process. Common methods include Greedy Search and Beam Search. The following diagram is adapted from [this article](https://deci.ai/blog/from-top-k-to-beam-search-llm-decoding-strategies/).

- **Greedy Search**: At each step, it selects the token with the highest probability. This approach easily falls into repetitive “repeater” loops.

- **Beam Search**: It maintains a beam of size *k*. For every path in the current beam, it expands the next token, then selects the top *k* paths with the highest cumulative probability as the new beam. This continues iteratively. Although it increases computation, the output is more deterministic while also being richer. Note that when *k*=1, it degenerates into Greedy Search.

![](https://www.waytoagi.com/api/kb-media/S6HDbEpJSoM5F8xneBUc1t0InNf)

### Probabilistic Sampling

Probabilistic sampling draws tokens according to the probability distribution. The three most common methods are:

- **Multinomial Sampling**: Pure random sampling directly from the probability distribution. It can easily select words with extremely low probability.

- **Top-k Sampling**: Random sampling is performed within the top *k* candidates by probability rank. Renormalization is applied before sampling. The parameter *k* is fixed, making it relatively hard to tune.

- **Top-p Sampling** (also known as Nucleus Sampling): First sort the output probabilities from largest to smallest, then perform random sampling within the smallest set of candidates whose cumulative probability reaches *p*. Renormalization is also required. It is essentially a dynamic version of Top-k and is widely used in practice.

![](https://www.waytoagi.com/api/kb-media/QMPFbzOqPoVEFZx7CuaccXGznee)

### Truncation Sampling

As mentioned earlier, Top-p sampling with its dynamic cutoff performs well in practice, but it still has bad cases. For example, suppose *p*=0.95, the first token has a probability of 0.96, the second has 0.03, and the rest sum to 0.01. According to the Top-p rule, the second token would be discarded. However, among the remaining tokens, the second one actually has a relatively high probability and should be considered.

**Truncation Sampling** (Truncation Sampling as Language Model Desmoothing) attempts to understand the characteristics of the probability distribution learned by LLMs from a more fundamental perspective and improves upon the above issue. A key insight is that the output of an LLM is actually **the superposition of the true distribution and a smoothed distribution**:

- The true distribution is truncated — some words never appear, so their probability is strictly 0.
- Because LLMs are neural networks, their outputs are continuous and smooth. This smoothness pulls the originally truncated true distribution into a long tail.

![](https://www.waytoagi.com/api/kb-media/ZhPObZgW8ofZ9Cx3zZwcmUEUnVf)

To understand why LLM outputs tend to be smoothed, we can first look at the Cross Entropy loss function used to train LLMs:

$$
\text{CE}(P,Q)=-\sum_x P(x)\log Q(x)
$$

where *P(x)* is the ground-truth distribution and *Q(x)* is the distribution predicted by the LLM. Suppose the true distribution *P(x)* is bimodal, as shown below.

- When *Q(x)* can only cover one of the peaks, the CE loss introduces huge errors in regions where *P(x)≠0* but *Q(x)≈0* (left figure below).
- In this case, the LLM network tends to learn the smoothed distribution shown in the right figure.

![](https://www.waytoagi.com/api/kb-media/KFrCbrWyKogjt5xdjxNcgGKlnvo)

In summary, we can conclude that:

- Cross Entropy (and Forward KL) forces the neural network to assign corresponding *Q(x)* values to all tokens where the true distribution *P(x)≠0*.
- This requires the LLM to accurately predict exactly which tokens have *P(x)≠0*, which is difficult. Therefore, the model’s solution is to assign a small probability mass to every token.
- The result is a smoothed distribution *Q(x)*.

**Back to the Original Sampling Problem**

Suppose we accept that the LLM output distribution is the superposition of the true distribution and a smoothed distribution. The problem then simplifies to: **Given the LLM’s output distribution, how do we recover the true distribution and then sample from it?**

Here is the conclusion first. The method is to compute the LLM’s entropy \( h_\theta(x_{<i}) \), set \( \epsilon = 0.0009 \) and \( \alpha = 0.03 \), and calculate \( \eta \) using the following formula. Finally, use \( \eta \) as the truncation threshold: select the candidate set above this threshold, renormalize the probabilities, and perform random sampling.

$$
\eta = \min(\epsilon, \alpha \exp(-h_\theta(x_{<i})))
$$

Readers interested in the mathematical derivation can continue; those who are not can skip directly to the next section.

First, we mathematically decompose the LLM’s output probability as follows (the expression differs slightly from the original paper):

$$
P_\theta(X_i \mid x_{<i}) = (1 - \lambda_{x_{<i}}) \cdot P^*(X_i \mid x_{<i}) + \lambda_{x_{<i}} \cdot Q(X_i \mid x_{<i})
$$

where

- \( \text{Prob}(X_i \mid x_{<i}) \) denotes the probability distribution of the token at position \( i \), given all preceding tokens.
- \( P_\theta(X_i \mid x_{<i}) \) is the output distribution produced by the LLM.
- \( P^*(X_i \mid x_{<i}) \) represents the true underlying distribution.
- \( Q(X_i \mid x_{<i}) \) represents the smoothing distribution.
- \( \lambda_{x_{<i}} \) is the smoothing intensity (the larger the value, the stronger the smoothing), with \( \lambda_{x_{<i}} \in [0, 1) \).
- We further define the second term \( Q'(X_i \mid x_{<i}) = \lambda_{x_{<i}} \cdot Q(X_i \mid x_{<i}) \) as the smoothing distribution modulated by the smoothing intensity \( \lambda_{x_{<i}} \).

Among these, \( P_\theta(X_i \mid x_{<i}) \) can be obtained with a single forward pass of the LLM. \( P^*(X_i \mid x_{<i}) \) is difficult to obtain directly, while \( Q(X_i \mid x_{<i}) \) requires certain prior assumptions. This paper assumes \( Q \) follows a uniform distribution over the vocabulary \( \mathcal{V} \) with a small fluctuation range:

$$
Q(X_i \mid x_{<i}) \in \left( \frac{1 - \delta}{|\mathcal{V}|}, \frac{1 + \delta}{|\mathcal{V}|} \right)
$$

Our goal is to obtain the probability density \( \eta \) of \( Q'(X_i \mid x_{<i}) = \lambda_{x_{<i}} \cdot Q(X_i \mid x_{<i}) \). Then, any token whose probability under \( P_\theta(X_i \mid x_{<i}) \) is smaller than \( \eta \) can be safely truncated. This guarantees that the maximum probability of any truncated token will not exceed \( \eta \).

The expression for \( Q'(X_i \mid x_{<i}) \) depends on the coefficient \( \lambda_{x_{<i}} \). There are two ways to choose \( \lambda_{x_{<i}} \):

- \( \bar{\lambda} \): a context-independent absolute probability. We simply fix a relatively small value, e.g., \( \bar{\lambda} = 0.2 \).
- \( \bar{\lambda}_{x_{<i}} \): a context-dependent relative probability. The author’s key insight is that the larger (i.e., more uniform) the entropy of the true distribution \( P^*(X_i \mid x_{<i}) \), the smaller the smoothing intensity \( \bar{\lambda}_{x_{<i}} \) should be.

Here the author introduces a clever prior by linking the smoothing intensity in the context-dependent case to the entropy of the true distribution. Specifically, it is assumed that the entropy of the smoothed probability distribution \( Q'(X_i|x_{<i}) \) after modulation by \( \lambda_{x<i} \) is positively correlated with the entropy of the true distribution \( P^*(X_i|x_{<i}) \). Furthermore, assuming \( Q'(X_i|x_{<i}) \) remains a uniform distribution, we have:

$$
H(Q') = -\sum_{j=1}^{N} \frac{1}{N} \ln \frac{1}{N} \propto H(P^*) = h(x_{<i})
$$

From this, the probability density of \( Q'(X_i|x_{<i}) \) can be derived as:

$$
Q'(X_i|x_{<i}) = \frac{1}{N} \propto \exp(-h(x_{<i}))
$$

That is:

$$
Q'(X_i|x_{<i}) = \alpha \exp(-h(x_{<i}))
$$

Additionally, since the maximum probability density of the known \( Q(X_i|x_{<i}) \) is:

$$
Q(X_i|x_{<i}) = \frac{1+\delta}{|\mathcal{V}|}
$$

The final smoothing intensity is defined as the minimum of the absolute and relative probability cases:

$$
\lambda_{x<i} = \min(\bar{\lambda}, \bar{\lambda}_{x<i})
$$

Consequently, the probability density of \( \eta \) for \( Q'(X_i|x_{<i}) \) becomes:

$$
\begin{aligned}
\eta &= \lambda_{x<i} \cdot Q(X_i|x_{<i}) \\
&= \min(\bar{\lambda} \cdot Q(X_i|x_{<i}), \bar{\lambda}_{x<i} \cdot Q(X_i|x_{<i})) \\
&= \min\left( \frac{\bar{\lambda} \cdot (1+\delta)}{|\mathcal{V}|}, Q'(X_i|x_{<i}) \right) \\
&= \min\left( \frac{\bar{\lambda} \cdot (1+\delta)}{|\mathcal{V}|}, \alpha \exp(-h(x_{<i})) \right)
\end{aligned}
$$

However, the author noticed that both terms inside the \(\min\) are difficult to compute directly, so approximations were introduced:

- The first term is directly replaced with \(\epsilon\)
- The second term replaces \( h(x_{<i}) \) with the model-estimated \( h_\theta(x_{<i}) \)

Thus, the final probability density threshold is:

$$
\eta = \min(\epsilon, \alpha \exp(-h_\theta(x_{<i})))
$$

Typically, \(\epsilon = 0.0009\) and \(\alpha = \sqrt{\epsilon}\).

### Summary

This section introduced basic deterministic sampling methods (such as Greedy Search and Beam Search) and stochastic sampling methods (such as Top-k and Top-p), with a particular focus on truncation sampling. The truncation sampling approach contains two important insights:

- The output of an LLM is essentially the superposition of the true distribution and a smoothed distribution.
- The larger (more uniform) the entropy of the true distribution, the smaller the smoothing intensity should be.

## Naive Speculative Sampling

LLM inference consists of two phases: prefill and decode. The former can reach speeds of 1k–50k tokens/sec, while the latter is typically only 10–500 tokens/sec — a difference of up to two orders of magnitude. The primary bottleneck limiting decode speed is the extremely low arithmetic intensity (compute-to-memory-access ratio) of GEMV operations.

**Speculative Sampling** introduces a two-stage approach of *draft* and *verify*. In the verify stage, it attempts to infer multiple tokens simultaneously, altering the workload pattern and thereby improving the compute-to-memory-access ratio.

### Core Idea

Speculative Sampling was independently proposed by teams at Google and DeepMind around the same time. The key insight is the observation that during decoding, the difficulty of generating tokens varies significantly across positions. Sometimes a smaller model can generate the token just as well; other times, only the large model can produce satisfactory results.

Building on this, during the decoding phase we maintain both a large model and a small model. The small model quickly generates a block of tokens, which is then fed into the large model to verify whether its proposals should be accepted.

As shown below, the green tokens are proposals generated by the small model. These are fed into the large model in one pass. The model checks them from left to right; the first red token is the first one rejected. A new token (blue) is then resampled according to a specific sampling rule.

![](https://www.waytoagi.com/api/kb-media/ZkonbdaO4otSA6x6aQwcZ2UEnHd)

It is clear that speculative sampling does not reduce the total computational cost of the large model. Instead, it increases the density of the compute-to-memory-access ratio. The time the large model takes to process one token is roughly equal to the time it takes to process an entire block. The speedup comes from better utilization of GPU hardware resources. In the ideal case, if the small model’s acceptance rate is high, inference time can be reduced by several times — an elegant solution.

Below we examine the acceptance and rejection strategy in detail. The pseudocode is as follows:

![](https://www.waytoagi.com/api/kb-media/GVIibJ5pRo79FIxFLLtcdl4znGg)

Where:

- \( q(\cdot|\cdot) \) is the output probability distribution of the large model, and \( p(\cdot|\cdot) \) is that of the small model.
- The small model generates a block of \( K \) tokens at once.
- **Acceptance condition**:
  - If the small model samples a token \( \tilde{x} \), and the large model’s probability \( q(\tilde{x}) \) is greater than the small model’s \( p(\tilde{x}) \), intuitively the token should not be less likely under the large model. Therefore, we should accept it with higher probability.
  - This probability is quantitatively expressed as \( r_0 = \min\left(1, \frac{q(\tilde{x})}{p(\tilde{x})}\right) \).
  - We roll a die \( r = U[0,1] \). If \( r < r_0 \), accept; otherwise, reject.

- **Resampling method**:
  - Conclusion: When rejection occurs, we filter all tokens \( x \) where \( q(x) > p(x) \), normalize their probabilities, and sample from this renormalized distribution.
  - The quantitative formulation is:

  $$
  P(x=\tilde{x}) = \frac{\max(q(\tilde{x})-p(\tilde{x}), 0)}{\sum_{x'}\max(q(x')-p(x'), 0)}
  $$

### Derivation of the Core Process

Following the notation from DeepMind’s paper *“Accelerating Large Language Model Decoding with Speculative Sampling”*, we now derive the full speculative sampling process.

Essentially, we want to verify that after applying the above complex strategy, the probability \( P(x=\tilde{x}) \) remains equal to the original target probability \( q(x=\tilde{x}) \).

The probability decomposition is as follows:

![](https://www.waytoagi.com/api/kb-media/GaIebhj5UoIak9xO4XBcrksanO2)

There are two possible paths to sampling \( \tilde{x} \):

- **Path 1**: The small model \( p(\cdot|\cdot) \) directly samples \( \tilde{x} \) and it is successfully accepted.
- **Path 2**: The small model samples a different value \( x \neq \tilde{x} \), rejection occurs, and \( \tilde{x} \) is then obtained through resampling.

**Note on Path 1:** If a rejection occurs for \( x \sim \tilde{x} \), it is impossible to obtain \( x \sim \tilde{x} \) through resampling. This is because a rejection indicates that \( q(x)q(\tilde{x}) < p(x)p(\tilde{x}) \). Consequently, in the resampling step, \( \max(q(x) - p(x), 0) \cdot \max(q(\tilde{x}) - p(\tilde{x}), 0) = 0 \), making it impossible to resample \( x \sim \tilde{x} \).

Next, we compute the probabilities for the two paths separately.

**Path 1**

$$
P_1 = p(\tilde{x}) \cdot \min\left(1, \frac{q(\tilde{x})}{p(\tilde{x})}\right) = \min(p(\tilde{x}), q(\tilde{x}))
$$

**Path 2**

$$
\begin{align*}
P_2 &= \sum_{x' \neq \tilde{x}} p(x')\left[1 - \min\left(1, \frac{q(x')}{p(x')}\right)\right] \cdot \frac{\max(q(\tilde{x}) - p(\tilde{x}), 0)}{\sum_{x''} \max(q(x'') - p(x''), 0)} \\
&= \sum_{x' \neq \tilde{x}} \left[p(x') - \min(p(x'), q(x'))\right] \cdot \frac{\max(q(\tilde{x}) - p(\tilde{x}), 0)}{\sum_{x''} \max(q(x'') - p(x''), 0)} \\
&= \sum_{x' \neq \tilde{x}} \max(p(x') - q(x'), 0) \cdot \frac{\max(q(\tilde{x}) - p(\tilde{x}), 0)}{\sum_{x''} \max(q(x'') - p(x''), 0)}
\end{align*}
$$

The above expression is somewhat complex, but we can make the following observations:

- The summation is missing the term where \( x' = \tilde{x} \). However, since the following equality holds, we can safely add this term back:

$$
\max(p(\tilde{x}) - q(\tilde{x}), 0) \cdot \max(q(\tilde{x}) - p(\tilde{x}), 0) = 0
$$

- The numerator and denominator of the resampling factor are independent of the summation index \( x' \), so we can factor them out.

Thus, we can simplify \( P_2 \) as follows:

$$
\begin{align*}
P_2 &= \frac{\max(q(\tilde{x}) - p(\tilde{x}), 0)}{\sum_{x''} \max(q(x'') - p(x''), 0)} \cdot \sum_{x'} \max(p(x') - q(x'), 0) \tag{1}
\end{align*}
$$

Next, we need to prove a counter-intuitive but correct lemma:

$$
\begin{align*}
\sum_{x} \max(p(x) - q(x), 0) = \sum_{x} \max(q(x) - p(x), 0) \tag{2}
\end{align*}
$$

**Hint:** Readers who are interested can derive it themselves. Starting from equation (3), replace the leading 1 with \( \sum_x p(x) \) and \( \sum_x q(x) \) respectively, then expand and simplify normally.

$$
\begin{align*}
1 - \sum_{x} \min(p(x), q(x)) \tag{3}
\end{align*}
$$

Once we have equation (2), substituting it into equation (1) allows us to easily simplify \( P_2 \), yielding:

$$
P_2 = \max(q(\tilde{x}) - p(\tilde{x}), 0)
$$

Adding path 1 and path 2 yields:

$$
P(x=\tilde{x})=P_1+P_2=\min(p(\tilde{x}), q(\tilde{x}))+\max(q(\tilde{x})-p(\tilde{x}), 0)=q(\tilde{x})
$$

$$
\begin{align*}
P(x=\tilde{x})&=P_1+P_2\\
&=\min(p(\tilde{x}), q(\tilde{x}))+\max(q(\tilde{x})-p(\tilde{x}), 0) \\
&=q(\tilde{x})
\end{align*}
$$

### Derivation of Core Metrics

The Google paper *Fast Inference from Transformers via Speculative Decoding* contains derivations for many core metrics. They are consolidated and explained below.

**Average Acceptance Rate**

Based on the speculative sampling algorithm described earlier, the average acceptance rate $\alpha$ can be calculated, where $q(x)$ is the output distribution of the large model (LLM) and $p(x)$ is the output distribution of the small model.

$$
\begin{aligned}
\alpha&=\mathbb{E}_{x \sim p(x)}(r_0(x)) \\
&=\mathbb{E}_{x \sim p(x)}\left(\min\left(1, \frac{q(x)}{p(x)}\right)\right) \\
&= \sum_x \min(p(x), q(x))
\end{aligned}
$$

**Average Generation Length**

If the verification process is viewed as a sequence of $k$ consecutive Bernoulli trials with acceptance probability $\alpha$, the output token length ranges from $[1, k+1]$ according to the algorithm flow. There are three cases:

- Case 1: If the first token is rejected by the large model, the large model’s sampled output is used directly, resulting in a generation length of $L=1$.

- Case 2: If the $t$-th token is accepted by the large model but the $(t+1)$-th token is rejected, the generation length is $L=t+1$. Note that $t \leq k-1$.

- Case 3: If all $k$ tokens are accepted by the large model, the theoretical maximum generation length should be $L=k$. However, during batched inference the large model performs one extra forward pass at negligible extra cost, so the final generation length becomes $L=k+1$.

Analyzing the three cases above, Case 1 can be regarded as a special case of Case 2 where $t=0$. Therefore, the final average generation length is the sum of all three cases:

$$
\begin{align}
L=\mathbb{E}(\text{# generated tokens})&=\sum_{t=0}^{k-1}\alpha^t(1-\alpha)\cdot(t+1) + \alpha^k(k+1)\tag{4}
\end{align}
$$

We first focus on the first term:

$$
\begin{align}
S \triangleq\sum_{t=0}^{k-1}\alpha^t(1-\alpha)\cdot(t+1)=(1-\alpha)\sum_{t=0}^{k-1}\alpha^t \cdot (t+1)\tag{5}
\end{align}
$$

Multiplying both sides of the above equation by $\alpha$ gives:

$$
\begin{align}
\alpha \cdot S =(1-\alpha)\sum_{t=0}^{k-1}\alpha^{t+1} \cdot (t+1)\tag{6}
\end{align}
$$

Subtracting equation (6) from equation (5) yields:

$$
\begin{aligned}
(1-\alpha) \cdot S&= (1-\alpha)\sum_{t=0}^{k-1}\alpha^t \cdot (t+1)-(1-\alpha)\sum_{t=0}^{k-1}\alpha^{t+1} \cdot (t+1) \\
&= (1-\alpha)\left[\sum_{t=0}^{k-1}\alpha^t \cdot (t+1)-\sum_{t=0}^{k-1}\alpha^{t+1} \cdot (t+1)\right]
\end{aligned}
$$

**Left-Right Elimination**

By eliminating the term \(1 - \alpha\) on both sides and performing the variable substitution \(t = t + 1\) on the second summation, we obtain:

$$
\begin{align*}
S&=\sum_{t=0}^{k-1}\alpha^t \cdot t-\sum_{t=1}^{k}\alpha^{t} \cdot t \\
&=1+\left(\sum_{t=1}^{k-1}\alpha^t\right) -\alpha^k\cdot k \\
&=[1+\left(\sum_{t=1}^{k-1}\alpha^t\right)]-\alpha^k \cdot k \\
&=\sum_{t=0}^{k-1}\alpha^t-\alpha^k \cdot k\tag{7}
\end{align*}
$$

Substituting Equation (7) into Equation (1) yields:

$$
\begin{aligned}
L&=\mathbb{E}(\text{#generated tokens}) \\
&= S + \alpha^k(k+1) \\
&=\sum_{t=0}^{k-1}\alpha^t-\alpha^k \cdot k + \alpha^k(k+1) \\
&=\frac{1-\alpha^{k+1}}{1-\alpha}
\end{aligned}
$$

The visualization is shown below (\(\gamma\) denotes the lookahead size \(k\)):

![](https://www.waytoagi.com/api/kb-media/UsaebC6fDomctbx87IhcAPXRnmd)

**Theoretical Speedup**

We have already derived that the expected generation length is

$$
L=\frac{1-\alpha^{k+1}}{1-\alpha}
$$

Assume that decoding 1 token with the large language model and decoding \(k\) tokens in parallel both take time \(T\), while decoding one token with the small model takes time \(c \cdot T\). Then:

- The decoding throughput of speculative sampling is \(\frac{L}{c \cdot T \cdot k + T}\)
- The decoding throughput of the original algorithm is \(\frac{1}{T}\)

Therefore, the speedup ratio is

$$
\eta=\frac{L / (c\cdot T \cdot k + T)}{1/T}=\frac{L}{c\cdot k+1} =\frac{1-\alpha^{k+1}}{(1-\alpha)(c k+1)}
$$

**Optimal Lookahead Length**

For fixed \(\alpha\) and \(c\), the optimal lookahead length \(\hat{k}\) is the integer value of \(k\) that maximizes \(\eta\). The relationship can be plotted as follows (the vertical axis \(\gamma\) represents the optimal length \(\hat{k}\)):

![](https://www.waytoagi.com/api/kb-media/Q4c3bl9YXoQsggxKcoEcHu6pnkh)

### Related Experiments

The DeepMind version focuses on distributed scenarios with extremely large models. The draft model chosen has 4B parameters, while the target large model has 70B parameters. The draft model adopts a “short and fat” architecture (wider and shallower), which reduces communication overhead when performing tensor-parallelism across multiple machines.

![](https://www.waytoagi.com/api/kb-media/Qa7YbgCpvogKD3xoj0NcYYtGneg)

As \(K\) increases, the total time required to generate a fixed 128 tokens first decreases and then increases. On the XSum dataset, the optimal value is \(\hat{k}=3\). The analysis is as follows:

- In the middle plot below, the acceptance probability gradually decreases as \(k\) grows.
- In the right plot, the average latency per call increases with larger \(k\) because the small model must decode more tokens each time. However, the large model’s step size also increases. When the acceptance probability does not drop significantly, the overall latency still decreases (left plot).
- The acceptance rate on the programming dataset HumanEval is noticeably higher than on XSum, presumably because code has more regular character patterns and is easier to predict.

![](https://www.waytoagi.com/api/kb-media/F3vcbM5ClomlsOxiFZBc7XymnLY)

### Summary

This section mainly introduced the fundamental concepts of speculative sampling:

- Speculative sampling consists of two stages—draft and verify. The draft process is pure overhead; the verify process is what actually delivers acceleration.
- We derived in detail the mathematical principles behind the core mechanism of speculative sampling. From a statistical perspective, the speculative sampling algorithm is strictly equivalent to the original autoregressive decoding process.

- Based on the mathematical derivation, the calculation methods for the core metrics can be obtained. These include average acceptance rate, average generation length, theoretical speedup ratio, and optimal lookahead length.

- From the preliminary experimental results, the choice of lookahead length is a critical parameter. Both excessively large and excessively small values are suboptimal. The optimal value on small benchmarks is \(\hat{k}=3\).

## Optimizing Speculative Sampling

Recalling the theoretical speedup formula from earlier, where α is the average acceptance probability, k is the lookahead length, and c is the inference cost ratio of the draft model compared to the original LLM:

$$
\eta=\frac{L / (c\cdot T \cdot k + T)}{1/T}=\frac{L}{c\cdot k+1} =\frac{1-\alpha^{k+1}}{(1-\alpha)(c k+1)}
$$

It is easy to see that the two main directions for improving speculative sampling are:

- Increasing the draft proposal acceptance rate α
- Reducing the inference time of the draft process c

This section introduces several classic methods, summarized as follows:

| Method Name | Overview | Acceptance Rate | Inference Time | Publication Date |
| --- | --- | --- | --- | --- |
| SpecInfer | Increases the number of draft candidates to improve acceptance rate | Significantly improved | Slightly increased | 2023.05 |
| Online Speculative Sampling | Online updating of the draft model to improve acceptance rate | Significantly improved | Almost unchanged | 2023.10 |
| Cascade Speculative Drafting | Uses hierarchical sampling to accelerate draft inference | Almost unchanged | Significantly reduced | 2023.11 |
| Decoding Speculative Decoding | Redesigns the draft model to accelerate draft inference | Almost unchanged | Significantly reduced | 2024.02 |
| TriForce | Hierarchically solves speculative sampling for 128K long sequences, accelerating draft inference | Almost unchanged | Significantly reduced | 2024.04 |

### SpecInfer

SpecInfer primarily expands the number of draft candidate sequences in the speculative sampling process into a Tree structure. It also employs a parallelized algorithm during the Verification stage, which improves the acceptance probability, increases the average generation length, and thereby enhances the overall speedup.

The differences compared to traditional serial decoding and speculative sampling decoding are shown below. The bottom-right figure illustrates the SpecInfer method. The main distinctions are the Tree-based speculative process (Speculator) and the parallel verification process (Verifier).

![](https://www.waytoagi.com/api/kb-media/YY1kbbkvSoKQc2xiUIUcL0V2nrd)

**Speculator**

The model used in the speculative process is generally called an SSM (Small Speculative Model). Naive speculative sampling uses one SSM to generate a single sequence. This paper explores generating multiple sequences using the following approaches:

- Method 1: Multiple independent SSMs. Some model families have several small models, such as the OPT family with OPT-125M and OPT-350M. Each SSM independently generates one sequence.

- Method 2: Expansion-based token Tree. Uses the top-K tokens from a single SSM, similar to beam search tree expansion. Each path from the root node to a leaf node constitutes a sequence.

- Method 3: Merged-based token Tree. Adopts a boosting-inspired approach. Starting with a dataset and an initial SSM₁, samples on which SSM₁ makes mistakes are collected and used to train a separate SSM₂, and so on. This yields multiple SSMs, each generating one sequence.

Schematic diagrams for Methods 2 and 3 are shown below:

![](https://www.waytoagi.com/api/kb-media/MgfkbrCopo8zf5xQeL2c7ivRnhS)

The authors also investigated the impact of the Top-K hyperparameter K in Method 2 on the acceptance rate. They found that as K increases, the probability of the correct answer appearing in the token tree improves accordingly.

![](https://www.waytoagi.com/api/kb-media/NfoDbLHlmorgCsxbN5FcuEUvnIQ)

**Tree-based Parallel Decoding**

In naive speculative sampling, since there is only one sequence, the original model only needs to perform decoding once. However, in SpecInfer, because there are multiple speculative candidate sequences, an efficient decoding process is required to obtain the original model’s predictions for all candidate sequences.

If each candidate sequence were executed serially, the process would be extremely slow and the acceleration effect would not be achieved. Therefore, SpecInfer utilizes Tree-attention with masking, as shown below:

- Extract each token in the Tree individually. Based on its path dependency to the root node, identify all related tokens.
- Set the attention mask to true for related tokens and mark all others as invalid.

![](https://www.waytoagi.com/api/kb-media/QmyFbxvYYoPTruxuw52c0o2knig)

**Verifier**

The verification process is related to the sampling strategy.

- **Deterministic Greedy Sampling**. Simply verify tokens one by one; as soon as any token fails to satisfy the `argmax` condition, stop and select the longest valid sequence.

- **More diverse Stochastic Decoding**. Similar to the probabilistic strategy in naive speculative sampling, when a rejection occurs, the probability can be adjusted and the token can be resampled.

The figure below illustrates the Stochastic Decoding process:

![](https://www.waytoagi.com/api/kb-media/Ix8xbMfBLoUR13xAjLXcvW05nlg)

**Experimental Results**

Although generating multiple sequences during the speculative process introduces some overhead, it significantly improves the acceptance rate, which in turn increases the average acceptance length and yields better speedup. As shown below, the achieved speedup ranges from 1.5× to 2.8×.

![](https://www.waytoagi.com/api/kb-media/L9EJbVuhMoUxWMxgGwzc5rwcnic)

In the Tree Expansion process, search width is a critical parameter that balances average generation length and speculative overhead. It was found that setting K too large or too small is suboptimal; a moderate value (e.g., K=3) performs best.

![](https://www.waytoagi.com/api/kb-media/JayCbpK0Po8ucfxtCj9cyMwlnnd)

### Online Speculative Sampling

The practical effectiveness of speculative sampling is highly dependent on the accuracy of the draft model. To further increase the acceptance probability of the draft model, this method adopts an online distillation approach. Specifically, bad cases produced by the draft model during decoding are collected; once a sufficient number accumulate, the draft model is updated. The process is illustrated below.

![](https://www.waytoagi.com/api/kb-media/Jy5Ib31WUoku8VxAP5DcHrfAn5f)

As previously noted, the commonly used formulas for average generation length and theoretical speedup in speculative sampling are:

$$
\mathbb{E}(|\tilde{y}|)=\frac{1-\alpha^{k+1}}{1-\alpha}, \quad \mathbb{E}(\text{speedup})=\frac{1-\alpha^{k+1}}{(1-\alpha)(kc+1)}
$$

The authors plotted the following curves to demonstrate that $\alpha$ has a very significant impact on performance improvement.

![](https://www.waytoagi.com/api/kb-media/FkTlb2GvBoixqQxFerec2rmHnWd)

Experiments show that online distillation can improve the acceptance rate by 10–65%, corresponding to speedups of 1.2–3.1×.

![](https://www.waytoagi.com/api/kb-media/LEBgbHHF0o32NExIspVcghQdndU)

In practice, this approach is relatively complex. On one hand, the training and deployment frameworks are often different; on the other hand, models in the deployment stage are usually quantized, so fine-tuning may require QLoRA, which adds considerable engineering overhead.

### Cascade Speculative Drafting

This method applies a cascaded approach to speculative sampling by further decomposing the original draft model both vertically and horizontally, as shown below.

![](https://www.waytoagi.com/api/kb-media/AbOHbCqbuosBtHxCArpcCNU1npb)

**Horizontal Direction**

The authors first analyzed the acceptance rates at different token positions. It is easy to see that the acceptance probability of later tokens declines exponentially, because if an earlier token is rejected, subsequent tokens are not even considered. The trend is shown below.

![](https://www.waytoagi.com/api/kb-media/EeaZbyAWtoCGx2xFBvvcVaTyn45)

Their idea is that since later tokens have lower acceptance probabilities, smaller models can be used for them. Consequently, draft models closer to the beginning are larger, while those toward the end are progressively smaller. In the earlier figure, $M_{d_1}$ is the largest, $M_{d_2}$ is the next largest, and $M_{d_3}$ is the smallest.

**Vertical Direction**

If a draft model is still not fast enough, an even smaller draft-mini model is paired with it—essentially a recursive approach. In the figure above, for the tokens at the “of books” position, in addition to $M_{d_2}$, a smaller $M_{d_3}$ is used as the draft-mini model.

**Complex Interleaving**

In even more intricate cases, as shown on the left side of the figure for the draft model predicting the “Twice the number” position, vertical decomposition ($M_{d_1} \rightarrow M_{d_3}$) is first applied, followed by horizontal decomposition ($M_{d_2} \rightarrow M_{d_3}$). One might think that is the end, but another vertical decomposition ($M_{d_2} \rightarrow M_{d_3}$) follows afterward.

**Experimental Results**

Compared with standard speculative decoding (S Decoding), this method can further improve performance, but the gains are not significant. Given the added engineering complexity, the benefit does not appear to justify the cost.

![](https://www.waytoagi.com/api/kb-media/BZjXbcFnko4RxnxW2yOcVepLnAh)

### Decoding Speculative Decoding

**Focusing on the speed of the draft model, the paper proposes that a wider and shallower network can achieve a 40% improvement in overall speculative sampling inference speed compared to the baseline, while maintaining the same average generated length (TAR).**

It is already known that there are two main directions to improve the acceleration of speculative sampling: increasing the average generated length \( L \), or reducing the draft model latency \( c \).

**The Difficulty of Improving TAR**

The authors first analyze the challenges of increasing \( \text{TAR} \), as shown below:

- Improving \( \text{TAR} \) to a certain extent requires increasing the output consistency between the draft network and the original model. The intuitive approach is to use a larger draft model.
- Taking OPT-66B as the target model, increasing \( \text{TAR} \) from 5.0 to 6.0 requires upgrading the draft model from OPT-125m to OPT-6.7b — a 50× increase in model parameters.
- At this point, the denominator grows along with the numerator. To keep the overall speedup ratio the same as when using OPT-125m, the latency of the OPT-6.7b model would need to be reduced by 50%.

![](https://www.waytoagi.com/api/kb-media/MiJGbgc4ZowRIUxNtcrc8mq0nbf)

From this observation, the authors saw the need for a model architecture that maintains the same \( \text{TAR} \) while significantly reducing latency. They therefore conducted a simple exploration of network architectures.

**Low-Latency Networks with Equivalent TAR**

The authors briefly analyzed the impact of network width and depth on inference latency, with the following findings:

- The left figure fixes the model size at 350M parameters. As the number of layers increases while width is reduced, overall latency grows linearly with depth.
- The right figure fixes the width and linearly increases the number of layers, again showing that overall latency is directly proportional to the number of layers.

![](https://www.waytoagi.com/api/kb-media/SrR4bXukLoWFDBxxbtUcruGdnpX)

Based on these results, the authors concluded that, for the same number of parameters, wider and shallower networks achieve faster inference. To obtain such a model, they applied the Sheared-LLaMA pruning framework on the MMLU dataset and produced a new draft model called **NoFT-Wide-1.3B**. With nearly identical \( \text{TAR} \), this model halves the latency, ultimately improving speculative sampling throughput from 23.10 to 32.59 tokens/s — a 40% speedup.

![](https://www.waytoagi.com/api/kb-media/KQRWbxIrJoLXJDx3LI3ctGAhnj8)

The core idea is to find a network architecture that preserves \( \text{TAR} \) while reducing latency. Although the work lacks large-scale accuracy validation, the approach is worth referencing; the conclusions, however, still require further verification.

### TriForce

**Algorithm Principle**

TriForce is an optimization of speculative sampling tailored for 128K long-sequence scenarios. Its main idea is to introduce a two-stage speculative sampling process to reduce the sampling overhead for very long contexts, as illustrated below:

- **Stage 1** (orange): Uses an extremely small model, Llama-68M, combined with the memory-efficient KV-Cache method StreamingLLM as a mini-draft. The target draft length is \( \gamma_1 \) tokens.
- **Stage 2** (blue): Uses the original model size, Llama-7B-128K, with a partial KV-Cache (retrieval cache) as the draft model. The target draft length is \( \gamma_2 \) tokens.
- **Stage 3** (green): Uses the full original model Llama-7B-128K with the complete 128K KV-Cache for final verification.

![](https://www.waytoagi.com/api/kb-media/BuCEb5x0hoBL2ixq0W5cTa6lnzf)

The interaction among the three stages is shown below. Although it looks complex, it is essentially a two-level speculative sampling process. The key points are:

- There are three types of KV-Cache: \( C_q \) from StreamingLLM at Stage 1, \( C_r \) (retrieval cache) at Stage 2, and the full \( C_p \) at Stage 3.
- There are two model types: the tiny model Llama-68M denoted as \( M_q \), and the original Llama-7B-128K denoted as \( M_p \).
- The red box shows the interaction between Stage 1 and Stage 2: \( M_q + C_q \) performs speculative drafting for \( \gamma_1 \) tokens, which are then verified by \( M_p + C_r \). Suppose \( n \) tokens are accepted (\( n \leq \gamma_2 \)).
- The green box shows the final verification of these \( n \) tokens using the full \( M_p + C_p \).

![](https://www.waytoagi.com/api/kb-media/SBi2b5fEgojok6xX8HzcSi2enkf)

**Retrieval Cache**

**TriForce: Hierarchical Speculative Sampling for 128K Long Sequences**

Compared with conventional multi-level speculative sampling algorithms, the biggest innovation of TriForce is its attempt to solve the KV-Cache problem for 128K-long sequences. The starting point is the sparsity characteristic of KV-Cache, which has already been observed in papers such as StreamingLLM and H₂O. In general, only a small portion of the KV-Cache is critical, while the vast majority can be discarded. Different papers propose different selection algorithms. The details of these methods will be covered in depth by Xiao A in a later dedicated topic on long sequences.

Here we assume the input sequence is 120K tokens long and the model needs to generate 256 output tokens, with a per-layer KV-Cache budget of 4K. First, we can use the attention scores of the 256 ground-truth (GT) output tokens to vote and select the **top-4K** KV-Cache entries. Then, we attempt to reconstruct these 256 tokens using only the selected KV-Cache. The personal understanding of “reconstruction” is to check whether, when using only these 4K selected KV-Cache entries, the token with the highest predicted probability at each position remains the original GT token. The results are shown below:

- As seen in Figure (a), except for the first two layers which have very low reconstruction success rates, the remaining layers can basically recover the original output using only 4K KV-Cache entries. This indicates that the first two layers cannot be pruned, while higher layers can undergo KV-Cache pruning.

- Figure (c) shows a similar conclusion. The horizontal axis represents the number of output tokens. Layer 1 is particularly sensitive, while the other layers change very slowly as the number of output tokens increases.

![](https://www.waytoagi.com/api/kb-media/LczKbodaGoXmYjxa8XTc3xGynMg)

The authors originally intended to directly apply the StreamingLLM and H₂O methods. However, after testing them on real benchmarks, the results were unsatisfactory, as shown below. PG-19 is a long-document benchmark released by DeepMind, and Needle Retrieval refers to the “needle-in-a-haystack” test. Both methods suffer from significant accuracy degradation. Among them, the **Top-k** method represents the theoretical upper bound from an oracle perspective.

![](https://www.waytoagi.com/api/kb-media/BowxbtfIFo7fD5x93yDcsQIqnve)

To address this, the authors proposed an improved Retrieval-based method. The idea is relatively straightforward: first divide the 120K KV-Cache into chunks, then select all tokens from the few most relevant chunks as the final chosen KV-Cache. The feature vector of each chunk is obtained by simply averaging all the KV-Cache entries belonging to that chunk, as shown below.

![](https://www.waytoagi.com/api/kb-media/ADIfbVnfvo730mxSCH1cg3HNnYN)

It is easy to see that chunk size is a hyperparameter; too large or too small is suboptimal. Through ablation experiments, the authors found that a moderate size yields the best results.

![](https://www.waytoagi.com/api/kb-media/KE4nbAptEoCi7HxMLbVcXxxInLd)

In summary:

- For long sequences, the Retrieval Cache approach is relatively simple and appears to deliver promising results.
- Two-level speculative sampling introduces significant engineering challenges for implementation.

### Summary

This section mainly introduces optimization methods from two perspectives: increasing the acceptance rate α and reducing the draft model inference time c. Five representative methods are covered, as shown in the table below:

| Method Name                  | Overview                                      | Acceptance Rate | Inference Time | Publication Date |
|------------------------------|-----------------------------------------------|-----------------|----------------|------------------|
| SpecInfer                    | Increase the number of draft candidates to improve acceptance rate | Significantly improved | Slightly increased | 2023.05 |
| Online Speculative Sampling  | Online updating of the draft model to improve acceptance rate | Significantly improved | Almost unchanged | 2023.10 |
| Cascade Speculative Drafting | Use hierarchical sampling to accelerate draft inference | Almost unchanged | Significantly reduced | 2023.11 |
| Decoding Speculative Decoding| Redesign the draft model to accelerate draft inference | Almost unchanged | Significantly reduced | 2024.02 |
| TriForce                     | Hierarchical approach to solve 128K long-sequence speculative sampling and accelerate draft inference | Almost unchanged | Significantly reduced | 2024.04 |

## Final Thoughts

Overall, the key insights from this article are as follows:

- Beam Search degenerates into Greedy Search when *k*=1.
- Truncated sampling is the theoretical foundation of Top-k and Top-p sampling. It rests on two important assumptions: first, that LLM outputs are essentially a superposition of the true distribution and a smoothed distribution; second, that the smoother the true distribution (i.e., the higher its entropy), the weaker the smoothing strength should be.
- The naive speculative sampling algorithm can be rigorously proven mathematically to be completely equivalent to standard decoding. A critical hyperparameter is the lookahead length *k*; values that are too large or too small are suboptimal and require careful tuning based on the dataset.
- The practical benefit of speculative sampling ultimately depends on the theoretical speedup ratio, which is closely tied to the acceptance rate *α* and the draft model inference latency *c*.
- Methods to improve the acceptance rate *α* include:
  - **SpecInfer**: Expands the number of draft candidate sequences in the speculative sampling process into a tree structure and employs parallelized algorithms during the verification stage. This increases the acceptance probability, leading to longer average generation lengths and higher speedup.
  - **Online Speculative Sampling**: Adopts an online distillation approach. It collects “bad cases” from the draft model during decoding, accumulates them to a certain threshold, and then updates the draft model accordingly.
- Methods to reduce inference latency *c* include:
  - **Cascade Speculative Drafting**: Applies a cascaded speculative sampling strategy by further decomposing the original draft model both vertically and horizontally.
  - **Decoding Speculative Decoding**: Proposes wider and shallower networks that, while maintaining comparable average generation length (TAR), improve overall speculative sampling inference speed by 40% over baseline methods.
  - **TriForce**: An optimization for speculative sampling in 128K-long sequence scenarios. The core idea is to introduce a two-level speculative sampling mechanism to significantly reduce the sampling overhead for ultra-long sequences.

**PS**: Since the author (Xiao A) has not personally implemented every detail mentioned above, most of the content was synthesized bottom-up through studying code and carefully reading excellent papers. In essence, this is a compilation of others’ wisdom — a knowledge porter. It remains “talking on paper.” I sincerely welcome experts with real hands-on experience to critique and refine these ideas. Only through the collision of thoughts can sparks fly, and truth emerges clearer through debate.

**If you want to learn about Transformer algorithms in NLP, multimodal, and AIGC applications, knowledge of LLM distributed training, as well as LLM quantization, inference acceleration, and deployment/servitization, feel free to follow me — aaronxic ~**

## References

[GitHub - DefTruth/Awesome-LLM-Inference: A curated list of Awesome LLM Inference Papers with codes, TensorRT-LLM, vLLM, streaming-llm, AWQ, SmoothQuant, WINT8/4, Continuous Batching, FlashAttention, PagedAttention etc.](https://link.zhihu.com/?target=https%3A//github.com/DefTruth/Awesome-LLM-Inference%3Ftab%3Dreadme-ov-file%23Parallel-Decoding-Sampling)

[Attention Required! | Cloudflare](https://link.zhihu.com/?target=https%3A//deci.ai/blog/from-top-k-to-beam-search-llm-decoding-strategies/)

[KL Divergence: Forward vs Reverse? - Agustinus Kristiadi](https://link.zhihu.com/?target=https%3A//agustinus.kristia.de/techblog/2016/12/21/forward-reverse-kl/)

[Truncation Sampling as Language Model Desmoothing](https://link.zhihu.com/?target=https%3A//arxiv.org/abs/2210.15191)

[Accelerating Large Language Model Decoding with Speculative Sampling](https://link.zhihu.com/?target=https%3A//arxiv.org/abs/2302.01318)

[Fast Inference from Transformers via Speculative Decoding](https://link.zhihu.com/?target=https%3A//arxiv.org/abs/2211.17192)

[marsggbo: In-depth Understanding of Bayesian Optimization](https://zhuanlan.zhihu.com/p/53826787)

[Bayesian Optimization (BayesianOptimization) - CSDN Blog](https://link.zhihu.com/?target=https%3A//blog.csdn.net/Leon_winter/article/details/86604553)
