Open
[草稿] [Bug修复] PyNative 单卡正确启用 activation checkpoint #8884
[草稿] [Bug修复] PyNative 单卡正确启用 activation checkpoint #8884
Open
xuxingleiAdd on Oct 28
Total: 2 files changed+184-0
@@ -317,6 +317,9 @@ class Trainer:
317 if self.enable_parallel:317 if self.enable_parallel:
318 # Apply parallelism to model318 # Apply parallelism to model
319 self._apply_parallelism(self.model, self.config.parallelism)319 self._apply_parallelism(self.model, self.config.parallelism)
320+ elif not self.is_inference:
321+ # Recompute and activation swap do not require distributed execution.
322+ self._apply_activation_checkpointing()
320 323 
321 # Set the backward scale for auxiliary losses (aux/mtp/index) once, for324 # Set the backward scale for auxiliary losses (aux/mtp/index) once, for
322 # every code path. These losses inject their gradient through dedicated325 # every code path. These losses inject their gradient through dedicated
@@ -541,6 +544,29 @@ class Trainer:
541 manual_seed(seed)544 manual_seed(seed)
542 np.random.seed(seed)545 np.random.seed(seed)
543 546 
547+ def _apply_activation_checkpointing(self) -> None:
548+ """Apply configured activation memory strategies without constructing a device mesh."""
549+ recompute = self.config.recompute
550+ recompute_comm = self.config.recompute_comm
551+ swap = self.config.swap
552+ if recompute.mode == "None" and not recompute_comm.enable and not swap.enable:
553+ return
554+ 
555+ # Import after model construction so model registration has completed.
556+ # pylint: disable=import-outside-toplevel
557+ from mindformers.pynative.base_models.gpt.parallelize import _unwrap_gptmodel
558+ from mindformers.pynative.distributed.activation_checkpoint import apply_ac
559+ 
560+ gptmodel = _unwrap_gptmodel(self.model)
561+ apply_ac(
562+ gptmodel.decoder,
563+ recompute,
564+ recompute_comm,
565+ swap,
566+ self.config.parallelism.pipeline_parallel,
567+ mtp_block=getattr(gptmodel, "mtp", None),
568+ )
atomgit-botatomgit-bot

🔵 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?

🔵 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?
569+ 
544 def _apply_parallelism(self, model, parallelism):570 def _apply_parallelism(self, model, parallelism):
545 """571 """
546 Apply parallelism strategies (FSDP/TP/CP/AC) to the model.572 Apply parallelism strategies (FSDP/TP/CP/AC) to the model.
@@ -0,0 +1,158 @@
1+# Copyright 2026 Huawei Technologies Co., Ltd
2+#
3+# Licensed under the Apache License, Version 2.0 (the "License");
4+# you may not use this file except in compliance with the License.
5+# You may obtain a copy of the License at
6+#
7+# http://www.apache.org/licenses/LICENSE-2.0
8+#
9+# Unless required by applicable law or agreed to in writing, software
10+# distributed under the License is distributed on an "AS IS" BASIS,
11+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+# See the License for the specific language governing permissions and
13+# limitations under the License.
14+# ============================================================================
15+"""CPU regression for Trainer's single-card activation-checkpoint lifecycle."""
16+from types import SimpleNamespace
17+ 
18+import numpy as np
19+import pytest
20+import mindspore as ms
21+from mindspore import Tensor, Parameter, nn
22+from hyper_parallel.platform.mindspore.activation_checkpoint import CheckpointWrapper
23+ 
24+from mindformers.pynative.base_models.gpt.gpt_model import GPTModel
25+from mindformers.pynative.distributed import activation_checkpoint as ac
26+from mindformers.pynative.trainer import trainer as trainer_module
27+ 
28+ 
29+@pytest.fixture(autouse=True)
30+def _cpu_pynative_and_reset_ac_cache():
31+ """Use the same isolated whitelist-cache policy as test_activation_checkpoint.py."""
32+ previous_mode = ms.get_context("mode")
33+ previous_target = ms.get_context("device_target")
34+ ms.set_context(mode=ms.PYNATIVE_MODE, device_target="CPU")
35+ ac._config_list = {} # pylint: disable=protected-access
36+ yield
37+ ac._config_list = {} # pylint: disable=protected-access
38+ ms.set_context(mode=previous_mode, device_target=previous_target)
39+ 
40+ 
41+class _Layer(nn.Cell):
42+ """A real differentiable Cell with a trainable parameter and replay observation."""
43+ def __init__(self, scale):
44+ super().__init__()
45+ self.weight = Parameter(Tensor([scale], ms.float32), name="weight")
46+ self.forward_calls = 0
47+ self.replay_calls = 0
48+ 
49+ def construct(self, x):
50+ if ac.is_in_recompute():
51+ self.replay_calls += 1
52+ else:
53+ self.forward_calls += 1
54+ hidden = x * self.weight
55+ return hidden * hidden + x * 0.25
56+ 
57+ 
58+class _Decoder(nn.Cell):
59+ """Minimal TransformerBlock-shaped decoder used by the upstream AC tests."""
60+ def __init__(self):
61+ super().__init__()
62+ self.layers = nn.CellList([_Layer(0.8), _Layer(0.9), _Layer(1.0)])
63+ self.config = SimpleNamespace(num_layers=3, mtp_num_layers=0)
64+ self.layer_start = 0
65+ self.layer_end = 2
66+ 
67+ def construct(self, x):
68+ for layer in self.layers:
69+ x = layer(x)
70+ return x
71+ 
72+ 
73+class _TinyGPT(GPTModel):
74+ """A GPTModel-typed container, avoiding construction of a full architecture."""
75+ def __init__(self):
76+ nn.Cell.__init__(self)
77+ self.decoder = _Decoder()
78+ self.mtp = None
79+ 
80+ def construct(self, x):
81+ return self.decoder(x)
82+ 
83+ 
84+class _ModelEnvelope(nn.Cell):
85+ """Mimic the standard GPT wrapper; its small CPU weights are already initialized."""
86+ def __init__(self):
87+ super().__init__(auto_prefix=False)
88+ self.model = _TinyGPT()
89+ 
90+ def construct(self, x):
91+ return self.model(x)
92+ 
93+ def to_empty(self):
94+ # No meta storage exists in this test; keep its initialized CPU tensors.
95+ return self
96+ 
97+ def init_states(self):
98+ return None
99+ 
100+ 
101+def _build_trainer(full):
102+ """Run Trainer.__init__ in a real, uninitialized single-process context."""
103+ model = _ModelEnvelope()
104+ original_layers = list(model.model.decoder.layers)
105+ original_params = {name: param for name, param in model.parameters_and_names()}
106+ config = {
107+ "training": {"steps": 1, "global_batch_size": 1, "local_batch_size": 1},
108+ "context": {"mode": ms.PYNATIVE_MODE, "device_target": "CPU"},
109+ "checkpoint": {"enable_save": False},
110+ "model": {"model_type": "deepseek_v3", "architectures": "DeepseekV3ForCausalLM"},
111+ "train_dataset": {"dataloader": {"type": "GeneratorDataset"}},
112+ "optimizer": {"type": "AdamW", "weight_decay": 0.0},
113+ "lr_scheduler": {"type": "ConstantWarmUpLR", "learning_rate": 0.001, "warmup_ratio": 0.0},
114+ "recompute": {"mode": "full", "full_recompute_layer": ["0-2"]} if full else {"mode": "None"},
115+ }
116+ trainer = trainer_module.Trainer(config=config, model=model, train_dataset=[{"x": 1}])
117+ assert ms.get_context("device_target") == "CPU"
118+ assert trainer.world_size == 1
119+ assert not trainer.enable_parallel
120+ assert trainer.model == [model]
121+ actual_params = dict(model.parameters_and_names())
122+ assert set(actual_params) == set(original_params)
123+ assert all(actual_params[name] is original_params[name] for name in original_params)
124+ assert {id(p) for p in trainer.optimizer.parameters} == {id(p) for p in original_params.values()}
125+ return model, original_layers
126+ 
127+ 
128+def _value_and_grads(model):
129+ x = Tensor([0.25, -0.5], ms.float32)
130+ weights = tuple(model.trainable_params())
131+ value, (input_grad, parameter_grads) = ms.value_and_grad(
132+ lambda t: model(t).sum(), grad_position=0, weights=weights
133+ )(x)
134+ return value.asnumpy(), input_grad.asnumpy(), [p.asnumpy() for p in parameter_grads]
135+ 
136+ 
137+@pytest.mark.level0
138+@pytest.mark.platform_x86_cpu
139+@pytest.mark.env_onecard
140+def test_singlecard_full_recompute_keeps_parameters_and_gradients():
141+ """Real Trainer construction installs AC only when enabled, with replay and identical gradients."""
142+ plain, plain_layers = _build_trainer(full=False)
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-botatomgit-bot

🔵 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?

🔵 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?
147+ plain_value, plain_dx, plain_dw = _value_and_grads(plain)
148+ wrapped_value, wrapped_dx, wrapped_dw = _value_and_grads(wrapped)
149+ np.testing.assert_allclose(wrapped_value, plain_value, rtol=1e-6, atol=1e-7)
150+ np.testing.assert_allclose(wrapped_dx, plain_dx, rtol=1e-6, atol=1e-7)
151+ assert len(wrapped_dw) == len(plain_dw) == 3
152+ for got, expected in zip(wrapped_dw, plain_dw):
153+ np.testing.assert_allclose(got, expected, rtol=1e-6, atol=1e-7)
154+ assert all(layer.forward_calls > 0 and layer.replay_calls == 0 for layer in plain_layers)
155+ assert all(layer.forward_calls > 0 and layer.replay_calls > 0 for layer in wrapped_layers)
156+ 
157+ 
158+