Load model, optim, and other training state from a local or remote checkpoint directory created via :meth:`save()` or :meth:`save_async()`.
(
self,
dir: PathOrStr,
model: nn.Module,
optim: Optimizer = None,
*,
load_optimizer_state: Optional[bool] = None,
load_trainer_state: Optional[bool] = None,
key_mapping: Optional[Dict[str, str]] = None,
allow_missing_keys: bool = False,
)
| 283 | return write_file(dir, fname, contents, self.save_overwrite) |
| 284 | |
| 285 | def load( |
| 286 | self, |
| 287 | dir: PathOrStr, |
| 288 | model: nn.Module, |
| 289 | optim: Optimizer = None, |
| 290 | *, |
| 291 | load_optimizer_state: Optional[bool] = None, |
| 292 | load_trainer_state: Optional[bool] = None, |
| 293 | key_mapping: Optional[Dict[str, str]] = None, |
| 294 | allow_missing_keys: bool = False, |
| 295 | ) -> Optional[Dict[str, Any]]: |
| 296 | """ |
| 297 | Load model, optim, and other training state from a local or remote checkpoint directory |
| 298 | created via :meth:`save()` or :meth:`save_async()`. |
| 299 | """ |
| 300 | dir = normalize_path(dir) |
| 301 | |
| 302 | # Maybe load trainer state. |
| 303 | trainer_state: Optional[Dict[str, Any]] = None |
| 304 | if load_trainer_state is not False: |
| 305 | # Try loading the given rank's state first, then fall back to rank 0 train state if it |
| 306 | # doesn't exist, which can happen when we're restoring a checkpoint with a different world size. |
| 307 | for path in (f"{dir}/train/rank{get_global_rank()}.pt", f"{dir}/train/rank0.pt"): |
| 308 | try: |
| 309 | trainer_state = torch.load(cached_path(path, quiet=True), weights_only=False) |
| 310 | break |
| 311 | except FileNotFoundError: |
| 312 | pass |
| 313 | |
| 314 | if load_trainer_state is True and trainer_state is None: |
| 315 | raise FileNotFoundError(f"Missing trainer state in checkpoint dir '{dir}'") |
| 316 | |
| 317 | # Load model and optimizer state. |
| 318 | model_and_optim_dir: str = f"{dir}/model_and_optim" |
| 319 | load_model_and_optim_state( |
| 320 | model_and_optim_dir, |
| 321 | model, |
| 322 | optim if load_optimizer_state else None, |
| 323 | process_group=None, |
| 324 | key_mapping=key_mapping, |
| 325 | pre_download=is_url(dir) and self.pre_download, |
| 326 | work_dir=self.work_dir, |
| 327 | thread_count=self.load_thread_count, |
| 328 | allow_missing_keys=allow_missing_keys |
| 329 | ) |
| 330 | return trainer_state |
| 331 | |
| 332 | def _save_train_state(self, dir: PathOrStr, wd: Path, train_state: Dict[str, Any]): |
| 333 | train_dir = wd / "train" |
no test coverage detected