Open
[草稿] [Bug修复] PyNative 单卡正确启用 activation checkpoint #8884
[草稿] [Bug修复] PyNative 单卡正确启用 activation checkpoint #8884
Open
xuxingleiAdd on Oct 28
xuxinglei
xuxingleiCollaborators
Oct 28

Fixes #2615

修改描述 (Description)

PyNative Trainer 在 world_size=1 时跳过并行处理,连带跳过 GPT 的 activation checkpoint 安装,导致已配置的 full recompute 未生效。本修改在非推理单卡路径、参数实例化之前调用现有 apply_ac,沿用原有重算层选择、后端和辅助损失缩放,不建立并行网格。

新增 CPU 回归使用真实 Trainer 构造路径,验证关闭重算时不包装、开启 full 时三层均包装,参数对象和优化器引用保持一致,并验证 backward 重放及 loss、输入和参数梯度与未包装参照一致。

修改类型 (Type of Change)

测试结果 (Test Results)

基线为官方 master 902de5f0aa5f16c77fe8f45c57550d333ac32634,修复提交为 7e616b80c9f0eb1228fc5369628e18f609db6b4a。

HYPER_PARALLEL_PLATFORM=mindspore python -m pytest -q \
  tests/st/test_ut/test_pynative/test_trainer/test_singlecard_activation_checkpoint.py

同一用例在原 Trainer 的 full 包装断言失败;修复后 1 passed。在 CANN 9.2.0、910B3、Python 3.12.14、MindSpore 2.12.0 master 构建与 MF CI 指定 HP MindSpore 后端包上,另完成实际 3 层 DeepSeek/mHC、B4×4096 的单微批前反向:三层各原始前向/重算一次,MoE 计数未重复,69 个训练梯度均为有限 FP32,未执行优化器更新。模型/优化器参数描述和首批四字段哈希与未包装构造一致。峰值 allocated 20,773,690,880 bytes、reserved 23,821,549,568 bytes;该结果仅为功能及内存可运行性检查,未作为吞吐对比或长程精度验收。

使用该提交的原配置 1000 步训练正在独立运行,500 步 checkpoint 及跨框架恢复验收尚未完成,整体跟踪 https://github.com/hf1s/hyper-parallel/issues/304 。

检查清单 (Checklist)

likedislike
Merge blocked
xuxingleixuxingleiCollaborators
Oct 28 Created pull request, commit ec570107
xuxingleixuxingleiCollaborators
Oct 28 Associated issue: [Bug]: PyNative 单卡跳过 activation checkpoint,full recompute 配置未生效
atomgit-bot
atomgit-botCollaborators
Oct 28 Comments:

变更摘要

本 PR 修复了 PyNative Trainer 在单卡(world_size=1)场景下不启用 activation checkpoint 的问题:此前 enable_parallel=False 会整体跳过并行处理分支,连带跳过 GPT 的重算包装安装,使已配置的 recompute.mode="full" 等重算策略失效。改动在非推理的单卡路径上、参数实例化之前新增 _apply_activation_checkpointing() 调用,复用已有的 apply_ac 完成重算层选择与包装,不构建并行网格;同时新增 CPU 回归用例,覆盖重算关闭/开启两种构造路径及前反向数值一致性。

主要改动

  • 单卡路径接入重算安装: 在 Trainer.__init__ 中为 enable_parallel 为假且非推理的场景增加 elif not self.is_inference 分支,调用 _apply_activation_checkpointing(),使单卡训练不再丢失已配置的重算与激活换出策略。
  • 新增 _apply_activation_checkpointing 方法: 该方法先检查 recompute.mode、recompute_comm.enable、swap.enable,全部未启用时直接返回;否则延迟导入 _unwrap_gptmodel 与 apply_ac,解包出 GPT 模型后对其 decoder 应用 apply_ac,并传入 parallelism.pipeline_parallel 与 mtp_block(取自 gptmodel.mtp),保持原有后端与辅助损失缩放逻辑。
  • 新增单卡 CPU 回归测试: 新增 test_singlecard_activation_checkpoint.py,通过真实 Trainer 构造路径(_ModelEnvelope 包裹 _TinyGPT 三层 decoder)验证关闭重算时不包装、mode="full" 时三层均被 CheckpointWrapper 包装。
  • 验证参数引用与梯度一致性: 用例断言参数对象集合及优化器 parameters 引用与构造前保持一致,并通过 ms.value_and_grad 比较包装与未包装模型的 loss、输入梯度、参数梯度数值接近,同时用 forward_calls/replay_calls 确认重算重放确实发生。
likedislike
Incorrect?
atomgit-bot
atomgit-botCollaborators
Oct 28 Comments:

代码审查

结论如下。

审查结论

已审查文件

  1. mindformers/pynative/trainer/trainer.py:新增分支(elif not self.is_inference: self._apply_activation_checkpointing())与新增方法 _apply_activation_checkpointing 已逐行核对。以下内容均已确认:

    • recompute / recompute_comm / swap 均为 TrainConfig 的 field(default_factory=...)(config.py:1062-1064),单卡路径读取不会 AttributeError;
    • 生效条件与参数序列和 _apply_spmd_parallelism Phase 4(parallelize.py:1996-2006)一致,pipeline_parallel、mtp_block 传参与多卡相同;
    • 调用点位于 to_empty()/init_states() 之前(trainer.py:317-344),与多卡路径的先后顺序一致;set_auxiliary_loss_backward_scale(331-337)仍覆盖单卡;
    • self.model 此时还是单个 Cell(列表化在 340 行),_unwrap_gptmodel(self.model) 入参形态正确。
    • 报告 2 个 P3 问题(非 GPT 模型的误导性失败、与多卡调用点重复易漂移)。
  2. tests/st/test_ut/test_pynative/test_trainer/test_singlecard_activation_checkpoint.py:已完整核对(fixture 的 _config_list 隔离、_TinyGPT/_ModelEnvelope 构造、参数身份与优化器引用断言、value_and_grad 梯度等价与 forward/replay 计数断言)。未发现阻断性缺陷:nn.Cell.__init__ 直连与 to_empty/init_states 空实现均为有注释说明的测试替身,参数名/参数对象身份断言恰好覆盖 apply_recompute 通过 model.layers[id] = ... 原地替换的语义。仅存 3 行文件尾空行等格式问题,属噪音,未报告。no issues(无需报告的问题)。

发现统计

  • P0:0
  • P1:0
  • P2:0
  • P3:2

总体风险判断

低。修复方向正确(在参数实例化前、非推理单卡路径安装 AC,不建并行网格),且与多卡路径的语义、参数、时序保持一致,回归用例覆盖了“关闭不包装 / 开启全层包装 / 参数与优化器身份不变 / 反向前反向一致”四项关键契约。剩余问题均为维护性与错误信息可读性层面的 P3,不影响本 PR 的正确性合入;唯一需要产品确认的是单卡下非 GPT-family 模型开启 recompute/swap 时应“报错”还是“警告后跳过”。

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

💬 仅评论

likedislike
Incorrect?
MindSpore-BotMindSpore-BotCollaborators
Oct 28 Added label: mindspore-cla/yes
MindSpore-Bot
MindSpore-BotCollaborators
Oct 28 Comments:

CLA Signature Pass

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

likedislike
昇思微(机器人)
昇思微(机器人)Collaborators
Oct 28 Comments:

@xuxinglei, 当前/check-pr未通过,原因如下:

以下Pull Request描述检查项未通过:
存在不符合模板的选项: Bug 修复 (Bug fix)
存在不符合模板的选项: 新特性 (New feature)
存在不符合模板的选项: 文档更新 (Documentation update)
存在不符合模板的选项: 代码重构 (Refactoring)
存在不符合模板的选项: 性能优化 (Performance improvement)
存在不符合模板的选项: 其他 (Other)
存在不符合模板的选项: 我已自验过该功能/修复 (Self-checked)
存在不符合模板的选项: 我已通过了本地的单元测试 (Passed local UTs)
存在不符合模板的选项: (如适用) 我已更新了对应文档 (Updated documentation)
存在不符合模板的选项: (如适用) 我已添加了新的测试用例 (Added new tests)
部分检查项缺失 请重新使用模板
模板中'Test Plan and Test Result' 信息为空,请补充对应信息。
/kind为空或类型无效, 请指定为 [ 'bug', 'task', 'feature', 'refactor', 'clean_code' ] 中的一种

请修改好上述检查错误后,重新使用/check-pr触发检查。

likedislike
昇思微(机器人)昇思微(机器人)Collaborators
Oct 28 Added label: pr-check-fail
atomgit-bot
atomgit-botCollaboratorsOct 28Start code review1
tests/st/test_ut/test_pynative/test_trainer/test_singlecard_activation_checkpoint.py
@@ -0,0 +143,4 @@
143+ wrapped, wrapped_layers = _build_trainer(full=True)
144+ 
145+ assert all(not isinstance(layer, CheckpointWrapper) for layer in plain.model.decoder.layers)
146+ assert all(isinstance(layer, CheckpointWrapper) for layer in wrapped.model.decoder.layers)
atomgit-bot
atomgit-botOct 28Comments:

🔵 Low Priority

变更行:第 140–146 行的唯一用例只覆盖 full=False(不包装)与 full=True(三层包装)两种组合,_build_trainer 也没有任何推理模式开关。

行为/契约:本 PR 的生产改动(trainer.py +26 行)明确将 apply_ac 限定在「非推理单卡路径」安装。也就是说修复引入了「inference 时必须不安装 AC」这一新门控。

失败模式:若后续改动把门控写反、或把 apply_ac 调用移到推理分支之外,本测试仍全部通过(full=False/True 两个断言都不会触发),而推理链路会静默构建 CheckpointWrapper,导致 decode 阶段多一次前向重算的内存/时延回归,无任何用例拦截。触发条件正是「门控条件被改坏」这一最贴近本次修复点的回归。

建议:增加以 inference 模式构造 Trainer 的负向用例,断言 full 重算配置在推理路径下不产生 CheckpointWrapper。这属于可选的覆盖增强,不是必须修复项。

likedislike
Incorrect?
atomgit-bot
atomgit-botCollaboratorsOct 28Start code review1
tests/st/test_ut/test_pynative/test_trainer/test_singlecard_activation_checkpoint.py
@@ -0,0 +143,4 @@
143+ wrapped, wrapped_layers = _build_trainer(full=True)
144+ 
145+ assert all(not isinstance(layer, CheckpointWrapper) for layer in plain.model.decoder.layers)
146+ assert all(isinstance(layer, CheckpointWrapper) for layer in wrapped.model.decoder.layers)
atomgit-bot
atomgit-botOct 28Comments:

🔵 Low Priority

变更行:第 145–146 行 assert all(not isinstance(layer, CheckpointWrapper) ...) 与 assert all(isinstance(layer, CheckpointWrapper) ...),以及第 154–155 行同样基于 all(...) 的重放计数断言。

行为/契约:这两组断言是本回归唯一用来证明「full 重算时三层都被 CheckpointWrapper 包装」的检查,但它们对可迭代对象为空一律返回 True。若被测路径把 decoder.layers 清空、替换为新的 CellList 或整体替换父节点(apply_ac 做原地替换时若实现改动为重建容器),all(...) 会在 0 个元素上空洞通过,测试仍报绿,而实际「无任何层被包装」的原始 bug(issue #2615)就会重新溜过去。

失败模式:len(wrapped.model.decoder.layers) == 0 时第 146 行恒为真;第 151 行只校验梯度个数为 3,不校验层数,因此不能补偿。触发条件是 apply_ac 相关的容器替换/清理逻辑回归。

建议:在第 145–146 行的 all(...) 断言前增加层数断言,避免空 CellList 让断言空洞通过。

likedislike
Incorrect?
atomgit-bot
atomgit-botCollaboratorsOct 28Start code review1
mindformers/pynative/trainer/trainer.py
@@ -547,0 +565,4 @@
565+ swap,
566+ self.config.parallelism.pipeline_parallel,
567+ mtp_block=getattr(gptmodel, "mtp", None),
568+ )
atomgit-bot
atomgit-botOct 28Comments:

🔵 Low Priority

变更行 trainer.py:557-560 在单卡训练路径上无条件 _unwrap_gptmodel(self.model)。_unwrap_gptmodel(base_models/gpt/parallelize.py:144-155)在 cells_and_names() 中找不到 GPTModel 时直接 raise ValueError(f"No GPTModel found in ... apply_fsdp_to_gptmodel only supports GPT-family models.")。

失效链路:变更前,world_size==1 时整个 _apply_parallelism() 被跳过,因此用户即便配置了 recompute.mode != "None" / swap.enable / recompute_comm.enable,单卡也从未走到 _unwrap_gptmodel,构造继续成功(只是重算未生效);变更后只要上述任一开关打开,就会在 Trainer.__init__(to_empty/init_states 之前)抛 ValueError,且错误信息指向 apply_fsdp_to_gptmodel,与用户实际开启的功能(activation checkpoint / swap)完全无关,排查成本高。

建议:在调用 _unwrap_gptmodel 前增加 GPT-family 判定,或在 _unwrap_gptmodel 之外捕获并改写错误信息,使单卡 AC 场景的失败语义清晰(明确“单卡 activation checkpoint/swap 需要 GPT-family 模型”);若决定对非 GPT 模型保持旧的“静默不生效”行为,则改为 logger.warning 后返回。

likedislike
Incorrect?
atomgit-bot
atomgit-botCollaboratorsOct 28Start code review1
mindformers/pynative/trainer/trainer.py
@@ -547,0 +565,4 @@
565+ swap,
566+ self.config.parallelism.pipeline_parallel,
567+ mtp_block=getattr(gptmodel, "mtp", None),
568+ )
atomgit-bot
atomgit-botOct 28Comments:

🔵 Low Priority

新增的 _apply_activation_checkpointing(trainer.py:547-568)把 _apply_spmd_parallelism 中 Phase 4 的调用整体复制了一份:同样的 recompute.mode != "None" or recompute_comm.enable or swap.enable 生效条件(parallelize.py:1998),同样的 apply_ac(decoder, recompute, recompute_comm, swap, pp, mtp_block=...) 参数序列(parallelize.py:1999-2006),并且这层提前返回条件还与 apply_ac 内部 enable_recompute/enable_swap 的判定(activation_checkpoint.py:1199-1202)第三份重复。

风险:后续若 apply_ac 增加参数(例如新的 layer 选择/后端开关)、或生效条件调整(例如新增一种 mode),两条路径中很容易只改多卡那一处;单卡分支会因自身早退条件或参数列表过期而静默不生效或 TypeError,且单卡与多卡的重算行为出现分歧——而这正是本 PR 要修复的“配置解析正确但未生效”类问题。

这不是当前的功能缺陷(现网两处逻辑一致),而是明确的维护性隐患。

建议:把“是否需要重算/交换”的判定与 apply_ac 的调用参数抽成一个共享 helper(例如放到 mindformers/pynative/distributed/activation_checkpoint.py,由 _apply_spmd_parallelism 与 Trainer._apply_activation_checkpointing 共同调用),避免单卡与多卡两份调用点各自漂移;至少应删掉本函数里的重复早退条件,直接依赖 apply_ac 自身的 enable_recompute/enable_swap 早退(仍需保留惰性 import 的前提判断时可复用同一判定函数)。

likedislike
Incorrect?
xuxingleixuxingleiCollaborators
Oct 28 Change title to "[草稿] [Bug修复] PyNative 单卡正确启用 activation checkpoint", originally titled "[Bug修复] PyNative 单卡正确启用 activation checkpoint".
MindSpore-Bot
MindSpore-BotCollaborators
7 days ago Comments:

PR Merge Reminder from Scavenger:
This PR has been inactive for 30 days (as no new commits, comments, configurations) and will be closed as it becomes obsolete after 30 days of continued inactivity.
Please track the PR merging process in time, and respond according to the relevant prompts given by the robot to speed up the PR merging.
该PR已经闲置30天(因没有新的提交、评论、配置)且将因继续闲置30天后变得过时而被关闭。
请及时跟踪PR的合入流程并根据机器人给出的提示做出相应的响应以加速PR的合入。

likedislike