Merged
fix: restore native checkpoint selection and HF export #1214
fix: restore native checkpoint selection and HF export #1214
Merged
jiangna1111Add on 27 days ago
Total: 5 files changed+166-84
@@ -744,3 +744,35 @@ def test_config_manager_overrides_recipe_owned_optional_components(monkeypatch,
744 assert source.compile.model.fullgraph is True744 assert source.compile.model.fullgraph is True
745 assert source.checkpointer.interval == 11745 assert source.checkpointer.interval == 11
746 assert source.checkpointer.extensions.verify_hash_manifest is False746 assert source.checkpointer.extensions.verify_hash_manifest is False
747+ 
748+ 
749+@pytest.mark.parametrize("recipe_owned", [False, True], ids=("upstream-native", "recipe-native"))
750+def test_config_manager_selects_native_checkpointer_owner(monkeypatch, tmp_path, recipe_owned):
jiangna1111
jiangna1111jiangna111125 days ago

补个测试,确保原生 checkpoint 用上 NPU 实现,同时不影响自定义实现和命令行参数。

likedislike
751+ pytest.importorskip("torch_checkpointing")
752+ from torchtitan.components.checkpointer.torch_checkpointing import TorchCheckpointingManager as NativeManager
753+ 
754+ from torchtitan_npu.extensions.torchtitan.components.torch_checkpointing import (
755+ TorchCheckpointingManager as NPUNativeManager,
756+ )
757+ 
758+ class RecipeNativeManager(NativeManager):
759+ @dataclass(kw_only=True, slots=True)
760+ class Config(NativeManager.Config):
761+ pass
762+ 
763+ source_manager = RecipeNativeManager if recipe_owned else NativeManager
764+ expected_manager = RecipeNativeManager if recipe_owned else NPUNativeManager
765+ source = Trainer.Config(
766+ model=_debug_model(),
767+ hf_assets_path=str(tmp_path),
768+ checkpointer=source_manager.Config(interval=11),
769+ )
770+ module_name = "_torchtitan_npu_native_checkpointer_registry"
771+ _install_config_registry(monkeypatch, module_name, lambda: source)
772+ 
773+ config = ConfigManager().parse_args(
774+ ["--module", module_name, "--config", "test_config", "--checkpointer.interval", "7"]
775+ )
776+ 
777+ assert config.checkpointer._owner is expected_manager # pylint: disable=protected-access
778+ assert config.checkpointer.interval == 7
@@ -3,9 +3,10 @@
3# This source code is licensed under the BSD-style license found in the3# This source code is licensed under the BSD-style license found in the
4# LICENSE file in the root directory of this source tree.4# LICENSE file in the root directory of this source tree.
5 5 
6-"""CPU round trip through the local native-checkpoint integration."""6+"""CPU save, restore, and HF export through the native-checkpoint integration."""
7 7 
8import copy8import copy
9+import json
9from contextlib import closing10from contextlib import closing
10 11 
11import pytest12import pytest
@@ -15,6 +16,7 @@ from torch.distributed.checkpoint.state_dict_saver import _stateful_to_state_dic
15 16 
16pytest.importorskip("torch_checkpointing")17pytest.importorskip("torch_checkpointing")
17 18 
19+from safetensors.torch import load_file
18from torch_checkpointing.storage.filesystem import LocalFileSystemStorageConfig20from torch_checkpointing.storage.filesystem import LocalFileSystemStorageConfig
19from torchtitan.components.optim import AdamW, LRSchedulersContainer, OptimizersContainer21from torchtitan.components.optim import AdamW, LRSchedulersContainer, OptimizersContainer
20 22 
@@ -89,3 +91,53 @@ def test_native_config_restores_full_state_after_async_and_final_save(tmp_path,
89 for requested, saved in ((1, 1), (-1, 2)):91 for requested, saved in ((1, 1), (-1, 2)):
90 assert restored.load(requested)92 assert restored.load(requested)
91 torch.testing.assert_close(_stateful_to_state_dict(restored.states), expected[saved], rtol=0, atol=0)93 torch.testing.assert_close(_stateful_to_state_dict(restored.states), expected[saved], rtol=0, atol=0)
94+ 
95+ 
96+def test_native_final_save_exports_hf_weights_and_preserves_integer_buffers(tmp_path, process_group):
97+ class HFExportAdapter:
98+ fqn_to_index_mapping = {"hf.weight": 1, "hf.counter": 1}
99+ 
100+ @staticmethod
101+ def to_hf(state_dict):
102+ return {"hf.weight": state_dict["weight"], "hf.counter": state_dict["counter"]}
103+ 
104+ weights = torch.tensor([[0.123456, -0.654321]], dtype=torch.float32)
105+ with torch.random.fork_rng(devices=[]):
106+ model = torch.nn.Linear(2, 1, bias=False)
107+ with torch.no_grad():
108+ model.weight.copy_(weights)
109+ model.register_buffer("counter", torch.tensor(3, dtype=torch.int64))
110+ optimizers = OptimizersContainer.Config(
111+ optimizers=[AdamW.Config(pattern=".*", lr=0.1, fused=False)],
112+ ).build(model_parts=[model])
113+ scheduler = LRSchedulersContainer.Config().build(optimizers=optimizers, training_steps=3)
114+ manager = TorchCheckpointingManager.Config(
115+ folder=str(tmp_path / "checkpoint"),
116+ last_save_in_hf=True,
117+ last_save_model_only=True,
118+ export_dtype="float16",
119+ ).build(
120+ storage_config=LocalFileSystemStorageConfig(use_direct_io=False),
121+ dataloader=None,
122+ model_parts=[model],
123+ optimizers=optimizers,
124+ lr_schedulers=scheduler,
125+ ema=None,
126+ states={},
127+ sd_adapter=HFExportAdapter(),
128+ )
129+ 
130+ with closing(manager):
131+ assert manager.save(2, last_step=True)
132+ 
133+ checkpoint_dir = tmp_path / "checkpoint" / "step-2"
134+ index = json.loads((checkpoint_dir / "model.safetensors.index.json").read_text())
135+ assert set(index["weight_map"]) == {"hf.weight", "hf.counter"}
136+ exported = {}
137+ for shard in set(index["weight_map"].values()):
138+ exported.update(load_file(checkpoint_dir / shard))
139+ assert set(exported) == {"hf.weight", "hf.counter"}
140+ assert exported["hf.weight"].dtype == torch.float16
141+ torch.testing.assert_close(exported["hf.weight"], weights.to(torch.float16), rtol=0, atol=0)
142+ assert exported["hf.counter"].dtype == torch.int64
143+ torch.testing.assert_close(exported["hf.counter"], torch.tensor(3, dtype=torch.int64), rtol=0, atol=0)
@@ -6,23 +6,37 @@
6 6 
7"""Opt-in local native checkpointing for the fixed TorchTitan API on NPU."""7"""Opt-in local native checkpointing for the fixed TorchTitan API on NPU."""
8 8 
9+import logging
9from dataclasses import dataclass10from dataclasses import dataclass
11+from typing import TYPE_CHECKING, Any
10 12 
11import torch13import torch
14+import torch.distributed as dist
12from torch.distributed.checkpoint.state_dict_saver import _stateful_to_state_dict15from torch.distributed.checkpoint.state_dict_saver import _stateful_to_state_dict
16+from torch_checkpointing.checkpoint_layout import LayoutInfo, SafetensorsSerialization
17+from torch_checkpointing.checkpoint_writer import CallbackArgs
18+from torch_checkpointing.hf.consolidation import consolidate_hf_safetensors_checkpoint
19+from torch_checkpointing.schema import ItemSpec
20+from torch_checkpointing.storage.filesystem import LocalFileSystemStorageConfig
13from torchtitan.components.checkpointer import torch_checkpointing as upstream21from torchtitan.components.checkpointer import torch_checkpointing as upstream
14from torchtitan.components.checkpointer.base import MODEL22from torchtitan.components.checkpointer.base import MODEL
15-from torchtitan.components.checkpointer.torch_checkpointing import _default_backend_config, _sync_save_config23+from torchtitan.components.checkpointer.torch_checkpointing import (
16-from torchtitan.tools.utils import GarbageCollection24+ _default_backend_config,
17- 25+ _item_specs,
18-from torchtitan_npu.patches.torchtitan.components.checkpointer.torch_checkpointing import (26+ _sync_save_config,
19- TorchCheckpointingManager as NativeLoadManager,
20)27)
28+from torchtitan.tools import filesystem
29+from torchtitan.tools.utils import GarbageCollection
21 30 
22from .torch_checkpointing_backend import adapt_checkpoint_manager31from .torch_checkpointing_backend import adapt_checkpoint_manager
23 32 
33+if TYPE_CHECKING:
34+ from collections.abc import Callable
24 35 
25-class TorchCheckpointingManager(NativeLoadManager):36+logger = logging.getLogger(__name__)
37+ 
38+ 
39+class TorchCheckpointingManager(upstream.TorchCheckpointingManager):
26 """Native checkpoint manager with NPU staging and metadata collectives."""40 """Native checkpoint manager with NPU staging and metadata collectives."""
27 41 
28 @dataclass(kw_only=True, slots=True)42 @dataclass(kw_only=True, slots=True)
@@ -35,6 +49,7 @@ class TorchCheckpointingManager(NativeLoadManager):
35 49 
36 @torch.no_grad()50 @torch.no_grad()
37 def _save_last_step(self, curr_step: int) -> None:51 def _save_last_step(self, curr_step: int) -> None:
52+ # The final save creates a fresh synchronous backend that also needs NPU adaptation.
38 if self.last_save_model_only:53 if self.last_save_model_only:
39 model_state = self.states[MODEL].state_dict()54 model_state = self.states[MODEL].state_dict()
40 model_state = {55 model_state = {
@@ -43,19 +58,63 @@ class TorchCheckpointingManager(NativeLoadManager):
43 else value58 else value
44 for key, value in model_state.items()59 for key, value in model_state.items()
45 }60 }
46- states = {MODEL: model_state}61+ states: dict[str, Any] = {MODEL: model_state}
62+ logger.info(f"Saving a model only checkpoint in {self.export_dtype} at last step, step {curr_step}.")
47 else:63 else:
48 states = self.states64 states = self.states
65+ logger.info(f"Saving a full checkpoint at last step, step {curr_step}.")
66+ 
67+ checkpoint_id = self._create_checkpoint_id(curr_step)
49 self._manager.close()68 self._manager.close()
50- config = _default_backend_config(69+ storage_config = self._manager_config.storage_config
70+ input_checkpoint_id = checkpoint_id
71+ item_specs: dict[str, ItemSpec] | None = None
72+ pre_finalize_callback: Callable[[CallbackArgs], None] | None = None
73+ if self.last_save_in_hf:
74+ assert self.sd_adapter is not None
75+ states = {MODEL: self.sd_adapter.to_hf(states[MODEL])}
atomgit-bot
atomgit-botatomgit-bot27 days ago

🟡 Medium Priority

变更行:torch_checkpointing.py:79 新增 states = {MODEL: self.sd_adapter.to_hf(states[MODEL])},该行位于 if self.last_save_in_hf: 分支内,而 states 在到达此处前有两种形态:

受影响契约:sd_adapter.to_hf(state_dict) 接收的是参数字典(仓库内 tools/checkpoint_conversion/convert_to_hf.py:138、export_quantized_hf.py:847 均先取 state_dict 再 to_hf;测试里的 _LinearHFAdapter.to_hf 直接做 state_dict.items())。把 Stateful 传进去会在 to_hf 内部触发 AttributeError: 'ModelWrapper' object has no attribute 'items'。

失败模式:用户以 last_save_model_only=False + last_save_in_hf=True 启动训练(合法的可选组合,二者均为 NativeManager.Config 字段),训练在最后一步 _save_last_step 时抛异常,既不会产出 HF 权重,也不再产出可 resume 的全量 checkpoint(此时 self._manager 已在第 72 行 close)。次要后果:该分支跳过了第 57-62 行的 export_dtype 转换,即使把类型修正为 dict,导出权重也会保持训练 dtype 而非 export_dtype。

触发条件与不确定度:需要显式设置 last_save_model_only=False;若上游 Config 对该组合有校验(视上游实现而定)则该路径不可达,因此置信度不设为高。当前新增测试只覆盖默认(model-only)路径,无法发现该问题。

建议:在 HF 分支开始前先把 MODEL 状态规整为 state dict(self.states[MODEL].state_dict())并施加 export_dtype,再交给 sd_adapter.to_hf;不要在不同分支中对同一变量分别承载 Stateful 与 dict 两种形态。并补充 last_save_model_only=False 且 last_save_in_hf=True 的单测。

likedislike
Incorrect?
jiangna1111
jiangna1111
26 days ago Comments:
likedislike
76+ input_checkpoint_id = filesystem.join(checkpoint_id, "sharded")
77+ item_specs = _item_specs()
78+ model_spec = item_specs[MODEL]
79+ item_specs[MODEL] = ItemSpec(
80+ requires_copy=model_spec.requires_copy,
81+ layout=LayoutInfo(
82+ f"{MODEL}_{{rank}}.safetensors",
83+ SafetensorsSerialization(),
84+ ),
85+ resharder=model_spec.resharder,
86+ required=model_spec.required,
87+ )
88+ fqn_to_index_mapping = self.sd_adapter.fqn_to_index_mapping
89+ hf_storage_config = storage_config or LocalFileSystemStorageConfig(use_direct_io=False)
90+ 
91+ # CallbackArgs.path is the shard directory before the backend's atomic rename.
xuyujun
xuyujunxuyujun25 days ago

这次修复的核心是 HF 导出的回调签名和分片目录,但新增 UT 只检查配置选到了哪个实现,已有 native 保存恢复用例也不会进入 HF 分支。以后这里再次退化,这些测试仍会通过。建议补一条 CPU 实际导出用例:开启 last_save_in_hf,最终保存后读取索引和 safetensors,检查 HF key、浮点 dtype/值,以及整数 buffer。把 PR 描述里已有人工验证的最小部分固化即可,不需要增加长跑。

likedislike
jiangna1111
jiangna1111
25 days ago Comments:
likedislike
92+ def pre_finalize_callback(args: CallbackArgs) -> None:
93+ # The backend's write barrier runs after this callback; synchronize before consolidation.
94+ if dist.is_initialized():
95+ dist.barrier()
96+ consolidate_hf_safetensors_checkpoint(
97+ args.path,
98+ output_dir=checkpoint_id,
99+ item_key=MODEL,
100+ fqn_to_index_mapping=fqn_to_index_mapping,
101+ storage_config=hf_storage_config,
102+ )
103+ 
104+ manager_config = _default_backend_config(
51 _sync_save_config(),105 _sync_save_config(),
52- storage_config=self._manager_config.storage_config,106+ storage_config=storage_config,
107+ items=item_specs,
53 )108 )
54- # The fixed upstream final-save path builds a fresh backend directly.109+ # torch_checkpointing 0.1.1 uses CallbackArgs; the upstream helper still types the old two-argument API.
55- manager = config.build()110+ manager_config.pre_finalize_callback = pre_finalize_callback
111+ manager = manager_config.build()
56 try:112 try:
57 adapt_checkpoint_manager(manager)113 adapt_checkpoint_manager(manager)
58- manager.save(self._create_checkpoint_id(curr_step), _stateful_to_state_dict(states))114+ manager.save(
115+ input_checkpoint_id,
116+ _stateful_to_state_dict(states),
117+ )
59 finally:118 finally:
60 manager.close()119 manager.close()
61- GarbageCollection.collect("GC collection invoked by native NPU checkpointer.")120+ GarbageCollection.collect("GC collection invoked by checkpointer.")
@@ -13,6 +13,7 @@ from dataclasses import dataclass, field
13from typing import Annotated, cast13from typing import Annotated, cast
14 14 
15import tyro15import tyro
16+from torchtitan.components.checkpointer.base import BaseCheckpointManager
16from torchtitan.config import derive17from torchtitan.config import derive
17from torchtitan.trainer import Trainer18from torchtitan.trainer import Trainer
18from torchtitan.training_engine import TrainingEngine19from torchtitan.training_engine import TrainingEngine
@@ -87,7 +88,7 @@ class TrainerEx(Trainer):
87 # expose NPU fields to Tyro; recipes explicitly instantiate optional components.88 # expose NPU fields to Tyro; recipes explicitly instantiate optional components.
88 optim: OptimConfig = field(default_factory=OptimConfig) # pyrefly: ignore [bad-override]89 optim: OptimConfig = field(default_factory=OptimConfig) # pyrefly: ignore [bad-override]
89 checkpointer: Annotated[ # pyrefly: ignore [bad-override]90 checkpointer: Annotated[ # pyrefly: ignore [bad-override]
90- CheckpointManager.Config | None, tyro.conf.AvoidSubcommands91+ BaseCheckpointManager.Config | None, tyro.conf.AvoidSubcommands
91 ] = None92 ] = None
92 compile: Annotated[CompileConfig | None, tyro.conf.AvoidSubcommands] = None # pyrefly: ignore [bad-override]93 compile: Annotated[CompileConfig | None, tyro.conf.AvoidSubcommands] = None # pyrefly: ignore [bad-override]
93 profiler: CANNProfiler.Config = field( # pyrefly: ignore [bad-override]94 profiler: CANNProfiler.Config = field( # pyrefly: ignore [bad-override]
@@ -103,6 +104,13 @@ class TrainerEx(Trainer):
103 # ``slots=True`` dataclasses are recreated by the decorator, so a104 # ``slots=True`` dataclasses are recreated by the decorator, so a
104 # zero-argument ``super()`` can retain the pre-decoration class cell.105 # zero-argument ``super()`` can retain the pre-decoration class cell.
105 Trainer.Config.__post_init__(self)106 Trainer.Config.__post_init__(self)
107+ if type(self.checkpointer).__module__ == "torchtitan.components.checkpointer.torch_checkpointing":
jiangna1111
jiangna1111jiangna111125 days ago

Trainer 支持不同 checkpoint 配置,并把上游原生配置换成 NPU 实现,避免训练时用错后端。

likedislike
108+ from torchtitan.components.checkpointer import torch_checkpointing as native
109+ 
110+ from torchtitan_npu.extensions.torchtitan.components import torch_checkpointing as npu_native
111+ 
112+ if type(self.checkpointer) is native.TorchCheckpointingManager.Config:
113+ self.checkpointer = derive(self.checkpointer, npu_native.TorchCheckpointingManager.Config)
106 # Single switch: ``--training.enable-cpu-offload`` drives both the114 # Single switch: ``--training.enable-cpu-offload`` drives both the
107 # FSDP offload policy (read by parallelize) and, through this115 # FSDP offload policy (read by parallelize) and, through this
108 # carrier field, the optimizer-container selection in the116 # carrier field, the optimizer-container selection in the
@@ -1,69 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-# Copyright (c) Meta Platforms, Inc. and affiliates.
3-#
4-# This source code is licensed under the BSD-style license found in the
5-# LICENSE file in the root directory of this source tree.
6- 
7-# Upstream-PR: https://github.com/pytorch/torchtitan/pull/4191
8-# Upstream-Commit: 3dadef77c25d7373e628b7db1cd7345b4af067fc
9-# Remove this opt-in subclass after the pinned TorchTitan includes #4191, and
10-# inherit its native manager directly. Do not backport the global Base/DCP
11-# refactor: dc3985 still dispatches through the _load hook.
12- 
13-"""Native-load backport for TorchTitan's dc3985 _load hook."""
14- 
15-import logging
16- 
17-import torch
18-from torch.distributed.checkpoint.state_dict_saver import _stateful_to_state_dict
19-from torch.distributed.checkpoint.stateful import Stateful
20-from torchtitan.components.checkpointer.base import MODEL
21-from torchtitan.components.checkpointer.torch_checkpointing import (
22- TorchCheckpointingManager as UpstreamTorchCheckpointingManager,
23-)
24-from torchtitan.observability import structured_logger as sl
25- 
26-logger = logging.getLogger(__name__)
27- 
28- 
29-class TorchCheckpointingManager(UpstreamTorchCheckpointingManager):
30- """Internal load backport; build through the NPU extension's Config."""
31- 
32- @sl.log_trace_span("checkpoint_load")
33- @torch.no_grad()
34- def _load(self, step: int = -1) -> bool:
35- model_only = step == 0
36- if step >= 0:
37- checkpoint_id = self._create_checkpoint_id(step)
38- else:
39- latest = self._find_load_step()
40- if latest >= 0:
41- checkpoint_id = self._create_checkpoint_id(latest)
42- model_only = latest == 0
43- else:
44- if not self.initial_load_path:
45- return False
46- if self.initial_load_in_hf:
47- raise ValueError("TorchCheckpointingManager does not yet support loading Hugging Face checkpoints.")
48- checkpoint_id = self.initial_load_path
49- model_only = self.initial_load_model_only
50- if not self._storage.isdir(checkpoint_id):
51- raise FileNotFoundError(f"Native checkpoint directory does not exist: {checkpoint_id}")
52- if not self._is_valid_checkpoint(checkpoint_id):
53- raise ValueError(f"Checkpoint {checkpoint_id!r} is not a native torch_checkpointing checkpoint.")
54- if model_only:
55- selected = {MODEL: self.states[MODEL]}
56- else:
57- for exclude_key in self.exclude_from_loading:
58- if exclude_key not in self.states:
59- raise ValueError(f"{exclude_key} not found in state_dict.")
60- selected = {key: value for key, value in self.states.items() if key not in self.exclude_from_loading}
61- state_dict = _stateful_to_state_dict(selected)
62- loaded = self._manager.load(checkpoint_id, into=state_dict, strict=True)
63- for key, target in selected.items():
64- if isinstance(target, Stateful):
65- target.load_state_dict(state_dict[key])
66- elif loaded[key] is not target:
67- raise TypeError(f"Cannot restore non-Stateful checkpoint state {key!r} of type {type(target).__name__}")
68- logger.info("Loaded native %s checkpoint from %s.", "model-only" if model_only else "full-state", checkpoint_id)
69- return True