Closed
feat: 增加 TorchFT 通用 backport 扩展点 #675
feat: 增加 TorchFT 通用 backport 扩展点 #675
Closed
zhangyifan999Add on Sep 1Closed at Oct 12
Total: 11 files changed+470-0
@@ -9,6 +9,11 @@ description = "Ascend NPU overrides for torchtitan"
9requires-python = ">=3.12"9requires-python = ">=3.12"
10dependencies = ["torchtitan", "torch-npu"]10dependencies = ["torchtitan", "torch-npu"]
11 11 
12+[project.optional-dependencies]
13+torchft = [
14+ "torchft @ git+https://github.com/pytorch/torchft.git@90d7f68961e7c0bcd4278f7ebba83b5cd876c099",
15+]
16+ 
12[tool.setuptools.packages.find]17[tool.setuptools.packages.find]
13include = ["torchtitan_npu*"]18include = ["torchtitan_npu*"]
14exclude = ["tests*", "CI*", "third_party*"]19exclude = ["tests*", "CI*", "third_party*"]
@@ -28,6 +33,7 @@ ignore-missing-imports = [
28 "torchao.*",33 "torchao.*",
29 "torchao_npu.*",34 "torchao_npu.*",
30 "torchft",35 "torchft",
36+ "torchft.*",
31 "cann_ops_transformer",37 "cann_ops_transformer",
32 "cann_ops_transformer.*",38 "cann_ops_transformer.*",
33 "tile_kernels",39 "tile_kernels",
@@ -0,0 +1,21 @@
1+# TorchFT 临时补丁
2+ 
3+本目录保存已提交 TorchFT 上游、但当前项目固定依赖尚未包含的临时补丁。
4+TorchFT 仅在显式启用故障容错训练时加载,普通训练不会导入这些模块。
5+ 
6+安装项目固定的 TorchFT 依赖:
7+ 
8+```bash
9+pip install -e '.[torchft]'
10+```
11+ 
12+`torchtitan_npu.patches.torchft.apply()` 是统一入口:它先安装 TorchTitan
13+实验层补丁,再安装本目录中的 accelerator 补丁。补丁的
14+`apply()` 必须允许重复调用。
15+ 
16+| PR | 补丁 | 移除条件 |
17+| --- | --- | --- |
18+| [#344](https://github.com/meta-pytorch/torchft/pull/344) | accelerator-neutral stream 与 ProcessGroup 注册 | PR 合入,并且 `pyproject.toml` 固定的 TorchFT 版本包含该提交 |
19+ 
20+满足移除条件后,应删除对应补丁、`apply()` 调用和相关兼容测试。全部补丁清理
21+完成后删除本目录。
@@ -0,0 +1,20 @@
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+"""Lazy registration for generic TorchFT backports pending upstream merge."""
8+ 
9+__all__ = ["apply"]
10+ 
11+ 
12+def apply() -> None:
13+ """Install TorchFT and TorchTitan backports after TorchFT is enabled."""
14+ from torchtitan_npu.patches.torchtitan.experiments import ( # noqa: F401
15+ torchft as _torchtitan_torchft,
16+ )
17+ 
18+ from . import accelerator
19+ 
20+ accelerator.apply()
@@ -0,0 +1,102 @@
1+# Pending upstream PR: https://github.com/meta-pytorch/torchft/pull/344
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
3+# Copyright (c) Meta Platforms, Inc. and affiliates.
4+#
5+# This source code is licensed under the BSD-style license found in the
6+# LICENSE file in the root directory of this source tree.
7+ 
8+"""Backport accelerator-neutral stream and ProcessGroup handling.
9+ 
10+Remove this module after the TorchFT dependency includes the PR.
11+"""
12+ 
13+from __future__ import annotations
14+ 
15+__all__ = [
16+ "apply",
17+ "get_stream_context",
18+ "record_event",
19+ "synchronize",
20+]
21+ 
22+from contextlib import nullcontext
23+from typing import TYPE_CHECKING, Any
24+ 
25+import torch
26+import torch.distributed as dist
27+from torchft.process_group import ProcessGroup as TorchFTProcessGroup
28+ 
29+if TYPE_CHECKING:
30+ from torch.distributed import PrefixStore, ProcessGroup
31+ 
32+_INSTALLED = False
33+ 
34+ 
35+def _current_accelerator_type() -> str | None:
36+ if not torch.accelerator.is_available():
37+ return None
38+ accelerator = torch.accelerator.current_accelerator()
39+ return None if accelerator is None else accelerator.type
40+ 
41+ 
42+def get_stream_context(stream: torch.Stream | None) -> Any:
43+ if stream is None or (accelerator := _current_accelerator_type()) is None:
44+ return nullcontext()
45+ accelerator_module = getattr(torch, accelerator, None)
46+ if accelerator_module is None or not hasattr(accelerator_module, "stream"):
47+ return nullcontext()
48+ return accelerator_module.stream(stream)
49+ 
50+ 
51+def record_event() -> None:
52+ accelerator = _current_accelerator_type()
53+ if accelerator is None:
54+ return
55+ accelerator_module = getattr(torch, accelerator)
56+ event = accelerator_module.Event(interprocess=True) if accelerator == "cuda" else accelerator_module.Event()
57+ accelerator_module.current_stream().record_event(event)
58+ 
59+ 
60+def synchronize() -> None:
61+ if (accelerator := _current_accelerator_type()) is not None:
62+ getattr(torch, accelerator).current_stream().synchronize()
hwcaifubi
hwcaifubihwcaifubiSep 3

This code comment section is from+42To+62

这部分已检视,上游torhcft代码硬编码了torch.xpu

likedislike
zhangyifan999
zhangyifan999
Sep 4 Comments:
likedislike
63+ 
64+ 
65+def _register_process_group(self: TorchFTProcessGroup, name: str) -> str:
66+ group_name = f"{self.getBackendName()}:{name}"
67+ 
68+ def create_pg(
69+ prefix_store: PrefixStore,
70+ rank: int,
71+ world_size: int,
72+ timeout: float,
73+ ) -> ProcessGroup:
74+ del prefix_store, rank, world_size, timeout
75+ return self
76+ 
77+ devices = ["cpu"]
78+ if (accelerator := _current_accelerator_type()) is not None and accelerator not in devices:
79+ devices.append(accelerator)
80+ dist.Backend.register_backend(group_name, create_pg, devices=devices)
81+ return group_name
82+ 
83+ 
84+def apply() -> None:
85+ """Install the fixed-version equivalent of the pending generic TorchFT PR."""
86+ global _INSTALLED
87+ if _INSTALLED:
88+ return
89+ 
90+ import torchft.manager as manager
91+ import torchft.utils as utils
92+ 
93+ utils.get_stream_context = get_stream_context
94+ utils.synchronize = synchronize
95+ utils.record_event = record_event
96+ # manager binds this symbol with a from-import before patches are applied.
97+ manager.get_stream_context = get_stream_context
hwcaifubi

https://github.com/meta-pytorch/torchft/blob/main/torchft/manager.py#L1 torchft.manager.get_stream_context似乎不存在?这里是给它动态增加了一个函数?

likedislike
zhangyifan999
zhangyifan999
Sep 4 Comments:
likedislike
98+ TorchFTProcessGroup._register = _register_process_group
99+ _INSTALLED = True
100+ 
101+ 
102+apply()
@@ -5,6 +5,9 @@
5- https://github.com/pytorch/torchtitan/pull/38645- https://github.com/pytorch/torchtitan/pull/3864
6- https://github.com/pytorch/torchtitan/pull/44746- https://github.com/pytorch/torchtitan/pull/4474
7- https://github.com/pytorch/torchtitan/pull/39857- https://github.com/pytorch/torchtitan/pull/3985
8+- https://github.com/pytorch/torchtitan/pull/4095
9+- https://github.com/pytorch/torchtitan/pull/4210
10+- https://github.com/pytorch/torchtitan/pull/4211
8-->11-->
9 12 
10# TorchTitan 临时补丁13# TorchTitan 临时补丁
@@ -36,5 +39,8 @@ grep -L "Pending upstream PR: https://github.com/pytorch/torchtitan/pull/" \
36| [#3864](https://github.com/pytorch/torchtitan/pull/3864) | 为 torchtitan 补充 LoggedAuxLoss 辅助损失框架 |39| [#3864](https://github.com/pytorch/torchtitan/pull/3864) | 为 torchtitan 补充 LoggedAuxLoss 辅助损失框架 |
37| [#4474](https://github.com/pytorch/torchtitan/pull/4474) | 补齐部分初始化的 optimizer state,支持完整 checkpoint 恢复 |40| [#4474](https://github.com/pytorch/torchtitan/pull/4474) | 补齐部分初始化的 optimizer state,支持完整 checkpoint 恢复 |
38| [#3985](https://github.com/pytorch/torchtitan/pull/3985) | 为 Trainer 补充 EMA 权重维护及 checkpoint 集成 |41| [#3985](https://github.com/pytorch/torchtitan/pull/3985) | 为 Trainer 补充 EMA 权重维护及 checkpoint 集成 |
42+| [#4095](https://github.com/pytorch/torchtitan/pull/4095) | 补充 DeepSeek-V4 token dispatcher 与 MoE 公共能力 |
43+| [#4210](https://github.com/pytorch/torchtitan/pull/4210) | 为 TorchFT ProcessGroup 增加可注册 factory |
44+| [#4211](https://github.com/pytorch/torchtitan/pull/4211) | 补齐 TorchFT manager、optimizer 和 trainer 通用能力 |
39 45 
40对应 PR 合入且 TorchTitan 依赖更新后,应删除相关补丁及导入;全部补丁清理完成后,删除本目录。46对应 PR 合入且 TorchTitan 依赖更新后,应删除相关补丁及导入;全部补丁清理完成后,删除本目录。
@@ -0,0 +1,6 @@
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+"""Optional TorchTitan experiment integrations."""
@@ -0,0 +1,23 @@
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+"""Backports corresponding to pending upstream TorchTitan TorchFT changes."""
8+ 
9+__all__ = [
10+ "OptimizerAdapter",
11+ "create_process_group",
12+ "install_all_reduce_hooks",
13+ "register_process_group_factory",
14+ "set_chunked_loss_lm_head",
15+]
16+ 
17+from .manager import install_all_reduce_hooks
18+from .optimizer import OptimizerAdapter
19+from .process_group_registry import (
20+ create_process_group,
21+ register_process_group_factory,
22+)
23+from .trainer import set_chunked_loss_lm_head
@@ -0,0 +1,90 @@
1+# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/4211
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
3+# Copyright (c) Meta Platforms, Inc. and affiliates.
4+#
5+# This source code is licensed under the BSD-style license found in the
6+# LICENSE file in the root directory of this source tree.
7+ 
8+"""Backport generic synchronous TorchFT hook support from TorchTitan.
9+ 
10+Remove this module after the TorchTitan dependency includes the PR.
11+"""
12+ 
13+from __future__ import annotations
14+ 
15+__all__ = ["apply", "install_all_reduce_hooks", "set_fsdp_all_reduce_hook"]
16+ 
17+from typing import TYPE_CHECKING, Any
18+ 
19+import torchtitan.experiments.torchft.manager
20+from torch.distributed._composable.fsdp.fully_shard import FSDPModule
21+from torch.distributed._composable.replicate_with_fsdp import ReplicateModule
22+ 
23+if TYPE_CHECKING:
24+ from collections.abc import Callable
25+ 
26+ import torch
27+ import torch.nn as nn
28+ 
29+ 
30+def _private_attr(owner: object, name: str) -> Any:
31+ """Access the fixed PyTorch FSDP parameter-group API used by this backport."""
32+ return getattr(owner, name)
33+ 
34+ 
35+def _set_private_attr(owner: object, name: str, value: object) -> None:
36+ setattr(owner, name, value)
37+ 
38+ 
39+def set_fsdp_all_reduce_hook(
40+ module: FSDPModule,
41+ hook: Callable[[torch.Tensor], None],
42+) -> None:
43+ get_fsdp_state = _private_attr(module, "_get_fsdp_state")
44+ state = get_fsdp_state()
45+ param_groups = _private_attr(state, "_fsdp_param_groups")
46+ if len(param_groups) <= 1:
47+ module.set_all_reduce_hook(hook)
48+ return
49+ 
50+ if not all(hasattr(group, "_all_reduce_hook") for group in param_groups):
51+ raise RuntimeError(
52+ "The installed PyTorch FSDP parameter-group API is incompatible with TorchFT all-reduce hooks."
53+ )
54+ for param_group in param_groups:
55+ _set_private_attr(param_group, "_all_reduce_hook", hook)
56+ 
57+ 
58+def install_all_reduce_hooks(
59+ model_parts: list[nn.Module],
60+ hook: Callable[[torch.Tensor], None],
61+) -> tuple[int, int]:
62+ num_replicate_modules = 0
63+ num_fsdp_modules = 0
64+ 
65+ def apply_hook(module: nn.Module) -> None:
66+ nonlocal num_replicate_modules, num_fsdp_modules
67+ if isinstance(module, ReplicateModule):
68+ num_replicate_modules += 1
69+ elif isinstance(module, FSDPModule):
70+ num_fsdp_modules += 1
71+ else:
72+ return
73+ set_fsdp_all_reduce_hook(module, hook)
74+ 
75+ for model_part in model_parts:
76+ model_part.apply(apply_hook)
77+ return num_replicate_modules, num_fsdp_modules
78+ 
79+ 
80+def apply() -> None:
81+ """Install the hook helpers on TorchTitan's TorchFT manager module."""
82+ torchtitan.experiments.torchft.manager.install_all_reduce_hooks = ( # pyrefly: ignore [missing-attribute]
83+ install_all_reduce_hooks
84+ )
85+ torchtitan.experiments.torchft.manager.set_fsdp_all_reduce_hook = ( # pyrefly: ignore [missing-attribute]
86+ set_fsdp_all_reduce_hook
87+ )
hwcaifubi
hwcaifubihwcaifubiSep 3

This code comment section is from+82To+87

同上

likedislike
zhangyifan999
zhangyifan999
Sep 4 Comments:
likedislike
88+ 
89+ 
90+apply()
@@ -0,0 +1,75 @@
1+# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/4211
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
3+# Copyright (c) Meta Platforms, Inc. and affiliates.
4+#
5+# This source code is licensed under the BSD-style license found in the
6+# LICENSE file in the root directory of this source tree.
7+ 
8+"""Backport TorchTitan's non-recursive TorchFT optimizer adapter.
9+ 
10+Remove this module after the TorchTitan dependency includes the PR.
11+"""
12+ 
13+from __future__ import annotations
14+ 
15+__all__ = ["OptimizerAdapter", "apply"]
16+ 
17+from typing import TYPE_CHECKING, Any
18+ 
19+import torchtitan.experiments.torchft.optimizer
20+from torchtitan.components.optimizer import OptimizersContainer
21+ 
22+if TYPE_CHECKING:
23+ from collections.abc import Mapping
24+ 
25+ import torch
26+ 
27+ 
28+class OptimizerAdapter:
29+ """Expose a container as one optimizer without re-entering FT dispatch."""
30+ 
31+ def __init__(self, owner: OptimizersContainer) -> None:
32+ self._owner = owner
33+ 
34+ @property
35+ def param_groups(self) -> list[dict[str, Any]]:
36+ return self._owner.param_groups
37+ 
38+ @property
39+ def state(self) -> Mapping[torch.Tensor, object]:
40+ return self._owner.state
41+ 
42+ def step(self, *args: Any, **kwargs: Any) -> None:
43+ unknown_kwargs = set(kwargs) - {"closure"}
44+ if len(args) > 1 or unknown_kwargs:
45+ raise TypeError("Unsupported optimizer step arguments")
46+ if args and "closure" in kwargs:
47+ raise TypeError("Unsupported optimizer step arguments")
48+ closure = args[0] if args else kwargs.get("closure")
49+ if closure is not None:
50+ raise ValueError("OptimizersContainer does not support closures")
51+ for optimizer in self._owner.optimizers:
52+ optimizer.step()
53+ return None
54+ 
55+ def zero_grad(self, *args: Any, **kwargs: Any) -> None:
56+ return OptimizersContainer.zero_grad(self._owner, *args, **kwargs)
57+ 
58+ def add_param_group(self, param_group: dict[str, Any]) -> None:
59+ self._owner.add_param_group(param_group)
60+ 
61+ def state_dict(self) -> dict[str, Any]:
62+ return self._owner.state_dict()
63+ 
64+ def load_state_dict(self, state_dict: dict[str, Any]) -> None:
65+ self._owner.load_state_dict(state_dict)
66+ 
67+ 
68+def apply() -> None:
69+ """Install the adapter on TorchTitan's TorchFT optimizer module."""
70+ torchtitan.experiments.torchft.optimizer.OptimizerAdapter = ( # pyrefly: ignore [missing-attribute]
71+ OptimizerAdapter
72+ )
73+ 
74+ 
75+apply()
@@ -0,0 +1,70 @@
1+# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/4210
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
3+# Copyright (c) Meta Platforms, Inc. and affiliates.
4+#
5+# This source code is licensed under the BSD-style license found in the
6+# LICENSE file in the root directory of this source tree.
7+ 
8+"""Backport TorchTitan's extensible TorchFT ProcessGroup factory registry.
9+ 
10+Remove this module after the TorchTitan dependency includes the PR.
11+"""
12+ 
13+from __future__ import annotations
14+ 
15+__all__ = [
16+ "ProcessGroupFactory",
17+ "apply",
18+ "create_process_group",
19+ "register_process_group_factory",
20+]
21+ 
22+from typing import TYPE_CHECKING, Protocol
23+ 
24+import torchtitan.experiments.torchft.manager
25+ 
26+if TYPE_CHECKING:
27+ from datetime import timedelta
28+ 
29+ from torchft.process_group import ProcessGroup
30+ 
31+ 
32+class ProcessGroupFactory(Protocol):
33+ def __call__(self, timeout: timedelta) -> ProcessGroup:
34+ """Create a TorchFT process group with the requested timeout."""
35+ ...
36+ 
37+ 
38+_PROCESS_GROUP_FACTORIES: dict[str, ProcessGroupFactory] = {}
39+ 
40+ 
41+def register_process_group_factory(name: str, factory: ProcessGroupFactory) -> None:
42+ normalized_name = name.strip().lower()
43+ if not normalized_name:
44+ raise ValueError("ProcessGroup factory name must not be empty")
45+ existing = _PROCESS_GROUP_FACTORIES.get(normalized_name)
46+ if existing is not None and existing is not factory:
47+ raise ValueError(f"ProcessGroup factory '{normalized_name}' is already registered")
48+ _PROCESS_GROUP_FACTORIES[normalized_name] = factory
49+ 
50+ 
51+def create_process_group(name: str, timeout: timedelta) -> ProcessGroup:
52+ normalized_name = name.strip().lower()
53+ factory = _PROCESS_GROUP_FACTORIES.get(normalized_name)
54+ if factory is None:
55+ available = ", ".join(sorted(_PROCESS_GROUP_FACTORIES)) or "none"
56+ raise ValueError(f"Unknown TorchFT ProcessGroup '{name}'. Registered factories: {available}")
57+ return factory(timeout)
58+ 
59+ 
60+def apply() -> None:
61+ """Install the registry API on TorchTitan's TorchFT manager module."""
62+ torchtitan.experiments.torchft.manager.create_process_group = ( # pyrefly: ignore [missing-attribute]
63+ create_process_group
64+ )
65+ torchtitan.experiments.torchft.manager.register_process_group_factory = ( # pyrefly: ignore [missing-attribute]
66+ register_process_group_factory
67+ )
68+ 
69+ 
70+apply()
@@ -0,0 +1,51 @@
1+# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/4211
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
3+# Copyright (c) Meta Platforms, Inc. and affiliates.
4+#
5+# This source code is licensed under the BSD-style license found in the
6+# LICENSE file in the root directory of this source tree.
7+ 
8+"""Backport TorchFT trainer behavior already available in regular Trainer.
9+ 
10+Remove this module after the TorchTitan dependency includes the PR.
11+"""
12+ 
13+from __future__ import annotations
14+ 
15+__all__ = ["apply", "set_chunked_loss_lm_head"]
16+ 
17+from typing import Any
18+ 
19+import torch.nn as nn
20+import torchtitan.experiments.torchft.trainer
21+from torchtitan.components.loss import ChunkedLossWrapper
22+ 
23+ 
24+def set_chunked_loss_lm_head(trainer: Any) -> None:
25+ if not isinstance(trainer.loss_fn, ChunkedLossWrapper):
26+ return
27+ 
28+ if trainer.parallel_dims.pp_enabled:
29+ if not trainer.pp_has_last_stage:
30+ return
31+ model_part = trainer.model_parts[-1]
32+ else:
33+ if len(trainer.model_parts) != 1:
34+ raise RuntimeError("Non-PP training must have exactly one model part")
35+ model_part = trainer.model_parts[0]
36+ 
37+ lm_head = getattr(model_part, "lm_head", None)
38+ if not isinstance(lm_head, nn.Module):
39+ raise RuntimeError("ChunkedLossWrapper requires an lm_head on this stage")
40+ trainer.loss_fn.set_lm_head(lm_head)
41+ vars(model_part)["_skip_lm_head"] = True
42+ 
43+ 
44+def apply() -> None:
45+ """Install the trainer helpers on TorchTitan's TorchFT trainer module."""
46+ torchtitan.experiments.torchft.trainer.set_chunked_loss_lm_head = ( # pyrefly: ignore [missing-attribute]
47+ set_chunked_loss_lm_head
48+ )
49+ 
50+ 
51+apply()