已关闭
[RFC]: NPU Context Parallel Attention v3 API Refactor #4703
yule100创建于 9月9日关闭于 15 天前
9月9日 添加了label:triage-review
TorchNPU-Bot
9月9日 评论:
9月9日 评论:
issue待分派,添加triage-review标签


9月9日 添加了label:rfc
9月9日 添加了label:bot-triaged;删除了label:triage-review
TorchNPU-Bot
9月9日 评论:
9月9日 评论:
检测到当前 issue 已关联 PR,自动添加标签:bot-triaged


此处折叠了9条事件消息 查看更多
19 天前 关联了里程碑:v26.2.0
chenrayray
15 天前 评论:
15 天前 评论:
已核对本单交付情况:CP attention v3 重构及分支同步的 7 个关联 PR 均已合入,覆盖 master、v2.10/v2.11/v2.12 及对应 26.2.0 分支;实现 PR 记录 UT、精度和内存验证。本次关闭限于 v3 重构范围,RFC 已列明的上游编译限制及非目标扩展不代表同时解决。
因此先关闭此单。如在目标版本仍有问题,或存在未完成的需求项,请重新打开,并补充版本、复现步骤/日志或具体待办,便于继续跟进。


15 天前 关闭了 issue
15 天前 issue状态由 TODO 改变为 DONE
15 天前 添加了label:resolved
状态(Status): Draft
作者(Authors): @yule100
创建日期(Created): 2026-09-09
更新日期(Updated): 2026-09-09
相关 Issue/PR: #45924(PR: refactor context parallel attention to v3 API with autograd-flowed stats)
1. 概述
1.1 简介
本提案对 NPU 上下文并行(Context Parallel, CP)注意力路径进行重构:将底层算子从 v1 API(
npu_fusion_attention/npu_fusion_attention_grad)升级为 v3 API(npu_fusion_attention_v3/npu_fusion_attention_grad_v3),并移除模块级全局栈_step_cache_stack,改为通过 op autograd kwargs 流转 softmax 统计信息(softmax_max / softmax_sum / seed / offset)。该重构使 CP 路径对 torch.compile / 流水线并行(PP)友好,并与原生 PyTorch CP(ring attention)的 merge + chunk + single philox 模式保持一致。1.2 动机
当前 NPU CP 实现存在以下痛点:
_step_cache_stack作为模块级 list 保存前向中间状态,后向时弹出。虽然 Python GIL 保证线程安全,但该模式与 recompute forward / 编译路径不兼容,且在多 graph task 场景下存在栈污染风险。npu_fusion_attention(v1)返回int类型的 seed / offset / numels,图模式下无法被优化器正确追踪,dropout 路径编译失败。_unwrap_args+DTensor.from_local,绕过了unwrap_to_op_info的 sharding propagation,导致 TP+CP 组合场景下 head_num 修正缺失,且from_local内部的_FromTorchTensorautograd.Function 在 dynamo / compiled_autograd tracing 时会 re-dispatch 无策略的 aten 算子(如detach_),导致编译中断。_op_strategy_context硬编码Shard(2),仅支持 BNSD,且覆盖了 layer-1 的 TP/DP 策略而非扩展。1.3 目标
目标:
_sdpa_handler的unwrap_to_op_info→propagate→wrap流程,编译安全。@register_sharding装饰器扩展 layer-1 策略,保留 DP/TP 并追加 CP(seq shard)。_allow_implicit_replication开关、kwargs 校验、TP+CP head_num 修正。非目标:
2. 用例分析
场景一:CP 训练(BNSD, causal/non-causal)
(world_size - 1) * 2次 all_to_all / all_gather(前向后向各 world_size - 1 轮 K/V rotate),与原生 CP 一致。_sdpa_handler对齐。test_context_parallel_attention.py覆盖 forward/backward 数值正确性、通信计数、bf16 ULP 容差。场景二:TP + CP 组合(多头切分 + 序列切分)
_npu_fusion_attention_handler(line 903-910)。场景三:编译路径(torch.compile / fullgraph)
from_local,避免 re-dispatch 无策略 aten 算子。compiled=True跳过(与 native 对齐)。3. 方案设计
3.1 总体方案
整体设计分为三层:
前向流程:
unwrap_to_op_info解包 DTensor → local args + output_spec(含 sharding propagation)。_make_forward_op(step_caches, pt)创建 per-step closure,内部调用npu_fusion_attention_v3,online softmax merge(python 或 ring_update op 两种实现)。_templated_ring_attention执行 ring K/V rotate,每步调用 closure,累积 merged softmax_max/sum。wrap(local_results, output_spec)构建 DTensor。softmax_max/sum 作为 DTensor 输出,autograd 会保存并传递给后向。后向流程:
unwrap_to_op_info解包,local_kwargs中包含 autograd 流转的 softmax_max / softmax_sum / attention_in / seed / offset。_make_backward_op_v2(merged_max, merged_sum, seed, offset, pt)创建 per-step closure,内部调用npu_fusion_attention_grad_v3,使用 merged stats + single seed/offset(与 native CP 的 single philox 一致)。_templated_ring_attention_backward执行 ring backward。wrap构建 DTensor。3.2 技术选型
_step_cache_stack3.3 功能与性能设计
功能实现:
npu_fusion_attention_v3返回 6-tuple(去除 numels),npu_fusion_attention_grad_v3接受 Tensor seed/offset(去除 numels 参数)。_merge_softmax_stats_python(纯 Python,fp32 merge)和_merge_softmax_stats_with_ring_update(调用torch_npu.npu_ring_attention_updateop,BNSD ↔ SBH 适配)。_templated_ring_attention在 causal 场景使用query.chunk(2, dim=2)[1],closure 内对后半段 stats 单独 merge 后 cat 回完整序列。性能影响:
merged_max.clone()仍保留,但不再有栈 pop 时的 detach 开销)。3.4 安全隐私与DFX设计
@register_sharding覆盖式保留(先调用 layer-1 函数获取策略列表,再 append CP 策略)。_sdpa_handler对齐,降低理解成本。raise RuntimeError,生产环境-O模式下不丢失校验。3.5 编程与调用设计
3.5.1 编程模型基本设计
_templated_ring_attentionAPI),torch_npu 支持 v3 算子。test/distributed/tensor/test_context_parallel_attention.py的TestContextParallelAttention.test_ring_attention_sdpa覆盖 is_causal × compiled × load_balance × rotater × dtype 子测试矩阵。3.5.2 接口定义与设计
3.5.2.1
npu_enable_cp_dtensor_dispatcher()_allow_implicit_replication。def npu_enable_cp_dtensor_dispatcher() -> None3.5.2.2
npu_disable_cp_dtensor_dispatcher()_allow_implicit_replication原值,注销 CP sharding rules。def npu_disable_cp_dtensor_dispatcher() -> None4. 测试设计
test_context_parallel_attention.py::TestContextParallelAttentiontest_ring_attention_sdpa:forward/backward 数值正确性(vs 单卡 SDPA),覆盖 is_causal={True,False}、compiled={False,True}、load_balance={False,True}、rotater={ALL_TO_ALL,ALL_GATHER}、test_forward_only={False,True}、use_context={False,True}、dtype={bfloat16,float32}。npu_ring_attention_update可用则 > 0。_bf16_ulp_diff <= 1。TestContextParallelUtilities覆盖_is_causal_behavior、_context_parallel_shardhead-tail / per-document load balancer。5. 缺点和风险
_make_backward_op→_make_backward_op_v2、_unwrap_args/_step_cache_stack/_scaled_dot_product_attention_cp_strategy/_register_npu_cp_sharding_rules等函数移除。若有外部代码引用这些内部符号,需迁移。风险评估:低(均为模块内部私有符号)。compiled=True暂跳过,与 native CP 一致,非本提案引入的回退。6. 现有技术
torch.distributed.tensor.experimental._context_parallel._attention):_templated_ring_attention/_templated_ring_attention_backward,使用 merge + chunk + single philox 模式,softmax stats 通过 op 输出流转。本提案直接复用其 ring 框架,仅替换 per-step op closure。torch_npu.distributed.tensor._attention):_npu_fusion_attention_handler走unwrap_to_op_info+propagate+wrap流程。本提案的 handler 镜像该流程。7. 未解决问题
torch.compilefullgraph 路径何时可用(依赖上游 DTensor dispatch + SDPA tracing 修复)?附录
torch.distributed.tensor.experimental._context_parallel._attention._sdpa_handlertorch_npu.distributed.tensor._attention._npu_fusion_attention_handler