Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / tools / dryrun / runner.py: 77%

287 statements  

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

1# Copyright 2026 Huawei Technologies Co., Ltd 

2# 

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

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

5# You may obtain a copy of the License at 

6# 

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

8# 

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

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

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

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

13# limitations under the License. 

14# ============================================================================ 

15"""Standalone FakeTensor dry-run orchestrator for the HyperModels LLM Trainer.""" 

16 

17import logging 

18import re 

19from pathlib import Path 

20from typing import Any, Iterator, Optional, Tuple, Union 

21 

22import torch 

23from torch import nn 

24from torch._subclasses.fake_tensor import FakeTensorMode, unset_fake_temporarily 

25 

26from hyper_parallel.distributed.mesh import DistributedSetup, MeshContext 

27from hyper_parallel.tools.dryrun.config import DryRunConfig, resolve_dryrun_config 

28from hyper_parallel.tools.dryrun.data_adapter import DryRunDataAdapter, collect_tensor_leaves 

29from hyper_parallel.tools.dryrun.memory_tracker import LogicalMemoryTracker, write_memory_snapshot 

30from hyper_parallel.tools.dryrun.ops import register_builtin_fake_ops, unsupported_operator_hint 

31from hyper_parallel.tools.dryrun.patches import ( 

32 FakeHostScalarShim, 

33 fsdp_device_context, 

34 install_dryrun_patches, 

35 install_tp_cross_entropy_replay, 

36 model_build_context, 

37 token_count_scalar_context, 

38) 

39from hyper_parallel.tools.dryrun.runtime import ( 

40 DryRunRuntime, 

41 fake_process_group, 

42 resolve_target_device, 

43 select_simulation_device, 

44 simulation_runtime_context, 

45) 

46from hyper_parallel.trainer.base import BaseTrainer 

47from hyper_parallel.trainer.config import TrainerConfig, normalize_distributed_setup_overrides 

48from hyper_parallel.trainer.runtime import memory_profiler as memory_profiler_module 

49from hyper_parallel.trainer.runtime.random import set_seed 

50from hyper_parallel.trainer.text_trainer import TextTrainer 

51 

52logger = logging.getLogger(__name__) 

53 

54 

55class HyperModelsDryRunRunner: 

56 """Orchestrate FakeTensor model build, training-loop execution, and memory snapshots.""" 

57 

58 def __init__( 

59 self, 

60 config: TrainerConfig, 

61 runtime: Optional[DryRunRuntime] = None, 

62 ) -> None: 

63 """Store configuration and install process-local dry-run patches.""" 

64 self.config = config 

65 self._runtime = runtime 

66 self._stage = "validation" 

67 self._target_device = "cpu" 

68 self._simulation_device = "cpu" 

69 self._resolved_dtype = torch.get_default_dtype() # pylint: disable=assignment-from-no-return 

70 install_dryrun_patches() 

71 

72 @staticmethod 

73 def _check_torch_version() -> None: 

74 """Require the FakeTensor collective tracking available in PyTorch 2.7.""" 

75 match = re.match(r"^(\d+)\.(\d+)", torch.__version__) 

76 version = tuple(int(part) for part in match.groups()) if match else (0, 0) 

77 if version < (2, 7): 

78 raise RuntimeError( 

79 "HyperModelsDryRunRunner requires PyTorch >= 2.7, found " 

80 f"{torch.__version__}" 

81 ) 

82 

83 def _get_runtime(self) -> DryRunRuntime: 

84 """Return the validated ``torchrun`` worker identity.""" 

85 if self._runtime is None: 

86 self._runtime = DryRunRuntime.from_torchrun_env() 

87 return self._runtime 

88 

89 def _validate_config(self) -> DryRunConfig: 

90 """Validate dry-run settings, unsupported feature boundaries, and topology.""" 

91 self._check_torch_version() 

92 dry_run = resolve_dryrun_config(self.config.dry_run) 

93 self.config.dry_run = dry_run 

94 runtime = self._get_runtime() 

95 dry_run.validate(world_size=runtime.world_size) 

96 if self.config.training.micro_batch_size < 1: 

97 raise ValueError("training.micro_batch_size must be >= 1") 

98 self._validate_unsupported_features() 

99 self._validate_topology(runtime) 

100 return dry_run 

101 

102 def _validate_unsupported_features(self) -> None: 

103 """Reject configurations whose memory lifetimes the tracker cannot represent.""" 

104 ac_cfg = getattr(self.config, "activation_checkpoint", None) 

105 activation_checkpoint = getattr(ac_cfg, "mode", None) 

106 if activation_checkpoint not in (None, "off", "none", "full", "selective", "hybrid"): 

107 raise NotImplementedError( 

108 f"LLM Dry-run does not support activation checkpoint mode {activation_checkpoint!r}" 

109 ) 

110 if getattr( 

111 self.config.fsdp_config, 

112 "activation_checkpointing", 

113 None, 

114 ) not in (False, None, "off", "none"): 

115 raise NotImplementedError("LLM Dry-run does not support FSDP activation checkpointing") 

116 if getattr(getattr(self.config, "hyper_offload", None), "enable", False): 

117 raise NotImplementedError("LLM Dry-run does not support hyper_offload") 

118 if self.config.peft is not None: 

119 raise NotImplementedError("LLM Dry-run does not support PEFT model mutation") 

120 if self.config.compile.enabled: 

121 raise NotImplementedError("LLM Dry-run does not support torch.compile") 

122 if self.config.accelerator.pp_size != 1: 

123 raise NotImplementedError("Dry-run does not support pipeline parallelism") 

124 

125 def _validate_topology(self, runtime: DryRunRuntime) -> None: 

126 """Validate the configured parallel topology against the launched world size.""" 

127 accelerator = self.config.accelerator 

128 topology_sizes = { 

129 "tp_size": accelerator.tp_size, 

130 "cp_size": accelerator.cp_size, 

131 "ep_size": accelerator.ep_size, 

132 "pp_size": accelerator.pp_size, 

133 "dp_shard_size": self.config.fsdp_config.dp_shard_size, 

134 "edp_shard_size": self.config.fsdp_config.edp_shard_size, 

135 } 

136 invalid_sizes = { 

137 name: size 

138 for name, size in topology_sizes.items() 

139 if not isinstance(size, int) or isinstance(size, bool) or size < 1 

140 } 

141 if invalid_sizes: 

142 raise ValueError(f"Dry-run parallel sizes must be positive integers, got {invalid_sizes}") 

143 non_dp_size = accelerator.tp_size * accelerator.cp_size * accelerator.pp_size 

144 if runtime.world_size % non_dp_size: 

145 raise ValueError( 

146 f"WORLD_SIZE {runtime.world_size} is not divisible by TP*CP*PP size {non_dp_size}" 

147 ) 

148 dp_size = runtime.world_size // non_dp_size 

149 fsdp_domain_size = dp_size * max(1, accelerator.cp_size) 

150 if fsdp_domain_size % self.config.fsdp_config.dp_shard_size: 

151 raise ValueError( 

152 f"DP+CP size {fsdp_domain_size} is not divisible by " 

153 f"dp_shard_size {self.config.fsdp_config.dp_shard_size}" 

154 ) 

155 expert_domain_size = dp_size * accelerator.cp_size * accelerator.tp_size 

156 if expert_domain_size % accelerator.ep_size: 

157 raise ValueError( 

158 f"expert domain size {expert_domain_size} is not divisible by ep_size {accelerator.ep_size}" 

159 ) 

160 expert_dp_size = expert_domain_size // accelerator.ep_size 

161 if expert_dp_size % self.config.fsdp_config.edp_shard_size: 

162 raise ValueError( 

163 f"expert DP size {expert_dp_size} is not divisible by " 

164 f"edp_shard_size {self.config.fsdp_config.edp_shard_size}" 

165 ) 

166 

167 @staticmethod 

168 def _snapshot_path(dry_run: DryRunConfig, runtime: DryRunRuntime) -> Optional[str]: 

169 """Resolve the rank-local snapshot output path, or ``None`` if unconfigured.""" 

170 if dry_run.snapshot.path is None: 

171 return None 

172 return str( 

173 Path(dry_run.snapshot.path).expanduser() 

174 / f"rank_{runtime.rank}" 

175 / "memory.pickle" 

176 ) 

177 

178 @staticmethod 

179 def _prewarm_standard_meshes(mesh_context: MeshContext) -> None: 

180 """Materialize child meshes used by the non-pipeline training path.""" 

181 meshes = [mesh_context.device_mesh, mesh_context.fsdp_non_moe_mesh] 

182 for axis in ("dp", "cp", "tp"): 

183 meshes.append(mesh_context.device_mesh[axis]) 

184 active_names = tuple( 

185 axis 

186 for axis, size in (("cp", mesh_context.cp_size), ("tp", mesh_context.tp_size)) 

187 if size > 1 

188 ) 

189 if active_names: 

190 active_mesh = mesh_context.device_mesh[active_names] 

191 meshes.append(active_mesh) 

192 meshes.extend(active_mesh[axis] for axis in active_names) 

193 if mesh_context.dp_cp_mesh is not None: 

194 meshes.append(mesh_context.dp_cp_mesh) 

195 dense_selector: Union[str, Tuple[str, str]] = "fsdp_shard" 

196 if mesh_context.dp_replicate_size > 1: 

197 dense_selector = ("fsdp_replicate", "fsdp_shard") 

198 meshes.append(mesh_context.fsdp_non_moe_mesh[dense_selector]) 

199 if mesh_context.fsdp_moe_mesh is not None: 

200 meshes.extend((mesh_context.fsdp_moe_mesh, mesh_context.fsdp_moe_mesh["ep"])) 

201 expert_selector: Union[str, Tuple[str, str]] = "edp_shard" 

202 if "edp_replicate" in mesh_context.fsdp_moe_mesh.mesh_dim_names: 

203 expert_selector = ("edp_replicate", "edp_shard") 

204 meshes.append(mesh_context.fsdp_moe_mesh[expert_selector]) 

205 for mesh in meshes: 

206 for mesh_dim in range(mesh.ndim): 

207 mesh.get_group(mesh_dim) 

208 

209 def _build_distributed_setup( 

210 self, 

211 runtime: DryRunRuntime, 

212 device_type: str, 

213 ) -> DistributedSetup: 

214 """Build the standard non-pipeline mesh and sharding setup.""" 

215 accelerator = self.config.accelerator 

216 tp_size = accelerator.tp_size 

217 cp_size = accelerator.cp_size 

218 dp_size = runtime.world_size // (tp_size * cp_size) 

219 dp_shard_size = self.config.fsdp_config.dp_shard_size 

220 dp_replicate_size = dp_size * cp_size // dp_shard_size 

221 mesh_context = MeshContext( 

222 dp_size=dp_size, 

223 dp_replicate_size=dp_replicate_size, 

224 dp_shard_size=dp_shard_size, 

225 edp_shard_size=self.config.fsdp_config.edp_shard_size, 

226 tp_size=tp_size, 

227 cp_size=cp_size, 

228 pp_size=1, 

229 ep_size=accelerator.ep_size, 

230 sequence_parallel=bool(accelerator.sequence_parallel), 

231 loss_parallel=bool(accelerator.loss_parallel), 

232 ) 

233 mesh_context.build_meshs(device_type, runtime.world_size) 

234 mesh_context.dp_rank = mesh_context.device_mesh.get_local_rank("dp") 

235 mesh_context.tp_rank = mesh_context.device_mesh.get_local_rank("tp") 

236 mesh_context.cp_rank = mesh_context.device_mesh.get_local_rank("cp") 

237 mesh_context.ep_rank = ( 

238 mesh_context.fsdp_moe_mesh.get_local_rank("ep") 

239 if mesh_context.fsdp_moe_mesh is not None 

240 else 0 

241 ) 

242 mesh_context.pp_rank = 0 

243 self._prewarm_standard_meshes(mesh_context) 

244 fsdp_enabled = ( 

245 dp_shard_size > 1 

246 or dp_replicate_size > 1 

247 or self.config.fsdp_config.edp_shard_size > 1 

248 ) 

249 return DistributedSetup( 

250 mesh_context=mesh_context, 

251 strategy_config=self.config.fsdp_config if fsdp_enabled else None, 

252 plan_overrides=self.config.plan_overrides, 

253 low_precision_config=getattr(self.config.training, "low_precision", None), 

254 fp32_main_params=self.config.optimizer.fp32_main_params, 

255 ) 

256 

257 def _build_target_model(self, setup: DistributedSetup) -> nn.Module: 

258 """Build the configured model through the deferred shape-only path.""" 

259 with model_build_context(): 

260 return self.config.model.build( 

261 distributed_setup=setup, 

262 peft_config=self.config.peft, 

263 activation_checkpoint=self.config.activation_checkpoint, 

264 compile_config=self.config.compile, 

265 model_init_dtype=self.config.model_init_dtype, 

266 ) 

267 

268 def _record_model_dtype(self, model: nn.Module) -> None: 

269 """Record the effective floating dtype from the built model.""" 

270 self._resolved_dtype = next( 

271 (tensor.dtype for tensor in model.parameters() if tensor.is_floating_point()), 

272 torch.get_default_dtype(), 

273 ) 

274 

275 def _materialize_fake_model(self, model: nn.Module) -> nn.Module: 

276 """Materialize meta parameters/buffers as FakeTensors without assigning values.""" 

277 simulation_device = self._get_runtime().torch_device(self._simulation_device) 

278 fake_parameter = next( 

279 (param for param in model.parameters() if hasattr(param, "fake_mode")), 

280 None, 

281 ) 

282 if fake_parameter is None: 

283 model.to_empty(device=simulation_device) 

284 return model 

285 converter = fake_parameter.fake_mode.fake_tensor_converter.meta_converter 

286 tensor_memo = converter.tensor_memo 

287 tensor_memo.clear() 

288 converter.tensor_memo = {} 

289 try: 

290 model.to_empty(device=simulation_device) 

291 finally: 

292 converter.tensor_memo = tensor_memo 

293 return model 

294 

295 @staticmethod 

296 def _initialize_flat_buffers(model: nn.Module) -> None: 

297 """Materialize enabled zero-copy FSDP flat shards before tracking.""" 

298 visited_states = set() 

299 for module in model.modules(): 

300 scheduler = getattr(module, "hsdp_scheduler", None) 

301 state = getattr(scheduler, "hsdp_state", None) 

302 if state is None or id(state) in visited_states: 

303 continue 

304 visited_states.add(id(state)) 

305 state.lazy_init() 

306 param_group = getattr(state, "param_group", None) 

307 if param_group is not None and param_group.enable_zero_copy: 

308 param_group._init_all_gather_buckets() 

309 for bucket in param_group.all_gather_buckets: 

310 bucket.init_flat_param_buffer(param_group.device) 

311 

312 def _prepare_base( 

313 self, 

314 setup: DistributedSetup, 

315 model: nn.Module, 

316 fake_mode: FakeTensorMode, 

317 ) -> BaseTrainer: 

318 """Assemble native trainer stages around the value-free model.""" 

319 runtime = self._get_runtime() 

320 simulation_device = runtime.torch_device(self._simulation_device) 

321 base = BaseTrainer.__new__(BaseTrainer) 

322 base.config = self.config 

323 base.local_rank = runtime.local_rank 

324 base.global_rank = runtime.rank 

325 base.world_size = runtime.world_size 

326 base.device = simulation_device 

327 base.distributed_setup = setup 

328 base.mesh = setup.mesh_context 

329 base.device_mesh = base.mesh.device_mesh 

330 base.dp_cp_mesh = base.mesh.dp_cp_mesh 

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

332 self.config.training.seed = base.default_seed 

333 set_seed( 

334 self.config.training.seed, 

335 self.config.training.enable_full_determinism, 

336 ) 

337 base.model = model 

338 base._finalize_model_build() 

339 base._build_loss() 

340 

341 trainer = TextTrainer.__new__(TextTrainer) 

342 trainer.base = base 

343 base.device = torch.device("cpu") 

344 try: 

345 with unset_fake_temporarily(): 

346 trainer._build_model_assets() 

347 trainer._build_data_transform() 

348 base._build_dataset() 

349 trainer._build_collate_fn() 

350 base._build_dataloader() 

351 if getattr(base, "train_dataloader", None) is None: 

352 raise ValueError("Dry-run requires a configured training dataloader") 

353 trainer._build_get_batch() 

354 finally: 

355 base.device = simulation_device 

356 

357 adapter = DryRunDataAdapter( 

358 base.get_batch, 

359 vocab_size=int(base.model.config.vocab_size), 

360 tp_size=base.mesh.tp_size, 

361 fake_mode=fake_mode, 

362 device=simulation_device, 

363 ) 

364 base.get_batch = adapter 

365 base._dryrun_data_adapter = adapter 

366 base.attach_model_integration_data_pipeline() 

367 base._compute_train_iters() 

368 base._build_optimizer() 

369 base.model_integration.attach_optimizer(base.optimizer) 

370 if self.config.lr_scheduler is not None: 

371 base._build_lr_scheduler() 

372 else: 

373 base.lr_scheduler = None 

374 base._build_training_context() 

375 base._build_graph_compiler() 

376 base._init_callbacks() 

377 return base 

378 

379 def _execute_step(self, base: BaseTrainer) -> dict[str, Any]: 

380 """Run the unmodified TextTrainer loop under logical memory tracking.""" 

381 self._initialize_flat_buffers(base.model) 

382 tracker = LogicalMemoryTracker( 

383 self._simulation_device, 

384 self._get_runtime().local_rank, 

385 stack_depth=self.config.dry_run.snapshot.stack_depth, 

386 ) 

387 trainer = TextTrainer.__new__(TextTrainer) 

388 trainer.base = base 

389 adapter = base._dryrun_data_adapter 

390 scalar_shim = FakeHostScalarShim() 

391 adapter.scalar_shim = scalar_shim 

392 if bool(getattr(base.mesh, "loss_parallel", False)): 

393 adapter.tp_replay = install_tp_cross_entropy_replay( 

394 0, (0,) * base.mesh.tp_size, 

395 ) 

396 with ( 

397 tracker, 

398 scalar_shim, 

399 token_count_scalar_context(adapter.current_token_counts, scalar_shim), 

400 ): 

401 tracker.track(self._existing_tensors(base)) 

402 trainer.train() 

403 snapshot = tracker.snapshot() 

404 snapshot["metadata"] = self._metadata( 

405 base, 

406 num_micro_batches=base.num_micro_batches, 

407 steps=base.state.global_step, 

408 ) 

409 return snapshot 

410 

411 @staticmethod 

412 def _existing_tensors(base: BaseTrainer) -> Iterator[torch.Tensor]: 

413 """Seed pre-step model and optimizer storages into the memory tracker.""" 

414 yield from base.model.parameters() 

415 yield from base.model.buffers() 

416 optimizers = getattr(base.optimizer, "chained_optimizers", None) 

417 if optimizers is None: 

418 optimizers = base.optimizer if isinstance(base.optimizer, list) else [base.optimizer] 

419 for optimizer in optimizers: 

420 for group in optimizer.param_groups: 

421 yield from group["params"] 

422 yield from collect_tensor_leaves(optimizer.state) 

423 

424 def _metadata( 

425 self, 

426 base: BaseTrainer, 

427 num_micro_batches: Optional[int] = None, 

428 steps: Optional[int] = None, 

429 ) -> dict[str, Any]: 

430 """Build reproducibility metadata embedded in the memory snapshot.""" 

431 runtime = self._get_runtime() 

432 adapter = getattr(base, "_dryrun_data_adapter", None) 

433 metadata = { 

434 "model": type(base.model).__name__, 

435 "torch_version": str(torch.__version__), 

436 "rank": runtime.rank, 

437 "world_size": runtime.world_size, 

438 "local_rank": runtime.local_rank, 

439 "target_device": self._target_device, 

440 "simulation_device": self._simulation_device, 

441 "initialization_device": "meta", 

442 "weights_loaded": False, 

443 "model_dtype": str(self._resolved_dtype), 

444 "batch_shapes": adapter.last_batch_shapes if adapter is not None else {}, 

445 "token_counts": dict(adapter.last_token_counts) if adapter is not None else {}, 

446 "batches_consumed": adapter.batch_count if adapter is not None else 0, 

447 "parallel": { 

448 "dp": base.mesh.dp_size, 

449 "dp_replicate": base.mesh.dp_replicate_size, 

450 "dp_shard": base.mesh.dp_shard_size, 

451 "tp": base.mesh.tp_size, 

452 "cp": base.mesh.cp_size, 

453 "ep": base.mesh.ep_size, 

454 "pp": base.mesh.pp_size, 

455 }, 

456 "reshard_after_forward": self.config.fsdp_config.reshard_after_forward, 

457 "comm_fusion": self.config.fsdp_config.comm_fusion, 

458 } 

459 if num_micro_batches is not None: 

460 metadata["num_micro_batches"] = num_micro_batches 

461 if steps is not None: 

462 metadata["steps"] = steps 

463 return metadata 

464 

465 def _run_simulation( 

466 self, 

467 runtime: DryRunRuntime, 

468 fake_mode: FakeTensorMode, 

469 snapshot_path: Optional[str], 

470 ) -> dict[str, Any]: 

471 """Execute the native training loop over FakeTensors and persist its snapshot.""" 

472 simulation_device = runtime.torch_device(self._simulation_device) 

473 try: 

474 self._stage = "distributed_setup" 

475 with fake_process_group(runtime): 

476 setup = self._build_distributed_setup(runtime, self._simulation_device) 

477 normalize_distributed_setup_overrides(setup, self.config) 

478 

479 self._stage = "model_build" 

480 with fake_mode: 

481 with fsdp_device_context(simulation_device): 

482 model = self._build_target_model(setup) 

483 self._record_model_dtype(model) 

484 self._stage = "materialize" 

485 model = self._materialize_fake_model(model) 

486 base = self._prepare_base(setup, model, fake_mode) 

487 self._stage = "fake_step" 

488 snapshot = self._execute_step(base) 

489 

490 if snapshot_path is not None: 

491 self._stage = "snapshot_generation" 

492 write_memory_snapshot(snapshot, snapshot_path) 

493 logger.info("HyperModels Dry-run memory snapshot: %s", snapshot_path) 

494 return snapshot 

495 except Exception as error: 

496 plugin_hint = unsupported_operator_hint(error) 

497 if plugin_hint is not None: 

498 raise RuntimeError( 

499 f"HyperModels Dry-run failed during {self._stage}: {plugin_hint}" 

500 ) from error 

501 raise RuntimeError( 

502 f"HyperModels Dry-run failed during {self._stage}: {error}" 

503 ) from error 

504 

505 def run(self) -> dict[str, Any]: 

506 """Run the configured training steps, write the rank-local snapshot, and return it.""" 

507 dry_run = self._validate_config() 

508 runtime = self._get_runtime() 

509 memory_profiler_module.memory_profiler.reset( 

510 None, global_rank=runtime.rank, tp_rank=0, dp_rank=0, 

511 ) 

512 register_builtin_fake_ops() 

513 snapshot_path = self._snapshot_path(dry_run, runtime) 

514 self._target_device = resolve_target_device(dry_run.target_device) 

515 self._simulation_device = select_simulation_device(self._target_device) 

516 fake_mode = FakeTensorMode(allow_non_fake_inputs=True) 

517 with simulation_runtime_context(self._simulation_device): 

518 return self._run_simulation(runtime, fake_mode, snapshot_path) 

519 

520 

521__all__ = ["HyperModelsDryRunRunner"]