Get the paths of the last 'last_n' checkpoints by parsing filenames in the output directory.
(output_dir: str, last_n: int = 5, use_deepspeed=False, **kwargs)
| 17 | |
| 18 | |
| 19 | def _get_checkpoint_paths(output_dir: str, last_n: int = 5, use_deepspeed=False, **kwargs): |
| 20 | """ |
| 21 | Get the paths of the last 'last_n' checkpoints by parsing filenames |
| 22 | in the output directory. |
| 23 | """ |
| 24 | try: |
| 25 | if not use_deepspeed: |
| 26 | checkpoint = torch.load(os.path.join(output_dir, "model.pt"), map_location="cpu") |
| 27 | else: |
| 28 | checkpoint = torch.load( |
| 29 | os.path.join(output_dir, "model.pt", "mp_rank_00_model_states.pt"), |
| 30 | map_location="cpu", |
| 31 | ) |
| 32 | avg_keep_nbest_models_type = checkpoint["avg_keep_nbest_models_type"] |
| 33 | val_step_or_epoch = checkpoint[f"val_{avg_keep_nbest_models_type}_step_or_epoch"] |
| 34 | sorted_items = sorted(val_step_or_epoch.items(), key=lambda x: x[1], reverse=True) |
| 35 | sorted_items = ( |
| 36 | sorted_items[:last_n] if avg_keep_nbest_models_type == "acc" else sorted_items[-last_n:] |
| 37 | ) |
| 38 | checkpoint_paths = [] |
| 39 | for key, value in sorted_items[:last_n]: |
| 40 | if not use_deepspeed: |
| 41 | ckpt = os.path.join(output_dir, key) |
| 42 | else: |
| 43 | ckpt = os.path.join(output_dir, key, "mp_rank_00_model_states.pt") |
| 44 | checkpoint_paths.append(ckpt) |
| 45 | |
| 46 | except: |
| 47 | print(f"{checkpoint} does not exist, avg the lastet checkpoint.") |
| 48 | # List all files in the output directory |
| 49 | files = os.listdir(output_dir) |
| 50 | # Filter out checkpoint files and extract epoch numbers |
| 51 | checkpoint_files = [f for f in files if f.startswith("model.pt.e")] |
| 52 | # Sort files by epoch number in descending order |
| 53 | checkpoint_files.sort(key=lambda x: int(re.search(r"(\d+)", x).group()), reverse=True) |
| 54 | # Get the last 'last_n' checkpoint paths |
| 55 | checkpoint_paths = [os.path.join(output_dir, f) for f in checkpoint_files[:last_n]] |
| 56 | |
| 57 | return checkpoint_paths |
| 58 | |
| 59 | |
| 60 | @torch.no_grad() |
no test coverage detected
searching dependent graphs…