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,
)
| 202 | return write_file(dir, fname, contents, self.save_overwrite) |
| 203 | |
| 204 | def load( |
| 205 | self, |
| 206 | dir: PathOrStr, |
| 207 | model: nn.Module, |
| 208 | optim: Optimizer = None, |
| 209 | *, |
| 210 | load_optimizer_state: Optional[bool] = None, |
| 211 | load_trainer_state: Optional[bool] = None, |
| 212 | key_mapping: Optional[Dict[str, str]] = None, |
| 213 | ) -> Optional[Dict[str, Any]]: |
| 214 | """ |
| 215 | Load model, optim, and other training state from a local or remote checkpoint directory |
| 216 | created via :meth:`save()` or :meth:`save_async()`. |
| 217 | """ |
| 218 | dir = normalize_path(dir) |
| 219 | |
| 220 | # Maybe load trainer state. |
| 221 | trainer_state: Optional[Dict[str, Any]] = None |
| 222 | if load_trainer_state is not False: |
| 223 | # Try loading the given rank's state first, then fall back to rank 0 train state if it |
| 224 | # doesn't exist, which can happen when we're restoring a checkpoint with a different world size. |
| 225 | for path in (f"{dir}/train/rank{get_global_rank()}.pt", f"{dir}/train/rank0.pt"): |
| 226 | try: |
| 227 | trainer_state = torch.load(cached_path(path, quiet=True), weights_only=False) |
| 228 | break |
| 229 | except FileNotFoundError: |
| 230 | pass |
| 231 | |
| 232 | if load_trainer_state is True and trainer_state is None: |
| 233 | raise FileNotFoundError(f"Missing trainer state in checkpoint dir '{dir}'") |
| 234 | |
| 235 | # Load model and optimizer state. |
| 236 | model_and_optim_dir: str = f"{dir}/model_and_optim" |
| 237 | load_model_and_optim_state( |
| 238 | model_and_optim_dir, |
| 239 | model, |
| 240 | optim if load_optimizer_state else None, |
| 241 | process_group=None, |
| 242 | key_mapping=key_mapping, |
| 243 | pre_download=is_url(dir) and self.pre_download, |
| 244 | work_dir=self.work_dir, |
| 245 | thread_count=self.load_thread_count, |
| 246 | ) |
| 247 | return trainer_state |
| 248 | |
| 249 | def _save_train_state(self, dir: PathOrStr, wd: Path, train_state: Dict[str, Any]): |
| 250 | train_dir = wd / "train" |
no test coverage detected