| """Checkpoint loading helpers shared across train/inference/submission.""" |
|
|
| from pathlib import Path |
|
|
| import re |
| import torch |
|
|
|
|
| def load_state_dict(path: Path, device: torch.device) -> dict: |
| """Load a state_dict with compatibility for multiple PyTorch versions.""" |
| try: |
| checkpoint = torch.load(path, map_location=device, weights_only=True) |
| except TypeError: |
| checkpoint = torch.load(path, map_location=device) |
|
|
| if isinstance(checkpoint, dict) and "state_dict" in checkpoint: |
| state_dict = checkpoint["state_dict"] |
| if isinstance(state_dict, dict): |
| return state_dict |
|
|
| if not isinstance(checkpoint, dict): |
| raise TypeError(f"Expected checkpoint dict at {path}, got {type(checkpoint)}") |
|
|
| return checkpoint |
|
|
|
|
| def resolve_stage2_checkpoint(ckpt_dir: Path, stage2_ckpt_name: str | None) -> Path: |
| """Resolve a Stage 2 checkpoint path, defaulting to the latest epoch checkpoint.""" |
| if stage2_ckpt_name: |
| candidate = ckpt_dir / stage2_ckpt_name |
| if not candidate.exists(): |
| raise FileNotFoundError(f"Stage 2 checkpoint not found: {candidate}") |
| return candidate |
|
|
| stage2_paths = list(ckpt_dir.glob("stage2_epoch_*.pt")) |
| if not stage2_paths: |
| raise FileNotFoundError(f"No stage2 checkpoints found in {ckpt_dir}") |
|
|
| def _epoch_num(path: Path) -> int: |
| match = re.search(r"stage2_epoch_(\d+)\.pt$", path.name) |
| return int(match.group(1)) if match else -1 |
|
|
| return max(stage2_paths, key=_epoch_num) |
|
|