Merged
feat: adapt optional native checkpoint backend on NPU #1156
feat: adapt optional native checkpoint backend on NPU #1156
Merged
jiangna1111Add on Nov 2
Total: 13 files changed+586-10
@@ -70,7 +70,7 @@ _setup_torchtitan "${TORCHTITAN_DIR}"
70# wheels, never the whole file, whose torch/torch_npu pins differ from the image70# wheels, never the whole file, whose torch/torch_npu pins differ from the image
71# build.71# build.
72"${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir attn-gym==0.0.16 spmd_types==0.2.5 \72"${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir attn-gym==0.0.16 spmd_types==0.2.5 \
73- 'torch_checkpointing>=0.1.0' 'torch_remat>=0.2.0'73+ 'torch_checkpointing==0.1.1' 'torch_remat>=0.2.0'
74# Grain needs its data-pipeline dependencies (for example etils and array-record).74# Grain needs its data-pipeline dependencies (for example etils and array-record).
75# Its dependency graph does not include torch or torch_npu.75# Its dependency graph does not include torch or torch_npu.
76"${PYTHON_BIN}" -m pip install --break-system-packages --no-cache-dir grain==0.2.1876"${PYTHON_BIN}" -m pip install --break-system-packages --no-cache-dir grain==0.2.18
@@ -59,7 +59,7 @@ pip install --no-deps -e .
59# re-running the whole file would upgrade the CANN stack mid-job (it broke the59# re-running the whole file would upgrade the CANN stack mid-job (it broke the
60# fused-op smoke tests once). New pure-Python runtime wheels go here by name.60# fused-op smoke tests once). New pure-Python runtime wheels go here by name.
61pip install --no-deps attn-gym==0.0.16 spmd_types==0.2.5 \61pip install --no-deps attn-gym==0.0.16 spmd_types==0.2.5 \
62- 'torch_checkpointing>=0.1.0' 'torch_remat>=0.2.0'62+ 'torch_checkpointing==0.1.1' 'torch_remat>=0.2.0'
63# Resolve Grain's own data-pipeline dependencies without changing the torch stack.63# Resolve Grain's own data-pipeline dependencies without changing the torch stack.
64pip install grain==0.2.1864pip install grain==0.2.18
65 65 
@@ -23,6 +23,19 @@
23`enable=False` 时既不会保存 checkpoint,也不会执行 checkpoint 加载。训练命令需要显式23`enable=False` 时既不会保存 checkpoint,也不会执行 checkpoint 加载。训练命令需要显式
24传入 `--checkpoint.enable`,或在 Python 配置中设置 `checkpoint.enable = True`。24传入 `--checkpoint.enable`,或在 Python 配置中设置 `checkpoint.enable = True`。
25 25 
26+## 可选 torch_checkpointing 后端
27+ 
28+默认使用 DCP。native 后端当前推荐使用 `torch_checkpointing==0.1.1`,可在 Python 训练配置中选择:
29+ 
30+```python
31+import torchtitan_npu
32+from torchtitan.components.checkpointer.torch_checkpointing import TorchCheckpointingManager
33+ 
34+config.checkpoint = TorchCheckpointingManager.Config(enable=True, folder="native-checkpoint")
35+```
36+ 
37+native 与 DCP 使用不同的 checkpoint 目录。
38+ 
26## checkpoint 格式与目录39## checkpoint 格式与目录
27 40 
28### DCP41### DCP

Config.build → 本仓 native manager → NPU 适配入口 → torch_checkpointing 后端回归验证

likedislike
@@ -0,0 +1,92 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2+#
3+# This source code is licensed under the BSD-style license found in the
4+# LICENSE file in the root directory of this source tree.
5+ 
6+"""CPU round trip through the local native-checkpoint integration."""
7+ 
8+import copy
9+from contextlib import closing
10+ 
11+import pytest
12+import torch
13+import torch.distributed as dist
14+from torch.distributed.checkpoint.state_dict_saver import _stateful_to_state_dict
15+ 
16+pytest.importorskip("torch_checkpointing")
xuyujun
xuyujunxuyujunNov 5

importorskip("torch_checkpointing") 只保证包存在、不保证 revision。实测装 0.1.0 时本文件在 collection 阶段就 ModuleNotFoundError: No module named 'torch_checkpointing.default_resharder',整轮 UT 中断(和 11-04 METADATA_FILE_NAME 那次 CI 失败同源)。而 .ci/unit_test.sh 仍是 >=0.1.0,docs 写 ==0.1.1。建议改为 pytest.importorskip("torch_checkpointing.default_resharder"),并把 .ci/unit_test.sh 收紧为 ==0.1.1。

likedislike
jiangna1111
jiangna1111
Nov 6 Comments:
likedislike
17+ 
18+from torch_checkpointing.storage.filesystem import LocalFileSystemStorageConfig
19+from torchtitan.components.optimizer import LRSchedulersContainer, OptimizersContainer, ParamGroupConfig
20+ 
21+from torchtitan_npu.extensions.torchtitan.components.torch_checkpointing import TorchCheckpointingManager
22+ 
23+pytestmark = pytest.mark.cpu
24+ 
25+ 
26+class _Progress:
27+ def __init__(self):
28+ self.step = 0
29+ 
30+ def state_dict(self):
31+ return {"step": self.step}
32+ 
33+ def load_state_dict(self, state):
34+ self.step = state["step"]
35+ 
36+ 
37+@pytest.fixture(name="process_group")
38+def fixture_process_group(tmp_path):
39+ dist.init_process_group("gloo", init_method=(tmp_path / "rendezvous").as_uri(), rank=0, world_size=1)
40+ yield
41+ dist.destroy_process_group()
42+ 
43+ 
44+def test_native_config_restores_full_state_after_async_and_final_save(tmp_path, process_group):
45+ def build_manager(*, load_only):
46+ with torch.random.fork_rng(devices=[]):
47+ model = torch.nn.Linear(2, 1, bias=False)
48+ optimizers = OptimizersContainer.Config(
49+ implementation="for-loop",
50+ param_groups=[ParamGroupConfig(pattern=".*", optimizer_name="AdamW", optimizer_kwargs={"lr": 0.1})],
51+ ).build(model_parts=[model])
52+ scheduler = LRSchedulersContainer(optimizers, lr_lambda=lambda step: 1.0)
53+ progress, dataloader = _Progress(), _Progress()
54+ manager = TorchCheckpointingManager.Config(
55+ enable=True,
56+ folder=str(tmp_path / "checkpoint"),
57+ interval=1,
58+ load_only=load_only,
59+ last_save_model_only=False,
60+ initial_load_path=str(tmp_path / "unused-initial-hf") if load_only else None,
61+ initial_load_in_hf=load_only,
62+ initial_load_in_hf_quantized=load_only,
63+ ).build(
64+ storage_config=LocalFileSystemStorageConfig(use_direct_io=False),
65+ dataloader=dataloader,
66+ model_parts=[model],
67+ optimizers=optimizers,
68+ lr_schedulers=scheduler,
69+ states={"progress": progress},
70+ sd_adapter=None,
71+ )
72+ return manager, model, optimizers, scheduler, progress, dataloader
73+ 
74+ manager, model, optimizers, scheduler, progress, dataloader = build_manager(load_only=False)
75+ expected = {}
76+ with closing(manager):
77+ for step in (1, 2):
78+ optimizers.zero_grad()
79+ model(torch.tensor([[0.25, -0.5]])).square().sum().backward()
80+ optimizers.step()
81+ scheduler.step()
82+ progress.step = dataloader.step = step
83+ expected[step] = copy.deepcopy(_stateful_to_state_dict(manager.states))
84+ assert manager.save(step, last_step=step == 2)
85+ manager.maybe_wait_for_staging()
86+ manager.maybe_wait_for_saving()
87+ 
88+ restored, *_ = build_manager(load_only=True)
89+ with closing(restored):
90+ for requested, saved in ((1, 1), (-1, 2)):
91+ assert restored.load(requested)
92+ torch.testing.assert_close(_stateful_to_state_dict(restored.states), expected[saved], rtol=0, atol=0)
@@ -0,0 +1,62 @@
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+"""Opt-in local native checkpointing for the fixed TorchTitan API on NPU."""
8+ 
9+from dataclasses import dataclass
10+ 
11+import torch
12+from torch.distributed.checkpoint.state_dict_saver import _stateful_to_state_dict
13+from torchtitan.components.checkpointer import torch_checkpointing as upstream
14+from torchtitan.components.checkpointer.base import MODEL
15+from torchtitan.components.checkpointer.torch_checkpointing import _default_backend_config, _sync_save_config
16+from torchtitan.tools.utils import GarbageCollection
17+ 
18+from torchtitan_npu.patches.torchtitan.components.checkpointer.torch_checkpointing import (
19+ TorchCheckpointingManager as NativeLoadManager,
20+)
21+ 
22+from .torch_checkpointing_backend import adapt_checkpoint_manager
23+ 
24+ 
25+class TorchCheckpointingManager(NativeLoadManager):
26+ """Native checkpoint manager with NPU staging and metadata collectives."""
27+ 
28+ @dataclass(kw_only=True, slots=True)
29+ class Config(upstream.TorchCheckpointingManager.Config):
30+ pass
31+ 
32+ def __init__(self, config: Config, **kwargs) -> None:
33+ super().__init__(config, **kwargs)
34+ if self.enable:
35+ adapt_checkpoint_manager(self._manager)
jiangna1111
jiangna1111jiangna1111Nov 5

This code comment section is from+32To+35

上游新建的带有旧后端的 CUDA 假设,适配npu

likedislike
36+ 
37+ @torch.no_grad()
38+ def _save_last_step(self, curr_step: int) -> None:
39+ if self.last_save_model_only:
40+ model_state = self.states[MODEL].state_dict()
41+ model_state = {
42+ key: value.to(self.export_dtype)
43+ if isinstance(value, torch.Tensor) and value.is_floating_point() and value.dtype != self.export_dtype
44+ else value
45+ for key, value in model_state.items()
46+ }
47+ states = {MODEL: model_state}
48+ else:
49+ states = self.states
50+ self._manager.close()
51+ config = _default_backend_config(
52+ _sync_save_config(),
53+ storage_config=self._manager_config.storage_config,
54+ )
55+ # The fixed upstream final-save path builds a fresh backend directly.
56+ manager = config.build()
57+ try:
58+ adapt_checkpoint_manager(manager)
59+ manager.save(self._create_checkpoint_id(curr_step), _stateful_to_state_dict(states))
60+ finally:
61+ manager.close()
62+ GarbageCollection.collect("GC collection invoked by native NPU checkpointer.")
@@ -0,0 +1,105 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2+#
3+# This source code is licensed under the BSD-style license found in the
4+# LICENSE file in the root directory of this source tree.
5+ 
6+"""Instance-local NPU adapters for torch_checkpointing 0.1.1."""
7+ 
8+from __future__ import annotations
9+ 
10+from dataclasses import replace
11+ 
12+import torch
13+import torch.distributed as dist
14+import torch_npu
15+from torch_checkpointing._state_dict_stager import StateDictStager, StorageManager
16+from torch_checkpointing.checkpoint_saver import AsyncCheckpointSaver
17+from torch_checkpointing.metadata_manager import DefaultMetadataManager
18+from torch_checkpointing.staging import DefaultStager
19+ 
20+ 
21+class _PinnedStoragePool(StorageManager):
jiangna1111

改用 NPU 运行时分配并管理的固定 CPU 内存,torch-npu带上 #46095 后可复用 host-registration 实现

likedislike
22+ def delete_unused(self):
23+ for size, storages in self._size_to_storages.items():
24+ del storages[self._size_to_storages_next_index[size] :]
25+ 
26+ def _new_storage(self, size):
27+ # Allocator-owned pinning needs no CUDA host-register/unregister calls.
28+ return torch.empty(size, dtype=torch.uint8, device="cpu").pin_memory(device="npu").untyped_storage()
29+ 
30+ 
31+class _NpuStateDictStager(StateDictStager):
32+ def __init__(self, config):
33+ # The upstream non-blocking default probes CUDA; retain the caller's setting.
34+ super().__init__(use_non_blocking_copy=config.use_non_blocking_copy)
35+ self._storage_manager = _PinnedStoragePool(pin_memory=True, share_memory=False, pin_memory_min_bytes=0)
36+ # Pinned-to-shared staging uses an extra host buffer and CPU copy.
37+ # TODO: Revisit with Ascend/pytorch #46095 after validating shared-memory pinning.
38+ self._shared_stager = StateDictStager(share_memory=config.use_shared_memory)
xuyujun
xuyujunxuyujunNov 5

这里是两遍 staging(pinned 池 + _shared_stager),异步保存会多一份完整 host 拷贝;且 use_non_blocking_copy 默认走 CUDA 版 can_pin_memory(),NPU 上恒为 False,D2H 退化成阻塞拷贝。建议注释写明 #46095 落地前的双份代价,并显式传 use_non_blocking_copy=True(或在 docs 标注该性能缺口)。

likedislike
jiangna1111
jiangna1111
Nov 6 Comments:
likedislike
39+ 
40+ def stage(self, state_dict):
41+ stream = torch_npu.npu.current_stream()
42+ try:
43+ host = super().stage(state_dict)
44+ finally:
45+ # Drain partial D2H copies before shared staging or error propagation.
46+ stream.synchronize()
47+ return self._shared_stager.stage(host)
48+ 
49+ def close(self):
50+ super().close()
51+ self._shared_stager.close()
52+ 
53+ def _stage_untyped_storage(self, storage):
54+ if storage.device.type == "cpu":
55+ return storage
56+ return super()._stage_untyped_storage(storage)
57+ 
58+ 
59+class _NpuStager(DefaultStager):
60+ def __init__(self, config):
61+ super().__init__(replace(config, use_pinned_memory=False))
62+ # A negative index makes the inherited CUDA-only device guards no-ops.
63+ self._cuda_device = -1
64+ self._npu_device = torch_npu.npu.current_device() if self._accelerator_available else None
65+ if self._accelerator_available and config.use_pinned_memory:
66+ self._state_dict_stager.close()
67+ self._state_dict_stager = _NpuStateDictStager(config)
68+ 
69+ def stage(self, state_dict, keys_not_requiring_copy=()):
70+ with torch.accelerator.device_index(self._npu_device):
71+ return super().stage(state_dict, keys_not_requiring_copy)
72+ 
73+ def _init_worker_thread(self):
74+ if self._npu_device is not None:
75+ torch_npu.npu.set_device(self._npu_device)
76+ 
77+ 
78+class _NpuMetadataManager(DefaultMetadataManager):
jiangna1111

torch-checkpointing的ee625c6 更新后,可以直接复用DefaultMetadataManager

likedislike
79+ def _all_gather_pickled_data(self, data, process_group=None):
80+ # Let the process group choose the collective device (NPU for HCCL).
81+ gathered = [None] * dist.get_world_size(process_group)
82+ dist.all_gather_object(gathered, data, group=process_group)
83+ result = {}
84+ for group_rank, value in enumerate(gathered):
85+ rank = dist.get_global_rank(process_group, group_rank) if process_group is not None else group_rank
86+ result[rank] = value
87+ return result
88+ 
89+ 
90+def adapt_checkpoint_manager(manager) -> None:
91+ """Replace device leaves before first use; retain upstream ownership."""
92+ # pylint: disable=protected-access
93+ # The fixed backend exposes no stager/metadata injection point.
94+ # Its saver and loader must share the same replacement metadata cache.
95+ metadata = manager._metadata_manager
96+ if metadata is not None:
97+ replacement = _NpuMetadataManager(rank_info=metadata._rank_info)
98+ manager._metadata_manager = replacement
99+ manager._saver._metadata_manager = replacement
100+ manager._loader._metadata_manager = replacement
101+ metadata.close()
102+ if isinstance(manager._saver, AsyncCheckpointSaver):
103+ stager = _NpuStager(manager._config.save.staging_config)
104+ manager._saver.stager.close()
105+ manager._saver._checkpoint_stager = stager
@@ -13,7 +13,6 @@ from torchtitan.experiments.graph_trainer.trainer import GraphTrainer
13from torchtitan_npu.config import manager as config_manager13from torchtitan_npu.config import manager as config_manager
14from torchtitan_npu.config.configs import OptimizerConfig, TrainingConfig14from torchtitan_npu.config.configs import OptimizerConfig, TrainingConfig
15from torchtitan_npu.config.converters import TrainerConfigConverter15from torchtitan_npu.config.converters import TrainerConfigConverter
16-from torchtitan_npu.extensions.torchtitan.components.checkpoint import CheckpointManager
17 16 
18from ...tools.profiler import CANNProfiler17from ...tools.profiler import CANNProfiler
19from ...trainer import TrainerEx18from ...trainer import TrainerEx
@@ -51,7 +50,6 @@ config_manager.register_config_converter(
51 target_type=GraphTrainerEx.Config,50 target_type=GraphTrainerEx.Config,
52 component_types={51 component_types={
53 "optimizer": OptimizerConfig,52 "optimizer": OptimizerConfig,
54- "checkpoint": CheckpointManager.Config,
55 "profiler": CANNProfiler.Config,53 "profiler": CANNProfiler.Config,
56 "training": TrainingConfig,54 "training": TrainingConfig,
57 },55 },
@@ -10,6 +10,8 @@ from copy import copy
10from dataclasses import dataclass, field10from dataclasses import dataclass, field
11from typing import Any11from typing import Any
12 12 
13+from torchtitan.components.checkpointer.base import BaseCheckpointManager
14+from torchtitan.components.checkpointer.dcp import CheckpointManager as DCPCheckpointManager
13from torchtitan.config import derive15from torchtitan.config import derive
14from torchtitan.tools.logging import logger16from torchtitan.tools.logging import logger
15from torchtitan.trainer import Trainer17from torchtitan.trainer import Trainer
@@ -32,6 +34,25 @@ from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import A
32from .tools.profiler import CANNProfiler34from .tools.profiler import CANNProfiler
33 35 
34 36 
37+def convert_checkpoint_config(checkpoint: BaseCheckpointManager.Config) -> BaseCheckpointManager.Config:
38+ """Adapt upstream defaults without replacing custom backend implementations."""
39+ source_type = type(checkpoint)
40+ # The EMA patch replaces the public DCP binding, while earlier recipes
41+ # may still hold its original Config (the actual EMA Config parent).
42+ if source_type in (DCPCheckpointManager.Config, DCPCheckpointManager.Config.__bases__[0]):
43+ return derive(checkpoint, CheckpointManager.Config)
44+ # Keep the optional native package lazy for DCP and user-defined backends.
45+ if source_type.__module__ == "torchtitan.components.checkpointer.torch_checkpointing":
46+ from torchtitan.components.checkpointer.torch_checkpointing import (
47+ TorchCheckpointingManager as UpstreamNativeManager,
48+ )
49+ from torchtitan_npu.extensions.torchtitan.components.torch_checkpointing import TorchCheckpointingManager
50+ 
51+ if source_type is UpstreamNativeManager.Config:
52+ return derive(checkpoint, TorchCheckpointingManager.Config)
53+ return checkpoint
54+ 
55+ 
jiangna1111
jiangna1111jiangna1111Nov 5

This code comment section is from+37To+55

接管上游默认类,不直接覆盖全部子类(防止新后端被覆盖)

likedislike
35def set_allow_hf32(allow: bool) -> None:56def set_allow_hf32(allow: bool) -> None:
36 """Set HF32 consistently on the NPU math backends."""57 """Set HF32 consistently on the NPU math backends."""
37 58 
@@ -51,7 +72,7 @@ class TrainerEx(Trainer):
51 optimizer: OptimizerConfig = field( # pyrefly: ignore [bad-override]72 optimizer: OptimizerConfig = field( # pyrefly: ignore [bad-override]
52 default_factory=OptimizerConfig,73 default_factory=OptimizerConfig,
53 )74 )
54- checkpoint: CheckpointManager.Config = field( # pyrefly: ignore [bad-override]75+ checkpoint: BaseCheckpointManager.Config = field(
55 default_factory=CheckpointManager.Config,76 default_factory=CheckpointManager.Config,
56 )77 )
57 profiler: CANNProfiler.Config = field( # pyrefly: ignore [bad-override]78 profiler: CANNProfiler.Config = field( # pyrefly: ignore [bad-override]
@@ -67,6 +88,7 @@ class TrainerEx(Trainer):
67 # ``slots=True`` dataclasses are recreated by the decorator, so a88 # ``slots=True`` dataclasses are recreated by the decorator, so a
68 # zero-argument ``super()`` can retain the pre-decoration class cell.89 # zero-argument ``super()`` can retain the pre-decoration class cell.
69 Trainer.Config.__post_init__(self)90 Trainer.Config.__post_init__(self)
91+ self.checkpoint = convert_checkpoint_config(self.checkpoint)
70 # Single switch: ``--training.enable-cpu-offload`` drives both the92 # Single switch: ``--training.enable-cpu-offload`` drives both the
71 # FSDP offload policy (read by parallelize) and, through this93 # FSDP offload policy (read by parallelize) and, through this
72 # carrier field, the optimizer-container selection in the94 # carrier field, the optimizer-container selection in the
@@ -262,11 +284,11 @@ class TrainerEx(Trainer):
262 284 
263config_manager.register_config_converter(285config_manager.register_config_converter(
264 Trainer.Config,286 Trainer.Config,
287+ # Backend selection belongs to Config.__post_init__, not a DCP coercion here.
265 TrainerConfigConverter(288 TrainerConfigConverter(
266 target_type=TrainerEx.Config,289 target_type=TrainerEx.Config,
267 component_types={290 component_types={
268 "optimizer": OptimizerConfig,291 "optimizer": OptimizerConfig,
269- "checkpoint": CheckpointManager.Config,
270 "profiler": CANNProfiler.Config,292 "profiler": CANNProfiler.Config,
271 "training": TrainingConfig,293 "training": TrainingConfig,
272 },294 },
@@ -8,4 +8,5 @@ from . import (
8 determinism, # noqa: F4018 determinism, # noqa: F401
9 device_copy, # noqa: F4019 device_copy, # noqa: F401
10 inductor_runtime_estimation, # noqa: F40110 inductor_runtime_estimation, # noqa: F401
11+ multiprocessing_reductions, # noqa: F401
11)12)

修复旧版 torch-npu 引用已移除的 _namedtensor_internals 导致的异步 checkpoint 保存失败,#39675合入后删除对应patch

likedislike
@@ -0,0 +1,190 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2+#
3+# This source code is licensed under the BSD-style license found in the
4+# LICENSE file in the root directory of this source tree.
5+#
6+# Upstream PR: https://gitcode.com/Ascend/pytorch/pull/39675
7+# Source commit: 0c9b75c7dc40361dc05642f8781ce051ebc50876
8+# Remove this backport when the supported torch-npu builds include that fix.
9+#
10+# Derived from Ascend/pytorch, torch_npu/multiprocessing/reductions.py.
11+# Upstream license retained verbatim below; it also covers PyTorch-derived code.
12+#
13+# From PyTorch:
14+#
15+# Copyright (c) 2020, Huawei Technologies Co., Ltd
16+# Copyright (c) 2016- Facebook, Inc (Adam Paszke)
17+# Copyright (c) 2014- Facebook, Inc (Soumith Chintala)
18+# Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)
19+# Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)
20+# Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
21+# Copyright (c) 2011-2013 NYU (Clement Farabet)
22+# Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
23+# Copyright (c) 2006 Idiap Research Institute (Samy Bengio)
24+# Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
25+#
26+# From Caffe2:
27+#
28+# Copyright (c) 2016-present, Facebook Inc. All rights reserved.
29+#
30+# All contributions by Facebook:
31+# Copyright (c) 2016 Facebook Inc.
32+#
33+# All contributions by Google:
34+# Copyright (c) 2015 Google Inc.
35+# All rights reserved.
36+#
37+# All contributions by Yangqing Jia:
38+# Copyright (c) 2015 Yangqing Jia
39+# All rights reserved.
40+#
41+# All contributions by Kakao Brain:
42+# Copyright 2019-2020 Kakao Brain
43+#
44+# All contributions by Cruise LLC:
45+# Copyright (c) 2022 Cruise LLC.
46+# All rights reserved.
47+#
48+# All contributions from Caffe:
49+# Copyright(c) 2013, 2014, 2015, the respective contributors
50+# All rights reserved.
51+#
52+# All other contributions:
53+# Copyright(c) 2015, 2016 the respective contributors
54+# All rights reserved.
55+#
56+# Caffe2 uses a copyright model similar to Caffe: each contributor holds
57+# copyright over their contributions to Caffe2. The project versioning records
58+# all such contribution and copyright details. If a contributor wants to further
59+# mark their specific copyright on a particular contribution, they should
60+# indicate their copyright solely in the commit message of the change when it is
61+# committed.
62+#
63+# All rights reserved.
64+#
65+# Redistribution and use in source and binary forms, with or without
66+# modification, are permitted provided that the following conditions are met:
67+#
68+# 1. Redistributions of source code must retain the above copyright
69+# notice, this list of conditions and the following disclaimer.
70+#
71+# 2. Redistributions in binary form must reproduce the above copyright
72+# notice, this list of conditions and the following disclaimer in the
73+# documentation and/or other materials provided with the distribution.
74+#
75+# 3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America
76+# and IDIAP Research Institute nor the names of its contributors may be
77+# used to endorse or promote products derived from this software without
78+# specific prior written permission.
79+#
80+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
81+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
82+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
83+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
84+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
85+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
86+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
87+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
88+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
89+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
90+# POSSIBILITY OF SUCH DAMAGE.
91+#
92+ 
93+"""Backport the removed Named Tensor check fix for legacy torch-npu reducers."""
94+ 
95+# The upstream reducer uses torch-npu's private IPC/storage interfaces.
96+# pylint: disable=protected-access
97+ 
98+import torch
99+from torch_npu.multiprocessing import reductions as npu_reductions
100+ 
101+ 
102+def _npu_reduce_tensor(tensor):
103+ from torch.nested._internal.nested_tensor import NestedTensor
104+ 
105+ if tensor.is_nested and not isinstance(tensor, NestedTensor):
106+ return npu_reductions.reduce_nested_tensor(tensor)
107+ 
108+ storage = tensor._typed_storage()
109+ 
110+ if tensor.requires_grad and not tensor.is_leaf:
111+ raise RuntimeError(
112+ "Cowardly refusing to serialize non-leaf tensor which requires_grad, "
113+ "since autograd does not support crossing process boundaries. "
114+ "If you just want to transfer the data, call detach() on the tensor "
115+ "before serializing (e.g., putting it on the queue)."
116+ )
117+ 
118+ torch.utils.hooks.warn_if_has_hooks(tensor)
119+ 
120+ if storage._untyped_storage.device.type == "npu":
121+ # torch-npu adds _share_npu_ to TypedStorage at import time.
122+ (
123+ device,
124+ handle,
125+ storage_size_bytes,
126+ storage_offset_bytes,
127+ ref_counter_handle,
128+ ref_counter_offset,
129+ event_handle,
130+ event_sync_required,
131+ ) = storage._share_npu_() # pyrefly: ignore [missing-attribute]
132+ tensor_offset = tensor.storage_offset()
133+ npu_reductions.shared_cache[handle] = npu_reductions.StorageWeakRef(storage)
134+ return (
135+ npu_reductions.rebuild_npu_tensor,
136+ (
137+ type(tensor),
138+ tensor.size(),
139+ tensor.stride(),
140+ tensor_offset, # tensor offset in its storage
141+ type(storage),
142+ tensor.dtype,
143+ device,
144+ handle, # identifier which NPU allocation is the storage in.
145+ storage_size_bytes, # size(in bytes) of the storage
146+ storage_offset_bytes, # offset(in bytes) of the storage in the NPU allocation
147+ tensor.requires_grad,
148+ ref_counter_handle,
149+ ref_counter_offset,
150+ event_handle,
151+ event_sync_required,
152+ ),
153+ )
154+ elif storage._untyped_storage.device.type == "meta":
155+ return (
156+ npu_reductions.rebuild_meta_tensor,
157+ (
158+ type(tensor),
159+ tensor.size(),
160+ tensor.stride(),
161+ tensor.storage_offset(),
162+ tensor.dtype,
163+ tensor.untyped_storage().size(),
164+ tensor.requires_grad,
165+ ),
166+ )
167+ 
168+ # _backward_hooks purposely omitted here, see Note [Don't serialize hooks]
169+ metadata = (
170+ tensor.storage_offset(),
171+ tensor.size(),
172+ tensor.stride(),
173+ tensor.requires_grad,
174+ )
175+ return (npu_reductions.rebuild_tensor, (type(tensor), storage, metadata))
176+ 
177+ 
178+def apply() -> None:
179+ """Backport #39675 for legacy reducers referencing the removed _namedtensor_internals module."""
180+ # Only patch the legacy reducer when its referenced PyTorch module is absent.
181+ if (
182+ not hasattr(torch, "_namedtensor_internals")
183+ and "_namedtensor_internals" in npu_reductions._npu_reduce_tensor.__code__.co_names
184+ ):
185+ npu_reductions._npu_reduce_tensor = _npu_reduce_tensor
186+ # Re-register ForkingPickler too; rebinding the Python function is not enough.
187+ npu_reductions._add_reductions_methods()
188+ 
189+ 
190+apply()
@@ -0,0 +1,24 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2+#
3+# This source code is licensed under the BSD-style license found in the
4+# LICENSE file in the root directory of this source tree.
5+ 
6+# Upstream-PR: https://github.com/pytorch/torchtitan/pull/5177
7+ 
8+"""Bridge the metadata import until TorchTitan includes #5177 (fb45f5e8)."""
9+ 
10+from importlib.util import find_spec
11+ 
12+ 
13+def apply() -> None:
14+ if find_spec("torch_checkpointing") is None:
15+ return
16+ import torch_checkpointing.distributed_metadata
17+ 
18+ if not hasattr(torch_checkpointing.distributed_metadata, "METADATA_FILE_NAME"):
19+ from torch_checkpointing.metadata_serialization import METADATA_FILE_NAME
20+ 
21+ torch_checkpointing.distributed_metadata.__dict__["METADATA_FILE_NAME"] = METADATA_FILE_NAME
22+ 
23+ 
24+apply()

上游 pr #4191 合入后删除

likedislike
@@ -0,0 +1,66 @@
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
hwcaifubi

这个patch是为什么?

likedislike
jiangna1111
jiangna1111
Nov 6 Comments:
likedislike
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 torch
16+from torch.distributed.checkpoint.state_dict_saver import _stateful_to_state_dict
17+from torch.distributed.checkpoint.stateful import Stateful
18+from torchtitan.components.checkpointer.base import MODEL
19+from torchtitan.components.checkpointer.torch_checkpointing import (
20+ TorchCheckpointingManager as UpstreamTorchCheckpointingManager,
21+)
22+from torchtitan.observability import structured_logger as sl
23+from torchtitan.tools.logging import logger
24+ 
25+ 
26+class TorchCheckpointingManager(UpstreamTorchCheckpointingManager):
27+ """Internal load backport; build through the NPU extension's Config."""
28+ 
29+ @sl.log_trace_span("checkpoint_load")
30+ @torch.no_grad()
31+ def _load(self, step: int = -1) -> bool:
32+ model_only = step == 0
33+ if step >= 0:
34+ checkpoint_id = self._create_checkpoint_id(step)
35+ else:
36+ latest = self._find_load_step()
37+ if latest >= 0:
38+ checkpoint_id = self._create_checkpoint_id(latest)
39+ model_only = latest == 0
40+ else:
41+ if not self.initial_load_path:
42+ return False
43+ if self.initial_load_in_hf:
44+ raise ValueError("TorchCheckpointingManager does not yet support loading Hugging Face checkpoints.")
45+ checkpoint_id = self.initial_load_path
46+ model_only = self.initial_load_model_only
47+ if not self._storage.isdir(checkpoint_id):
48+ raise FileNotFoundError(f"Native checkpoint directory does not exist: {checkpoint_id}")
49+ if not self._is_valid_checkpoint(checkpoint_id):
50+ raise ValueError(f"Checkpoint {checkpoint_id!r} is not a native torch_checkpointing checkpoint.")
51+ if model_only:
52+ selected = {MODEL: self.states[MODEL]}
53+ else:
54+ for exclude_key in self.exclude_from_loading:
55+ if exclude_key not in self.states:
56+ raise ValueError(f"{exclude_key} not found in state_dict.")
57+ selected = {key: value for key, value in self.states.items() if key not in self.exclude_from_loading}
58+ state_dict = _stateful_to_state_dict(selected)
59+ loaded = self._manager.load(checkpoint_id, into=state_dict, strict=True)
60+ for key, target in selected.items():
61+ if isinstance(target, Stateful):
62+ target.load_state_dict(state_dict[key])
63+ elif loaded[key] is not target:
64+ raise TypeError(f"Cannot restore non-Stateful checkpoint state {key!r} of type {type(target).__name__}")
65+ logger.info("Loaded native %s checkpoint from %s.", "model-only" if model_only else "full-state", checkpoint_id)
66+ return True
@@ -19,6 +19,7 @@ import torch
19import torchtitan.trainer19import torchtitan.trainer
20from torchtitan.trainer import Trainer20from torchtitan.trainer import Trainer
21 21 
22+from torchtitan_npu.patches.torchtitan.components import checkpointer # noqa: F401
22from torchtitan_npu.patches.torchtitan.components.checkpoint import EMACheckpointManager23from torchtitan_npu.patches.torchtitan.components.checkpoint import EMACheckpointManager
23from torchtitan_npu.patches.torchtitan.components.ema import EMAOptimizersContainer24from torchtitan_npu.patches.torchtitan.components.ema import EMAOptimizersContainer
24from torchtitan_npu.patches.torchtitan.models.common.aux_loss import AuxLoss25from torchtitan_npu.patches.torchtitan.models.common.aux_loss import AuxLoss
@@ -121,12 +122,14 @@ class EMATrainer(Trainer):
121 )122 )
122 123 
123 def __init__(self, config: Config) -> None:124 def __init__(self, config: Config) -> None:
124- config.checkpoint.ema_weights = config.ema_weights125+ if config.ema_weights.enable:
jiangna1111

加开关防止新后端进入这部分,等后续上游ema合入后可以删除相关patch内容

likedislike
126+ config.checkpoint.ema_weights = config.ema_weights
125 super().__init__(config)127 super().__init__(config)
126 128 
127- self.ema_optimizer = cast("Any", self.checkpointer).ema_optimizer129+ if config.ema_weights.enable:
128- self.optimizers.register_step_pre_hook(lambda *_args, **_kwargs: self.ema_optimizer.wait_for_param_reads())130+ self.ema_optimizer = cast("Any", self.checkpointer).ema_optimizer
129- self.optimizers.register_step_post_hook(lambda *_args, **_kwargs: self.ema_optimizer.step(self.step))131+ self.optimizers.register_step_pre_hook(lambda *_args, **_kwargs: self.ema_optimizer.wait_for_param_reads())
132+ self.optimizers.register_step_post_hook(lambda *_args, **_kwargs: self.ema_optimizer.step(self.step))
hwcaifubi
hwcaifubihwcaifubiNov 5

This code comment section is from+129To+132

ema是不是可以先不适配,等后续版本升级再全部去掉patch

likedislike
jiangna1111
jiangna1111
Nov 6 Comments:
likedislike
130 133 
131 134 
132def apply() -> None:135def apply() -> None: