Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / checkpoint / dcp_checkpointer.py: 85%

296 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"""Distributed-checkpoint (DCP) backend for :class:`CheckpointerBase`.""" 

17 

18__all__ = [ 

19 "STEP_PREFIX", 

20 "DistributedCheckpointer", 

21 "initialize_optimizer_state", 

22] 

23 

24import gc 

25import logging 

26import os 

27from functools import partial 

28from typing import Any, Dict, List, Optional 

29 

30import torch 

31import torch.distributed as dist 

32 

33from hyper_parallel import SkipDTensorDispatch 

34from hyper_parallel.components.optim.mixed_precision_optimizer import ( 

35 FP32_MAIN_PARAM_STATE_KEY, 

36 MIXED_PRECISION_OPTIMIZER_STATE_KEY, 

37 MixedPrecisionOptimizer, 

38) 

39from hyper_parallel.models.build_options import ( 

40 IS_CUDA_AVAILABLE, 

41 IS_NPU_AVAILABLE, 

42 get_torch_device, 

43) 

44from hyper_parallel.components.checkpoint.base import CheckpointerBase 

45from hyper_parallel.core.distributed_checkpoint import ( 

46 StandardLoadPlanner, 

47 async_save as dcp_async_save, 

48 load as dcp_load, 

49 save as dcp_save, 

50) 

51from hyper_parallel.core.distributed_checkpoint.utils import flatten_state_dict 

52from hyper_parallel.core.optimizer.adamw import AdamW as HyperAdamW 

53from hyper_parallel.core.optimizer.muon import Muon as HyperMuon 

54from hyper_parallel.core.optimizer.optimizer import ChainedOptimizer 

55 

56 

57logger = logging.getLogger(__name__) 

58 

59 

60def _empty_cache() -> None: 

61 """Collect host and device memory around checkpoint I/O.""" 

62 gc.collect() 

63 if IS_CUDA_AVAILABLE or IS_NPU_AVAILABLE: 

64 get_torch_device().empty_cache() 

65 

66# Layout of a checkpoint root: 

67# 

68# checkpoints/ 

69# ├── latest_checkpoint_iteration.txt # step number of the newest checkpoint 

70# └── global_step_42/ 

71# ├── .metadata # DCP global metadata, written last 

72# ├── __0_0.safetensors, ... # DCP shard payloads 

73# └── extra_state/ 

74# └── extra_state_rank_{R}.pt # per-rank training state 

75# 

76# ``.metadata`` doubles as the completeness signal: ``FileSystemWriter``'s 

77# ``finalize_checkpoint`` only writes it after every rank's shard writes have 

78# been collected, so a directory carrying it holds a fully persisted checkpoint 

79# and one missing it was interrupted mid-save. 

80STEP_PREFIX = "global_step_" 

81LATEST_CHECKPOINT_FILE = "latest_checkpoint_iteration.txt" 

82_EXTRA_STATE_DIR = "extra_state" 

83_EXTRA_STATE_FILE = "extra_state_rank_{rank}.pt" 

84_DCP_METADATA_FILE = ".metadata" 

85 

86# ``extra_state`` must carry this key; the checkpointer stamps a sentinel over 

87# it in the skeleton handed to an embedded-bundle load, so a load that read 

88# nothing back is distinguishable from a genuine restore. A real checkpoint is 

89# never written at a step this low. 

90_STEP_KEY = "global_step" 

91_UNRESTORED_STEP = -1 

92 

93 

94def _get_rank() -> int: 

95 """Return this process' global rank, or 0 outside a process group.""" 

96 if dist.is_available() and dist.is_initialized(): 

97 return dist.get_rank() 

98 return 0 

99 

100 

101def _barrier() -> None: 

102 """Synchronize all ranks, tolerating single-process (non-distributed) runs.""" 

103 if dist.is_available() and dist.is_initialized(): 

104 dist.barrier() 

105 

106 

107def _prepare_main_param_state_for_dcp_load( 

108 state_dict: Dict[str, Any], 

109 available_keys: set[str], 

110) -> None: 

111 """Select the ordinary or fp32-main optimizer checkpoint branch.""" 

112 flattened_state, _ = flatten_state_dict(state_dict) 

113 optimizer_state = state_dict.get("optimizer") 

114 optimizer_state_is_list = isinstance(optimizer_state, list) 

115 optimizer_states = ( 

116 optimizer_state 

117 if optimizer_state_is_list 

118 else [optimizer_state] 

119 ) 

120 for optimizer_index, optimizer_state in enumerate(optimizer_states): 

121 if not isinstance(optimizer_state, dict): 

122 continue 

123 if MIXED_PRECISION_OPTIMIZER_STATE_KEY not in optimizer_state: 

124 continue 

125 

126 state_prefix = ( 

127 f"optimizer.{optimizer_index}" 

128 if optimizer_state_is_list 

129 else "optimizer" 

130 ) 

131 main_param_prefix = ( 

132 f"{state_prefix}.{MIXED_PRECISION_OPTIMIZER_STATE_KEY}." 

133 f"{FP32_MAIN_PARAM_STATE_KEY}." 

134 ) 

135 expected_keys = { 

136 key for key in flattened_state if key.startswith(main_param_prefix) 

137 } 

138 if not expected_keys: 

139 continue 

140 

141 checkpoint_keys = { 

142 key for key in available_keys if key.startswith(main_param_prefix) 

143 } 

144 if not checkpoint_keys: 

145 optimizer_state.pop(MIXED_PRECISION_OPTIMIZER_STATE_KEY) 

146 continue 

147 

148 missing_keys = sorted(expected_keys - checkpoint_keys) 

149 if missing_keys: 

150 preview = ", ".join(missing_keys[:10]) 

151 raise RuntimeError( 

152 "Mixed-precision optimizer checkpoint is incomplete; missing " 

153 f"{len(missing_keys)} fp32 main parameter(s): {preview}" 

154 ) 

155 

156 

157def _prune_missing_extra_state(state: Dict[str, Any], available: set[str], prefix: str = "extra_state") -> None: 

158 """Keep fresh restore templates from masquerading as absent saved progress. 

159 

160 Args: 

161 state: Mutable loading template whose missing fields must be removed. 

162 available: Persisted extra-state leaf names. 

163 prefix: Flattened name of the current subtree. 

164 """ 

165 for key in list(state): 

166 name = f"{prefix}.{key}" 

167 if not any(entry == name or entry.startswith(name + ".") for entry in available): 

168 del state[key] 

169 elif isinstance(state[key], dict): 

170 _prune_missing_extra_state(state[key], available, name) 

171 

172 

173class _ModelStrictLoadPlanner(StandardLoadPlanner): 

174 """Allow partial optimizer state while still requiring a complete model. 

175 

176 A parameter that never received a gradient --- a frozen weight, an MoE expert 

177 no batch routed to, or simply a checkpoint written before the first 

178 ``step()`` --- has no optimizer state to save. Meanwhile the load side primes 

179 the optimizer (see :func:`initialize_optimizer_state`) so DCP has entries to 

180 fill, which means it legitimately asks for keys the checkpoint does not 

181 carry. Under the planner's default strict mode that is a hard error, so 

182 ``allow_partial_load`` lets those entries keep the zero-initialised values 

183 the optimizer would have created on its next step anyway. 

184 

185 ``allow_partial_load`` is global to the planner and cannot be scoped to the 

186 optimizer subtree, so model completeness is re-checked here: a truncated 

187 model checkpoint must still fail loudly instead of resuming half-loaded. 

188 """ 

189 

190 def __init__(self, strict_model: bool = True) -> None: 

191 """Load partially, optionally demanding every requested model key.""" 

192 super().__init__(allow_partial_load=True) 

193 self.strict_model = strict_model 

194 

195 def configure_planner( 

196 self, 

197 state_dict: Dict[str, Any], 

198 metadata: Any, 

199 **kwargs: Any, 

200 ) -> None: 

201 """Normalize optional state before flattening the load skeleton. 

202 

203 Args: 

204 state_dict: Model, optimizer and optional extra-state loading template. 

205 metadata: Persisted checkpoint metadata. 

206 **kwargs: Planner configuration forwarded to the base implementation. 

207 """ 

208 _prepare_main_param_state_for_dcp_load( 

209 state_dict, 

210 set(metadata.state_dict_metadata), 

211 ) 

212 extra = state_dict.get("extra_state") 

213 if isinstance(extra, dict): 

214 extra_keys = {key for key in metadata.state_dict_metadata if key.startswith("extra_state.")} 

215 _prune_missing_extra_state(extra, extra_keys) 

216 super().configure_planner(state_dict, metadata, **kwargs) 

217 

218 def build_local_plan(self) -> Any: 

219 """Validate model coverage, then defer to the standard planner.""" 

220 if self.state_dict is None or self.metadata is None: 

221 return super().build_local_plan() 

222 

223 available = self.metadata.state_dict_metadata 

224 missing = [fqn for fqn in self.state_dict if fqn not in available] 

225 

226 missing_model = sorted(fqn for fqn in missing if fqn.startswith("model.")) 

227 if self.strict_model and missing_model: 

228 preview = ", ".join(missing_model[:10]) 

229 suffix = " ..." if len(missing_model) > 10 else "" 

230 raise RuntimeError( 

231 f"Checkpoint is missing {len(missing_model)} model key(s) required " 

232 f"for a full-model resume: {preview}{suffix}" 

233 ) 

234 

235 missing_optimizer = sorted(fqn for fqn in missing if fqn.startswith("optimizer.")) 

236 if missing_optimizer: 

237 preview = ", ".join(missing_optimizer[:3]) 

238 logger.warning( 

239 "%s optimizer entries are absent from the checkpoint and keep their " 

240 "zero-initialised values (e.g. %s). Expected for parameters that " 

241 "never received a gradient, or for a checkpoint written with " 

242 "save_optimizer=false.", 

243 len(missing_optimizer), 

244 preview, 

245 ) 

246 

247 return super().build_local_plan() 

248 

249 

250def _optimizer_parameters(optimizer: Any) -> List[torch.Tensor]: 

251 """Return trainable parameters managed by an optimizer.""" 

252 parameters = [] 

253 for group in optimizer.param_groups: 

254 for param in group["params"]: 

255 if param.requires_grad: 

256 parameters.append(param) 

257 return parameters 

258 

259 

260def _prime_optimizer_state( 

261 optimizer: Any, 

262 params: List[torch.Tensor], 

263) -> None: 

264 """Run a parameter-neutral optimizer step to materialize its state.""" 

265 for param in params: 

266 param.grad = torch.zeros_like(param) 

267 for group in optimizer.param_groups: 

268 if "lr" in group: 

269 group["lr"] = 0.0 

270 if "weight_decay" in group: 

271 group["weight_decay"] = 0.0 

272 # zeros_like must retain DTensor dispatch so newly created state keeps the parameter mesh and placements. 

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

274 optimizer.step() 

275 

276 

277def _materialize_hyper_optimizer_state( 

278 optimizer: Any, 

279 params: List[torch.Tensor], 

280) -> bool: 

281 """Create lazy Hyper AdamW/Muon state without executing an update step.""" 

282 if isinstance(optimizer, HyperMuon): 

283 state_keys = ("momentum_buffer",) 

284 elif isinstance(optimizer, HyperAdamW): 

285 state_keys = ("exp_avg", "exp_avg_sq") 

286 else: 

287 return False 

288 

289 param_ids = {id(param) for param in params} 

290 # zeros_like must retain DTensor dispatch so newly created state keeps the parameter mesh and placements. 

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

292 for group in optimizer.param_groups: 

293 group["step"] = group.get("step") or 0 

294 for param in group["params"]: 

295 if id(param) not in param_ids: 

296 continue 

297 state = optimizer.state[param] 

298 for state_key in state_keys: 

299 state.setdefault( 

300 state_key, 

301 torch.zeros_like(param, memory_format=torch.preserve_format), 

302 ) 

303 if isinstance(optimizer, HyperAdamW) and group.get("amsgrad", False): 

304 state.setdefault( 

305 "max_exp_avg_sq", 

306 torch.zeros_like(param, memory_format=torch.preserve_format), 

307 ) 

308 return True 

309 

310 

311def _restore_optimizer_hyperparams( 

312 optimizer: Any, 

313 saved_hyperparams: List[tuple[Optional[float], Optional[float]]], 

314) -> None: 

315 """Restore optimizer hyperparameters after state priming.""" 

316 for group, (lr, weight_decay) in zip(optimizer.param_groups, saved_hyperparams): 

317 if lr is not None: 

318 group["lr"] = lr 

319 if weight_decay is not None: 

320 group["weight_decay"] = weight_decay 

321 optimizer.zero_grad(set_to_none=True) 

322 

323 

324def _leaf_optimizers(optimizer: Any) -> List[Any]: 

325 """Return the concrete optimizers that own lazy tensor state.""" 

326 inner_optimizer = ( 

327 optimizer.optimizer 

328 if isinstance(optimizer, MixedPrecisionOptimizer) 

329 else optimizer 

330 ) 

331 if isinstance(inner_optimizer, ChainedOptimizer): 

332 return list(inner_optimizer.chained_optimizers) 

333 return [inner_optimizer] 

334 

335 

336def initialize_optimizer_state(optimizer: Any) -> bool: 

337 """Materialize optimizer state so a DCP load has entries to fill. 

338 

339 ``Optimizer.state`` is empty until the first ``step()``, and DCP loads 

340 strictly into the keys the caller's state_dict already contains. Restoring a 

341 freshly built optimizer therefore reads *nothing* and silently resumes with 

342 zeroed moments --- the model continues from the checkpoint while Adam starts 

343 over. Priming with zero gradients creates the ``exp_avg`` / ``exp_avg_sq`` 

344 entries the checkpoint will overwrite. 

345 

346 Hyper AdamW and Muon states are created directly. This avoids running Muon's 

347 HSDP communication and Newton-Schulz update merely to allocate zero momentum. 

348 Unknown optimizer implementations retain the parameter-neutral priming-step 

349 fallback, with ``lr`` and ``weight_decay`` forced to zero. 

350 

351 Args: 

352 optimizer: Optimizer whose state is materialized. 

353 

354 Returns: 

355 Whether the optimizer now carries per-parameter state. 

356 """ 

357 leaf_optimizers = _leaf_optimizers(optimizer) 

358 if all(leaf_optimizer.state for leaf_optimizer in leaf_optimizers): 

359 return True 

360 

361 leaf_parameters = { 

362 leaf_optimizer: _optimizer_parameters(leaf_optimizer) 

363 for leaf_optimizer in leaf_optimizers 

364 if not leaf_optimizer.state 

365 } 

366 if any(not params for params in leaf_parameters.values()): 

367 return False 

368 if any( 

369 param.grad is not None 

370 for params in leaf_parameters.values() 

371 for param in params 

372 ): 

373 logger.warning( 

374 "Optimizer parameters already carry gradients; skipping state priming " 

375 "to avoid corrupting them. Optimizer state may not be restored." 

376 ) 

377 return False 

378 

379 for leaf_optimizer, params in leaf_parameters.items(): 

380 if _materialize_hyper_optimizer_state(leaf_optimizer, params): 

381 continue 

382 saved_hyperparams = [ 

383 (group.get("lr"), group.get("weight_decay")) 

384 for group in leaf_optimizer.param_groups 

385 ] 

386 try: 

387 _prime_optimizer_state(leaf_optimizer, params) 

388 finally: 

389 _restore_optimizer_hyperparams(leaf_optimizer, saved_hyperparams) 

390 

391 return all(leaf_optimizer.state for leaf_optimizer in leaf_optimizers) 

392 

393 

394class DistributedCheckpointer(CheckpointerBase): 

395 """Persist a training payload through ``hyper_parallel``'s DCP. 

396 

397 ``extra_state`` can live in either of two layouts, chosen by 

398 ``extra_state_per_rank`` at save time: 

399 

400 * ``True`` --- one ``torch.save`` file per rank under ``extra_state/``. 

401 Always correct. 

402 * ``False`` --- embedded in the DCP payload. Fewer files, but DCP 

403 deduplicates entries sharing an FQN across ranks (see 

404 ``distributed_checkpoint/utils.py::plan_ownership_masks``), so every rank 

405 restores whichever rank's copy won. Only valid when the extra state is 

406 rank-invariant. 

407 

408 :meth:`load` auto-detects which layout a checkpoint on disk used, so the 

409 flag may differ from the run that produced it. 

410 """ 

411 

412 def __init__(self, extra_state_per_rank: bool = True) -> None: 

413 """Select the ``extra_state`` layout used by :meth:`save`.""" 

414 self.extra_state_per_rank = extra_state_per_rank 

415 self._async_save_response: Optional[Any] = None 

416 

417 # ------------------------------------------------------------------ 

418 # Layout helpers 

419 # ------------------------------------------------------------------ 

420 

421 @staticmethod 

422 def _extra_state_path(checkpoint_dir: str, rank: int) -> str: 

423 """Return this rank's extra_state file inside ``checkpoint_dir``.""" 

424 return os.path.join( 

425 checkpoint_dir, _EXTRA_STATE_DIR, _EXTRA_STATE_FILE.format(rank=rank) 

426 ) 

427 

428 @staticmethod 

429 def _is_complete(checkpoint_path: str) -> bool: 

430 """Report whether ``checkpoint_path`` holds a fully persisted checkpoint. 

431 

432 Presence of the DCP metadata file is the signal: it is written only once 

433 every rank's shards are on disk. ``use_collectives=False`` names it 

434 ``{rank}.metadata`` instead of a single shared ``.metadata``, so both 

435 spellings count. 

436 """ 

437 if not os.path.isdir(checkpoint_path): 

438 return False 

439 if os.path.isfile(os.path.join(checkpoint_path, _DCP_METADATA_FILE)): 

440 return True 

441 return any( 

442 name.endswith(_DCP_METADATA_FILE) for name in os.listdir(checkpoint_path) 

443 ) 

444 

445 @staticmethod 

446 def _latest_pointer_path(checkpoint_dir: str) -> str: 

447 """Return the path of the newest-checkpoint pointer file.""" 

448 return os.path.join(checkpoint_dir, LATEST_CHECKPOINT_FILE) 

449 

450 def _write_latest_pointer(self, checkpoint_dir: str, global_step: int) -> None: 

451 """Record which checkpoint is newest, so resume need not scan the tree. 

452 

453 Only the step number is stored: the directory name is 

454 ``STEP_PREFIX + step``, and that prefix is a module constant rather than 

455 anything configurable, so writing it down would just be a second copy of 

456 a value the reader already has. 

457 """ 

458 with open(self._latest_pointer_path(checkpoint_dir), "w", encoding="utf-8") as handle: 

459 handle.write(f"{global_step}\n") 

460 

461 def _read_latest_pointer(self, checkpoint_dir: str) -> Optional[str]: 

462 """Resolve the pointer file to a usable checkpoint directory. 

463 

464 Returns ``None`` when the file is absent, unreadable, or names a 

465 checkpoint that is missing or incomplete --- every one of which is a 

466 reason to fall back to scanning rather than to fail. 

467 """ 

468 pointer_path = self._latest_pointer_path(checkpoint_dir) 

469 if not os.path.isfile(pointer_path): 

470 return None 

471 

472 try: 

473 with open(pointer_path, encoding="utf-8") as handle: 

474 global_step = int(handle.read().strip()) 

475 except (OSError, ValueError): 

476 logger.warning( 

477 "Ignoring unreadable %s; falling back to scanning %s.", 

478 pointer_path, 

479 checkpoint_dir, 

480 ) 

481 return None 

482 

483 candidate = os.path.join(checkpoint_dir, f"{STEP_PREFIX}{global_step}") 

484 if not self._is_complete(candidate): 

485 logger.warning( 

486 "%s points at %s, which is missing or incomplete; falling back to " 

487 "scanning %s.", 

488 pointer_path, 

489 candidate, 

490 checkpoint_dir, 

491 ) 

492 return None 

493 return candidate 

494 

495 def _list_checkpoints(self, checkpoint_dir: str) -> List[tuple]: 

496 """List ``(step, path)`` for every complete checkpoint, oldest first.""" 

497 if not os.path.isdir(checkpoint_dir): 

498 return [] 

499 

500 found = [] 

501 for entry in os.listdir(checkpoint_dir): 

502 entry_path = os.path.join(checkpoint_dir, entry) 

503 if not os.path.isdir(entry_path) or not entry.startswith(STEP_PREFIX): 

504 continue 

505 try: 

506 step = int(entry[len(STEP_PREFIX):]) 

507 except ValueError: 

508 continue 

509 if self._is_complete(entry_path): 

510 found.append((step, entry_path)) 

511 

512 found.sort(key=lambda item: item[0]) 

513 return found 

514 

515 def find_latest_checkpoint(self, checkpoint_dir: str) -> Optional[str]: 

516 """Return a complete checkpoint itself or the newest one under its root. 

517 

518 The pointer file written after each save answers this in one read. It is 

519 only a cache, though --- checkpoints produced before it existed, or 

520 copied in by hand, are still found by scanning the directory. A 

521 checkpoint interrupted mid-save has no DCP metadata and is skipped by 

522 both paths, so resume never lands on a half-written one. 

523 

524 Args: 

525 checkpoint_dir: Concrete checkpoint directory or root containing saved steps. 

526 """ 

527 if self._is_complete(checkpoint_dir): 

528 return checkpoint_dir 

529 from_pointer = self._read_latest_pointer(checkpoint_dir) 

530 if from_pointer is not None: 

531 return from_pointer 

532 

533 candidates = self._list_checkpoints(checkpoint_dir) 

534 if not candidates: 

535 return None 

536 return candidates[-1][1] 

537 

538 # ------------------------------------------------------------------ 

539 # Async coordination 

540 # ------------------------------------------------------------------ 

541 

542 def maybe_wait_for_async_save(self) -> None: 

543 """Block until an in-flight async save finishes. 

544 

545 Safe to call when nothing is pending. This is the single entry point for 

546 async-save coordination --- it runs before every new save, before a 

547 restore, and at train end, so two saves never overlap and the process 

548 never exits with a half-persisted checkpoint. Publishing the checkpoint 

549 is not done here: the persist callback has already written the pointer by 

550 the time the future resolves, and waiting for this call to come around 

551 would leave the checkpoint unnamed until the next save. 

552 """ 

553 if self._async_save_response is None: 

554 return 

555 

556 rank = _get_rank() 

557 try: 

558 logger.info("[rank %s] waiting for async DCP save to finish...", rank) 

559 self._async_save_response.persist_completion.result() 

560 logger.info("[rank %s] async DCP save has been finished...", rank) 

561 except Exception: # pylint: disable=broad-except 

562 logger.exception("[rank %s] async DCP save failed", rank) 

563 raise 

564 finally: 

565 self._async_save_response = None 

566 

567 def abort_async_save(self) -> None: 

568 """Discard an in-flight checkpoint before process recovery. 

569 

570 Completed checkpoints remain published. The attempted save-step marker 

571 belongs to the callback and is retained even when persistence is dropped. 

572 """ 

573 if self._async_save_response is None: 

574 return 

575 self._async_save_response.abort() 

576 self._async_save_response = None 

577 

578 def raise_for_failed_async_save(self) -> None: 

579 """Re-raise an in-flight async save's failure as soon as it is known. 

580 

581 Non-blocking: a save still running is left alone, so a training loop can 

582 afford to ask every step. That is the point --- the thread that resolves 

583 the future cannot propagate anything into the training loop, so a failure 

584 otherwise waits for the next :meth:`maybe_wait_for_async_save`, which is 

585 the next save, and a long ``save_steps`` interval turns one failed save 

586 into thousands of wasted steps. 

587 """ 

588 response = self._async_save_response 

589 if response is None or not response.persist_completion.done(): 

590 return 

591 

592 # Dropped before the raise, so one failed save is reported once rather 

593 # than at every step that follows it. The drain has nothing left to wait 

594 # for either way. 

595 self._async_save_response = None 

596 response.persist_completion.result() 

597 

598 def _publish_latest(self, save_dir: str, step: int) -> None: 

599 """Point the latest-checkpoint file at a checkpoint that is fully on disk. 

600 

601 Deliberately collective-free: the async path calls this from its persist 

602 callback, which runs on a background thread while the training loop is 

603 still issuing its own collectives, and a ``dist`` call from there would 

604 race them. Rank 0 writing on its own is enough, because the persisting 

605 child processes coordinate among themselves and rank 0 hosts their 

606 coordinator --- its success already implies every rank's shards and the 

607 shared ``.metadata`` have landed. 

608 """ 

609 if _get_rank() == 0: 

610 self._write_latest_pointer(os.path.dirname(save_dir), step) 

611 

612 logger.info( 

613 "Distributed checkpoint saved successfully: global_step=%s, dir=%s", 

614 step, 

615 save_dir, 

616 ) 

617 

618 def _finalize_checkpoint(self, save_dir: str, step: int) -> None: 

619 """Publish a synchronously written checkpoint as the newest one. 

620 

621 The leading barrier holds rank 0 until every rank has finished writing, 

622 so the pointer is never published over a checkpoint that is still being 

623 assembled; the trailing one keeps the ranks in step afterwards. The async 

624 path cannot borrow this and publishes from its persist callback instead. 

625 """ 

626 _barrier() 

627 self._publish_latest(save_dir, step) 

628 

629 # ------------------------------------------------------------------ 

630 # Save 

631 # ------------------------------------------------------------------ 

632 

633 def save( 

634 self, 

635 path: str, 

636 state: Dict[str, Any], 

637 *, 

638 global_step: int, 

639 save_async: bool = False, 

640 ) -> None: 

641 """Write ``state`` into ``path``; see :meth:`CheckpointerBase.save`.""" 

642 # Never let two saves overlap: they would compete for host memory and, 

643 # in async mode, race on the checkpoint directory. 

644 self.maybe_wait_for_async_save() 

645 

646 payload = dict(state) 

647 extra_state = payload.pop("extra_state", None) 

648 

649 if extra_state is not None and self.extra_state_per_rank: 

650 os.makedirs(os.path.join(path, _EXTRA_STATE_DIR), exist_ok=True) 

651 _barrier() 

652 # Written before the shards so that every persisted model/optimizer 

653 # payload is already backed by the progress state to resume from it. 

654 torch.save(extra_state, self._extra_state_path(path, _get_rank())) 

655 else: 

656 os.makedirs(path, exist_ok=True) 

657 _barrier() 

658 if extra_state is not None: 

659 payload["extra_state"] = extra_state 

660 

661 # Free residual training-step allocations before DCP allocates its 

662 # collective buffers for the gather pass. 

663 _empty_cache() 

664 

665 if save_async: 

666 # Publishing from the persist callback, rather than from the next 

667 # ``maybe_wait_for_async_save``, is what keeps the pointer honest: 

668 # a run that dies after an async save has landed but before the 

669 # next save would otherwise leave a complete checkpoint on disk 

670 # that the pointer never names. 

671 self._async_save_response = dcp_async_save( 

672 payload, 

673 checkpoint_id=path, 

674 callback=partial(self._publish_latest, path, global_step), 

675 ) 

676 logger.info("Async DCP save dispatched: %s", path) 

677 else: 

678 dcp_save(payload, checkpoint_id=path) 

679 logger.info("Sync DCP save completed: %s", path) 

680 

681 _empty_cache() 

682 

683 if not save_async: 

684 self._finalize_checkpoint(path, global_step) 

685 

686 # ------------------------------------------------------------------ 

687 # Load 

688 # ------------------------------------------------------------------ 

689 

690 def load( 

691 self, 

692 path: str, 

693 state: Dict[str, Any], 

694 *, 

695 strict_model: bool = True, 

696 extra_state_skeleton: Optional[Dict[str, Any]] = None, 

697 ) -> Dict[str, Any]: 

698 """Fill ``state`` from ``path``; see :meth:`CheckpointerBase.load`.""" 

699 self.maybe_wait_for_async_save() 

700 

701 # Auto-detect the layout the checkpoint was written with, so the 

702 # configured ``extra_state_per_rank`` may differ from the producing run. 

703 extra_state_file = self._extra_state_path(path, _get_rank()) 

704 from_file = os.path.isfile(extra_state_file) 

705 

706 if extra_state_skeleton is not None and not from_file: 

707 skeleton = dict(extra_state_skeleton) 

708 skeleton[_STEP_KEY] = _UNRESTORED_STEP 

709 state["extra_state"] = skeleton 

710 

711 try: 

712 dcp_load( 

713 state, 

714 checkpoint_id=path, 

715 planner=_ModelStrictLoadPlanner(strict_model=strict_model), 

716 ) 

717 except Exception: 

718 logger.exception("Failed to load checkpoint from %s", path) 

719 raise 

720 

721 if extra_state_skeleton is not None: 

722 state["extra_state"] = self._read_extra_state( 

723 path, state, extra_state_file, from_file 

724 ) 

725 

726 # Hold every rank here until all of them have finished reading, so no 

727 # rank starts training against a checkpoint others are still loading. 

728 _barrier() 

729 return state 

730 

731 def _read_extra_state( 

732 self, 

733 path: str, 

734 state: Dict[str, Any], 

735 extra_state_file: str, 

736 from_file: bool, 

737 ) -> Dict[str, Any]: 

738 """Return the extra_state bundle from wherever the checkpoint kept it.""" 

739 if from_file: 

740 logger.info("Reading extra_state from %s", extra_state_file) 

741 return torch.load(extra_state_file, weights_only=False) 

742 

743 extra = state.get("extra_state") or {} 

744 if extra.get(_STEP_KEY, _UNRESTORED_STEP) == _UNRESTORED_STEP: 

745 raise FileNotFoundError( 

746 f"Checkpoint {path} carries no training state for rank " 

747 f"{_get_rank()}: neither a per-rank file ({extra_state_file}) nor " 

748 "an extra_state entry inside the DCP. Resume needs the progress " 

749 "state saved beside the model shards; set " 

750 "checkpoint.restore_train_state=false to load the weights only." 

751 ) 

752 logger.info("Read extra_state embedded in the DCP state dict") 

753 return extra