LLM 推理优化综述:KV Cache、Continuous Batching 与投机解码

梳理大语言模型推理中的采样策略、Prefill 与 Decode 性能分析、KV cache、Continuous batching、并行推理、Speculative decoding 与 Multi-token prediction,并讨论生成结果的可复现性。

Author

Nov, 29, 2026

7 min

Introduction

推理优化:

推理优化根据时间顺序主要分为四个模块:

  1. scheduling, 包括 continuous batching 和 chunked prefill
  2. model optimization, 主要是 fast kernels, parallelism
    1. flash attention, flash infer
    2. cuda graph
    3. kernel fusion
    4. overlap
    5. quantization
  3. kv cache optimization, 包括 paged attention 和 prefix caching
  4. sampler, 包括 structured outputs 和 speculative decoding.

推理的 metric:

  1. TTFT
  2. TPT
  3. throughput

推理优化的原则:

  1. never sits GPU idle
  2. never wastes memory
  3. never compute twice

Sampling Strategy

Strategies

每一步选择概率最高的 token

特点:完全确定,相同输入必定有相同输出。缺点是容易陷入局部最优,或者在长文本生成中陷入死循环

表达式

xt=arg⁡max⁡xP(x∣x<t)x_t = \arg\max_{x} P(x\mid x_{<t})

代码

import torch

def greedy_search(logits):
    # logits: (b * s, V)
    next_token = torch.argmax(logits, dim=-1)
    return next_token

Random Sampling

将 logits 经过 softmax 转化为概率分布之后,直接按照分布进行随机采样

xt∼P(x∣x<t)x_t \sim P(x\mid x_{<t})

特点是极具创意性和多样性,但缺点在于具有长尾效应,概率极低但非0的低质量 token 也可能被选中,导致生成文本语无伦次

import torch
import torch.nn.functional as F

def random_sampling(logits):
    # logits: (b * s, V)
    probs = F.softmax(logits, dim=-1)
    next_token = torch.multinomial(probs, num_samples=1)
    return next_token.squeeze(-1)

Temperature

对 logits 进行缩放

P(xi)=exp⁡(logitsi)/T∑jexp⁡(logitsj/T)P(x_i) = \frac{\exp(\mathrm{logits}_i) / T}{\sum_j \exp(\mathrm{logits}_j / T)}

作用机制:

  1. T→0T\to0: softmax 趋向于 one-hot vector, 效果等同于 greedy search
  2. T=1T=1: 保持原有的 softmax 概率分布
  3. T>1T>1: 平滑概率分布,使得原本概率低的 token 被选中的概率增加
import torch
import torch.nn.functional as F

def sample_with_temperature(logits, temperature=0.7):
    if temperature == 0:
        return torch.argmax(logits, dim=-1)

    scaled_logits = logits / temperature
    probs = F.softmax(scaled_logits, dim=-1)
    return torch.multinomial(probs, num_samples=1).squeeze(-1)

Top-K sampling

top-K 采样可以解决随机采样长尾低概率 token 导致的胡言乱语 (Fan et al., 2018). 其策略在于在采样前,只保留概率最高的前 K 个 token, 并对这 KK 个 token 的概率进行重新归一化,其余 token 彻底丢弃。

[pn1,…,pnK]=TopK(p(⋅∣x1:n)),xn+1∼Uniform({n1,…,nK})[p_{n_1},\dots,p_{n_K}]=\mathrm{TopK}(p(\cdot\mid x_{1:n})),\quad x_{n+1}\sim\mathrm{Uniform}(\{n_1,\dots,n_K\})

top-K 采样的问题在于对于某些分布很陡峭的情况,K 个 token 可能比较多,容易放进来脏数据;对于分布很平缓的情况,K 显的太小,会扼杀多样性。

import torch
import torch.nn.functional as F

def top_k_sampling(logits, k=50):
    top_values, top_indices = torch.topk(logits, k, dim=-1)

    filtered_logits = torch.full_like(logits, float('-inf'))
    filtered_logits.scatter_(-1, top_indices, top_values)
    probs = F.softmax(filtered_logits, dim=-1)
    return torch.multinomial(probs, num_samples=1).squeeze(-1)

Top-p sampling

Top-p sampling 通过动态调整候选集的大小来解决 top-K 的动态适应问题 (Holtzman et al., 2020). 其策略是将所有的 token 按照概率从大到小排序并计算累计概率, 当累计概率超过阈值 pp 时截断,只保留这个动态集合的 token

Vp=arg⁡min⁡∣Vp∣, s.t. ∑x∈VpP(x∣∣x1:n)≥pP(xi)={P(x∣∣x1:n)/∑x∈VpP(x∣∣x1:n), if x∈Vp0, otherwise\begin{aligned} &\mathcal{V}_p=\arg\min |\mathcal{V}_p|,\ \mathrm{s.t.}\ \sum_{x\in\mathcal{V}_p} P(x\mid \mid x_{1:n}) \geq p\\ &P(x_i) = \begin{cases} P(x\mid \mid x_{1:n})/\sum_{x\in\mathcal{V}_p} P(x\mid \mid x_{1:n}),&\text{ if } x\in \mathcal{V}_p\\ 0, &\text{ otherwise} \end{cases} \end{aligned}

Top-p sampling 的优势在于能够自适应 logits 的分布,如果模型对下一步很确定,候选集可能只有 1-2 个词,如果模型很犹豫,候选集会自动扩大到几十个词

import torch
import torch.nn.functional as F

def top_p_sampling(logits, p=0.9):
    # descending order
    sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
    sorted_probs = F.softmax(sorted_logits, dim=-1)

    # compute accumulative probs
    cumulative_probs = torch.cumsum(sorted_probs, dim=-1)

    # find top-p mask
    sorted_indices_to_remove = cumulative_probs > p
    sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
    sorted_indices_to_remove[..., 0] = 0

    # recover the logits indices
    indices_to_remove = sorted_indices_to_remove.scatter(-1, sorted_indices, sorted_indices_to_remove)

    filtered_logits = logits.clone()
    filtered_logits[indices_to_remove] = float('-inf')

    probs = F.softmax(filtered_logits, dim=-1)
    return torch.multinomial(probs, num_samples=1).squeeze(-1)

beam search 同时生成多条候选 sequence, 然后生成若干(由 num_beams) 决定之后,选取概率最高的 sequence 并重复这个过程。

其代码实现比较复杂,TODO

beam search 的问题在于在 open-ended generation 场景下效果不是很好,主要原因有:

  1. beam search 比较适用于输出长度(某种程度上)可预测,比如翻译或者总结。但是对于 open-ended generation, 其表现就会打折扣
  2. beam search 也会有重复输出的问题,我们必须使用 n-gram 等 penalty 来避免这个问题
  3. 对人类来说,我们想要生成更加 “surprise” 的文本,而 beam search 的输出则是 predictable.

Practices

transformers 里默认使用 greedy search, max_token 为 2020 对应的代码为

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from accelerate import Accelerator

device = Accelerator().device

tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to(device)

model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", dtype=torch.float16).to(device)
# explicitly set to default length because Llama2 generation length is 4096
outputs = model.generate(**inputs,
                         do_sample=False, # can be omited, grredy search
                         max_new_tokens=20)
tokenizer.batch_decode(outputs, skip_special_tokens=True)
'Hugging Face is an open-source company that provides a suite of tools and services for building, deploying, and maintaining natural language processing'
  1. Fan, A., Lewis, M., & Dauphin, Y. (2018). Hierarchical neural story generation. Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), 889–898.
  2. Holtzman, A., Buys, J., Du, L., Forbes, M., & Choi, Y. (2020). The Curious Case of Neural Text Degeneration. https://arxiv.org/abs/1904.09751

Inference roofline models

Prefilling

Decoding

PD disaggregation

KV Cache

KV cache 是什么,为什么要有 KV cache, KV cache 为什么会造成显存过大的问题,如何解决?

Why KV cache

How KV cache works

kv cache 拼接

def custom_attention(query, key, value, past_key_value=None):
    # key: [b, s, d]
    # value: [b, s, d]
    # past_key_value: [b, s', d]
    if past_key_value is not None:
        past_key, past_value = past_key_value
        key = torch.cat([past_key, key], dim=-2)
        value = torch.cat([past_value, value], dim=-2)

    attention_weights = query @ key.transpose(-2, -1)

    ...

    return output, (key, value)

dynamic cache

class DynamicCache(Cache):
    def __init__(self) -> None:
        self.key_cache = List[torch.Tensor] = []
        self.value_cache = List[torch.Tensor] = []

    def update(self, key_states, value_states, layer_idx, cache_kwargs):
        if layer_idex >= len(self.key_cache):
            self.key_cache.append(key_states)
            self.value_cache.append(value_states)
        else:
            self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=-2)
            self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=-2)


        return self.key_cache[layer_idx], self.value_cache[layer_idx]

attention 调用

class Attention(nn.Module):
    def forward(self, hidden_states, past_key_value=None, use_cache=False, layer_idx=None):
        query = self.q_proj(hidden_states)
        key = self.k_proj(hidden_states)
        value = self.v_proj(hidden_states)

        # ...
        if past_key_value is not None:
            key, value = past_key_value.update(key, value, layer_idx, cache_kwargs)

        attention_output = F.scaled_dot_product_attention(query, key, value)

        if use_cache:
            return attention_output, past_key_value

        return attention_output

其他 cache:

  1. DynamicCache: 默认实现,动态增长,灵活性高
  2. StaticCache: 预分配固定大小的张量,与 torch.compile 结合更好,可以减少动态形状带来的开销
  3. QuantizedCache: 量化缓存,对 K/V 进行量化来节省显存
  4. PagedAttentionCache: 借鉴 vLLM 的分页注意力思想,管理非连续显存块
class PagedAttentionCache:
    def __init__(self, block_size=16):
        self.physical_blocks = []
        self.block_tables = {}

    def allocate(self, sequence_id, num_tokens):
        logical_blocks = []
        for _ in range((num_tokens + block_size - 1) // block_size):
            block = self.physical_blocks.pop()
            logical_blocks.append(block)

        self.block_tables[sequence_id] = logical_blocks

    def get_kv(self, sequence_id, token_idx):
        block_idx = token_idx // block_size
        offset = token_idx % block_size
        physical_block = self.block_tables[sequence_id][block_idx]
        return self._read_block(physical_block, offset)

Analysis

KV cache 会把 decoding 过程从 GEMM 变成 GEMV (General Matrix-Vector Multiply)

How to optimize KV cache

  1. Ainslie, J., Lee-Thorp, J., de Jong, M., Zemlyanskiy, Y., Lebron, F., & Sanghai, S. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. The 2023 Conference on Empirical Methods in Natural Language Processing. https://openreview.net/forum?id=hmOwOZWzYE
  2. Shazeer, N. (2019). Fast Transformer Decoding: One Write-Head is All You Need. https://arxiv.org/abs/1911.02150

Continuous batching

Parallelism

追求高吞吐,用 EP, 追求低 latency 用 TP

  1. batch size 小时,追求 low latency 可以开 TP, 把参数放在不同的 rank 上
  2. batch size 大时,追求 high throughput, 可以开 EP, 提高通信速度

EP

MoE 的内存访问情况如下表所示

Stageboundcomponents
Attentionmemory bound(attention weights + kv cache)
dispatchcommunication bound(B*topK + H)
MoEmemory boundN * experts weights
combinecommunication(B*topK + H)

推理时,一般需要比较大的 EP size, 因为除了 MoE layer 之外,其他阶段耗时随 batch size 增加而减小,为了保证总耗时不变,我们就得增大 EP, 减少 单卡专家数量,降低 MoE 耗时。因此增大 EP 可以降低 MoE 耗时,提高吞吐

TP 和 EP 的对比

Practices

Speculative decoding

【llm基础】为什么说投机解码是无损的 - 燕雄飞的一天的文章 - 知乎

备忘:关于 LLM 的加速解码:speculative 解码 - 张 Mc 的文章 - 知乎

https://aclanthology.org/2023.findings-emnlp.257/

Speculative Decoding: 从Padding 的视角重新理解投机解码 - 笑渐不闻声渐悄的文章 - 知乎

https://proceedings.mlr.press/v202/leviathan23a.html

有没有speculative decoding的综述? - DeclK的回答 - 知乎

speculative decoding 使用了两个模型来加速推理

  1. draft model (MdM_d) , 用于生成一个 candidate sequence
  2. target model (MtM_t), 用于对 candidate sequence 进行验证

工作原理:

  1. drafting: 给定一个 prompt x1:nx_{1:n}, draft model 基于 prompt 生成一个包含 KK 个 token 的 candidate sequence y1,…,yky_1,\dots,y_k
  2. verification: target model 对 输入 {(x1:n,y1:k)}k=1K\{(x_{1:n}, y_{1:k})\}_{k=1}^K 进行一次 forward 计算每个 token 的可能性
  3. acceptance/rejection: 顺序检查 candidate sequence 中的每一个 token, 如果一个 token 不是概率最大的 token, 则该 token 与后续所有的 token 都会被丢弃
  4. correction: 对于第一个被丢弃的 token, 使用 target model 生成的 token 来替换该 token, 然后调用 draft model 进一步生成

MTP

Multi-token prediction (MTP) 是一个被广泛应用于 DeepSeek-V3 (DeepSeek-AI et al., 2025), DeepSeek-V4 (DeepSeek-AI, 2026), MiMo-V2-Flash (Team et al., 2026), MiniMax-M2 (MiniMax et al., 2026), Qwen3-Next (Q. Team, 2025), GLM-4.5 (G.-4-5 Team et al., 2025).

MTP 在训练阶段可以提高模型表现,在推理阶段可以作为 draft model 来实现 speculative decoding.

MTP 优势:

  1. 训练阶段可以提高训练信号的密度,提高数据使用效率

Method

(Gloeckle et al., 2024) 系统研究了用于语言模型的 multi-token prediction;DeepSeek-V3 (DeepSeek-AI et al., 2025) 随后采用了这一训练目标,后续其他模型也采用了这个模块。

Experiments

Comparison

ModelDeepSeek-V3DeepSeek-V4MiMo-V2-FlashMiniMax-M2Qwen3-NextGLM-4.5
architecture
parameters14B
Depth1
MTP loss weight0.3 -> 0.10.3 -> 0.1
inference
RL

好处:

  1. 提高 RL rollout 效率
  2. 减少 GPU idle time
  1. DeepSeek-AI. (2026). DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligence. https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro/blob/main/DeepSeek_V4.pdf
  2. DeepSeek-AI, Liu, A., Feng, B., Xue, B., Wang, B., Wu, B., Lu, C., Zhao, C., Deng, C., Zhang, C., Ruan, C., Dai, D., Guo, D., Yang, D., Chen, D., Ji, D., Li, E., Lin, F., Dai, F., … Pan, Z. (2025). DeepSeek-V3 Technical Report. https://arxiv.org/abs/2412.19437 back: 1, 2
  3. Gloeckle, F., Youbi Idrissi, B., Roziere, B., Lopez-Paz, D., & Synnaeve, G. (2024). Better & Faster Large Language Models via Multi-token Prediction. In R. Salakhutdinov, Z. Kolter, K. Heller, A. Weller, N. Oliver, J. Scarlett, & F. Berkenkamp (Eds.), Proceedings of the 41st International Conference on Machine Learning (Vol. 235, pp. 15706–15734). PMLR. https://proceedings.mlr.press/v235/gloeckle24a.html
  4. MiniMax, :, Chen, A., Li, A., Zhou, B., Gong, B., Jiang, B., Dan, B., Yu, C., Wang, C., Ma, C., Zhong, C., Zhu, C., Xiao, C., Yang, C., Du, C., Zhang, C., Zhang, C., Huang, C., … Ge, Z. (2026). The MiniMax-M2 Series: Mini Activations Unleashing Max Real-World Intelligence. https://arxiv.org/abs/2605.26494
  5. Team, C., Xiao, B., Xia, B., Yang, B., Gao, B., Shen, B., Zhang, C., He, C., Lou, C., Luo, F., Wang, G., Xie, G., Zhang, H., Lv, H., Li, H., Chen, H., Xu, H., Zhang, H., Liu, H., … Yue, Z. (2026). MiMo-V2-Flash Technical Report. https://arxiv.org/abs/2601.02780
  6. Team, G.-4-5, Zeng, A., Lv, X., Zheng, Q., Hou, Z., Chen, B., Xie, C., Wang, C., Yin, D., Zeng, H., Zhang, J., Wang, K., Zhong, L., Liu, M., Lu, R., Cao, S., Zhang, X., Huang, X., Wei, Y., … Tang, J. (2025). GLM-4.5: Agentic, Reasoning, and Coding (ARC) Foundation Models. https://arxiv.org/abs/2508.06471
  7. Team, Q. (2025). Qwen3-Next: Towards Ultimate Training & Inference Efficiency. https://qwen.ai/blog?id=4074cca80393150c248e508aa62983f9cb7d27cd&from=research.latest-advancements-list

Reproducibility

https://www.zhihu.com/question/1985728420773111747/answer/1986028555235266900

针对大语言模型生成的随机性,重复生成几次的性价比最高? - deephub的回答 - 知乎