# 上下文并行

**上下文并行**（Context parallelism，CP）是一种用于训练和运行 transformer 神经网络的并行化方案，它将输入张量和所有激活值沿序列长度维度划分到多个 GPU 上，使每个设备处理长序列的一个片段而非整个序列。<sup>[1](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/features/context_parallel.html)</sup> 它主要用于长上下文语言模型的训练，可降低处理无法在单个 GPU 上高效容纳的序列时的内存占用和计算成本。<sup>[2](https://docs.nvidia.com/nemo-framework/user-guide/24.07/nemo-2.0/longcontext/contextparallel/index.html)</sup>

| 关键事实 | 详情 |
|---|---|
| 划分对象 | 沿序列维度划分网络输入和所有激活值；不同于早期的序列并行，后者仅划分 Dropout 和 LayerNorm 的激活值<sup>[1](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/features/context_parallel.html)</sup> |
| 对权重的影响 | 无；权重在上下文并行组内的各 GPU 之间复制<sup>[3](https://docs.nvidia.com/megatron-core/developer-guide/latest/apidocs/core/core.parallel_state.html)</sup> |
| 通信 | 注意力在前向传播中需要对键/值（KV）做全收集（all-gather），在反向传播中需要对 KV 激活梯度做归约散射（reduce-scatter），以环形拓扑中的点对点交换实现<sup>[1](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/features/context_parallel.html)</sup> |
| 内存节省 | 前向传播时每块 GPU 只存储自身序列块的 KV，反向传播时重新收集 KV<sup>[1](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/features/context_parallel.html)</sup> |
| 典型用途 | 8K token 或更长的序列；与张量并行、流水线并行和数据并行结合使用<sup>[4](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/parallelism-guide.html)</sup> |
| 示例规模 | 序列长度为 8K token、CP 为 2 时，每块 GPU 处理 4K token<sup>[1](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/features/context_parallel.html)</sup> |
| 环境要求 | Megatron Core 0.5.0 或更高版本，以及 Transformer Engine 1.1 或更高版本<sup>[1](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/features/context_parallel.html)</sup> |

## 工作原理

大多数 transformer 模块每次只处理一个 token。线性层和 LayerNorm 没有 token 间的操作，因此在上下文并行下，它们在每块 GPU 所负责的本地序列片段上原样运行。<sup>[1](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/features/context_parallel.html)</sup> 注意力是例外：每个 token 的查询（Q）必须与同一序列中所有 token 的键和值（KV）相结合，因此每块 GPU 都需要访问其他片段的 KV。<sup>[1](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/features/context_parallel.html)</sup>

**通信模式。** 在前向传播中，各 GPU 执行全收集以获取完整的 KV 序列；在反向传播中，对 KV 的激活梯度应用归约散射。为限制激活内存，前向传播时每块 GPU 只存储自身块的 KV，在计算反向传播时再重新收集 KV。这些集合通信以环形拓扑排列的点对点通信实现，交换发生在某块 GPU 与其他张量并行组中的对应 GPU 之间。<sup>[1](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/features/context_parallel.html)</sup> 在 NeMo Framework 的实现中，每块 GPU 在前向传播时处理序列的一个片段，反向传播时通过上述环形结构的方案在各 GPU 之间重新组装 KV 对。<sup>[2](https://docs.nvidia.com/nemo-framework/user-guide/24.07/nemo-2.0/longcontext/contextparallel/index.html)</sup>

**负载均衡。** 在因果注意力下，靠后的 token 需要关注的前驱 token 比靠前的 token 更多，因此简单切分序列会导致部分 GPU 承担更多工作。Megatron Core 通过将序列切分为 `2 * cp_size` 个等长块并以之字形模式分配来解决这一问题：CP 为 2 时，四个块分别以（块 0、块 3）分配给 GPU 0、（块 1、块 2）分配给 GPU 1，从而平衡组内的计算量。<sup>[5](https://docs.nvidia.com/megatron-core/developer-guide/nightly/apidocs/core/core.utils.html)</sup> 该方案要求文档长度能被 `2 * cp_size` 整除。<sup>[5](https://docs.nvidia.com/megatron-core/developer-guide/nightly/apidocs/core/core.utils.html)</sup>

**通信量。** KV 交换可以利用多查询注意力（MQA）或分组查询注意力（GQA）来减少通信量，因为这些注意力变体使用一个或少数几个头来处理 KV，而非每个查询头各用一个。<sup>[1](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/features/context_parallel.html)</sup>

## 与其他并行方案的关系

上下文并行是大规模训练中使用的若干并行维度之一，与张量并行（TP）、流水线并行（PP）、专家并行（EP）和数据并行（DP）并列。<sup>[4](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/parallelism-guide.html)</sup> 一个任务的总 GPU 数为 TP × PP × CP × DP 的乘积，其中 EP 属于专家并行的分解方式，而非额外的独立乘数。<sup>[4](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/parallelism-guide.html)</sup> 由于 CP 划分的是序列而非模型，它对权重没有影响，权重在上下文并行组的各 GPU 之间复制；该组内的 GPU 必须相互通信以交换其他序列块的信息，因为注意力需要完整序列长度的 token。<sup>[3](https://docs.nvidia.com/megatron-core/developer-guide/latest/apidocs/core/core.parallel_state.html)</sup>

Megatron Core 的指南建议对 8K token 或更长的序列使用 CP，并指出它可减少激活内存，且能与 TP、PP 和 DP 结合使用。<sup>[4](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/parallelism-guide.html)</sup> 推荐的示例配置包括：LLaMA-3 8B 在 8 块 GPU 上使用 CP 为 2、序列长度 8K；LLaMA-3 70B 在 64 块 GPU 上使用 TP 4、PP 4 和 CP 2；LLaMA-3.1 405B 在 1024 块 GPU 上使用 TP 8、PP 8 和 CP 2。<sup>[4](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/parallelism-guide.html)</sup>

上下文并行与 Megatron 中早期的序列并行（SP）形成对比：后者仅沿序列划分 Dropout 和 LayerNorm 的激活值；CP 则沿该维度同时划分网络输入和每一个激活值。<sup>[1](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/features/context_parallel.html)</sup>

## 与 Ring Attention 和 DeepSpeed Ulysses 的关系

Megatron 的 CP 被描述为类似于 [Ring Attention](https://www.edgepedia.org/zh/ring-attention)——加州大学伯克利分校的刘浩（Hao Liu）、马泰·扎哈里亚（Matei Zaharia）和[彼得·阿比尔](https://www.edgepedia.org/zh/pieter-abbeel)（Pieter Abbeel）提出的分块方案，它将长序列分布到各设备上，同时将键值块的通信与分块注意力计算重叠进行。<sup>[1](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/features/context_parallel.html)</sup><sup> • </sup><sup>[6](https://arxiv.org/abs/2310.01889)</sup> Megatron 的实现以两种方式追求更高性能：它使用当前的开源和 cuDNN flash attention 内核，并避免了下三角因果掩码带来的额外工作，同时保持各 GPU 之间的负载均衡。<sup>[1](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/features/context_parallel.html)</sup>

另一类实现是微软 [DeepSpeed](https://www.edgepedia.org/zh/deepspeed) 项目中的 **DeepSpeed Ulysses**，它沿序列维度划分输入，并使用全对全（all-to-all）集合通信而非环形交换。在注意力之前，对划分后的 Q、K、V 执行全对全，使每块 GPU 获得不重叠的注意力头子集所对应的完整序列；第二次全对全在各头之间收集结果并沿序列重新划分。<sup>[7](https://developer.nvidia.com/blog/scaling-ai-inference-across-multiple-gpus-using-nvidia-tensorrt-with-multi-device-inference-support/)</sup><sup> • </sup><sup>[8](https://github.com/deepspeedai/DeepSpeed/blob/master/blogs/deepspeed-ulysses/README.md)</sup> 设隐藏维度为 h、序列长度为 N、并行度为 P，其每条链路的通信量为 4Nh/P，当 N 和 P 成比例增长时保持不变；DeepSpeed 的分析认为 Megatron 式的全收集和归约散射方案每条链路为 4Nh，是其 P 倍。<sup>[8](https://github.com/deepspeedai/DeepSpeed/blob/master/blogs/deepspeed-ulysses/README.md)</sup> 一个已知局限是 Ulysses 的并行度无法有效扩展到超过注意力头数量的规模。<sup>[9](https://openreview.net/pdf?id=wCXAlfvCy6)</sup> 还有一种更简单的 AllGather KV 方法也被用作基线实现：各 rank 在计算本地注意力之前通过全收集集合通信交换各自的 K 和 V 分片。<sup>[7](https://developer.nvidia.com/blog/scaling-ai-inference-across-multiple-gpus-using-nvidia-tensorrt-with-multi-device-inference-support/)</sup>

## 动态上下文并行

真实训练数据具有长尾序列长度分布：一小部分超长样本占据了不成比例的大量计算和内存，导致数据并行 rank 和微批次之间的不均衡。<sup>[10](https://developer.nvidia.com/blog/speeding-up-variable-length-training-with-dynamic-context-parallelism-and-nvidia-megatron-core/)</sup> Megatron Core 中引入的**动态上下文并行**（Dynamic Context Parallelism，Dynamic-CP）按微批次选择上下文并行大小，而非根据最长序列固定该大小。该框架在初始化时为每个 rank 构建多个 CP 组，使用数据迭代器封装器进行动态重调度和打包，并通过扩展的 PackedSeqParams 传递每次迭代的 CP 配置。由成本模型、求解器和模拟器三部分构成的工作流在 GPU 约束下平衡工作负载与内存，确定打包方式和 CP 大小。<sup>[10](https://developer.nvidia.com/blog/speeding-up-variable-length-training-with-dynamic-context-parallelism-and-nvidia-megatron-core/)</sup>

在 Llama 13B 基准测试中，与纯打包相比，Dynamic-CP 在 GitHub 数据集上实现了 1.48 倍加速，在 CommonCrawl 上实现了 1.25 倍加速，在数千块 GPU 的环境中端到端提升超过 35%。<sup>[10](https://developer.nvidia.com/blog/speeding-up-variable-length-training-with-dynamic-context-parallelism-and-nvidia-megatron-core/)</sup>

## 在生产训练中的应用

当序列长度增长到其他方案无法经济处理时，上下文并行被应用于大规模训练任务。英伟达（NVIDIA）的 Nemotron 3 Nano Omni 模型在预训练后期阶段引入 CP，在第 5 阶段使用 2 路 CP，在第 6 阶段使用 16 路 CP，以适应约 340 亿 token 的长上下文文本和视觉数据中日益增长的序列长度。<sup>[11](https://research.nvidia.com/labs/nemotron/files/NVIDIA-Nemotron-3-Omni-report.pdf)</sup> 在推理中，多设备 TensorRT 部署使用上下文并行将序列划分到各 GPU 上，该方法被描述为天然适合扩散模型和 DiT 模型，因为这些模型的双向注意力避免了因果掩码带来的负载不均衡问题。<sup>[7](https://developer.nvidia.com/blog/scaling-ai-inference-across-multiple-gpus-using-nvidia-tensorrt-with-multi-device-inference-support/)</sup>

## References

1. [Context Parallel Package, Megatron Core documentation, NVIDIA](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/features/context_parallel.html)
2. [Context Parallelism, NVIDIA NeMo Framework User Guide](https://docs.nvidia.com/nemo-framework/user-guide/24.07/nemo-2.0/longcontext/contextparallel/index.html)
3. [core.parallel_state, Megatron Core API documentation, NVIDIA](https://docs.nvidia.com/megatron-core/developer-guide/latest/apidocs/core/core.parallel_state.html)
4. [Parallelism Strategies Guide, Megatron Core documentation, NVIDIA](https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/parallelism-guide.html)
5. [core.utils, Megatron Core API documentation, NVIDIA](https://docs.nvidia.com/megatron-core/developer-guide/nightly/apidocs/core/core.utils.html)
6. [Hao Liu, Matei Zaharia, Pieter Abbeel (2023). Ring Attention with Blockwise Transformers for Near-Infinite Context. arXiv.](https://arxiv.org/abs/2310.01889)
7. [Scaling AI Inference Across Multiple GPUs Using NVIDIA TensorRT with Multi-Device Inference Support, NVIDIA Technical Blog](https://developer.nvidia.com/blog/scaling-ai-inference-across-multiple-gpus-using-nvidia-tensorrt-with-multi-device-inference-support/)
8. [DeepSpeed-Ulysses: System Optimizations for Enabling Training of Extreme Long Sequence Transformer Models, DeepSpeed documentation](https://github.com/deepspeedai/DeepSpeed/blob/master/blogs/deepspeed-ulysses/README.md)
9. [Published as a conference paper at ICLR 2025 (discussion of DeepSpeed-Ulysses scaling limits), OpenReview](https://openreview.net/pdf?id=wCXAlfvCy6)
10. [Speeding Up Variable-Length Training with Dynamic Context Parallelism and NVIDIA Megatron Core, NVIDIA Technical Blog](https://developer.nvidia.com/blog/speeding-up-variable-length-training-with-dynamic-context-parallelism-and-nvidia-megatron-core/)
11. [Nemotron 3 Nano Omni: Efficient and Open Multimodal Intelligence, NVIDIA Research](https://research.nvidia.com/labs/nemotron/files/NVIDIA-Nemotron-3-Omni-report.pdf)

---
*Initially written Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 人工智能与数据 › Machine learning and neural computation › Neural networks and deep learning › Deep learning software and hardware › Distributed and large-scale training

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/context-parallelism

English original: https://www.edgepedia.org/context-parallelism
