| 944 | |
| 945 | |
| 946 | def save_checkpoint(args, accelerator, global_step): |
| 947 | output_dir = args.output_dir |
| 948 | |
| 949 | # _before_ saving state, check if this save would set us over the `checkpoints_total_limit` |
| 950 | if accelerator.is_main_process and args.checkpoints_total_limit is not None: |
| 951 | checkpoints = os.listdir(output_dir) |
| 952 | checkpoints = [d for d in checkpoints if d.startswith("checkpoint")] |
| 953 | checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1])) |
| 954 | |
| 955 | # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints |
| 956 | if len(checkpoints) >= args.checkpoints_total_limit: |
| 957 | num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1 |
| 958 | removing_checkpoints = checkpoints[0:num_to_remove] |
| 959 | |
| 960 | logger.info( |
| 961 | f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints" |
| 962 | ) |
| 963 | logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}") |
| 964 | |
| 965 | for removing_checkpoint in removing_checkpoints: |
| 966 | removing_checkpoint = os.path.join(output_dir, removing_checkpoint) |
| 967 | shutil.rmtree(removing_checkpoint) |
| 968 | |
| 969 | save_path = Path(output_dir) / f"checkpoint-{global_step}" |
| 970 | accelerator.save_state(save_path) |
| 971 | logger.info(f"Saved state to {save_path}") |
| 972 | |
| 973 | |
| 974 | if __name__ == "__main__": |