Merged
[fix] 迁移 TorchFT 适配至 dev_0.4.0 #1086
zhangyifan999Add on Oct 25
[fix] 迁移 TorchFT 适配至 dev_0.4.0 #1086
Merged
Total: 7 files changed+105-180
| @@ -48,9 +48,6 @@ project-excludes = [ | |||
| 48 | "torchtitan_npu/ops/triton", "torchtitan_npu/ops/tilelang", | 48 | "torchtitan_npu/ops/triton", "torchtitan_npu/ops/tilelang", |
| 49 | # Re-enable with the DeepSeek-V3.2 folded-token model migration. | 49 | # Re-enable with the DeepSeek-V3.2 folded-token model migration. |
| 50 | "torchtitan_npu/models/deepseek_v3_2/sharding.py", | 50 | "torchtitan_npu/models/deepseek_v3_2/sharding.py", |
| 51 | - # TorchFT still targets the trainer before the folded-token migration. | ||
| 52 | - "torchtitan_npu/patches/torchtitan/experiments/torchft", | ||
| 53 | - "torchtitan_npu/extensions/torchtitan/experiments/torchft", | ||
| 54 | ] | 51 | ] |
| 55 | ignore-missing-imports = [ | 52 | ignore-missing-imports = [ |
| 56 | "attn_gym", | 53 | "attn_gym", |
| @@ -33,8 +33,6 @@ collect_ignore = [ | |||
| 33 | "ema", | 33 | "ema", |
| 34 | "extensions/experiment/cv_parallel", | 34 | "extensions/experiment/cv_parallel", |
| 35 | "extensions/torchtitan/experiments/graph_trainer", | 35 | "extensions/torchtitan/experiments/graph_trainer", |
| 36 | - "extensions/torchtitan/experiments/torchft", | ||
| 37 | - "patches/torchft", | ||
| 38 | "patches/torchtitan/experiments/graph_trainer", | 36 | "patches/torchtitan/experiments/graph_trainer", |
| 39 | # Qwen runtime migration is deferred. Upstream eagerly imports CUDA-only | 37 | # Qwen runtime migration is deferred. Upstream eagerly imports CUDA-only |
| 40 | # CuTeDSL code, which is not installed in the NPU test image. | 38 | # CuTeDSL code, which is not installed in the NPU test image. |
| @@ -35,6 +35,10 @@ assert config.checkpoint.enable and config.checkpoint.enable_ft_dataloader_check | |||
| 35 | assert config.model_spec.model.n_layers == 4 | 35 | assert config.model_spec.model.n_layers == 4 |
| 36 | assert config.parallelism.expert_parallel_degree == 4 | 36 | assert config.parallelism.expert_parallel_degree == 4 |
| 37 | assert config.parallelism.data_parallel_shard_degree == 4 | 37 | assert config.parallelism.data_parallel_shard_degree == 4 |
| 38 | +assert config.training.max_context_length == config.model_spec.max_context_length == 256 | ||
| 39 | +assert config.training.num_tokens_per_microbatch_per_dp_rank == 256 | ||
| 40 | +assert config.training.num_tokens_per_train_step == 4096 | ||
| 41 | +assert config.training.num_tokens_per_train_step // (256 * 4 * 2) == 2 | ||
| 38 | assert isinstance(config.profiler, npu_trainer.CANNProfiler.Config) | 42 | assert isinstance(config.profiler, npu_trainer.CANNProfiler.Config) |
| 39 | 43 | ||
| 40 | full_config = ConfigManager().parse_args([ | 44 | full_config = ConfigManager().parse_args([ |
| @@ -68,6 +72,7 @@ def set_path(root, path, value): | |||
| 68 | setattr(target, parts[-1], value) | 72 | setattr(target, parts[-1], value) |
| 69 | 73 | ||
| 70 | unsupported = ( | 74 | unsupported = ( |
| 75 | + ('sdc_replayer', object(), 'does not support the upstream SDC replay engine'), | ||
| 71 | ('checkpoint.enable', False, 'requires checkpoint'), | 76 | ('checkpoint.enable', False, 'requires checkpoint'), |
| 72 | ('checkpoint.enable_ft_dataloader_checkpoints', False, 'requires checkpoint'), | 77 | ('checkpoint.enable_ft_dataloader_checkpoints', False, 'requires checkpoint'), |
| 73 | ('model_spec.flavor', 'deepseek_v4_dense', 'DeepSeek-V4 Flash'), | 78 | ('model_spec.flavor', 'deepseek_v4_dense', 'DeepSeek-V4 Flash'), |
| @@ -90,6 +95,7 @@ for path, value, message in unsupported: | |||
| 90 | 95 | ||
| 91 | initialize_ft = Mock() | 96 | initialize_ft = Mock() |
| 92 | def initialize_once(trainer, cfg): | 97 | def initialize_once(trainer, cfg): |
| 98 | + assert trainer.sdc_replayer is None | ||
| 93 | initialize_ft(cfg) | 99 | initialize_ft(cfg) |
| 94 | trainer.model_parts = [] | 100 | trainer.model_parts = [] |
| 95 | trainer.loss_fn = None | 101 | trainer.loss_fn = None |
| @@ -113,6 +119,10 @@ with patch.object(module.FaultTolerantTrainer, '__init__', initialize_once), \\ | |||
| 113 | ) | 119 | ) |
| 114 | assert trainer._sdc is build_sdc.return_value | 120 | assert trainer._sdc is build_sdc.return_value |
| 115 | recovery.assert_called_once() | 121 | recovery.assert_called_once() |
| 122 | + trainer.load_state_dict({'step': 7, 'ntokens_seen': 1024}) | ||
| 123 | + assert trainer.step == 7 | ||
| 124 | + assert trainer.ntokens_seen == 1024 | ||
| 125 | + assert trainer.sdc_replayer is None | ||
| 116 | 126 | ||
| 117 | for ft_manager, message in ( | 127 | for ft_manager, message in ( |
| 118 | (Mock(), 'requires FTManagerEx'), | 128 | (Mock(), 'requires FTManagerEx'), |
| @@ -148,3 +158,54 @@ assert AuxiliaryLoss.group_acc == {} | |||
| 148 | """ | 158 | """ |
| 149 | result = subprocess.run([sys.executable, "-c", program], capture_output=True, text=True, timeout=120) | 159 | result = subprocess.run([sys.executable, "-c", program], capture_output=True, text=True, timeout=120) |
| 150 | assert result.returncode == 0, result.stderr | 160 | assert result.returncode == 0, result.stderr |
| 161 | + | ||
| 162 | + | ||
| 163 | +def test_ft_train_step_consumes_collated_valid_tokens(monkeypatch): | ||
| 164 | + from types import SimpleNamespace | ||
| 165 | + from unittest.mock import Mock | ||
| 166 | + | ||
| 167 | + import torch | ||
| 168 | + | ||
| 169 | + from torchtitan_npu.extensions.torchtitan.experiments.torchft import trainer as module | ||
| 170 | + | ||
| 171 | + optimizer, schedulers = Mock(), Mock() | ||
| 172 | + schedulers.schedulers = [Mock()] | ||
| 173 | + schedulers.schedulers[0].get_last_lr.return_value = [0.01] | ||
| 174 | + parallel = SimpleNamespace(dp_enabled=False, pp_enabled=False, ep_enabled=False) | ||
| 175 | + parallel.get_optional_mesh = lambda _: None | ||
| 176 | + inputs = [ | ||
| 177 | + ({"tokens": torch.tensor([1, 2]), "num_valid_tokens": torch.tensor(2)}, torch.tensor([2, 3])), | ||
| 178 | + ({"tokens": torch.tensor([3, 4]), "num_valid_tokens": torch.tensor(1)}, torch.tensor([4, -100])), | ||
| 179 | + ] | ||
| 180 | + observed = [] | ||
| 181 | + | ||
| 182 | + def forward_backward_step(*, input_dict, labels, global_valid_tokens): | ||
| 183 | + assert "num_valid_tokens" not in input_dict | ||
| 184 | + observed.append((input_dict["tokens"].clone(), labels.clone(), global_valid_tokens.item())) | ||
| 185 | + return torch.tensor(0.5) | ||
| 186 | + | ||
| 187 | + trainer = SimpleNamespace( | ||
| 188 | + config=SimpleNamespace(training=SimpleNamespace(disable_cuda_graphs=True, max_norm=1.0)), | ||
| 189 | + optimizers=optimizer, | ||
| 190 | + lr_schedulers=schedulers, | ||
| 191 | + step=1, | ||
| 192 | + metrics_processor=Mock(should_log=Mock(return_value=False)), | ||
| 193 | + parallel_dims=parallel, | ||
| 194 | + gradient_accumulation_steps=2, | ||
| 195 | + num_pp_microbatches=1, | ||
| 196 | + device=torch.device("cpu"), | ||
| 197 | + model_parts=[torch.nn.Linear(1, 1)], | ||
| 198 | + checkpointer=Mock(), | ||
| 199 | + forward_backward_step=forward_backward_step, | ||
| 200 | + ) | ||
| 201 | + monkeypatch.setattr(module.dist_utils, "clip_grad_norm_", lambda *args, **kwargs: torch.tensor(1.0)) | ||
| 202 | + | ||
| 203 | + module.FaultTolerantTrainerEx._train_step(trainer, iter(inputs)) | ||
| 204 | + | ||
| 205 | + assert len(observed) == 2 | ||
| 206 | + assert [entry[2] for entry in observed] == [3, 3] | ||
| 207 | + torch.testing.assert_close(observed[0][0], torch.tensor([1, 2])) | ||
| 208 | + torch.testing.assert_close(observed[1][1], torch.tensor([4, -100])) | ||
| 209 | + optimizer.zero_grad.assert_called_once_with(set_to_none=True) | ||
| 210 | + optimizer.step.assert_called_once_with() | ||
| 211 | + schedulers.step.assert_called_once_with() | ||
| @@ -16,6 +16,8 @@ from torch.utils._pytree import tree_flatten, tree_unflatten | |||
| 16 | from torchft.manager import Manager | 16 | from torchft.manager import Manager |
| 17 | 17 | ||
| 18 | if TYPE_CHECKING: | 18 | if TYPE_CHECKING: |
| 19 | + from torchft.process_group import ProcessGroup | ||
| 20 | + | ||
| 19 | from torchtitan_npu.extensions.torchtitan.experiments.torchft.process_group import ProcessGroupHCCLEx | 21 | from torchtitan_npu.extensions.torchtitan.experiments.torchft.process_group import ProcessGroupHCCLEx |
这个是不是可以删除了 ![]() ![]() | |||
| 20 | 22 | ||
| 21 | 23 | ||
| @@ -66,7 +68,7 @@ class TorchFTCommitTimeoutError(RuntimeError): | |||
| 66 | 68 | ||
| 67 | 69 | ||
| 68 | class ManagerEx(Manager): | 70 | class ManagerEx(Manager): |
| 69 | - _pg: "ProcessGroupHCCLEx" | 71 | + _pg: "ProcessGroup" |
| 70 | _user_state_dicts: dict[str, Any] | 72 | _user_state_dicts: dict[str, Any] |
| 71 | _quorum_future: Any | 73 | _quorum_future: Any |
| 72 | _pending_state_dict: Any | 74 | _pending_state_dict: Any |
| @@ -10,7 +10,6 @@ from collections.abc import Iterator | |||
| 10 | from dataclasses import dataclass, field | 10 | from dataclasses import dataclass, field |
| 11 | 11 | ||
| 12 | import torch | 12 | import torch |
| 13 | -from torchtitan.components.loss import IGNORE_INDEX | ||
| 14 | from torchtitan.distributed import utils as dist_utils | 13 | from torchtitan.distributed import utils as dist_utils |
| 15 | from torchtitan.experiments.torchft.checkpoint import TorchFTCheckpointManager | 14 | from torchtitan.experiments.torchft.checkpoint import TorchFTCheckpointManager |
| 16 | from torchtitan.experiments.torchft.trainer import FaultTolerantTrainer | 15 | from torchtitan.experiments.torchft.trainer import FaultTolerantTrainer |
| @@ -42,6 +41,7 @@ class FaultTolerantTrainerEx(TrainerEx, FaultTolerantTrainer): | |||
| 42 | 41 | ||
| 43 | def __init__(self, config: Config) -> None: | 42 | def __init__(self, config: Config) -> None: |
| 44 | self._validate_supported_config(config) | 43 | self._validate_supported_config(config) |
| 44 | + self.sdc_replayer = None | ||
| 45 | super().__init__(config) | 45 | super().__init__(config) |
| 46 | ft_manager = self.ft_manager | 46 | ft_manager = self.ft_manager |
| 47 | if not isinstance(ft_manager, FTManagerEx): | 47 | if not isinstance(ft_manager, FTManagerEx): |
| @@ -62,6 +62,8 @@ class FaultTolerantTrainerEx(TrainerEx, FaultTolerantTrainer): | |||
| 62 | @staticmethod | 62 | @staticmethod |
| 63 | def _validate_supported_config(config: Config) -> None: | 63 | def _validate_supported_config(config: Config) -> None: |
| 64 | FTManagerEx.validate_config(config.fault_tolerance) | 64 | FTManagerEx.validate_config(config.fault_tolerance) |
| 65 | + if config.sdc_replayer is not None: | ||
| 66 | + raise ValueError("The pinned TorchFT trainer does not support the upstream SDC replay engine") | ||
| 65 | if not config.checkpoint.enable or not config.checkpoint.enable_ft_dataloader_checkpoints: | 67 | if not config.checkpoint.enable or not config.checkpoint.enable_ft_dataloader_checkpoints: |
| 66 | raise ValueError("NPU TorchFT requires checkpoint and per-replica dataloader checkpointing") | 68 | raise ValueError("NPU TorchFT requires checkpoint and per-replica dataloader checkpointing") |
| 67 | 69 | ||
| @@ -105,7 +107,7 @@ class FaultTolerantTrainerEx(TrainerEx, FaultTolerantTrainer): | |||
| 105 | return self.recovery.run_step(self._train_step, data_iterator) | 107 | return self.recovery.run_step(self._train_step, data_iterator) |
| 106 | 108 | ||
| 107 | def _train_step(self, data_iterator: Iterator[tuple[dict[str, torch.Tensor], torch.Tensor]]): | 109 | def _train_step(self, data_iterator: Iterator[tuple[dict[str, torch.Tensor], torch.Tensor]]): |
| 108 | - """Keep the v0.3 FT loop, but finish metrics before authorizing updates.""" | 110 | + """Finish metrics before authorizing the FT optimizer update.""" |
| 109 | self.optimizers.zero_grad(set_to_none=self.config.training.disable_cuda_graphs) | 111 | self.optimizers.zero_grad(set_to_none=self.config.training.disable_cuda_graphs) |
| 110 | lr = self.lr_schedulers.schedulers[0].get_last_lr()[0] | 112 | lr = self.lr_schedulers.schedulers[0].get_last_lr()[0] |
| 111 | should_log = self.metrics_processor.should_log(self.step) | 113 | should_log = self.metrics_processor.should_log(self.step) |
| @@ -115,9 +117,9 @@ class FaultTolerantTrainerEx(TrainerEx, FaultTolerantTrainer): | |||
| 115 | local_valid_tokens = torch.tensor(0, dtype=torch.int64) | 117 | local_valid_tokens = torch.tensor(0, dtype=torch.int64) |
| 116 | for _ in range(self.gradient_accumulation_steps): | 118 | for _ in range(self.gradient_accumulation_steps): |
| 117 | microbatches = [] | 119 | microbatches = [] |
| 118 | - for _ in range(self.num_pipeline_parallel_microbatches): | 120 | + for _ in range(self.num_pp_microbatches): |
| 119 | input_dict, labels = next(data_iterator) | 121 | input_dict, labels = next(data_iterator) |
| 120 | - local_valid_tokens += (labels != IGNORE_INDEX).sum() | 122 | + local_valid_tokens += input_dict.pop("num_valid_tokens") |
| 121 | microbatches.append((input_dict, labels)) | 123 | microbatches.append((input_dict, labels)) |
| 122 | microbatch_groups.append(microbatches) | 124 | microbatch_groups.append(microbatches) |
| 123 | 125 | ||
| @@ -174,6 +176,8 @@ class FaultTolerantTrainerEx(TrainerEx, FaultTolerantTrainer): | |||
| 174 | assert ft_pg is not None, "Synchronous TorchFT requires a loss process group" | 176 | assert ft_pg is not None, "Synchronous TorchFT requires a loss process group" |
| 175 | loss_mesh = parallel_dims.get_optional_mesh("loss") | 177 | loss_mesh = parallel_dims.get_optional_mesh("loss") |
| 176 | local_avg_loss = accumulated_loss * global_valid_tokens / local_valid_tokens | 178 | local_avg_loss = accumulated_loss * global_valid_tokens / local_valid_tokens |
| 179 | + # Loss is normalized by replica-local valid tokens; average the | ||
| 180 | + # cross-replica SUM over the current participants. | ||
| 177 | global_avg_loss = dist_utils.dist_sum(accumulated_loss, loss_mesh, ft_pg) / ft_pg.size() | 181 | global_avg_loss = dist_utils.dist_sum(accumulated_loss, loss_mesh, ft_pg) / ft_pg.size() |
建议改:这里仍对 ![]() ![]() | |||
| 178 | global_max_loss = dist_utils.dist_max(local_avg_loss, loss_mesh, ft_pg) | 182 | global_max_loss = dist_utils.dist_max(local_avg_loss, loss_mesh, ft_pg) |
| 179 | global_ntokens_seen = dist_utils.dist_sum( | 183 | global_ntokens_seen = dist_utils.dist_sum( |
| @@ -512,15 +512,15 @@ def deepseek_v4_flash_8p_torchft() -> Trainer.Config: | |||
| 512 | model.n_layers = 4 | 512 | model.n_layers = 4 |
| 513 | model.compress_ratios = model.compress_ratios[:4] | 513 | model.compress_ratios = model.compress_ratios[:4] |
| 514 | base.model_spec.flavor = "deepseek_v4_flash_4layers_16experts" | 514 | base.model_spec.flavor = "deepseek_v4_flash_4layers_16experts" |
| 515 | + base.model_spec.max_context_length = 256 | ||
| 516 | + base.training.max_context_length = 256 | ||
| 517 | + base.training.num_tokens_per_microbatch_per_dp_rank = 256 | ||
| 515 | config = _torchft_flash_config( | 518 | config = _torchft_flash_config( |
| 516 | base, | 519 | base, |
| 517 | expert_parallel_degree=4, | 520 | expert_parallel_degree=4, |
| 518 | data_parallel_shard_degree=4, | 521 | data_parallel_shard_degree=4, |
| 519 | global_batch_size=16, | 522 | global_batch_size=16, |
| 520 | ) | 523 | ) |
| 521 | - config.training.num_tokens_per_microbatch_per_dp_rank = 256 | ||
| 522 | - assert config.model_spec is not None | ||
| 523 | - config.model_spec.max_context_length = 256 | ||
| 524 | config.debug.seed = 42 | 524 | config.debug.seed = 42 |
| 525 | return config | 525 | return config |
| 526 | 526 | ||
| @@ -1,37 +1,32 @@ | |||
| 1 | # Pending upstream PR: https://github.com/pytorch/torchtitan/pull/4534 | 1 | # Pending upstream PR: https://github.com/pytorch/torchtitan/pull/4534 |
| 2 | # Pending upstream PR: https://github.com/pytorch/torchtitan/pull/4575 | 2 | # Pending upstream PR: https://github.com/pytorch/torchtitan/pull/4575 |
| 3 | -# Pending upstream PR: https://github.com/pytorch/torchtitan/pull/4663 | ||
| 4 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 5 | # Copyright (c) Meta Platforms, Inc. and affiliates. | 3 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 6 | # | 5 | # |
| 7 | # This source code is licensed under the BSD-style license found in the | 6 | # This source code is licensed under the BSD-style license found in the |
| 8 | # LICENSE file in the root directory of this source tree. | 7 | # LICENSE file in the root directory of this source tree. |
| 9 | 8 | ||
| 10 | -"""Backport TorchFT config overrides, chunked-loss setup, and replica loss averaging. | 9 | +"""Backport TorchFT config overrides and chunked-loss setup. |
| 11 | 10 | ||
| 12 | Remove this module after the TorchTitan dependency includes the PR. | 11 | Remove this module after the TorchTitan dependency includes the PR. |
| 13 | """ | 12 | """ |
| 14 | 13 | ||
| 15 | -from __future__ import annotations | ||
| 16 | - | ||
| 17 | import json | 14 | import json |
| 18 | from typing import TYPE_CHECKING, cast | 15 | from typing import TYPE_CHECKING, cast |
| 19 | 16 | ||
| 20 | import torch | 17 | import torch |
| 21 | import torchtitan.experiments.torchft.trainer | 18 | import torchtitan.experiments.torchft.trainer |
| 22 | from torch.distributed.elastic.multiprocessing.errors import record | 19 | from torch.distributed.elastic.multiprocessing.errors import record |
| 23 | -from torchtitan.components.loss import IGNORE_INDEX, ChunkedLossWrapper | 20 | +from torchtitan.components.loss import ChunkedLossWrapper |
| 24 | from torchtitan.config import TORCH_DTYPE_MAP, apply_overrides | 21 | from torchtitan.config import TORCH_DTYPE_MAP, apply_overrides |
| 25 | from torchtitan.distributed import utils as dist_utils | 22 | from torchtitan.distributed import utils as dist_utils |
| 26 | from torchtitan.distributed.cudagraph import wrap_with_cuda_graph | 23 | from torchtitan.distributed.cudagraph import wrap_with_cuda_graph |
| 27 | from torchtitan.experiments.torchft.optimizer import TorchFTOptimizersContainer | 24 | from torchtitan.experiments.torchft.optimizer import TorchFTOptimizersContainer |
| 25 | +from torchtitan.experiments.torchft.trainer import FaultTolerantTrainer | ||
| 28 | from torchtitan.tools import utils | 26 | from torchtitan.tools import utils |
| 29 | from torchtitan.tools.logging import logger | 27 | from torchtitan.tools.logging import logger |
| 30 | 28 | ||
| 31 | if TYPE_CHECKING: | 29 | if TYPE_CHECKING: |
| 32 | - from collections.abc import Iterator | ||
| 33 | - | ||
| 34 | - from torchtitan.experiments.torchft.trainer import FaultTolerantTrainer | ||
| 35 | from torchtitan.protocols import BaseModel | 30 | from torchtitan.protocols import BaseModel |
| 36 | 31 | ||
| 37 | 32 | ||
| @@ -51,6 +46,7 @@ def patched_init(self, config: FaultTolerantTrainer.Config): | |||
| 51 | 46 | ||
| 52 | # init distributed and build meshes (FT override handles ft_manager creation) | 47 | # init distributed and build meshes (FT override handles ft_manager creation) |
| 53 | self.parallel_dims = parallel_dims = self.init_distributed() | 48 | self.parallel_dims = parallel_dims = self.init_distributed() |
| 49 | + dist_utils.set_spmd_backend(config.parallelism.spmd_backend) | ||
| 54 | 50 | ||
| 55 | # Logging needs to happen after distributed initialized | 51 | # Logging needs to happen after distributed initialized |
| 56 | config.maybe_log() | 52 | config.maybe_log() |
| @@ -81,18 +77,15 @@ def patched_init(self, config: FaultTolerantTrainer.Config): | |||
| 81 | config.tokenizer.build(tokenizer_path=config.hf_assets_path) if config.tokenizer is not None else None | 77 | config.tokenizer.build(tokenizer_path=config.hf_assets_path) if config.tokenizer is not None else None |
| 82 | ) | 78 | ) |
| 83 | 79 | ||
| 80 | + num_pp_microbatches = config.parallelism.num_pp_microbatches if parallel_dims.pp_enabled else 1 | ||
| 84 | # build dataloader | 81 | # build dataloader |
| 85 | - dataloader_batch_size = ( | 82 | + num_tokens_per_batch = config.training.num_tokens_per_microbatch_per_dp_rank |
| 86 | - config.parallelism.pipeline_parallel_microbatch_size | ||
| 87 | - if parallel_dims.pp_enabled | ||
| 88 | - else config.training.local_batch_size | ||
| 89 | - ) | ||
| 90 | self.dataloader = config.dataloader.build( | 83 | self.dataloader = config.dataloader.build( |
| 91 | dp_world_size=batch_degree, | 84 | dp_world_size=batch_degree, |
| 92 | dp_rank=batch_rank, | 85 | dp_rank=batch_rank, |
| 93 | tokenizer=self.tokenizer, | 86 | tokenizer=self.tokenizer, |
| 94 | - seq_len=config.training.seq_len, | 87 | + max_context_length=config.training.max_context_length, |
| 95 | - local_batch_size=dataloader_batch_size, | 88 | + num_tokens_per_batch=num_tokens_per_batch, |
| 96 | ) | 89 | ) |
| 97 | 90 | ||
| 98 | # build model (using meta init) | 91 | # build model (using meta init) |
| @@ -137,7 +130,7 @@ def patched_init(self, config: FaultTolerantTrainer.Config): | |||
| 137 | ( | 130 | ( |
| 138 | model_param_count, | 131 | model_param_count, |
| 139 | self.metrics_processor.num_flops_per_token, | 132 | self.metrics_processor.num_flops_per_token, |
| 140 | - ) = model_config.get_nparams_and_flops(model, config.training.seq_len) | 133 | + ) = model_config.get_nparams_and_flops(model, config.training.max_context_length) |
| 141 | 134 | ||
| 142 | logger.info( | 135 | logger.info( |
| 143 | f"{color.blue}Model {model_spec.name} {model_spec.flavor} " | 136 | f"{color.blue}Model {model_spec.name} {model_spec.flavor} " |
| @@ -160,27 +153,19 @@ def patched_init(self, config: FaultTolerantTrainer.Config): | |||
| 160 | compile_config=config.compile, | 153 | compile_config=config.compile, |
| 161 | ) | 154 | ) |
| 162 | 155 | ||
| 163 | - # verify batch sizes | 156 | + self.num_pp_microbatches = num_pp_microbatches |
| 164 | - global_batch_size = config.training.global_batch_size | 157 | + num_tokens_per_dp_rank = config.training.num_tokens_per_microbatch_per_dp_rank * self.num_pp_microbatches |
| 165 | - if global_batch_size < 0: | 158 | + num_tokens_per_train_step = config.training.num_tokens_per_train_step |
| 166 | - # This global batch size results in 1 gradient accumulation | 159 | + if num_tokens_per_train_step < 0: |
| 167 | - # step. | 160 | + num_tokens_per_train_step = num_tokens_per_dp_rank * batch_degree |
| 168 | - global_batch_size = config.training.local_batch_size * batch_degree | 161 | + if num_tokens_per_train_step % (num_tokens_per_dp_rank * batch_degree) != 0: |
| 169 | - assert global_batch_size > 0 | 162 | + raise ValueError( |
| 170 | - assert global_batch_size % (config.training.local_batch_size * batch_degree) == 0, ( | 163 | + "training.num_tokens_per_train_step " |
| 171 | - f"global batch size must be multiple of local batch size times " | 164 | + f"({num_tokens_per_train_step}) must be divisible by the number " |
| 172 | - f"data-parallel degree ({global_batch_size} " | 165 | + "of tokens processed globally in one gradient accumulation " |
| 173 | - f"% ({config.training.local_batch_size} * {batch_degree}) != 0)" | 166 | + f"iteration ({num_tokens_per_dp_rank * batch_degree})." |
| 174 | - ) | 167 | + ) |
| 175 | - | 168 | + self.gradient_accumulation_steps = num_tokens_per_train_step // (num_tokens_per_dp_rank * batch_degree) |
| 176 | - # calculate gradient accumulation steps | ||
| 177 | - self.gradient_accumulation_steps = global_batch_size // (config.training.local_batch_size * batch_degree) | ||
| 178 | - assert self.gradient_accumulation_steps > 0 | ||
| 179 | - self.num_pipeline_parallel_microbatches = ( | ||
| 180 | - config.training.local_batch_size // config.parallelism.pipeline_parallel_microbatch_size | ||
| 181 | - if parallel_dims.pp_enabled | ||
| 182 | - else 1 | ||
| 183 | - ) | ||
| 184 | 169 | ||
| 185 | # apply parallelisms and initialization | 170 | # apply parallelisms and initialization |
| 186 | if parallel_dims.pp_enabled: | 171 | if parallel_dims.pp_enabled: |
| @@ -298,6 +283,7 @@ def patched_init(self, config: FaultTolerantTrainer.Config): | |||
| 298 | 283 | ||
| 299 | self.train_context = dist_utils.get_spmd_context( | 284 | self.train_context = dist_utils.get_spmd_context( |
| 300 | parallel_dims=parallel_dims, | 285 | parallel_dims=parallel_dims, |
| 286 | + spmd_typechecking=(config.parallelism.spmd_backend == "spmd_types" and config.debug.spmd_typechecking), | ||
| 301 | ) | 287 | ) |
| 302 | self.fwd_bwd_fn = self._forward_backward_body | 288 | self.fwd_bwd_fn = self._forward_backward_body |
| 303 | if not config.training.disable_cuda_graphs: | 289 | if not config.training.disable_cuda_graphs: |
| @@ -325,8 +311,8 @@ def patched_init(self, config: FaultTolerantTrainer.Config): | |||
| 325 | loss_fn=self.loss_fn, | 311 | loss_fn=self.loss_fn, |
| 326 | validation_context=self.train_context, | 312 | validation_context=self.train_context, |
| 327 | metrics_processor=self.metrics_processor, | 313 | metrics_processor=self.metrics_processor, |
| 328 | - seq_len=config.training.seq_len, | 314 | + seq_len=config.training.max_context_length, |
| 329 | - local_batch_size=config.training.local_batch_size, | 315 | + num_tokens_per_batch=num_tokens_per_batch, |
| 330 | pp_schedule=pp_schedule, | 316 | pp_schedule=pp_schedule, |
| 331 | pp_has_first_stage=pp_has_first_stage, | 317 | pp_has_first_stage=pp_has_first_stage, |
| 332 | pp_has_last_stage=pp_has_last_stage, | 318 | pp_has_last_stage=pp_has_last_stage, |
| @@ -334,10 +320,10 @@ def patched_init(self, config: FaultTolerantTrainer.Config): | |||
| 334 | 320 | ||
| 335 | logger.info( | 321 | logger.info( |
| 336 | "Trainer is initialized with " | 322 | "Trainer is initialized with " |
| 337 | - f"local batch size {config.training.local_batch_size}, " | 323 | + f"{num_tokens_per_dp_rank} tokens per DP rank, " |
| 338 | - f"global batch size {global_batch_size}, " | 324 | + f"{num_tokens_per_train_step} tokens per train step, " |
| 339 | f"gradient accumulation steps {self.gradient_accumulation_steps}, " | 325 | f"gradient accumulation steps {self.gradient_accumulation_steps}, " |
| 340 | - f"sequence length {config.training.seq_len}, " | 326 | + f"maximum context length {config.training.max_context_length}, " |
| 341 | f"total steps {config.training.steps} " | 327 | f"total steps {config.training.steps} " |
| 342 | f"(warmup {config.lr_scheduler.warmup_steps})" | 328 | f"(warmup {config.lr_scheduler.warmup_steps})" |
| 343 | ) | 329 | ) |
| @@ -360,135 +346,12 @@ def _configure_chunked_loss(self) -> None: | |||
| 360 | lm_head = self.model_parts[0].lm_head | 346 | lm_head = self.model_parts[0].lm_head |
| 361 | assert lm_head is not None, "Model must have lm_head for ChunkedLossWrapper" | 347 | assert lm_head is not None, "Model must have lm_head for ChunkedLossWrapper" |
| 362 | self.loss_fn.set_lm_head(lm_head) # pyrefly: ignore[bad-argument-type] | 348 | self.loss_fn.set_lm_head(lm_head) # pyrefly: ignore[bad-argument-type] |
| 363 | - self.model_parts[0]._skip_lm_head = True # pyrefly: ignore[bad-argument-type] | 349 | + self.model_parts[0]._skip_lm_head = True |
| 364 | - | ||
| 365 | - | ||
| 366 | -def patched_train_step(self, data_iterator: Iterator[tuple[dict[str, torch.Tensor], torch.Tensor]]): | ||
| 367 | - self.optimizers.zero_grad(set_to_none=self.config.training.disable_cuda_graphs) | ||
| 368 | - # Save the current step learning rate for logging | ||
| 369 | - lr = self.lr_schedulers.schedulers[0].get_last_lr()[0] | ||
| 370 | - should_log = self.metrics_processor.should_log(self.step) | ||
| 371 | - | ||
| 372 | - # Keep these variables local to shorten the code as these are | ||
| 373 | - # the major variables that are used in the training loop. | ||
| 374 | - parallel_dims = self.parallel_dims | ||
| 375 | - # All groups form one optimizer step; each group feeds one fwd-bwd call. | ||
| 376 | - microbatch_groups: list[list[tuple[dict[str, torch.Tensor], torch.Tensor]]] = [] | ||
| 377 | - local_valid_tokens = torch.tensor(0, dtype=torch.int64) | ||
| 378 | - for _ in range(self.gradient_accumulation_steps): | ||
| 379 | - microbatches = [] | ||
| 380 | - for _ in range(self.num_pipeline_parallel_microbatches): | ||
| 381 | - input_dict, labels = next(data_iterator) | ||
| 382 | - local_valid_tokens += (labels != IGNORE_INDEX).sum() | ||
| 383 | - microbatches.append((input_dict, labels)) | ||
| 384 | - microbatch_groups.append(microbatches) | ||
| 385 | - | ||
| 386 | - # Keep the global token count on device so loss normalization does not | ||
| 387 | - # introduce a CPU synchronization in the training path. | ||
| 388 | - global_valid_tokens = local_valid_tokens.to(self.device) | ||
| 389 | - if parallel_dims.dp_enabled: | ||
| 390 | - batch_mesh = parallel_dims.get_mesh("batch") | ||
| 391 | - global_valid_tokens = dist_utils.dist_sum_tensor(global_valid_tokens, batch_mesh) | ||
| 392 | - | ||
| 393 | - accumulated_loss: torch.Tensor | None = None | ||
| 394 | - for microbatches in microbatch_groups: | ||
| 395 | - input_dict_mbs = [] | ||
| 396 | - label_mbs = [] | ||
| 397 | - for input_dict, labels in microbatches: | ||
| 398 | - for key, value in input_dict.items(): | ||
| 399 | - if isinstance(value, torch.Tensor): | ||
| 400 | - input_dict[key] = value.to(self.device) | ||
| 401 | - input_dict_mbs.append(input_dict) | ||
| 402 | - label_mbs.append(labels.to(self.device)) | ||
| 403 | - | ||
| 404 | - if parallel_dims.pp_enabled: | ||
| 405 | - fwd_bwd_input_dict = input_dict_mbs | ||
| 406 | - fwd_bwd_labels = label_mbs | ||
| 407 | - else: | ||
| 408 | - assert len(input_dict_mbs) == len(label_mbs) == 1 | ||
| 409 | - fwd_bwd_input_dict = input_dict_mbs[0] | ||
| 410 | - fwd_bwd_labels = label_mbs[0] | ||
| 411 | - | ||
| 412 | - loss = self.forward_backward_step( | ||
| 413 | - input_dict=fwd_bwd_input_dict, | ||
| 414 | - labels=fwd_bwd_labels, | ||
| 415 | - global_valid_tokens=global_valid_tokens, | ||
| 416 | - ) | ||
| 417 | - if should_log: | ||
| 418 | - loss = loss.detach() | ||
| 419 | - if accumulated_loss is None: | ||
| 420 | - # Take ownership before the next replay overwrites the | ||
| 421 | - # graph-owned output. Later losses accumulate in place. | ||
| 422 | - accumulated_loss = loss.clone() | ||
| 423 | - else: | ||
| 424 | - accumulated_loss.add_(loss) | ||
| 425 | - | ||
| 426 | - grad_norm = dist_utils.clip_grad_norm_( | ||
| 427 | - [p for m in self.model_parts for p in m.parameters()], | ||
| 428 | - self.config.training.max_norm, | ||
| 429 | - foreach=True, | ||
| 430 | - pp_mesh=parallel_dims.get_optional_mesh("pp"), | ||
| 431 | - ep_enabled=parallel_dims.ep_enabled, | ||
| 432 | - ) | ||
| 433 | - self.checkpointer.maybe_wait_for_staging() | ||
| 434 | - self.optimizers.step() | ||
| 435 | - self.lr_schedulers.step() | ||
| 436 | - | ||
| 437 | - # log metrics | ||
| 438 | - if not should_log: | ||
| 439 | - return | ||
| 440 | - | ||
| 441 | - assert accumulated_loss is not None | ||
| 442 | - | ||
| 443 | - if parallel_dims.dp_cp_enabled: | ||
| 444 | - # FT addition: use ft_manager.loss_sync_pg for extra process group | ||
| 445 | - ft_pg = self.ft_manager.loss_sync_pg | ||
| 446 | - loss_mesh = parallel_dims.get_optional_mesh("loss") | ||
| 447 | - | ||
| 448 | - # For global_avg_loss, we want the average loss across all ranks: | ||
| 449 | - # accumulated_loss = local_loss_sum / global_valid_tokens | ||
| 450 | - # global_avg_loss = sum(local_loss_sum) / global_valid_tokens | ||
| 451 | - # = sum(accumulated_loss) | ||
| 452 | - # | ||
| 453 | - # For global_max_loss, we want the max of local average losses across ranks: | ||
| 454 | - # local_avg_loss = local_loss_sum / local_valid_tokens | ||
| 455 | - # = (accumulated_loss * global_valid_tokens) / local_valid_tokens | ||
| 456 | - # global_max_loss = max(local_avg_loss) | ||
| 457 | - local_avg_loss = accumulated_loss * global_valid_tokens / local_valid_tokens | ||
| 458 | - global_avg_loss, global_max_loss, global_ntokens_seen = ( | ||
| 459 | - dist_utils.dist_sum(accumulated_loss, loss_mesh, ft_pg), | ||
| 460 | - dist_utils.dist_max(local_avg_loss, loss_mesh, ft_pg), | ||
| 461 | - dist_utils.dist_sum( | ||
| 462 | - torch.tensor(self.ntokens_seen, dtype=torch.int64, device=self.device), | ||
| 463 | - loss_mesh, | ||
| 464 | - ft_pg, | ||
| 465 | - ), | ||
| 466 | - ) | ||
| 467 | - # ft_pg is None in semi-sync training. | ||
| 468 | - if ft_pg is not None: | ||
| 469 | - # Avoid artificial jumps in logged loss when replicas leave or rejoin. | ||
| 470 | - global_avg_loss /= ft_pg.size() | ||
| 471 | - else: | ||
| 472 | - global_avg_loss = global_max_loss = accumulated_loss.item() | ||
| 473 | - global_ntokens_seen = self.ntokens_seen | ||
| 474 | - | ||
| 475 | - extra_metrics = { | ||
| 476 | - "n_tokens_seen": global_ntokens_seen, | ||
| 477 | - "lr": lr, | ||
| 478 | - } | ||
| 479 | - self.metrics_processor.log( | ||
| 480 | - self.step, | ||
| 481 | - global_avg_loss, | ||
| 482 | - global_max_loss, | ||
| 483 | - grad_norm.item(), | ||
| 484 | - extra_metrics=extra_metrics, | ||
| 485 | - ) | ||
| 486 | 350 | ||
| 487 | 351 | ||
| 488 | def apply() -> None: | 352 | def apply() -> None: |
| 489 | torchtitan.experiments.torchft.trainer.FaultTolerantTrainer.__init__ = patched_init | 353 | torchtitan.experiments.torchft.trainer.FaultTolerantTrainer.__init__ = patched_init |
| 490 | torchtitan.experiments.torchft.trainer.FaultTolerantTrainer._configure_chunked_loss = _configure_chunked_loss | 354 | torchtitan.experiments.torchft.trainer.FaultTolerantTrainer._configure_chunked_loss = _configure_chunked_loss |
| 491 | - torchtitan.experiments.torchft.trainer.FaultTolerantTrainer.train_step = patched_train_step | ||
| 492 | 355 | ||
| 493 | 356 | ||
| 494 | apply() | 357 | apply() |


必须改:请 rebase 到当前
dev_0.4.0tip05f4deba。本地merge-tree已确认本文件与 tip 冲突——tip 自 merge-base 起补了 muon/vision/dsv3.2 的 ignore,本 MR 只删了 torchft 两行。三方合并时请保留 tip 其它collect_ignore/ deferral,同时继续取消"extensions/torchtitan/experiments/torchft"和"patches/torchft";不 rebase 合不进去。