Merged
feat: adapt signed SDC replay in NPU Trainer #1155
feat: adapt signed SDC replay in NPU Trainer #1155
Merged
jiangna1111Add on Nov 2
Total: 8 files changed+129-2
@@ -50,6 +50,7 @@
50 ".experiments.graph_trainer.ep_overlap_shape_queries",50 ".experiments.graph_trainer.ep_overlap_shape_queries",
51 ".experiments.graph_trainer.ep_ready_nodes_dedup",51 ".experiments.graph_trainer.ep_ready_nodes_dedup",
52 ".experiments.graph_trainer.ep_shape_live_out",52 ".experiments.graph_trainer.ep_shape_live_out",
53+ ".observability",
jiangna1111

临时登记本次 SDC patch 的导入激活顺序,代上游pr合入后随对应 patch一起删除

likedislike
53 ".models.common.attention_metadata",54 ".models.common.attention_metadata",
54 ".models.common.decoder",55 ".models.common.decoder",
55 ".models.common.moe",56 ".models.common.moe",
@@ -4,6 +4,11 @@ SDC(Silent Data Corruption,静默数据损坏)用于检测 Ascend NPU 训
4仅支持 Eager 模式或使用 `torch.compile(backend="inductor")` 的 Compile 模式。该能力默认关闭,按需启用。4仅支持 Eager 模式或使用 `torch.compile(backend="inductor")` 的 Compile 模式。该能力默认关闭,按需启用。
5Eager 模式通过 torch-npu 原生环境变量启用,Compile 模式通过 `--sdc.*` CLI 参数启用。5Eager 模式通过 torch-npu 原生环境变量启用,Compile 模式通过 `--sdc.*` CLI 参数启用。
6 6 
7+本文说明通过 `config.sdc` 或 torch-npu 原生开关启用的 NPU SDC。
8+上游重放一致性检查使用 `config.sdc_replayer`,通用用法与约束见[上游说明](https://github.com/pytorch/torchtitan/blob/dc3985ad4912f67f71d5a125f2fdf40144ec8354/torchtitan/observability/silent_data_corruption.md)。
9+该入口与本文的 `config.sdc` 检测开关及 torch-npu 原生 SDC 开关互斥。
10+本仓通过临时 patch 将重放摘要按位视为 `int64`,兼容 NPU 比较;不改哈希算法或重放流程。
11+ 
7## 启动入口12## 启动入口
8 13 
9首先两种模式都需要通过 `torchrun -m torchtitan_npu.train` 启动训练。14首先两种模式都需要通过 `torchrun -m torchtitan_npu.train` 启动训练。
@@ -5,6 +5,6 @@
5 5 
6"""Compiled SDC implementation."""6"""Compiled SDC implementation."""
7 7 
8-__all__ = ["SDC"]8+__all__ = ["SDC", "validate_sdc_replay_config"]
9 9 
10-from .sdc import SDC10+from .sdc import SDC, validate_sdc_replay_config
@@ -174,3 +174,23 @@ class SDC(Configurable):
174 continue174 continue
175 canonical = name if len(model_parts) == 1 else f"model_parts.{part_index}.{name}"175 canonical = name if len(model_parts) == 1 else f"model_parts.{part_index}.{name}"
176 yield canonical, parameter176 yield canonical, parameter
177+ 
178+ 
179+def validate_sdc_replay_config(sdc_config: SDC.Config) -> None:
180+ """Reject detector settings incompatible with SDC replay."""
181+ 
182+ if sdc_config.gradient_enabled or sdc_config.hccl_mode != 0:
183+ raise ValueError("SDC replay cannot be combined with config.sdc detection")
184+ 
185+ # Match torch-npu: default false and the last enable entry wins.
186+ native_gradient = "false"
187+ for item in os.environ.get("NPU_ASD_CONFIG", "").split(","):
188+ pair = item.split(":")
189+ if len(pair) == 2 and pair[0] == "enable":
190+ native_gradient = pair[1]
191+ if native_gradient != "false" or os.environ.get("NPU_ASD_ENABLE", "0") != "0":
192+ raise ValueError(
193+ "SDC replay requires native SDC disabled: "
194+ "NPU_ASD_CONFIG enable:false and NPU_ASD_ENABLE=0; "
195+ "set these before importing torch-npu in a fresh worker"
196+ )
@@ -77,6 +77,10 @@ class TrainerEx(Trainer):
77 self.optimizer._cpu_offload = self.training.enable_cpu_offload77 self.optimizer._cpu_offload = self.training.enable_cpu_offload
78 self._post_init_optimizer()78 self._post_init_optimizer()
79 validate_anticipatory_config(self)79 validate_anticipatory_config(self)
80+ if self.sdc_replayer is not None:
81+ from torchtitan_npu.extensions.components.sdc import validate_sdc_replay_config
82+ 
83+ validate_sdc_replay_config(self.sdc)
80 84 
81 def _post_init_optimizer(self) -> None:85 def _post_init_optimizer(self) -> None:
82 # Overrides may already have materialized and replaced the CLI schema.86 # Overrides may already have materialized and replaced the CLI schema.
@@ -17,6 +17,8 @@ from .experiments.graph_trainer import ( # noqa: F401
17 ep_shape_live_out,17 ep_shape_live_out,
18)18)
19 19 
20+from . import observability # noqa: F401
21+ 
20# ``attention_metadata`` carries the backend-owned metadata contract and must22# ``attention_metadata`` carries the backend-owned metadata contract and must
21# be applied before ``decoder`` binds the map builder that reads it, and before23# be applied before ``decoder`` binds the map builder that reads it, and before
22# ``mtp`` dispatches that map per layer.24# ``mtp`` dispatches that map per layer.
@@ -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+from . import sdc_replayer # noqa: F401
@@ -0,0 +1,89 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2+# Copyright (c) Meta Platforms, Inc. and affiliates.
hwcaifubi

缺少上游PR

likedislike
jiangna1111
jiangna1111
Nov 3 Comments:
likedislike
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+# Upstream-PR: https://github.com/pytorch/torchtitan/pull/5769
7+ 
8+"""Use signed 64-bit SDC replay digests for NPU transfer and comparison.
9+ 
10+This module is the sole patch owner of ``SDCReplayer._signature``; the upstream
11+constructor, capability probe and replay lifecycle remain unchanged.
12+Remove this module and its import entries after the TorchTitan dependency
13+includes PR #5769.
14+"""
15+ 
16+from __future__ import annotations
17+ 
18+import random
19+ 
20+import torch
21+import torchtitan.observability.sdc_replayer
22+from torchtitan.observability.sdc_replayer import (
23+ SDCReplayer,
24+ _accelerator_rng_states,
25+ _local_tensor,
26+ _ReplaySignature,
27+)
28+ 
29+ 
30+def _npu_signature(self: SDCReplayer, loss: torch.Tensor) -> _ReplaySignature:
31+ # pylint: disable=protected-access
32+ schema: list[tuple[str, tuple[int, ...], str, str]] = []
33+ digests: list[torch.Tensor] = []
34+ digest_device = _local_tensor(loss).device
35+ 
36+ def add_tensor(name: str, tensor: torch.Tensor | None) -> None:
37+ if tensor is None:
38+ schema.append((f"{name}:none", (), "none", "none"))
39+ digests.append(torch.zeros((), dtype=torch.int64, device=digest_device))
40+ return
41+ local = _local_tensor(tensor.detach())
42+ schema.append((name, tuple(local.shape), str(local.dtype), str(local.device)))
43+ if local.numel() == 0:
44+ digests.append(torch.zeros((), dtype=torch.int64, device=digest_device))
45+ return
46+ if local.is_complex():
47+ local = torch.view_as_real(local)
48+ # Preserve all 64 hash bits and use the signed representation for
49+ # NPU transfer/comparison, including hashes of CPU RNG state.
50+ digests.append(torch.hash_tensor(local).view(torch.int64).to(digest_device))
51+ 
52+ add_tensor("loss", loss)
53+ add_tensor("rng:cpu", torch.get_rng_state())
54+ accelerator_rng_states = _accelerator_rng_states(self._device)
55+ if accelerator_rng_states is not None:
56+ for index, rng_state in enumerate(accelerator_rng_states):
57+ add_tensor(f"rng:accelerator:{index}", rng_state)
58+ 
59+ seen_buffers: set[tuple[int, str]] = set()
60+ for module_index, root in enumerate(self._modules):
61+ for module_name, module in root.named_modules():
62+ for buffer_name, buffer in module._buffers.items():
63+ buffer_key = (id(module), buffer_name)
64+ if buffer_key in seen_buffers:
65+ continue
66+ seen_buffers.add(buffer_key)
67+ qualified_name = f"{module_name}.{buffer_name}" if module_name else buffer_name
68+ add_tensor(f"buffer:{module_index}:{qualified_name}", buffer)
69+ 
70+ seen_parameters: set[int] = set()
71+ for module_index, module in enumerate(self._modules):
72+ for name, parameter in module.named_parameters():
73+ if id(parameter) in seen_parameters:
74+ continue
75+ seen_parameters.add(id(parameter))
76+ add_tensor(f"gradient:{module_index}:{name}", parameter.grad)
77+ 
78+ state = (
79+ ("state:python_rng", random.getstate()),
80+ *((f"state:{name}", accessor.get()) for name, accessor in self._scalar_state.items()),
81+ )
82+ return _ReplaySignature(tuple(schema), tuple(digests), state)
83+ 
84+ 
85+def apply() -> None:
86+ torchtitan.observability.sdc_replayer.SDCReplayer._signature = _npu_signature # pylint: disable=protected-access
87+ 
88+ 
89+apply()