上下文并行指南¶
概述¶
本指南介绍如何使用上下文并行(Context Parallel),这是一种长序列推理优化技术。上下文并行包括 PCP(预填充上下文并行)和 DCP(解码上下文并行),能够降低长序列 LLM 推理中的 NPU 内存占用并提升推理速度。
上下文并行的优势¶
上下文并行主要解决长上下文请求的服务问题。由于预填充(Prefill)和解码(Decode)具有显著不同的特性及服务水平目标(SLO),我们需要分别为它们实现上下文并行。主要考量点包括:
- 对于长上下文预填充,我们可以使用上下文并行,通过在查询令牌间分摊预填充的计算时间来降低首令牌延迟(TTFT)。
- 对于长上下文解码,我们可以使用上下文并行来减少 KV 缓存的重复,从而为 KV 缓存腾出更多空间以增加批次大小(进而提升吞吐量)。
欲了解更多关于上下文并行的理论和实现细节,请参阅 上下文并行开发者指南。
支持场景¶
目前上下文并行可与大多数其他功能结合使用,支持的功能如下:
| Eager 模式 | 图模式 | 前缀缓存 |
分块预填充 |
投机解码 (MTP) |
PD 分离 |
MLAPO | |
|---|---|---|---|---|---|---|---|
| PCP | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| DCP | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
如何使用上下文并行¶
您可以通过 PCP 和 DCP 启用 prefill_context_parallel_size 和 decode_context_parallel_size,请参考以下示例:
-
离线示例:
from vllm import LLM, SamplingParams prompts = [ "The future of AI is", ] sampling_params = SamplingParams(temperature=0.8, top_p=0.95) llm = LLM( model="deepseek-ai/DeepSeek-V2-Lite", tensor_parallel_size=2, decode_context_parallel_size=2, prefill_context_parallel_size=2, ) outputs = llm.generate(prompts, sampling_params) -
Online example:
The total world size is tensor_parallel_size * prefill_context_parallel_size, so the examples above need 4 NPUs for each.
Constraints¶
-
While using DCP, the following constraints must be met:
- For MLA-based model, such as DeepSeek-R1:
tensor_parallel_size >= decode_context_parallel_sizetensor_parallel_size % decode_context_parallel_size == 0
- For GQA-based model, such as Qwen3-235B:
(tensor_parallel_size // num_key_value_heads) >= decode_context_parallel_size(tensor_parallel_size // num_key_value_heads) % decode_context_parallel_size == 0
- For MLA-based model, such as DeepSeek-R1:
-
While using Context Parallel in KV cache transfer-needed scenario (e.g. KV pooling, PD disaggregation), to simplify KV cache transmission,
cp_kv_cache_interleave_sizemust be set to the same value of KV cacheblock_size(default: 128), which specifies CP to split KV cache in a block-interleave style. For example:
实验结果¶
为评估上下文并行在长序列 LLM 推理场景中的有效性,我们使用 DeepSeek-R1-W8A8 和 Qwen3-235B 模型,在 64 卡 Ascend Atlas A3 推理产品*64G (A3) 环境下部署 PD 分离实例,配置和性能数据如下。
-
DeepSeek-R1-W8A8:
配置 输入长度
32k输入长度
64k输入长度
128kP 节点: (DP2 TP8 EP16) *2
D 节点: (DP32 EP32)*1TTFT: 9.3s
TPOT: 72msTTFT: 22.8s
TPOT: 74msTTFT: 73.2s
TPOT: 82msP 节点: (PCP2 TP8 DCP8 EP16) *2
D 节点: (DP32 EP32)*1TTFT: 7.9s
TPOT: 74msTTFT: 15.9s
TPOT: 78msTTFT: 46.0s
TPOT: 83ms -
Qwen3-235B:
配置 输入长度
32k输入长度
64k输入长度
120kP 节点: (DP2 TP8 EP16) *2
D 节点: (DP32 EP32)*1TTFT: 5.1s
TPOT: 65msTTFT: 13.1s
TPOT: 85msTTFT: 33.9s
TPOT: 120msP 节点: (PCP2 TP8 DCP2 EP16) *2
D 节点: (DP32 EP32)*1TTFT: 3.0s
TPOT: 66msTTFT: 8.9s
TPOT: 86msTTFT: 22.7s
TPOT: 121ms