Merged
[fix](patch): 先加载 torchtitan.config,修复 CP 循环导入 (#5744) #1238
[fix](patch): 先加载 torchtitan.config,修复 CP 循环导入 (#5744) #1238
Merged
weijinyiAdd on 25 days ago
weijinyi
weijinyiCollaborators
25 days ago

描述

回合上游 #5744([config] Remove the CP import cycle):在 patch 包最前面加载 torchtitan.config,让 CP-first import 不再受入口顺序影响。

0.4.0 的 torchtitan/config/__init__.py 重新导出了 ParallelismConfig(#4908 引入),于是

from torchtitan.distributed.context_parallel import ContextParallelLoadBalancer

先执行时走 context_parallel → config/__init__ → config/parallelism → context_parallel 闭环,抛

ImportError: cannot import name 'ContextParallelLoadBalancer' from partially
initialized module 'torchtitan.distributed.context_parallel'

(在 torchtitan 0.4.0 树上已复现;先 import torchtitan.config 后正常。)

改动

1 个文件,+10/−1,纯 import。与上游的差异只有这 5 行:

# The import order below is the patch activation order, not isort's.
# ruff: noqa: I001

# Upstream #5744: 0.4.0's ``torchtitan.config`` re-exports ``ParallelismConfig``,
# so a module that imports ``torchtitan.distributed.context_parallel`` first
# re-enters the half-initialized CP module.  Loading the package here makes the
# entry order stop mattering.  Drop it when the pin carries #5744.
import torchtitan.config  # noqa: F401

放置位置在 torch-pipelining 兼容 stub 之后、首个 torchtitan 子包导入之前(stub 必须早于 0.4.0 的 dist_moe.runtime 加载)。I001 由行内 noqa 上提为文件级,因为该文件的导入顺序是 patch 激活顺序。

当前状态

dev_0.4.0 已 pin torchtitan==0.4.0,循环依赖真实存在;但当前没有激活路径:5a04c044 适配 0.4.0 时不再激活 patches/torchtitan/distributed/context_parallel.py(文件仍在树上,模块级 import 该 CP 模块),也没有其他模块引用它。

因此本 PR 是为把 doc-chunk balancer 迁到 0.4.0 API、重新引入 CP import 时准备的防护,不是修当下必现的崩溃。成本 2 行;pin 追上 #5744 后删除。

范围:为什么只回 #5744

同批评估过的两条不再纳入:

  • #5607 / #5745 的可执行内容全部服务于 VarlenInnerAttention / VarlenAttentionMetadata;DeepSeek-V4/V4.1 不引用这些组件(CP backend 是 CPInnerAttention + 自建 metadata),没有可复用机制。
  • 只有将来为非 V4 模型跑 stock varlen CP(跟随上游 #5071)时,#5745 才作为 #5071/#5746 的前置被回合。

类型

Checklist:

如何测试

未新增 UT:导入顺序改动,失败只取决于"谁先导入",正向的 import torchtitan.config 在任何 pin 上无害。

在 torchtitan 0.4.0 树上用干净进程手工验证:

导入顺序 结果
直接 from torchtitan.distributed.context_parallel import ContextParallelLoadBalancer ImportError: ... circular import
先 import torchtitan.config,再执行上一行 正常

本分支检查:

python3 scripts/check_architecture_boundaries.py   # passed
ruff check / ruff format                           # passed

精度和性能验证结果

无。改动只有 import,不触及 kernel、collective、参数、checkpoint 或配置语义。

其他信息

  • 已 rebase 到 dev_0.4.0 当前头 5a04c044(pin torchtitan==0.4.0),冲突已解决。
  • 分支名 backport/cp-varlen-contract 沿用最初提交的范围;内容已收窄为只回 #5744(平台不支持修改 PR 的源分支名)。
likedislike
Pull Request has been successfully merged by CANN-robot.
(Thank you for weijinyi's contribution.)
weijinyiweijinyiCollaborators
25 days ago Created pull request, commit 32f75c9b
atomgit-bot
atomgit-botCollaborators
25 days ago Comments:

变更摘要

本 PR 回合(backport)上游 pytorch/torchtitan 的 #5607 / #5745 / #5744 中的通用契约部分,使 dev_0.4.0 在当前 pin 上即可按 origin/main 的写法实现 context parallel 的 varlen attention。核心是新增 torchtitan_npu/patches/torchtitan/models/common/varlen_attention.py,引入上游 #5745 形状的 VarlenAttentionMetadata(frozen dataclass、携带 window_size、可被子类继承、注册为 PyTree),并让 VarlenInnerAttention 同时接受 pin 的 VarlenMetadata 与新 metadata,窗口优先取 metadata、否则回落到 per-layer Config.window_size;同时新增 SlidingWindowVarlenInnerAttention 与 patches/torchtitan/__init__.py 中的 import torchtitan.config 顺序护栏。

主要改动

  • 新增 VarlenAttentionMetadata 契约:在 varlen_attention.py 中定义 @dataclass(frozen=True, slots=True) 的 VarlenAttentionMetadata,字段包含 cu_seq_q/cu_seq_k/max_q/max_k 及 window_size(默认 None 表示沿用模块配置),并通过 torch.export.register_dataclass 注册为 PyTree,以支持 CUDAGraph replay 拷贝 document offsets。
  • VarlenInnerAttention 兼容两种 metadata:通过 apply() 把 _forward 与 _forward_varlen 挂到 torch_titan_attention.VarlenInnerAttention,_forward 校验入参为 VarlenMetadata 或 VarlenAttentionMetadata 后统一走 _forward_varlen,窗口由 _window_size_of 决定(metadata 声明优先,否则回落 Config.window_size),CP 变体的 metadata 子类可直接直达 kernel 调用。
  • 新增 SlidingWindowVarlenInnerAttention:其 Config 接受 sliding_window_size(计入 query 自身,因此 4 折算为 window_size=(3, 0)),__post_init__ 拒绝非正数或与默认 window_size 冲突的配置,build_attention_metadata 基于 create_varlen_metadata_for_document 构造带窗口的 VarlenAttentionMetadata。
  • 名称指向与激活顺序:apply() 将 torch_titan_attention.VarlenAttentionMetadata 与仓库 metadata seam attention_metadata.VarlenAttentionMetadata 同步指向新类(pin 的 VarlenMetadata 保持原样),并用 _npu_varlen_contract 标记实现幂等;patches/torchtitan/__init__.py 先 import torchtitan.config 作为 #5744 的循环导入护栏,并在 attention_metadata 之后导入 varlen_attention。
  • 配套基线与测试:.ci/architecture_import_baseline.json 的激活顺序中新增 .models.common.varlen_attention;新增 tests/unit_tests/patches/torchtitan/models/common/test_varlen_attention.py,以记录器替换 kernel,覆盖冻结语义、PyTree 拆解还原、CP 子类直达、窗口优先级、滑窗折算、非法输入报错及两模块类一致性等 CPU 用例。
likedislike
Incorrect?
atomgit-bot
atomgit-botCollaborators
25 days ago Comments:

代码审查

审查结论

各文件审查结果

文件 结论
.ci/architecture_import_baseline.json 无问题。新增的 ".models.common.varlen_attention" 位于 token_dispatcher 与 deepseek_v3.mtp 之间,与 torchtitan_npu/patches/torchtitan/__init__.py 中相对导入的实际顺序一致;键名拼写无误(patch_metadata / missing / import / activation_order)。
torchtitan_npu/patches/torchtitan/__init__.py 无问题。import torchtitan.config 置于所有 patch 导入之前,文件级 # ruff: noqa: I001 与逐行 F401 组合合理;把 varlen_attention 排在 attention_metadata 之后的注释与代码一致。
torchtitan_npu/patches/torchtitan/models/common/varlen_attention.py 3 项发现(1 个新契约缺口、1 个跨模块语义改写、1 个可选健壮性项)。
tests/unit_tests/patches/torchtitan/models/common/test_varlen_attention.py 2 项发现(1 个关键路径测试缺口、1 个断言过宽)。

已报告发现(共 5 条)

  • P2 ×3
    1. SlidingWindowVarlenInnerAttention.Config.sliding_window_size 未参与 attention_metadata_key,而 decoder 按该键去重构建 metadata(默认键为 Config 类本身),同 backend 不同窗口的两层会共用一份 metadata,第二层以错误窗口静默前向。
    2. apply() 把 attention_metadata.VarlenAttentionMetadata(原为 pin 的 VarlenMetadata 别名、且是 AttentionMetadata union 成员)改写为新的 frozen dataclass,使 VarlenAttentionMetadata is not VarlenMetadata 且不再是该 union 成员,破坏既有 seam 语义。
    3. 测试用假的 _Layer 手工提供 window_size 属性,未验证真实 VarlenInnerAttention 实例是否暴露该属性——而这正是所有既有 pin 模型的唯一窗口来源。
  • P3 ×2
    4. VarlenAttentionMetadata 未关 eq,Tensor 字段参与相等比较会抛 bool(Tensor) ambiguous(可选改进,与本仓 AscVarlenMetadata 保持一致即可)。
    5. 冻结语义用例使用 pytest.raises(Exception),无法区分 FrozenInstanceError,契约回归可能静默通过。

总体风险判断

本次变更是“契约回移”性质的补丁,activation 顺序、边界基线与文档都做了同步,主路径(pin 的 VarlenMetadata + Config.window_size)在语义上未被改动,无 P0/P1。真正的风险集中在两处新契约的“周边一致性”:新窗口字段没有进入 metadata 的去重键(同类多层不同窗口会静默取错窗口),以及对既有 seam 导出名的改写使 union/别名关系失配;两者当前都因仓内暂无对应消费者而处于潜伏状态,建议在接入 SlidingWindowVarlenInnerAttention 之前先补齐键与并集的实现,避免后续以精度问题的形式暴露。

类型 数量
🔴 阻塞 0
🟡 建议 3

💬 仅评论

likedislike
Incorrect?
CANN-robotCANN-robotCollaborators
25 days ago Added label: cann-cla/yes
CANN-robot
CANN-robotCollaborators
25 days ago Comments:

Thanks for your pull-request.
The full list of commands accepted by me can be found at here.
You can get sig-info at here.
You can self-configure the PR merge rules for this repository. For more details, please refer to Here.
For more, you also can visit HICANN.


PR Approval Progress

✅ Congratulations! All modules have met the lgtm and approve requirements.

Module Approval Details

module lgtm status approve status
repo-cann/torchtitan-npu ✅ xuyujun, zzyyjj012 (2/2) ✅ xuyujun (1/1)

💡 Tip:

  • Committer can comment /approve or /lgtm
  • Commenting /approve implies both code review (lgtm) and intent to merge (approve)

CLA Signature Pass

lrwei0709, thanks for your pull request. All authors of the commits have signed the CLA. 👍

likedislike
46 messages are collapsed here。 See more
zzyyjj012
zzyyjj012Collaborators
23 days ago Comments:

/lgtm

likedislike
xuyujun
xuyujunCollaborators
23 days ago Comments:

/approve

likedislike
CANN-robotCANN-robotCollaborators
23 days ago Added label: lgtmapproved
CANN-robotCANN-robotCollaborators
23 days ago Merged pull request
CANN-robot
CANN-robotCollaborators
23 days ago Comments:

Pull Request 已合并或已关闭。

If you want to solve this problem, you can click here to do it in the FAQs.

likedislike