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

212 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"""Text Trainer assembled from the shared BaseTrainer stages.""" 

16 

17__all__ = ["TextTrainer"] 

18 

19from collections import defaultdict 

20from itertools import count 

21from typing import Any, Dict, Iterator, Optional 

22 

23import torch 

24 

25from hyper_parallel.data.batching import calculate_num_micro_batches 

26from hyper_parallel.data.text import build_chat_template 

27from hyper_parallel.trainer.runtime.loss_aggregation import count_loss_token 

28from hyper_parallel.trainer.runtime.logging import create_logger 

29from hyper_parallel.trainer.runtime.memory import print_device_mem_info 

30from hyper_parallel.trainer.runtime.memory_profiler import memory_profiler 

31from hyper_parallel.trainer.runtime.device import synchronize 

32from hyper_parallel.trainer.runtime.worker_recovery import ( 

33 recovery_constructor, 

34 recovery_epoch_initialized, 

35 recovery_train_loop, 

36 recovery_train_step, 

37) 

38from hyper_parallel.trainer.base import BaseTrainer 

39from hyper_parallel.data.distributed import DistributedDataLoader 

40from hyper_parallel.trainer.config import TrainerConfig 

41 

42logger = create_logger(__name__) 

43 

44 

45class TextTrainer: 

46 """Compose the text training runtime from explicit BaseTrainer stages.""" 

47 

48 base: BaseTrainer 

49 

50 @recovery_constructor 

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

52 """Build the text Trainer in the same explicit order as VeOmni.""" 

53 self.base = BaseTrainer.__new__(BaseTrainer) 

54 self.base.config = config 

55 

56 self.base._setup() 

57 memory_profiler.reset( 

58 self.base.config.memory, 

59 global_rank=self.base.global_rank, 

60 tp_rank=self.base.mesh.tp_rank, 

61 dp_rank=self.base.mesh.dp_rank, 

62 ) 

63 self.base._build_model() 

64 self.base._build_loss() 

65 

66 # datasets 

67 self._build_model_assets() 

68 self._build_data_transform() 

69 self.base._build_dataset() 

70 

71 # dataloader 

72 self._build_collate_fn() 

73 self.base._build_dataloader() 

74 

75 # get_batch 

76 self._build_get_batch() 

77 self.base.attach_model_integration_data_pipeline() 

78 self.base._compute_train_iters() 

79 

80 self.base._build_optimizer() 

81 self.base.model_integration.attach_optimizer(self.base.optimizer) 

82 self.base._build_lr_scheduler() 

83 self.base._build_training_context() 

84 self.base._build_graph_compiler() 

85 self.base._init_callbacks() 

86 

87 def _build_model_assets(self) -> None: 

88 """Build tokenizer-backed assets for text training.""" 

89 config: TrainerConfig = self.base.config 

90 

91 if config.dataset is None: 

92 raise ValueError("dataset must define a build target") 

93 

94 assets_config = config.dataset.model_assets 

95 tokenizer_target = assets_config.tokenizer 

96 

97 if tokenizer_target is None: 

98 self.base.tokenizer = None 

99 elif getattr(tokenizer_target, "pretrained_model_name_or_path", None): 

100 self.base.tokenizer = tokenizer_target.build() 

101 else: 

102 self.base.tokenizer = tokenizer_target.build( 

103 pretrained_model_name_or_path=config.model.pretrained_model_name_or_path, 

104 ) 

105 

106 self.base.chat_template = None 

107 

108 if assets_config.chat_template is not None: 

109 if self.base.tokenizer is None: 

110 raise ValueError("dataset.model_assets.tokenizer is required for conversation data") 

111 

112 if isinstance(assets_config.chat_template, str): 

113 self.base.chat_template = build_chat_template( 

114 assets_config.chat_template, 

115 self.base.tokenizer, 

116 chat_template_kwargs=assets_config.chat_template_kwargs, 

117 log_first_rendered_template=config.debug.log_first_rendered_template, 

118 ) 

119 else: 

120 if assets_config.chat_template_kwargs or config.debug.log_first_rendered_template: 

121 raise ValueError( 

122 "dataset.model_assets chat-template options require chat_template='tokenizer'" 

123 ) 

124 

125 self.base.chat_template = assets_config.chat_template.build( 

126 tokenizer=self.base.tokenizer, 

127 ) 

128 

129 self.base.model_assets = [self.base.model_config] 

130 

131 if self.base.tokenizer is not None: 

132 self.base.model_assets.append(self.base.tokenizer) 

133 

134 if self.base.chat_template is not None: 

135 self.base.model_assets.append(self.base.chat_template) 

136 

137 def _build_data_transform(self) -> None: 

138 """Build the configured text sample transform.""" 

139 dataset_config = self.base.config.dataset 

140 

141 if dataset_config is None: 

142 raise ValueError("dataset must define a build target") 

143 

144 if dataset_config.data_transform is None: 

145 self.base.data_transform = None 

146 return 

147 

148 self.base.data_transform = dataset_config.data_transform.build( 

149 tokenizer=self.base.tokenizer, 

150 chat_template=self.base.chat_template, 

151 max_seq_len=dataset_config.data_config["max_seq_len"], 

152 ) 

153 

154 def _build_collate_fn(self) -> None: 

155 """Build the text collator and gradient-accumulation batch count.""" 

156 dataloader_config = self.base.config.dataloader 

157 

158 if dataloader_config is None or dataloader_config.collate_fn is None: 

159 raise ValueError("dataloader.collate_fn must define a build target") 

160 

161 training_config = self.base.config.training 

162 self.base.num_micro_batches = calculate_num_micro_batches( 

163 global_batch_size=training_config.global_batch_size, 

164 micro_batch_size=training_config.micro_batch_size, 

165 dp_world_size=self.base.mesh.dp_size, 

166 ) 

167 max_seq_len = self.base.config.dataset.data_config["max_seq_len"] 

168 

169 self.base.collate_fn = dataloader_config.collate_fn.build( 

170 mesh_context=self.base.mesh, 

171 max_seq_len=max_seq_len, 

172 ) 

173 

174 def _build_get_batch(self) -> None: 

175 """Build the DataLoader-to-LLM batch runtime.""" 

176 config = self.base.config 

177 

178 if config.dataloader.get_batch is None: 

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

180 

181 get_batch = config.dataloader.get_batch.build( 

182 mesh_context=self.base.mesh, 

183 dataloader_context=self.base.dataloader_context, 

184 device=self.base.device, 

185 tokenizer=self.base.tokenizer, 

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

187 pp_shared_data=bool(getattr(config.dataloader, "pp_shared_data", False)), 

188 ) 

189 self.base.get_batch = get_batch 

190 

191 @property 

192 def distributed_setup(self) -> Any: 

193 """Return the shared distributed setup.""" 

194 return self.base.distributed_setup 

195 

196 @property 

197 def mesh(self) -> Any: 

198 """Return the shared mesh context.""" 

199 return self.base.mesh 

200 

201 @property 

202 def dp_cp_mesh(self) -> Any: 

203 """Return the shared data/context-parallel mesh.""" 

204 return self.base.dp_cp_mesh 

205 

206 def on_train_begin(self) -> None: 

207 """Dispatch the training-begin lifecycle hook.""" 

208 self.base.on_train_begin() 

209 

210 def on_train_end(self) -> None: 

211 """Dispatch the training-end lifecycle hook.""" 

212 self.base.on_train_end() 

213 

214 def on_epoch_begin(self) -> None: 

215 """Dispatch the epoch-begin lifecycle hook.""" 

216 self.base.on_epoch_begin() 

217 

218 def on_epoch_end(self) -> None: 

219 """Dispatch the epoch-end lifecycle hook.""" 

220 self.base.on_epoch_end() 

221 

222 def on_step_begin(self) -> None: 

223 """Dispatch the step-begin lifecycle hook.""" 

224 self.base.on_step_begin() 

225 

226 def on_micro_step_begin(self, micro_batch: dict[str, Any]) -> None: 

227 """Dispatch the micro-step-begin lifecycle hook. 

228 

229 Args: 

230 micro_batch: Prepared inputs and lightweight metric metadata. 

231 """ 

232 self.base.on_micro_step_begin(micro_batch) 

233 

234 def on_micro_step_end(self, loss_dict: dict[str, torch.Tensor]) -> None: 

235 """Dispatch the micro-step-end lifecycle hook. 

236 

237 Args: 

238 loss_dict: Named losses and metrics from the completed forward-backward step. 

239 """ 

240 self.base.on_micro_step_end(loss_dict) 

241 

242 def on_step_end( 

243 self, 

244 loss: Any = None, 

245 loss_dict: Any = None, 

246 grad_norm: Any = None, 

247 ) -> None: 

248 """Dispatch the step-end lifecycle hook. 

249 

250 Args: 

251 loss: Aggregated loss for the optimizer step. 

252 loss_dict: Named loss values for the optimizer step. 

253 grad_norm: Gradient norm measured before the optimizer update. 

254 """ 

255 self.base.on_step_end( 

256 loss=loss, 

257 loss_dict=loss_dict, 

258 grad_norm=grad_norm, 

259 ) 

260 

261 def forward_backward_step( 

262 self, 

263 data_iterator: Any, 

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

265 """Fetch and execute one forward-backward micro-step. 

266 

267 Args: 

268 data_iterator: Iterator providing one raw FB batch per call. 

269 

270 Returns: 

271 Loss tensor and named loss tensors for this FB step. 

272 """ 

273 model_inputs, loss_inputs = self.base.get_batch(data_iterator) 

274 self.base.current_token_counts = count_loss_token(loss_inputs) 

275 metric_inputs = { 

276 **model_inputs, 

277 **loss_inputs, 

278 "token_count": self.base.current_token_counts["foundation_tokens"], 

279 } 

280 self.on_micro_step_begin(metric_inputs) 

281 del metric_inputs 

282 loss, loss_dict = self.base.forward_backward_step(model_inputs, loss_inputs) 

283 self.on_micro_step_end(loss_dict) 

284 

285 return loss, loss_dict 

286 

287 @recovery_train_step 

288 def train_step(self, data_iterator: Any) -> Dict[str, float]: 

289 """Execute one text training step. 

290 

291 Args: 

292 data_iterator: Iterator providing the step's micro-batches. 

293 

294 Returns: 

295 Aggregated loss and gradient norm for the completed step. 

296 """ 

297 memory_profiler.step() 

298 num_micro_steps = self.base.num_micro_batches 

299 self.base.begin_loss_step() 

300 

301 self.on_step_begin() 

302 self.base.model_integration.begin_step(self.base.state.global_step + 1) 

303 synchronize() 

304 

305 total_loss = 0.0 

306 total_loss_dict = defaultdict(int) 

307 

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

309 batches = (self.base.get_batch(data_iterator) for _ in range(num_micro_steps)) 

310 total_loss, total_loss_dict = self.base.pipeline_forward_backward(batches, num_micro_steps) 

311 else: 

312 for micro_step in range(num_micro_steps): 

313 self.base.model_reshard(micro_step, num_micro_steps) 

314 self.base.configure_fsdp_gradient_sync( 

315 micro_step, 

316 num_micro_steps, 

317 ) 

318 self.base.begin_fsdp_runtime_diagnostics(micro_step) 

319 loss, loss_dict = self.forward_backward_step( 

320 data_iterator, 

321 ) 

322 

323 total_loss += loss.item() 

324 for loss_name, loss_value in loss_dict.items(): 

325 total_loss_dict[loss_name] += loss_value.item() 

326 

327 total_loss, grad_norm = self.base.prepare_optimizer_step(total_loss, total_loss_dict) 

328 self.base.step_optimizers_and_schedulers() 

329 

330 # Checkpoint and logging callbacks observe the number of completed 

331 # optimizer updates. 

332 self.base.state.global_step += 1 

333 grad_norm_value = float(grad_norm) 

334 self.base._end_model_integration_step( # pylint: disable=protected-access 

335 {"loss": total_loss, "grad_norm": grad_norm_value} 

336 ) 

337 self.on_step_end( 

338 loss=total_loss, 

339 loss_dict=total_loss_dict, 

340 grad_norm=grad_norm_value, 

341 ) 

342 

343 return { 

344 "loss": total_loss, 

345 "grad_norm": grad_norm_value, 

346 } 

347 

348 @recovery_epoch_initialized 

349 def _create_data_iterator(self) -> Optional[Iterator[Any]]: 

350 """Construct the native iterator before consuming this epoch's data.""" 

351 loader = self.base.train_dataloader 

352 return iter(loader) if loader is not None else None 

353 

354 def _train_epoch(self, epoch: int, balanced_loader: bool) -> bool: 

355 """Consume complete optimizer steps and report whether the source epoch ended.""" 

356 data_iterator = self._create_data_iterator() 

357 start_step = self.base.state.global_step - epoch * self.base.train_steps 

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

359 

360 if balanced_loader: 

361 start_step = 0 

362 train_steps = self.base.train_iters - self.base.state.global_step 

363 

364 for _ in range(start_step, train_steps): 

365 try: 

366 self.train_step(data_iterator) 

367 except StopIteration: 

368 if balanced_loader: 

369 optimizers = self.base.optimizer 

370 for optimizer in optimizers if isinstance(optimizers, list) else [optimizers]: 

371 optimizer.zero_grad() 

372 

373 logger.info( 

374 "epoch:%s Dataloader finished with drop_last %s", epoch, self.base.config.dataloader.drop_last 

375 ) 

376 return True 

377 

378 return False 

379 

380 @recovery_train_loop 

381 def train(self) -> None: 

382 """Run the configured global optimizer steps by Dataset epoch.""" 

383 try: 

384 self.on_train_begin() 

385 logger.info( 

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

387 self.base.local_rank, 

388 self.base.state.global_step, 

389 self.base.train_iters, 

390 self.base.state.epoch, 

391 self.base.train_epochs, 

392 ) 

393 

394 train_dataloader = self.base.train_dataloader 

395 balanced_loader = isinstance(train_dataloader, DistributedDataLoader) 

396 start_epoch = self.base.state.epoch 

397 epochs = count(start_epoch) if balanced_loader else range(start_epoch, self.base.train_epochs) 

398 for epoch in epochs: 

399 if self.base.state.global_step >= self.base.train_iters: 

400 break 

401 

402 # The first collective iterator may hold a restored checkpoint cursor. 

403 if train_dataloader is not None and (not balanced_loader or epoch != start_epoch): 

404 train_dataloader.set_epoch(epoch) 

405 

406 self.base.state.epoch = epoch 

407 self.on_epoch_begin() 

408 epoch_start_step = self.base.state.global_step 

409 epoch_exhausted = self._train_epoch(epoch, balanced_loader) 

410 

411 if balanced_loader and epoch != start_epoch and self.base.state.global_step == epoch_start_step: 

412 raise ValueError("Offline source epoch cannot provide one complete optimizer step") 

413 

414 self.on_epoch_end() 

415 self.base.state.epoch = epoch + 1 if not balanced_loader or epoch_exhausted else epoch 

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

417 

418 if self.base.state.global_step >= self.base.train_iters: 

419 break 

420 

421 memory_profiler.stop() 

422 self.on_train_end() 

423 

424 except BaseException: 

425 try: 

426 memory_profiler.stop() 

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

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

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

430 finally: 

431 self.base.abort_profilers() 

432 raise 

433 

434 if balanced_loader: 

435 try: 

436 train_dataloader.wait_for_prefetch() 

437 finally: 

438 train_dataloader.close() 

439 

440 synchronize() 

441 self.base.destroy_distributed()