# LLM 推理优化综述:KV Cache、Continuous Batching 与投机解码 > 梳理大语言模型推理中的采样策略、Prefill 与 Decode 性能分析、KV cache、Continuous batching、并行推理、Speculative decoding 与 Multi-token prediction,并讨论生成结果的可复现性。 - **URL**: https://maosong.website/blog/inference/ - **Authors**: Mao Song - **Published**: 2026-10-16 00:00:00+0800 - **Modified**: 2026-10-16 00:00:00+0800 --- ## Introduction 推理优化: - kv cache - paged attention - speculative decoding - PD disaggregation 推理优化根据时间顺序主要分为四个模块: 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 - [LLM推理中的temperature、top_k、top_p理解 - 姚光超的文章 - 知乎](https://zhuanlan.zhihu.com/p/32968633664) - [Basic LLM Inference/Generation,一篇就够了。 - LastWhisper的文章 - 知乎](https://zhuanlan.zhihu.com/p/694176507) - [一文搞懂大模型生成文本的解码策略 - 吃果冻不吐果冻皮的文章 - 知乎](https://zhuanlan.zhihu.com/p/1921914053485376792) - [Generation configurations: temperature, top-k, top-p, and test time compute](https://huyenchip.com/2024/01/16/sampling.html) - [大模型中目前最快最好的解码策略是什么呢?还有哪些问题值得研究? - 白白小白的回答 - 知乎](https://www.zhihu.com/question/641130465/answer/1944129627581834804) ### Strategies #### Greedy Search 每一步选择概率最高的 token 特点:完全确定,相同输入必定有相同输出。缺点是容易陷入局部最优,或者在长文本生成中陷入死循环 表达式 $ x_t = \arg\max_{x} P(x\mid x_{1$: 平滑概率分布,使得原本概率低的 token 被选中的概率增加 ```python 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 导致的胡言乱语 [@fan2018hierarchical]. 其策略在于在采样前,只保留概率最高的前 K 个 token, 并对这 $K$ 个 token 的概率进行重新归一化,其余 token 彻底丢弃。 $ [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 显的太小,会扼杀多样性。 ```python 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 的动态适应问题 [@holtzman2020curiouscaseneuraltext]. 其策略是将所有的 token 按照概率从大到小排序并计算累计概率, 当累计概率超过阈值 $p$ 时截断,只保留这个动态集合的 token $ \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 个词,如果模型很犹豫,候选集会自动扩大到几十个词 ```python 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 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 为 $20$ 对应的代码为 ```python 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' ``` ## Inference roofline models ### Prefilling ### Decoding ### PD disaggregation ## KV Cache KV cache 是什么,为什么要有 KV cache, KV cache 为什么会造成显存过大的问题,如何解决? ### Why KV cache ### How KV cache works kv cache 拼接 ```python 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 ```python 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 调用 ```python 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 的分页注意力思想,管理非连续显存块 ```python 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 - Shared KV: MQA [@MQA], GQA [@GQA] - Windowed KV: Longformer - Quantized Compression: KVQuant - infra上:paged attention,kv cache offloading ## Continuous batching - https://huggingface.co/blog/faster-transformers ## Parallelism 追求高吞吐,用 EP, 追求低 latency 用 TP 1. batch size 小时,追求 low latency 可以开 TP, 把参数放在不同的 rank 上 2. batch size 大时,追求 high throughput, 可以开 EP, 提高通信速度 ### EP MoE 的内存访问情况如下表所示 | Stage | bound | components | | --------- | ------------------- | ------------------------------ | | Attention | memory bound | (attention weights + kv cache) | | dispatch | communication bound | (B\*topK + H) | | MoE | memory bound | N \* experts weights | | combine | communication | (B\*topK + H) | 推理时,一般需要比较大的 EP size, 因为除了 MoE layer 之外,其他阶段耗时随 batch size 增加而减小,为了保证总耗时不变,我们就得增大 EP, 减少 单卡专家数量,降低 MoE 耗时。因此增大 EP 可以降低 MoE 耗时,提高吞吐 TP 和 EP 的对比 ### Practices ## Speculative decoding [【llm基础】为什么说投机解码是无损的 - 燕雄飞的一天的文章 - 知乎](https://zhuanlan.zhihu.com/p/2000545509719438645) [备忘:关于 LLM 的加速解码:speculative 解码 - 张 Mc 的文章 - 知乎](https://zhuanlan.zhihu.com/p/1961426996279083425) https://aclanthology.org/2023.findings-emnlp.257/ [Speculative Decoding: 从Padding 的视角重新理解投机解码 - 笑渐不闻声渐悄的文章 - 知乎](https://zhuanlan.zhihu.com/p/1991904699117490479) https://proceedings.mlr.press/v202/leviathan23a.html [有没有speculative decoding的综述? - DeclK的回答 - 知乎](https://www.zhihu.com/question/657854511/answer/1983922186562594120) speculative decoding 使用了两个模型来加速推理 1. draft model ($M_d$) , 用于生成一个 candidate sequence 2. target model ($M_t$), 用于对 candidate sequence 进行验证 工作原理: 1. drafting: 给定一个 prompt $x_{1:n}$, draft model 基于 prompt 生成一个包含 $K$ 个 token 的 candidate sequence $y_1,\dots,y_k$ 2. verification: target model 对 输入 $\{(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](/blog/deepseek/#deepseek-v3) [@DeepSeek-V3], DeepSeek-V4 [@DeepSeek-V4], MiMo-V2-Flash [@MiMo-V2-Flash], MiniMax-M2 [@MiniMax-M2], Qwen3-Next [@Qwen3-Next], [GLM-4.5](/blog/glm/#glm-45) [@GLM-4.5]. MTP 在训练阶段可以提高模型表现,在推理阶段可以作为 draft model 来实现 speculative decoding. MTP 优势: 1. 训练阶段可以提高训练信号的密度,提高数据使用效率 ### Method [@MTP] 系统研究了用于语言模型的 multi-token prediction;DeepSeek-V3 [@DeepSeek-V3] 随后采用了这一训练目标,后续其他模型也采用了这个模块。 ### Experiments ### Comparison | Model | DeepSeek-V3 | DeepSeek-V4 | MiMo-V2-Flash | MiniMax-M2 | Qwen3-Next | GLM-4.5 | | --------------- | ----------- | ----------- | ------------- | ---------- | ---------- | ------- | | architecture | | | | | | | | parameters | 14B | | | | | | | Depth | | 1 | | | | | | MTP loss weight | 0.3 -> 0.1 | 0.3 -> 0.1 | | | | | | inference | | | | | | | | RL | | | | | | | 好处: 1. 提高 RL rollout 效率 2. 减少 GPU idle time ## Reproducibility https://www.zhihu.com/question/1985728420773111747/answer/1986028555235266900 [针对大语言模型生成的随机性,重复生成几次的性价比最高? - deephub的回答 - 知乎](https://www.zhihu.com/question/1966808564841559137/answer/1966827830059960168)