Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / trainer / base.py: 70%

693 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-12-05 05:12 +0800

1# Copyright 2025-2026 Bytedance Ltd. and/or its affiliates 

2# Copyright 2026 Huawei Technologies Co., Ltd 

3# 

4# Licensed under the Apache License, Version 2.0 (the "License"); 

5# you may not use this file except in compliance with the License. 

6# You may obtain a copy of the License at 

7# 

8# http://www.apache.org/licenses/LICENSE-2.0 

9# 

10# Unless required by applicable law or agreed to in writing, software 

11# distributed under the License is distributed on an "AS IS" BASIS, 

12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

13# See the License for the specific language governing permissions and 

14# limitations under the License. 

15 

16""" 

17Base Trainer class for distributed training. 

18 

19This module provides the BaseTrainer class which serves as the foundation 

20for all trainer implementations. Subclasses can override specific methods 

21to customize training behavior. 

22 

23Features: 

24 - Callback system for extensible training hooks 

25 - Distributed training support 

26 - Gradient accumulation 

27 - Checkpointing 

28""" 

29 

30from __future__ import annotations 

31 

32import json 

33import logging 

34import os 

35import sys 

36from abc import ABC 

37from collections import defaultdict 

38from collections.abc import Callable, Iterator 

39from contextlib import nullcontext 

40from dataclasses import replace 

41from functools import partial 

42from typing import TYPE_CHECKING, Any, Dict, List, Optional 

43 

44import torch 

45import torch.distributed as dist 

46from torch.distributed.checkpoint.stateful import Stateful 

47from torch.optim.lr_scheduler import LRScheduler 

48from torch.utils.data import Dataset 

49from transformers import PretrainedConfig, PreTrainedModel, PreTrainedTokenizerBase 

50from transformers.modeling_outputs import ModelOutput 

51 

52from hyper_parallel import DTensor, HSDPModule, SkipDTensorDispatch 

53from hyper_parallel.auto_parallel.hyper_offload import OffloadSession 

54from hyper_parallel.core.tensor_parallel import loss_parallel 

55from hyper_parallel.core.utils import clip_grad_norm_ 

56from hyper_parallel.trainer.config import ( 

57 OptimizerSwapConfig, 

58 TrainerConfig, 

59 normalize_distributed_setup_overrides, 

60 save_configs, 

61) 

62from hyper_parallel.data.dataset_logging import enable_dataset_logging 

63from hyper_parallel.data.batching import ( 

64 OmniPackingLoader, OmniParallelBatch, RepeatingDataLoader, TokenBatchLoader, build_dataloader, 

65) 

66from hyper_parallel.data.parallel import DataLoaderParallelContext, create_dataloader_parallel_context 

67from hyper_parallel.trainer.runtime.distributed import ( 

68 all_reduce, 

69 get_global_rank_safe, 

70 get_local_rank_safe, 

71 get_world_size_safe, 

72) 

73from hyper_parallel.trainer.runtime.distributed import ( 

74 create_distributed_setup_from_config, 

75 destroy_process_group, 

76 initialize_distributed, 

77) 

78from hyper_parallel.trainer.runtime.logging import setup_logging 

79from hyper_parallel.trainer.runtime.loss_aggregation import count_loss_token 

80from hyper_parallel.trainer.runtime.metrics import mean_global_loss 

81from hyper_parallel.components.losses.aux_loss import aux_loss_scale_context, bind_aux_loss_scale 

82from hyper_parallel.trainer.callbacks.moe_monitor_callback import MoEMonitorCallback 

83from hyper_parallel.components.ops import ops 

84from hyper_parallel.trainer.runtime.pipeline import TrainerPipeline 

85from hyper_parallel.models._transformers.loss_parallel import causal_lm_loss_parallel 

86from hyper_parallel.models._transformers.model_builder import _validate_optimize_dtype 

87from hyper_parallel.models.external_state import get_model_external_state 

88from hyper_parallel.models.registry import resolve_model_adapter 

89from hyper_parallel.components.losses.model_output import ModelOutputLoss 

90from hyper_parallel.core.optimizer import ( 

91 ChainedOptimizer, 

92 SwapOptimizerConfig, 

93 swap_optimizer, 

94) 

95from hyper_parallel.components.optim.mixed_precision_optimizer import ( 

96 Float16OptimizerWithFloat16Params, 

97 MixedPrecisionOptimizer, 

98) 

99from hyper_parallel.trainer.runtime import fsdp as fsdp_runtime 

100from hyper_parallel.trainer.runtime import model_integration as model_integration_runtime 

101from hyper_parallel.trainer.runtime.data_iterator import HyperIter 

102from hyper_parallel.trainer.runtime.logging import enable_third_party_logging 

103from hyper_parallel.trainer.runtime.memory import empty_cache, print_device_mem_info 

104from hyper_parallel.trainer.runtime.memory_profiler import memory_profiler 

105from hyper_parallel.trainer.runtime.random import enable_high_precision_for_bf16, set_seed 

106from hyper_parallel.trainer.runtime.device import ( # pylint: disable=syntax-error 

107 get_device_type, 

108 is_device_runtime_simulated, 

109 get_torch_device, 

110 synchronize, 

111) 

112 

113from hyper_parallel.trainer.callbacks import ( 

114 EnvironMeterCallback, 

115 EvaluateCallback, 

116 GarbageCollectionCallback, 

117 LoggingCallback, 

118 ProfilerCallback, 

119 StressDetectCallback, 

120 TqdmCallback, 

121 CheckpointerCallback, 

122 TrainerState, 

123) 

124from hyper_parallel.trainer.runtime.worker_recovery import ( 

125 recovery_constructor, 

126 recovery_epoch_initialized, 

127 recovery_optimizer_update, 

128 recovery_train_loop, 

129 recovery_train_initialized, 

130 recovery_train_step, 

131) 

132 

133logger = logging.getLogger(__name__) 

134 

135if TYPE_CHECKING: 

136 from hyper_parallel.compile.compiler import GraphCompiler 

137 from hyper_parallel.data.text.chat_template import ChatTemplate 

138 from hyper_parallel.data.distributed import BalancingAlgorithm, CostModel 

139 from hyper_parallel.data.distributed.schema import SampleMetadata 

140 

141 

142def _to_swap_optimizer_config(config: OptimizerSwapConfig) -> SwapOptimizerConfig: 

143 """Translate the trainer-facing swap section into the core swap config. 

144 

145 Args: 

146 config: Resolved ``optimizer.swap`` configuration section. 

147 

148 Returns: 

149 The backend-neutral swap configuration consumed by ``swap_optimizer``. 

150 """ 

151 return SwapOptimizerConfig( 

152 swap_times=config.swap_times, 

153 state_keys=config.state_keys, 

154 min_numel=config.min_numel, 

155 # ``None`` means "leave it to the backend default", not "off": the core 

156 # config declares ``packed_swap: bool = True``, so pass that default 

157 # through rather than letting ``None`` read as a hard False. 

158 packed_swap=True if config.packed_swap is None else config.packed_swap, 

159 ) 

160 

161 

162def _attach_optimizer_swap(optimizer: Any, config: OptimizerSwapConfig) -> Any: 

163 """Attach optimizer-state swap to every Adam/AdamW leaf of ``optimizer``. 

164 

165 Every YAML optimizer target returns a ``ChainedOptimizer`` of leaf 

166 optimizers -- also for a single AdamW -- and the fp32 main-parameter wrapper 

167 keeps the same leaf containers. The swap runtime wraps one concrete 

168 Adam/AdamW and delegates everything else, so it is attached to the leaves 

169 and the outer object keeps dispatching. 

170 

171 Args: 

172 optimizer: Optimizer built by the configured target, optionally already 

173 wrapped for fp32 main parameters. 

174 config: Resolved ``optimizer.swap`` configuration section. 

175 

176 Returns: 

177 The optimizer carrying swap-wrapped leaves. A leaf the swap runtime does 

178 not support fails here, before the first training step. 

179 """ 

180 swap_config = _to_swap_optimizer_config(config) 

181 chained = optimizer.optimizer if isinstance(optimizer, MixedPrecisionOptimizer) else optimizer 

182 if not isinstance(chained, ChainedOptimizer): 

183 return swap_optimizer(optimizer, swap_config) 

184 

185 names = list(chained.optimizers_dict) 

186 leaves = [swap_optimizer(chained.optimizers_dict[name], swap_config) for name in names] 

187 # In place: the fp32 main-parameter wrapper aliases both containers. 

188 chained.chained_optimizers[:] = leaves 

189 for name, leaf in zip(names, leaves): 

190 chained.optimizers_dict[name] = leaf 

191 return optimizer 

192 

193 

194class BaseTrainer(Stateful, ABC): 

195 """ 

196 Base trainer class for distributed model training. 

197 

198 This class provides the core training infrastructure including: 

199 - Distributed initialization and parallelism setup 

200 - Model, optimizer, and scheduler initialization 

201 - Training step execution with gradient accumulation 

202 - Checkpointing and fault tolerance 

203 - Metrics logging 

204 

205 Subclasses can override the following methods to customize behavior: 

206 - `_build_distributed_setup()`: Connect AutoModel DistributedSetup/MeshContext 

207 - `_build_model()`: Connect AutoModel from_pretrained/parallelize 

208 - `_build_model_assets()`: Build tokenizer/processor assets 

209 - `_build_data_transform()`: Build modality-specific sample transforms 

210 - `forward_backward_step()`: Customize forward/backward logic 

211 - `train_step()`: Customize training step execution 

212 - `train()`: Train the model 

213 

214 Callback Hooks: 

215 The trainer calls callback methods at various stages: 

216 - evaluate_callback: evaluation callback 

217 - trace_callback: tracing callback (meter, wandb, tqdm, profile) 

218 - checkpoint_callback: checkpointing callback 

219 """ 

220 

221 # Core configs 

222 config: TrainerConfig 

223 device: torch.device 

224 # Attached at runtime by the model-integration pipeline (the Omni dataset builder sets 

225 # ``data_transform``, the integration adapter attaches ``get_batch`` and 

226 # ``num_micro_batches``): bare annotations, which assign nothing, so runtime behaviour is 

227 # unchanged -- they exist so the type checker sees the contract this class reads. 

228 data_transform: Any 

229 get_batch: Any 

230 num_micro_batches: int 

231 

232 # AutoModel distributed setup. 

233 # These objects have one owner: ``../build_options.py`` and 

234 # ``../components/distributed/mesh.py``. Trainer code consumes them but must 

235 # not create a second DeviceMesh or a VeOmni ParallelState. 

236 dist_info: Any 

237 distributed_setup: Any 

238 mesh_context: Any 

239 device_mesh: Any 

240 moe_mesh: Any 

241 

242 # Data 

243 train_dataset: Dataset 

244 data_transform: Any 

245 collate_fn: Any 

246 get_batch: Any 

247 dataloader_context: DataLoaderParallelContext | None = None 

248 train_dataloader: Any = None 

249 num_micro_batches: int 

250 

251 # Model 

252 model: PreTrainedModel = None 

253 model_parts: Optional[List[torch.nn.Module]] = None 

254 pipeline_runtime: Optional[TrainerPipeline] = None 

255 hsdp_model_parts: List[torch.nn.Module] = [] 

256 fsdp_runtime_diagnostics: Optional[fsdp_runtime.FSDPRuntimeDiagnostics] = None 

257 model_integration: Optional[model_integration_runtime.ModelIntegrationSession] = None 

258 model_config: PretrainedConfig = PretrainedConfig() 

259 tokenizer: PreTrainedTokenizerBase = None 

260 processor: Any = None 

261 chat_template: Optional[ChatTemplate] = None 

262 model_assets: List[Any] = [] 

263 

264 # Training components 

265 optimizer = None 

266 lr_scheduler: LRScheduler = None 

267 loss_fn: Optional[torch.nn.Module] = None 

268 

269 # Training context 

270 model_fwd_context: Any 

271 model_bwd_context: Any 

272 

273 # # Runtime metrics, controlled by trace_callback 

274 # environ_meter: helper.EnvironMeter # see in trace_callback.EnvironMeterCallback 

275 # step_env_metrics: Dict[str, Any] # mfu, flops, tokens, etc 

276 # step_train_metrics: Dict[str, Any] # loss, grad_norm, lr, etc 

277 

278 # # Checkpointer 

279 # checkpointer: CheckpointerBase # see in checkpoint_callback.CheckpointerCallback 

280 

281 # Callback system 

282 state: TrainerState 

283 

284 # Default seed when training.seed is omitted. 

285 default_seed: int = 42 

286 

287 @recovery_constructor 

288 def __init__(self, config: TrainerConfig) -> None: 

289 """ 

290 Initialize the trainer. 

291 

292 Args: 

293 args: Global Arguments 

294 Should have attributes: model, data, train 

295 model: ModelArguments 

296 data: DataArguments 

297 train: TrainingArguments 

298 """ 

299 

300 self.config: TrainerConfig = config 

301 

302 # General setup owns distributed initialization as its first stage. 

303 # ``_build_distributed_setup`` remains a reserved backend hook; the 

304 # trainer only defines its contract here. 

305 self._setup() 

306 memory_profiler.reset( 

307 self.config.memory, 

308 global_rank=self.global_rank, 

309 tp_rank=self.mesh.tp_rank, 

310 dp_rank=self.mesh.dp_rank, 

311 ) 

312 

313 # Reserved atomic model-build interface. 

314 # 

315 # Owner: 

316 # - ``../_transformers/auto_model.py::HyperAutoModel*.from_pretrained`` 

317 # - ``../_transformers/model_builder.py`` for materialization, 

318 # checkpoint loading, PEFT/quantization, and parallelize. 

319 # 

320 # Contract: 

321 # - consume the ``DistributedSetup`` created above; 

322 # - set ``model`` and the resolved checkpoint ``model_config``; 

323 # - return a materialized, weight-loaded, already-parallelized model; 

324 # - never call a second trainer-side ``build_parallelize_model``. 

325 self._build_model() 

326 self._build_loss() 

327 

328 # Build trainer-owned data components after the model finalizes parameters and sharding. 

329 self._build_model_assets() 

330 self._build_data_transform() 

331 self._build_dataset() 

332 self._build_collate_fn() 

333 self._build_dataloader() 

334 self._compute_train_iters() 

335 

336 self._build_optimizer() 

337 self.model_integration.attach_optimizer(self.optimizer) 

338 self._build_lr_scheduler() 

339 self._build_training_context() 

340 self._init_callbacks() 

341 

342 def _setup(self): 

343 """Initialize logging, distributed state, and the local device.""" 

344 # log args 

345 setup_logging() 

346 

347 # Initialize distributed process group 

348 backend = getattr(self.config.training, "backend", "nccl") 

349 if backend == "hccl" and self.config.training.enable_full_determinism: 

350 # HCCL reads this when creating communicators, before set_seed runs below. 

351 os.environ["HCCL_DETERMINISTIC"] = "true" 

352 initialize_distributed(backend=backend) 

353 

354 self.local_rank = get_local_rank_safe() 

355 self.global_rank = get_global_rank_safe() 

356 self.world_size = get_world_size_safe() 

357 if self.config.debug.check_dataset: 

358 enable_dataset_logging(self.config.debug.check_dataset) 

359 

360 if self.config.training.seed is None: 

361 self.config.training.seed = self.default_seed 

362 

363 if self.global_rank == 0: 

364 logger.info( 

365 "Trainer config:\n%s", 

366 json.dumps(self.config.to_dict(), indent=2), 

367 ) 

368 

369 # init distributed environment 

370 device_str = f"{get_device_type()}:{self.local_rank}" 

371 get_torch_device().set_device(device_str) 

372 self.device = torch.device(device_str) 

373 

374 logger.info("Process rank: %s, world size: %s", self.global_rank, self.world_size) 

375 

376 # Register distributed_setup; the Trainer-side desugar fills its 

377 # normalized plan_overrides/module_replacements (05 §15.2.6) so the 

378 # AutoModels build pipeline never sees raw YAML PlanOverride DTOs. 

379 self.distributed_setup = create_distributed_setup_from_config(self.config) 

380 normalize_distributed_setup_overrides(self.distributed_setup, self.config) 

381 self.mesh = self.distributed_setup.mesh_context 

382 self.device_mesh = self.mesh.device_mesh 

383 self.dp_cp_mesh = self.mesh.dp_cp_mesh 

384 

385 # Set random seed 

386 set_seed(self.config.training.seed, self.config.training.enable_full_determinism) 

387 

388 # Enable high precision for bf16 

389 enable_high_precision_for_bf16() 

390 

391 # Enable third party logging 

392 if self.local_rank == 0: 

393 enable_third_party_logging() 

394 

395 # Save arguments 

396 if self.global_rank == 0: 

397 save_configs(self.config, self.config.checkpoint.checkpoint_dir) 

398 

399 def _combine_pipeline_chunks(self, build: Callable) -> torch.nn.Module: 

400 """Build the remaining virtual stages and register the rank's training parameters.""" 

401 local_count = self.config.pipeline.local_stage_count 

402 if local_count == 1 and self.config.pipeline.schedule != "mpipe": 

403 return self.model 

404 spec = resolve_model_adapter(self.model).pipeline_parallel() 

405 if spec.combine_chunks is None: 

406 raise ValueError("The model pipeline adapter must support virtual chunks for interleaved training") 

407 parts = [self.model] 

408 for index in range(1, local_count): 

409 setup = replace(self.distributed_setup, pipeline_chunk_index=index) 

410 parts.append(build(distributed_setup=setup)) 

411 return spec.combine_chunks(tuple(parts), self.mesh.pp_mesh.get_group()) 

412 

413 def _build_model(self) -> None: 

414 """Build the model and derive Trainer-owned runtime state.""" 

415 self.peft_config = self.config.peft 

416 ops.set_backends(getattr(self.config, "ops", {})) 

417 build = partial( 

418 self.config.model.build, 

419 peft_config=self.peft_config, 

420 activation_checkpoint=self.config.activation_checkpoint, 

421 compile_config=self.config.compile, 

422 # The final dtype is applied inside the atomic build (05 stage-5 

423 # item 5); the Trainer no longer patches it afterwards. 

424 model_init_dtype=self.config.model_init_dtype, 

425 ) 

426 self._finalize_model_build(build) 

427 

428 def _finalize_model_build(self, build: Callable) -> None: 

429 """Validate parameter dtypes and derive Trainer-owned model runtime state.""" 

430 if self.config.pipeline.schedule == "mpipe" and self.mesh.dp_size != 1: 

431 raise ValueError("MPipe currently requires DP1 for variable-image visual FSDP execution") 

432 self.model = build(distributed_setup=self.distributed_setup) 

433 if self.config.accelerator.pp_size > 1 and not self.config.compile.selects_graph_compiler(): 

434 if getattr(self.model, "_hp_pipeline_partition", None) is None: 

435 raise ValueError("Eager Trainer PP requires a model factory that installs a pipeline partition") 

436 self.model = self._combine_pipeline_chunks(build) 

437 _validate_optimize_dtype( 

438 self.model, 

439 fp32_main_params=self.config.optimizer.fp32_main_params, 

440 ) 

441 self.model_config = self.model.config 

442 if self.global_rank == 0: 

443 logger.info( 

444 "Model config:\n%s", 

445 json.dumps(self.model.config.to_dict(), indent=2), 

446 ) 

447 if self.config.accelerator.loss_parallel: 

448 for part in getattr(self.model, "parts", (self.model,)): 

449 part.loss_function = causal_lm_loss_parallel 

450 model_parts = getattr(self.model, "parts", None) 

451 self.model_parts = list(model_parts) if model_parts is not None else [self.model] 

452 self.hsdp_model_parts = [ 

453 model_part 

454 for model_part in self.model_parts 

455 if isinstance(model_part, HSDPModule) 

456 ] 

457 self.model_integration = model_integration_runtime.build_model_integration_session( 

458 self.model, 

459 self.config, 

460 self.global_rank, 

461 self.mesh, 

462 ) 

463 self.fsdp_runtime_diagnostics = ( 

464 fsdp_runtime.build_fsdp_runtime_diagnostics(self.hsdp_model_parts) 

465 if getattr(self.config.debug, "check_fsdp_runtime", False) 

466 else None 

467 ) 

468 

469 def _build_loss(self) -> None: 

470 """Build the configured loss module or use the model-output default.""" 

471 loss_fn = ( 

472 self.config.loss_fn.build() 

473 if self.config.loss_fn is not None 

474 else ModelOutputLoss() 

475 ) 

476 

477 if not isinstance(loss_fn, torch.nn.Module): 

478 raise ValueError("config.loss_fn must build a torch.nn.Module") 

479 

480 self.loss_fn = loss_fn 

481 # Model-integrated objectives may need to intercept the model before its 

482 # ordinary forward materializes an otherwise avoidable output tensor. 

483 loss_model_binding_hook = getattr(self.loss_fn, "bind_model", None) 

484 

485 if callable(loss_model_binding_hook): 

486 for part in getattr(self.model, "parts", (self.model,)): 

487 loss_model_binding_hook(part, self.distributed_setup) 

488 

489 def _build_model_assets(self) -> None: 

490 """Require a concrete Trainer to build modality-specific model assets.""" 

491 raise NotImplementedError("Concrete Trainer must implement _build_model_assets") 

492 

493 def _build_data_transform(self) -> None: 

494 """Require a concrete Trainer to build its sample transform.""" 

495 raise NotImplementedError("Concrete Trainer must implement _build_data_transform") 

496 

497 def _build_dataset(self) -> None: 

498 """Build and assign one Dataset or a train-validation-test tuple.""" 

499 data_config = getattr(self.config.dataset, "data_config", {}) 

500 self.dataloader_context = create_dataloader_parallel_context( 

501 self.mesh, 

502 data_index_cache=bool(data_config.get("data_index_cache", False)), 

503 shared_storage=( 

504 False if is_device_runtime_simulated() 

505 else not bool(data_config.get("no_shared_storage", False)) 

506 ), 

507 tp_source_rank=( 

508 None 

509 if is_device_runtime_simulated() 

510 or self.config.dataloader.load_balance is not None 

511 else 0 

512 ), 

513 ) 

514 dataset_result = self.config.dataset.build( 

515 transform=self.data_transform, 

516 tokenizer=self.tokenizer, 

517 mesh_context=self.mesh, 

518 training_config=self.config.training, 

519 sampler_type=self.config.dataloader.sampler_type, 

520 dataloader_context=self.dataloader_context, 

521 ) 

522 

523 if isinstance(dataset_result, tuple) and len(dataset_result) == 3: 

524 self.train_dataset, self.valid_dataset, self.test_dataset = dataset_result 

525 return 

526 

527 self.train_dataset = dataset_result 

528 self.valid_dataset = self.test_dataset = None 

529 

530 def _build_collate_fn(self) -> None: 

531 """Require a concrete Trainer to build its micro-batch collator.""" 

532 raise NotImplementedError("Concrete Trainer must implement _build_collate_fn") 

533 

534 def _build_dataloader( 

535 self, 

536 *, 

537 metadata_fn: Callable[[Any], SampleMetadata] | None = None, 

538 cost_model: CostModel | None = None, 

539 balancing_algorithm: BalancingAlgorithm | None = None, 

540 ) -> None: 

541 """Build and assign train, validation, and test dataloaders.""" 

542 split_names = ("train", "valid", "test") 

543 datasets = (self.train_dataset, self.valid_dataset, self.test_dataset) 

544 data_config = getattr(self.config.dataset, "data_config", {}) 

545 online_data = self._get_data_source_type() == "online" 

546 max_seq_len = data_config["max_seq_len"] 

547 

548 if online_data and getattr(self.config.dataloader, "repeat", None) is False: 

549 raise ValueError( 

550 "Online epochs/max_steps requires dataloader.repeat=true; omit it to use the Online default" 

551 ) 

552 

553 dataloaders, batch_samplers = build_dataloader( 

554 self.config.dataloader, 

555 datasets=datasets, 

556 collate_fn=self.collate_fn, 

557 mesh_context=self.mesh, 

558 training_config=self.config.training, 

559 data_config=data_config, 

560 max_seq_len=max_seq_len, 

561 default_seed=self.default_seed, 

562 metadata_fn=metadata_fn, 

563 model_config=self.model_config, 

564 cost_model=cost_model, 

565 balancing_algorithm=balancing_algorithm, 

566 ) 

567 

568 for split_name, dataloader, batch_sampler in zip(split_names, dataloaders, batch_samplers): 

569 setattr(self, f"{split_name}_dataloader", dataloader) 

570 setattr(self, f"{split_name}_batch_sampler", batch_sampler) 

571 

572 if online_data and data_config.get("repeat", True): 

573 if self.train_dataloader is not None: 

574 if isinstance(self.train_dataloader, (TokenBatchLoader, OmniPackingLoader)): 

575 self.train_dataloader.repeat = True 

576 else: 

577 self.train_dataloader = RepeatingDataLoader(self.train_dataloader) 

578 

579 # The loader checkpoints the source pass and its native sampler together. 

580 self.train_batch_sampler = None 

581 

582 def attach_model_integration_data_pipeline(self) -> None: 

583 """Attach the final data pipeline through one shared Trainer path.""" 

584 self.model_integration.attach_data_pipeline( 

585 runtime_adapter=getattr(self.get_batch, "runtime_input_adapter", None), 

586 get_batch=self.get_batch, 

587 model_assets=tuple(self.model_assets), 

588 ) 

589 

590 def _compute_train_iters(self) -> None: 

591 """Normalize configured limits into total steps, steps per epoch, and epoch count.""" 

592 source_type = self._get_data_source_type() 

593 

594 if source_type == "online": 

595 train_iters, train_steps = self._compute_online_train_iters() 

596 else: 

597 train_iters, train_steps = self._compute_offline_train_iters() 

598 

599 self.train_iters = train_iters 

600 self.train_steps = train_steps 

601 self.train_epochs = (self.train_iters + self.train_steps - 1) // self.train_steps 

602 logger.info("Training plan: total_steps=%s, steps_per_epoch=%s, epochs=%s", 

603 self.train_iters, self.train_steps, self.train_epochs) 

604 

605 def _get_data_source_type(self) -> str: 

606 """Resolve the required text source type or the intrinsically Online Omni runtime.""" 

607 batch_target = self.config.dataloader.get_batch 

608 

609 if batch_target is None: 

610 raise ValueError("dataloader.get_batch must define a batching runtime target") 

611 

612 batch_factory = batch_target.callable 

613 

614 if isinstance(batch_factory, type) and issubclass(batch_factory, OmniParallelBatch): 

615 source_type = "online" 

616 else: 

617 source_type = batch_target.source_type 

618 

619 return source_type 

620 

621 def _compute_online_train_iters(self) -> tuple[int, int]: 

622 """Convert Online epochs/max_steps into optimizer-step limits. 

623 

624 Example: 

625 ``training: {epochs: 2, max_steps: 100}`` and 

626 ``dataset: {data_config: {repeat: true}}`` produce 200 total steps, 

627 100 steps per epoch, and therefore two epochs. Repeat defaults to true. 

628 

629 Returns: 

630 Total optimizer steps and optimizer steps per epoch. 

631 """ 

632 training = self.config.training 

633 

634 if training.epochs is None or training.max_steps is None: 

635 raise ValueError("Online requires training.epochs and training.max_steps") 

636 

637 if self.config.dataloader.load_balance is not None: 

638 raise ValueError("epochs/max_steps requires a native DataLoader; load_balance retains the legacy plan") 

639 

640 if self.config.dataset.data_config.get("repeat", True) is not True: 

641 raise ValueError("Online epochs/max_steps requires dataset.data_config.repeat=true") 

642 

643 train_iters = training.epochs * training.max_steps 

644 train_steps = training.max_steps 

645 return train_iters, train_steps 

646 

647 def _compute_offline_train_iters(self) -> tuple[int, int]: 

648 """Convert Offline train_iters/train_samples into optimizer-step limits. 

649 

650 Example: 

651 ``training: {train_iters: 100, global_batch_size: 16}`` or 

652 ``training: {train_samples: 1600, global_batch_size: 16}`` produces 

653 100 total steps. With 40 loader batches and four micro-batches per 

654 update, each epoch provides ten steps, yielding ten epochs. 

655 

656 Returns: 

657 Total optimizer steps and optimizer steps per epoch. Non-Online 

658 training entries retain their existing total-run calculation. 

659 """ 

660 training = self.config.training 

661 

662 if training.epochs is not None: 

663 raise ValueError("epochs/max_steps is only supported for online; offline uses train_iters/train_samples") 

664 

665 if training.train_iters is not None and training.train_samples is not None: 

666 raise ValueError("configure only one of training.train_iters and training.train_samples") 

667 

668 if training.train_iters is None and training.train_samples is None: 

669 raise ValueError("configure one of training.train_iters or training.train_samples") 

670 

671 train_iters = training.train_iters 

672 

673 if training.train_samples is not None: 

674 train_iters = training.train_samples // training.global_batch_size 

675 

676 if train_iters <= 0: 

677 raise ValueError("training configuration must produce at least one train iteration") 

678 

679 try: 

680 micro_batches_per_epoch = len(self.train_dataloader) 

681 except TypeError: 

682 micro_batches_per_epoch = 0 

683 

684 if micro_batches_per_epoch: 

685 train_steps = micro_batches_per_epoch // self.num_micro_batches 

686 

687 if train_steps <= 0: 

688 raise ValueError("train DataLoader must provide one complete optimizer step per epoch") 

689 

690 else: 

691 # Preserve the legacy plan for loaders whose length is not known. 

692 train_steps = train_iters 

693 

694 return train_iters, train_steps 

695 

696 _optimizer_needs_layouts = False 

697 

698 def _build_optimizer(self) -> None: 

699 """Build the configured optimizer with the runtime model context.""" 

700 config: TrainerConfig = self.config 

701 self._optimizer_needs_layouts = False 

702 external = get_model_external_state(self.model) 

703 

704 if external is not None: 

705 def wrap_dense(dense_raw: Any) -> Any: 

706 """Wrap dense parameters in FP32 main and optional state swap. 

707 

708 Args: 

709 dense_raw: Constructed dense optimizer. 

710 """ 

711 dense = ( 

712 Float16OptimizerWithFloat16Params(dense_raw, self.model) 

713 if config.optimizer.fp32_main_params else dense_raw 

714 ) 

715 

716 if config.optimizer.swap.enabled: 

717 dense = _attach_optimizer_swap(dense, config.optimizer.swap) 

718 

719 return dense 

720 

721 self.optimizer = external.build_optimizer(config.optimizer, wrap_dense=wrap_dense) 

722 return 

723 

724 optimizer = config.optimizer.target.build(model=self.model).get_optimizer() 

725 if config.compile.selects_graph_compiler() and ( 

726 config.optimizer.fp32_main_params 

727 or any(getattr(leaf, "is_muon", False) for leaf in optimizer.chained_optimizers)): 

728 if config.optimizer.swap.enabled: 

729 raise ValueError("optimizer.swap.enabled is unsupported with deferred graph optimizer binding") 

730 if config.checkpoint.restore_from is not None and config.checkpoint.restore_optimizer: 

731 raise ValueError( 

732 "GraphCompiler cannot restore optimizer state for Muon or optimizer.fp32_main_params " 

733 "before parameter layouts are bound; set checkpoint.restore_optimizer=false " 

734 "to load model weights without optimizer state" 

735 ) 

736 optimizer.defer_parameter_binding() 

737 self._optimizer_needs_layouts = True 

738 self.optimizer = ( 

739 Float16OptimizerWithFloat16Params(optimizer, self.model) 

740 if config.optimizer.fp32_main_params else optimizer 

741 ) 

742 

743 # Swap is attached after the fp32 main-parameter wrap so leaf optimizers 

744 # already reference their final parameters, and the lr scheduler built 

745 # right after reads the wrapped ``self.optimizer.param_groups``. 

746 if config.optimizer.swap.enabled: 

747 self.optimizer = _attach_optimizer_swap(self.optimizer, config.optimizer.swap) 

748 

749 def _build_lr_scheduler(self) -> None: 

750 """Build the learning rate scheduler with the configured iteration budget.""" 

751 config: TrainerConfig = self.config 

752 scheduler_iters = config.training.lr_scheduler_iters or self.train_iters 

753 

754 if scheduler_iters <= 0: 

755 raise ValueError("training.lr_scheduler_iters must be positive when configured") 

756 

757 lr_scheduler = config.lr_scheduler.build( 

758 optimizer=self.optimizer, 

759 train_iters=scheduler_iters, 

760 ) 

761 self.lr_scheduler = lr_scheduler.get_lr_scheduler() 

762 

763 def _build_training_context(self): 

764 """Build training context for distributed training.""" 

765 if self.config.accelerator.loss_parallel: 

766 tp_mesh = self.device_mesh["tp"] 

767 self.model_fwd_context = partial(loss_parallel, mesh=tp_mesh) 

768 else: 

769 self.model_fwd_context = nullcontext() 

770 self.model_bwd_context = nullcontext() 

771 offload = self.config.hyper_offload 

772 self.hyper_offload_context = nullcontext() 

773 if offload.enable: 

774 self.hyper_offload_context = OffloadSession(offload) 

775 logger.info("HyperOffload enabled: peak planner with communication masking; %s", offload) 

776 self.graph_compiler: Optional[GraphCompiler] = None 

777 

778 def _build_graph_compiler(self) -> None: 

779 """Build the optional joint-graph compiler for this trainer runtime.""" 

780 

781 if not self.config.compile.selects_graph_compiler(): 

782 return 

783 # Keep eager trainers independent of the graph compiler and its pass import tree. 

784 from hyper_parallel.compile.compiler import GraphCompiler # pylint: disable=C0415 

785 

786 self.graph_compiler = GraphCompiler( 

787 model=self.model, 

788 train_fn=self._graph_train_fn, 

789 trainer_config=self.config, 

790 device=self.device, 

791 mesh_context=self.mesh, 

792 source_shard_info=getattr(self.model, "_source_shard_info", None), 

793 ) 

794 

795 def _graph_train_fn( 

796 self, 

797 model: torch.nn.Module, 

798 model_inputs: Dict[str, Any], 

799 labels: Optional[torch.Tensor], 

800 current_token_counts: Dict[str, torch.Tensor], 

801 ) -> tuple[torch.Tensor, Dict[str, torch.Tensor]]: 

802 """Capture forward/loss with explicit runtime token counts.""" 

803 model_fwd_context = ( 

804 self.model_fwd_context() 

805 if callable(self.model_fwd_context) 

806 else self.model_fwd_context 

807 ) 

808 with model_fwd_context: 

809 outputs = model(**model_inputs, use_cache=False) 

810 # Counts must be graph inputs: packed lengths and ignored-label counts 

811 # can vary even when tensor shapes happen to match the first batch. 

812 loss, loss_dict = self.postforward( 

813 outputs, labels, 

814 current_token_counts=current_token_counts, 

815 ) 

816 return loss, loss_dict 

817 

818 def _init_callbacks(self): 

819 """Initialize callbacks.""" 

820 dp_cp_mesh = self.mesh.dp_cp_mesh 

821 self.moe_monitor = MoEMonitorCallback( 

822 self.model, 

823 dp_group=dp_cp_mesh.get_group() if dp_cp_mesh is not None else None, 

824 tp_group=self.device_mesh["tp"].get_group() if self.mesh.sequence_parallel else None, 

825 ) 

826 self.state = TrainerState() 

827 # Raw AUX is not normalized with the backward loss; average its observations. 

828 self.environ_meter_callback = EnvironMeterCallback(self, microbatch_mean_metrics=("router_aux_loss",)) 

829 self.tqdm_callback = TqdmCallback(self) 

830 self.logging_callback = LoggingCallback(self) 

831 self.evaluate_callback = EvaluateCallback(self) 

832 self.garbage_collection_callback = GarbageCollectionCallback(self) 

833 self.profiler_callback = ProfilerCallback(self) 

834 self._callbacks = [ 

835 self.environ_meter_callback, 

836 self.logging_callback, 

837 self.tqdm_callback, 

838 self.evaluate_callback, 

839 self.garbage_collection_callback, 

840 self.profiler_callback, 

841 ] 

842 if self.config.stress_detect.op_stress_detect.detection_interval > 0: 

843 self.stress_detect_callback = StressDetectCallback(self) 

844 self._callbacks.append(self.stress_detect_callback) 

845 # Registered to save, to restore, or both --- the two are independent, so 

846 # a run that only loads an existing checkpoint still needs the callback. 

847 if ( 

848 self.config.checkpoint.save_ckpt 

849 or self.config.checkpoint.save_hf_weights 

850 or self.config.checkpoint.restore_from is not None 

851 ): 

852 self.checkpoint_callback = CheckpointerCallback(self) 

853 self._callbacks.append(self.checkpoint_callback) 

854 else: 

855 logger.info( 

856 "Checkpointing is inactive (save_ckpt=false, save_hf_weights=false, " 

857 "restore_from=None); " 

858 "no checkpoint callback registered." 

859 ) 

860 

861 @recovery_train_initialized 

862 def on_train_begin(self) -> None: 

863 """Run all registered callbacks at the start of training.""" 

864 # During process recovery, callbacks must not depend on collective communication. 

865 # If collectives are required, process recovery must be adapted for that scenario. 

866 for callback in self._callbacks: 

867 callback.on_train_begin(self.state) 

868 

869 def on_train_end(self) -> None: 

870 """Run all registered callbacks at the end of training.""" 

871 for callback in self._callbacks: 

872 callback.on_train_end(self.state) 

873 

874 def on_epoch_begin(self) -> None: 

875 """Run all registered callbacks at the start of an epoch.""" 

876 for callback in self._callbacks: 

877 callback.on_epoch_begin(self.state) 

878 

879 def on_epoch_end(self) -> None: 

880 """Run all registered callbacks at the end of an epoch.""" 

881 for callback in self._callbacks: 

882 callback.on_epoch_end(self.state) 

883 

884 def on_step_begin(self, **kwargs: Any) -> None: 

885 """Run all registered callbacks at the start of a training step.""" 

886 for callback in self._callbacks: 

887 callback.on_step_begin(self.state, **kwargs) 

888 

889 def on_micro_step_begin(self, micro_batch: Dict[str, Any], **kwargs: Any) -> None: 

890 """Run all registered callbacks before one forward-backward micro step. 

891 

892 Args: 

893 micro_batch: Prepared inputs for the current micro step. 

894 **kwargs: Additional callback context. 

895 """ 

896 for callback in self._callbacks: 

897 callback.on_micro_step_begin(self.state, micro_batch, **kwargs) 

898 

899 def on_micro_step_end(self, loss_dict: Dict[str, torch.Tensor], **kwargs: Any) -> None: 

900 """Run all registered callbacks after one forward-backward micro step. 

901 

902 Args: 

903 loss_dict: Named losses and metrics returned by the completed micro step. 

904 **kwargs: Additional callback context. 

905 """ 

906 for callback in self._callbacks: 

907 callback.on_micro_step_end(self.state, loss_dict=loss_dict, **kwargs) 

908 

909 def on_step_end( 

910 self, 

911 loss: Optional[float] = None, 

912 loss_dict: Optional[Dict[str, Any]] = None, 

913 grad_norm: Optional[float] = None, 

914 ) -> None: 

915 """Run all registered callbacks at the end of a training step. 

916 

917 Args: 

918 loss: Aggregated loss for the optimizer step. 

919 loss_dict: Named loss values for the optimizer step. 

920 grad_norm: Gradient norm measured before the optimizer update. 

921 """ 

922 if self.state.global_step == 1: 

923 self._print_step_one_op_backends() 

924 for callback in self._callbacks: 

925 callback.on_step_end(self.state, loss=loss, loss_dict=loss_dict, grad_norm=grad_norm) 

926 

927 def _print_step_one_op_backends(self) -> None: 

928 """Print the first step's operator backends to stderr on global rank zero.""" 

929 local_usage = ops.used_backends() 

930 world_size = get_world_size_safe() 

931 reports = [local_usage] 

932 if world_size > 1: 

933 # Some operators only run on pipeline stages or modality ranks other than rank zero. 

934 reports = [()] * world_size 

935 dist.all_gather_object(reports, local_usage) 

936 if get_global_rank_safe() == 0: 

937 usage = sorted({entry for report in reports for entry in report}) 

938 if usage: 

939 rows = [("Op", "Variant", "Backend"), *usage] 

940 widths = [max(len(value) for value in column) for column in zip(*rows)] 

941 rows.insert(1, tuple("-" * width for width in widths)) 

942 table = "\n".join( 

943 " ".join(value.ljust(width) for value, width in zip(row, widths)).rstrip() 

944 for row in rows 

945 ) 

946 # Use the config log stream so torchrun applies the same worker prefix. 

947 print(f"Fused operator backends used in training step 1\n\n{table}", file=sys.stderr, flush=True) 

948 

949 def preforward(self, micro_batch: List[Dict[str, Any]]) -> Dict[str, Any]: 

950 """Preprocess micro batches before forward pass. 

951 

952 Tensors are moved to ``self.device`` non-blockingly. Nested dicts 

953 (e.g. ``multimodal_metadata`` emitted by ``PackingCollator``) are 

954 recursed so inner tensor values land on the device too; Python ints 

955 / lists / etc. pass through unchanged. 

956 

957 Args: 

958 micro_batch: Batch fields to move to the training device. 

959 

960 Returns: 

961 Batch fields with tensors moved to the training device. 

962 """ 

963 

964 def _to_device(v: Any) -> Any: 

965 if isinstance(v, torch.Tensor): 

966 return v.to(self.device, non_blocking=True) 

967 

968 if isinstance(v, dict): 

969 return {k: _to_device(vv) for k, vv in v.items()} 

970 

971 return v 

972 

973 # chunk_mbs_config = getattr(self.config.training, "chunk_mbs_config", None) 

974 # self._chunk_mbs_ranges = build_chunk_mbs_ranges(micro_batch, chunk_mbs_config) 

975 micro_batch = {k: _to_device(v) for k, v in micro_batch.items()} # type: ignore 

976 # if getattr(self, "LOG_SAMPLE", True): 

977 # self.LOG_SAMPLE = False 

978 return micro_batch 

979 

980 def postforward( 

981 self, outputs: ModelOutput, labels: Optional[torch.Tensor], 

982 *, 

983 current_token_counts: Dict[str, torch.Tensor], 

984 ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: 

985 """Postprocess model outputs after forward pass. 

986 

987 Args: 

988 outputs: Model outputs consumed by the configured loss. 

989 labels: Labels associated with the current micro-batch. 

990 current_token_counts: Per-loss token counts for the current micro-batch. 

991 

992 Returns: 

993 Backward loss and named globally aggregated loss values. 

994 """ 

995 # The default empty-shard guard must use the same aligned supervision 

996 # count as loss weighting, including already-shifted packed targets. 

997 if isinstance(self.loss_fn, ModelOutputLoss): 

998 local_loss = self.loss_fn( 

999 model_output=outputs, labels=labels, 

1000 valid_token_count=current_token_counts.get("foundation_tokens"), 

1001 ) 

1002 else: 

1003 local_loss = self.loss_fn(model_output=outputs, labels=labels) 

1004 # Names are static graph metadata; diagnostics added below are not losses. 

1005 self.loss_names = tuple(local_loss) if isinstance(local_loss, dict) else ("foundation_loss",) 

1006 # Every foundation-family objective receives the same external token weight. 

1007 # Bind each branch before backward can reach its independently injected losses. 

1008 foundation_losses = ( 

1009 (value for key, value in local_loss.items() if key.split("_loss", maxsplit=1)[0] == "foundation") 

1010 if isinstance(local_loss, dict) else (local_loss,) 

1011 ) 

1012 for foundation_loss in foundation_losses: 

1013 if foundation_loss is not None: 

1014 bind_aux_loss_scale(foundation_loss) 

1015 loss_dict: Dict[str, torch.Tensor] = mean_global_loss( 

1016 local_loss, 

1017 current_token_counts, 

1018 device_mesh=self.mesh, 

1019 ) 

1020 loss = torch.stack(list(loss_dict.values())).sum() 

1021 # Model-declared extra metrics join the logged mapping only after 

1022 # the backward loss is fixed: log-only, never part of the loss. 

1023 extra_metrics = getattr(outputs, "extra_metrics", None) 

1024 if extra_metrics is None: 

1025 model_ref = getattr(self, "model", None) 

1026 extra_metrics = getattr(model_ref, "pending_extra_metrics", None) 

1027 if extra_metrics is not None: 

1028 model_ref.pending_extra_metrics = None 

1029 if extra_metrics: 

1030 for name, value in extra_metrics.items(): 

1031 loss_dict[name] = value.detach().float() 

1032 # Log-only outputs share the eager/graph path without entering backward loss. 

1033 moe_monitor = getattr(self, "moe_monitor", None) 

1034 if moe_monitor is not None: 

1035 aux_loss = moe_monitor.last_mean_aux_loss 

1036 if aux_loss is not None: 

1037 loss_dict["router_aux_loss"] = aux_loss 

1038 return loss, loss_dict 

1039 

1040 def forward_backward_step( 

1041 self, 

1042 micro_batch: dict[str, torch.Tensor], 

1043 loss_inputs: Optional[dict[str, torch.Tensor]] = None, 

1044 ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: 

1045 """Run forward and backward computation for one micro batch. 

1046 

1047 Args: 

1048 micro_batch: Inputs forwarded to the model. 

1049 loss_inputs: Loss-only labels and masks from the get-batch runtime. If 

1050 omitted, the legacy single-dictionary path is preserved. 

1051 

1052 Returns: 

1053 Backward loss and the named globally aggregated loss mapping. 

1054 """ 

1055 for name, count in self.current_token_counts.items(): 

1056 self.step_token_counts[name] = self.step_token_counts.get(name, 0) + count.detach() 

1057 channel_loss_callback = getattr(self, "channel_loss_callback", None) 

1058 micro_step_context = ( 

1059 channel_loss_callback.micro_step_context(self.state, micro_batch) 

1060 if channel_loss_callback is not None 

1061 else nullcontext() 

1062 ) 

1063 offload_context = getattr(self, "hyper_offload_context", nullcontext()) 

1064 with offload_context, micro_step_context, aux_loss_scale_context(): 

1065 micro_batch = self.preforward(micro_batch) 

1066 # TextTrainer passes loss-only fields separately. Keep the legacy 

1067 # BaseTrainer/VLM one-dictionary call contract working as well. 

1068 if loss_inputs is None: 

1069 loss_inputs = { 

1070 name: micro_batch[name] 

1071 for name in ("labels", "shift_labels", "loss_mask") 

1072 if name in micro_batch 

1073 } 

1074 else: 

1075 loss_inputs = self.preforward(loss_inputs) 

1076 labels = loss_inputs.get("labels", micro_batch.get("labels")) 

1077 

1078 # A model-integrated loss can translate the public batch fields into 

1079 # model-family protocol arguments before the model forward starts. 

1080 prepare_model_inputs = getattr( 

1081 self.loss_fn, 

1082 "prepare_model_inputs", 

1083 None, 

1084 ) 

1085 if callable(prepare_model_inputs): 

1086 micro_batch = prepare_model_inputs(micro_batch, loss_inputs) 

1087 if channel_loss_callback is not None: 

1088 channel_loss_callback.strip_model_inputs(micro_batch) 

1089 self.model_integration.record_batch(micro_batch, loss_inputs) 

1090 

1091 if self.graph_compiler is not None: 

1092 runtime_adapter = getattr(getattr(self, "get_batch", None), "runtime_input_adapter", None) 

1093 if runtime_adapter is not None: 

1094 micro_batch = runtime_adapter.prepare_graph_inputs(micro_batch) 

1095 if self.config.training.empty_cache_before_backward: 

1096 logger.warning( 

1097 "training.empty_cache_before_backward is ignored in graph compiler mode " 

1098 "because forward and backward execute in one joint graph" 

1099 ) 

1100 # The traced ``loss_dict`` values flow back as extra graph 

1101 # outputs (emitted after the gradients), so the logging 

1102 # metrics keep per-key parity with the eager path. 

1103 loss, loss_dict = self.graph_compiler.forward_backward( 

1104 model_inputs=micro_batch, 

1105 labels=labels, 

1106 current_token_counts=self.current_token_counts, 

1107 ) 

1108 else: 

1109 model_fwd_context = ( 

1110 self.model_fwd_context() 

1111 if callable(self.model_fwd_context) 

1112 else self.model_fwd_context 

1113 ) 

1114 with model_fwd_context: 

1115 outputs: ModelOutput = self.model(**micro_batch, use_cache=False) 

1116 

1117 # with use_parallel_state("base"): 

1118 loss, loss_dict = self.postforward( 

1119 outputs, labels, 

1120 current_token_counts=self.current_token_counts, 

1121 ) 

1122 prefetch_plan = getattr(self.train_dataloader, "prefetch_plan", None) 

1123 if callable(prefetch_plan): 

1124 prefetch_plan() # pylint: disable=not-callable # Guarded dynamic hook. 

1125 # The loss graph owns everything required for backward. Releasing 

1126 # the model output here avoids retaining large vocabulary logits 

1127 # until the whole backward pass finishes. 

1128 del outputs 

1129 if self.config.training.empty_cache_before_backward: 

1130 empty_cache() 

1131 

1132 # Backward pass 

1133 with self.model_bwd_context: 

1134 loss.backward() 

1135 prefetch = getattr(self.train_dataloader, "prefetch", None) 

1136 if callable(prefetch): 

1137 prefetch() # pylint: disable=not-callable # Guarded dynamic hook. 

1138 

1139 del micro_batch 

1140 return loss, loss_dict 

1141 

1142 def pipeline_forward_backward( 

1143 self, batches: Iterator[tuple[dict, dict]], count: int, 

1144 ) -> tuple[float, dict[str, float]]: 

1145 """Run one optimizer step through the model-owned pipeline partition. 

1146 

1147 Args: 

1148 batches: Model and loss inputs for the local data-parallel replica. 

1149 count: Number of microbatches to schedule. 

1150 """ 

1151 if self.pipeline_runtime is None: 

1152 self.pipeline_runtime = TrainerPipeline(self) 

1153 return self.pipeline_runtime.run(batches, count) 

1154 

1155 def model_reshard(self, micro_step: int, num_micro_steps: int) -> None: 

1156 """Reshard model after backward pass; policy lives in ``runtime/fsdp.py``. 

1157 

1158 Args: 

1159 micro_step: Zero-based micro-step index. 

1160 num_micro_steps: Number of micro-steps in the optimizer step. 

1161 """ 

1162 fsdp_runtime.model_reshard(self.hsdp_model_parts, self.config.fsdp_config, micro_step, num_micro_steps) 

1163 

1164 def _configure_fsdp_gradient_sync(self, micro_step: int, num_micro_steps: int): 

1165 """Configure FSDP gradient synchronization; policy lives in ``runtime/fsdp.py``.""" 

1166 fsdp_runtime.configure_fsdp_gradient_sync( 

1167 self.hsdp_model_parts, 

1168 self.config.fsdp_config, 

1169 self.mesh.dp_replicate_size, 

1170 micro_step, 

1171 num_micro_steps, 

1172 ) 

1173 

1174 def configure_fsdp_gradient_sync(self, micro_step: int, num_micro_steps: int) -> None: 

1175 """Configure FSDP gradient synchronization for an external training loop. 

1176 

1177 Args: 

1178 micro_step: Zero-based micro-step index. 

1179 num_micro_steps: Number of micro-steps in the optimizer step. 

1180 """ 

1181 self._configure_fsdp_gradient_sync(micro_step, num_micro_steps) 

1182 

1183 def begin_fsdp_runtime_diagnostics(self, micro_step: int) -> None: 

1184 """Begin observing one FSDP forward/backward micro-step when enabled. 

1185 

1186 Args: 

1187 micro_step: Microbatch index. 

1188 """ 

1189 if self.fsdp_runtime_diagnostics is not None: 

1190 self.fsdp_runtime_diagnostics.begin_micro_step( 

1191 self.state.global_step, 

1192 micro_step, 

1193 ) 

1194 

1195 def validate_fsdp_runtime_before_optimizer(self) -> None: 

1196 """Fail before optimizer updates when FSDP prefetch state is unsafe.""" 

1197 if self.fsdp_runtime_diagnostics is not None: 

1198 self.model_integration.record_fsdp_trace( 

1199 self.fsdp_runtime_diagnostics.trace_evidence() 

1200 ) 

1201 self.fsdp_runtime_diagnostics.validate_before_optimizer_step() 

1202 

1203 def begin_loss_step(self) -> None: 

1204 """Reset scalar counters before reading the next optimizer step.""" 

1205 self.step_token_counts = {} 

1206 

1207 def _loss_denominator(self) -> float: 

1208 """Return the optimizer-step valid-token count across DP/CP.""" 

1209 family = self.loss_names[0].split("_loss", maxsplit=1)[0] 

1210 count = self.step_token_counts[f"{family}_tokens"].detach().clone() 

1211 mesh = self.mesh.dp_cp_mesh 

1212 if mesh is not None and mesh.size() > 1: 

1213 count = all_reduce(count.to(self.device), op="sum", group=mesh.get_group()) 

1214 else: 

1215 count = count.item() 

1216 return max(count, 1) 

1217 

1218 @torch.no_grad() 

1219 def loss_normalize(self, loss: float, loss_dict: Dict[str, float], *, denominator: float | None = None) -> float: 

1220 """Normalize Trainer-owned gradients and loss metrics before clipping. 

1221 

1222 External providers expose their owned parameters through ``parameters`` 

1223 and normalize those gradients in ``prepare_optimizer_step`` instead. 

1224 

1225 Args: 

1226 loss: Summed step objective before token normalization. 

1227 loss_dict: Step loss metrics, normalized in place. 

1228 denominator: Optional precomputed valid-token count. 

1229 """ 

1230 if denominator is None: 

1231 denominator = self._loss_denominator() 

1232 external = get_model_external_state(self.model) 

1233 excluded = {id(param) for param in external.parameters.values()} if external is not None else set() 

1234 with SkipDTensorDispatch(): 

1235 for parameter in self.model.parameters(): 

1236 if id(parameter) in excluded: 

1237 continue 

1238 grad = getattr(parameter, "main_grad", None) 

1239 if grad is None: 

1240 grad = parameter.grad 

1241 if grad is not None: 

1242 if isinstance(grad, DTensor): 

1243 grad = grad.to_local() 

1244 grad.div_(denominator) 

1245 for name in self.loss_names: 

1246 loss_dict[name] /= denominator 

1247 return loss / denominator 

1248 

1249 def prepare_optimizer_step(self, loss: float, loss_dict: Dict[str, float]) -> tuple[float, Any]: 

1250 """Normalize the step objective before clipping and optimizer preparation. 

1251 

1252 Args: 

1253 loss: Summed step objective before token normalization. 

1254 loss_dict: Step loss metrics, normalized in place. 

1255 

1256 Returns: 

1257 Normalized loss and the global gradient norm before clipping. 

1258 """ 

1259 if self._optimizer_needs_layouts: 

1260 self.optimizer.bind_parameter_layouts(self.graph_compiler.optimizer_parameter_layouts) 

1261 denominator = self._loss_denominator() 

1262 loss = self.loss_normalize(loss, loss_dict, denominator=denominator) 

1263 return loss, self.clip_grad_norm(gradient_divisor=denominator) 

1264 

1265 def clip_grad_norm(self, *, gradient_divisor: float = 1.0) -> Any: 

1266 """Run pre-optimizer diagnostics and clipping in their required order.""" 

1267 self.model_integration.after_backward_before_clip() 

1268 self.validate_fsdp_runtime_before_optimizer() 

1269 max_grad_norm = self.config.training.max_grad_norm 

1270 external = get_model_external_state(self.model) 

1271 

1272 if external is not None: 

1273 preparation = external.prepare_optimizer_step(max_norm=max_grad_norm, gradient_divisor=gradient_divisor) 

1274 self.model_integration.after_clip(preparation.post_clip_norm) 

1275 return preparation.global_norm 

1276 

1277 grad_norm: Any = 0.0 

1278 post_clip_norm = None 

1279 compiler = getattr(self, "graph_compiler", None) 

1280 clip_kwargs = {"parameter_layouts": compiler.parameter_layouts} if compiler is not None else {} 

1281 if self.pipeline_runtime is not None: 

1282 clip_kwargs["pp_group"] = self.mesh.pp_mesh.get_group() 

1283 if max_grad_norm > 0: 

1284 grad_norm = clip_grad_norm_(self.model, max_grad_norm, **clip_kwargs) 

1285 

1286 if self.model_integration.runtime_enabled: 

1287 grad_norm_value = ( 

1288 float(grad_norm.item()) 

1289 if isinstance(grad_norm, torch.Tensor) 

1290 else float(grad_norm) 

1291 ) 

1292 clip_coefficient = min( 

1293 float(max_grad_norm) / (grad_norm_value + 1.0e-6), 

1294 1.0, 

1295 ) 

1296 post_clip_norm = grad_norm_value * clip_coefficient 

1297 elif self.model_integration.runtime_enabled: 

1298 grad_norm = clip_grad_norm_(self.model, float("inf"), **clip_kwargs) 

1299 post_clip_norm = grad_norm 

1300 

1301 self.model_integration.after_clip(post_clip_norm) 

1302 return grad_norm 

1303 

1304 @recovery_optimizer_update 

1305 def step_optimizers_and_schedulers(self) -> None: 

1306 """Step every optimizer and scheduler, then expose the final state.""" 

1307 optimizers = self.optimizer if isinstance(self.optimizer, list) else [self.optimizer] 

1308 for optimizer in optimizers: 

1309 # Keep zeros_like dispatched so lazily created optimizer states retain DTensor metadata. 

1310 with SkipDTensorDispatch(no_skip={torch.zeros_like}): 

1311 optimizer.step() 

1312 optimizer.zero_grad() 

1313 moe_monitor = getattr(self, "moe_monitor", None) 

1314 if moe_monitor is not None: 

1315 moe_monitor.on_step_end() 

1316 self.model_integration.after_optimizer() 

1317 

1318 schedulers = ( 

1319 self.lr_scheduler 

1320 if isinstance(self.lr_scheduler, list) 

1321 else ([self.lr_scheduler] if self.lr_scheduler is not None else []) 

1322 ) 

1323 for scheduler in schedulers: 

1324 scheduler.step() 

1325 

1326 def _end_model_integration_step(self, metrics: Dict[str, Any]) -> None: 

1327 """Persist structured step metrics and global input identity.""" 

1328 

1329 if not self.model_integration.runtime_enabled: 

1330 return 

1331 

1332 resolved_metrics = dict(metrics) 

1333 optimizers = self.optimizer if isinstance(self.optimizer, list) else [self.optimizer] 

1334 learning_rates = [] 

1335 for optimizer in optimizers: 

1336 inner = getattr(optimizer, "optimizer", optimizer) 

1337 leaves = getattr(inner, "chained_optimizers", (inner,)) 

1338 for leaf in leaves: 

1339 learning_rates.extend( 

1340 group.get("lr") 

1341 for group in getattr(leaf, "param_groups", ()) 

1342 if group.get("lr") is not None 

1343 ) 

1344 

1345 if learning_rates: 

1346 resolved_metrics["lr"] = float(learning_rates[0]) 

1347 

1348 token_counts = getattr(self, "step_token_counts", {}) 

1349 token_values = [] 

1350 for value in token_counts.values(): 

1351 token_values.append(float(value.item() if torch.is_tensor(value) else value)) 

1352 

1353 if token_values: 

1354 resolved_metrics["tokens"] = sum(token_values) 

1355 

1356 resolved_metrics["samples"] = self.config.training.global_batch_size 

1357 self.model_integration.end_step(resolved_metrics) 

1358 

1359 @recovery_train_step 

1360 def train_step( 

1361 self, 

1362 data_iterator: Any, 

1363 ) -> Dict[str, float]: 

1364 """Execute one optimizer update from the next dataloader batch. 

1365 

1366 Args: 

1367 data_iterator: Iterator providing the next micro-batches. 

1368 

1369 Returns: 

1370 Aggregated loss and gradient norm. 

1371 """ 

1372 memory_profiler.step() 

1373 micro_batches: List[Dict[str, Any]] = next(data_iterator) 

1374 self.state.global_step += 1 

1375 

1376 self.on_step_begin(micro_batches=micro_batches) 

1377 self.model_integration.begin_step(self.state.global_step) 

1378 

1379 # Forward and backward for each micro batch 

1380 synchronize() 

1381 

1382 total_loss = 0.0 

1383 total_loss_dict = defaultdict(int) 

1384 

1385 # token num for fixed_ce_loss in postforward 

1386 self.begin_loss_step() 

1387 num_micro_steps = len(micro_batches) 

1388 if getattr(self.model, "_hp_pipeline_partition", None) is not None: 

1389 batches = ((batch, {name: batch[name] for name in ("labels", "shift_labels", "loss_mask") 

1390 if name in batch}) for batch in micro_batches) 

1391 total_loss, total_loss_dict = self.pipeline_forward_backward(batches, num_micro_steps) 

1392 else: 

1393 # forward and backward pass with gradient_accumulationsteps 

1394 for micro_step, micro_batch in enumerate(micro_batches): 

1395 self.model_reshard(micro_step, num_micro_steps) 

1396 self._configure_fsdp_gradient_sync(micro_step, num_micro_steps) 

1397 self.begin_fsdp_runtime_diagnostics(micro_step) 

1398 loss: torch.Tensor 

1399 loss_dict: Dict[str, torch.Tensor] 

1400 # token num for fixed_ce_loss in postforward 

1401 self.current_token_counts = count_loss_token(micro_batch) 

1402 loss, loss_dict = self.forward_backward_step(micro_batch) 

1403 self.on_micro_step_end(loss_dict) 

1404 

1405 total_loss += loss.item() 

1406 for k, v in loss_dict.items(): 

1407 total_loss_dict[k] += v.item() 

1408 

1409 total_loss, grad_norm = self.prepare_optimizer_step(total_loss, total_loss_dict) 

1410 self.step_optimizers_and_schedulers() 

1411 

1412 grad_norm_value = grad_norm.item() if isinstance(grad_norm, torch.Tensor) else float(grad_norm) 

1413 self._end_model_integration_step({"loss": total_loss, "grad_norm": grad_norm_value}) 

1414 self.on_step_end(loss=total_loss, loss_dict=total_loss_dict, grad_norm=grad_norm_value) 

1415 return { 

1416 "loss": total_loss, 

1417 "grad_norm": grad_norm_value, 

1418 } 

1419 

1420 def abort_profilers(self) -> None: 

1421 """Release process-local profiling resources while preserving a training error.""" 

1422 try: 

1423 memory_profiler.abort() 

1424 # Cleanup must also preserve the training error if interrupted. 

1425 except BaseException: # pylint: disable=broad-exception-caught 

1426 logger.exception("Failed to stop memory profiling while aborting training.") 

1427 profiler_callback = getattr(self, "profiler_callback", None) 

1428 if profiler_callback is not None: 

1429 try: 

1430 profiler_callback.close() 

1431 # Cleanup must also preserve the training error if interrupted. 

1432 except BaseException: # pylint: disable=broad-exception-caught 

1433 logger.exception("Failed to stop performance profiling while aborting training.") 

1434 

1435 def destroy_distributed(self) -> None: 

1436 """Synchronize all ranks and tear down the distributed process group.""" 

1437 graph_compiler = getattr(self, "graph_compiler", None) 

1438 if graph_compiler is not None: 

1439 graph_compiler.close() 

1440 if not dist.is_available() or not dist.is_initialized(): 

1441 return 

1442 

1443 empty_cache() 

1444 dist.barrier() 

1445 

1446 synchronize() 

1447 destroy_process_group() 

1448 

1449 @recovery_epoch_initialized 

1450 def _initialize_train_epoch(self, epoch: int, start_epoch: int) -> None: 

1451 """Prepare the native epoch iterator and dispatch epoch callbacks.""" 

1452 if epoch != start_epoch: 

1453 self.train_dataloader.set_epoch(epoch) 

1454 self.data_iterator = HyperIter( 

1455 self.train_dataloader, 

1456 use_background_prefetcher=self.config.dataloader.use_background_prefetcher, 

1457 ) 

1458 self.state.epoch = epoch 

1459 self.on_epoch_begin() 

1460 

1461 @recovery_train_loop 

1462 def train(self) -> None: 

1463 """Run the configured training loop.""" 

1464 offload_context = getattr(self, "hyper_offload_context", None) 

1465 try: 

1466 config: TrainerConfig = self.config 

1467 self.on_train_begin() 

1468 self.data_iterator = HyperIter( 

1469 self.train_dataloader, 

1470 use_background_prefetcher=config.dataloader.use_background_prefetcher, 

1471 ) 

1472 logger.info( 

1473 "Rank%s Start training. Global step: %s. Train iters: %s. Start epoch: %s. Train epochs: %s.", 

1474 self.local_rank, self.state.global_step, self.train_iters, self.state.epoch, self.train_epochs, 

1475 ) 

1476 

1477 try: 

1478 start_epoch = self.state.epoch 

1479 for epoch in range(start_epoch, self.train_epochs): 

1480 self._initialize_train_epoch(epoch, start_epoch) 

1481 

1482 start_step = self.state.global_step - epoch * self.train_steps 

1483 train_steps = min(self.train_steps, self.train_iters - epoch * self.train_steps) 

1484 for _ in range(start_step, train_steps): 

1485 try: 

1486 self.train_step(self.data_iterator) 

1487 except StopIteration: 

1488 logger.info( 

1489 "epoch:%s Dataloader finished with drop_last %s", 

1490 epoch, 

1491 config.dataloader.drop_last, 

1492 ) 

1493 break 

1494 

1495 self.on_epoch_end() 

1496 self.state.epoch = epoch + 1 

1497 

1498 print_device_mem_info(f"VRAM usage after epoch {epoch + 1}") 

1499 

1500 if config.dataloader.use_background_prefetcher: 

1501 self.data_iterator.stop() 

1502 

1503 memory_profiler.stop() 

1504 self.on_train_end() 

1505 finally: 

1506 if config.dataloader.use_background_prefetcher: 

1507 self.data_iterator.stop() 

1508 

1509 except BaseException: 

1510 try: 

1511 memory_profiler.stop() 

1512 # Snapshot export must preserve the training error even if interrupted. 

1513 except BaseException: # pylint: disable=broad-exception-caught 

1514 logger.exception("Failed to save memory snapshot after training error.") 

1515 finally: 

1516 self.abort_profilers() 

1517 if isinstance(offload_context, OffloadSession): 

1518 try: 

1519 offload_context.close() 

1520 # Preserve the causal training error if session cleanup fails. 

1521 except BaseException: # pylint: disable=broad-exception-caught 

1522 logger.exception("Failed to close the HyperOffload session after training error.") 

1523 raise 

1524 

1525 if isinstance(offload_context, OffloadSession): 

1526 offload_context.close() 

1527 synchronize() 

1528 

1529 self.destroy_distributed()