|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement. |
| 3 | + |
| 4 | +import enum |
| 5 | +import os |
| 6 | +import re |
| 7 | +import time |
| 8 | +from typing import Any, Dict |
| 9 | + |
| 10 | +import torch |
| 11 | +import torch.distributed as dist |
| 12 | +import torch.distributed.checkpoint as dcp |
| 13 | +import torch.nn as nn |
| 14 | +from torch.distributed.checkpoint.state_dict import ( |
| 15 | + get_model_state_dict, |
| 16 | + get_optimizer_state_dict, |
| 17 | + set_model_state_dict, |
| 18 | + set_optimizer_state_dict, |
| 19 | +) |
| 20 | +from torchtrain.logging_utils import rank0_log |
| 21 | + |
| 22 | + |
| 23 | +class IntervalType(enum.Enum): |
| 24 | + SECONDS = enum.auto() |
| 25 | + STEPS = enum.auto() |
| 26 | + |
| 27 | + |
| 28 | +class ModelWrapper: |
| 29 | + def __init__(self, model: nn.Module) -> None: |
| 30 | + self.model = model |
| 31 | + |
| 32 | + def state_dict(self) -> None: |
| 33 | + return get_model_state_dict(self.model) |
| 34 | + |
| 35 | + def load_state_dict(self, state_dict: Dict[str, Any]) -> None: |
| 36 | + set_model_state_dict(self.model, state_dict) |
| 37 | + |
| 38 | + |
| 39 | +class OptimizerWrapper: |
| 40 | + def __init__(self, model: nn.Module, optim: torch.optim.Optimizer) -> None: |
| 41 | + self.model = model |
| 42 | + self.optim = optim |
| 43 | + |
| 44 | + def state_dict(self) -> None: |
| 45 | + return get_optimizer_state_dict(self.model, self.optim) |
| 46 | + |
| 47 | + def load_state_dict(self, state_dict: Dict[str, Any]) -> None: |
| 48 | + set_optimizer_state_dict(self.model, self.optim, optim_state_dict=state_dict) |
| 49 | + |
| 50 | + |
| 51 | +class CheckpointManager: |
| 52 | + def __init__( |
| 53 | + self, |
| 54 | + model: nn.Module, |
| 55 | + optimizer: torch.optim.Optimizer, |
| 56 | + states: Dict[str, Any], |
| 57 | + folder: str, |
| 58 | + interval_type: IntervalType, |
| 59 | + interval: int, |
| 60 | + ) -> None: |
| 61 | + self.folder = folder |
| 62 | + self.states = states |
| 63 | + self.states.update( |
| 64 | + { |
| 65 | + "model": ModelWrapper(model), |
| 66 | + "optimizer": OptimizerWrapper(model, optimizer), |
| 67 | + } |
| 68 | + ) |
| 69 | + self.interval_type = interval_type |
| 70 | + self.interval = interval |
| 71 | + self.begin = 0 |
| 72 | + self.work = None |
| 73 | + self.pg = dist.new_group(backend="gloo") |
| 74 | + self.doit = None |
| 75 | + |
| 76 | + def reset(self) -> None: |
| 77 | + self.begin = time.monotonic() |
| 78 | + |
| 79 | + def create_checkpoint_id(self, step: int) -> str: |
| 80 | + return os.path.join(self.folder, f"step-{step}") |
| 81 | + |
| 82 | + def save(self, curr_step: int, force: bool = False) -> None: |
| 83 | + if not self.folder: |
| 84 | + return |
| 85 | + |
| 86 | + if not force: |
| 87 | + if self.interval_type == IntervalType.STEPS and not ( |
| 88 | + curr_step % self.interval == 0 |
| 89 | + ): |
| 90 | + return |
| 91 | + if self.interval_type == IntervalType.SECONDS: |
| 92 | + doit = (time.monotonic() - self.begin) >= self.interval |
| 93 | + self.doit = torch.tensor(int(doit)) |
| 94 | + if self.work is None: |
| 95 | + self.work = dist.all_reduce(self.doit, group=self.pg, async_op=True) |
| 96 | + return |
| 97 | + elif curr_step % 5 == 4: |
| 98 | + self.work.wait() |
| 99 | + self.work = None |
| 100 | + doit = self.doit.item() |
| 101 | + self.doit = None |
| 102 | + if doit == 0: |
| 103 | + return |
| 104 | + else: |
| 105 | + return |
| 106 | + |
| 107 | + if self.work: |
| 108 | + self.work.wait() |
| 109 | + self.work = None |
| 110 | + self.doit = None |
| 111 | + |
| 112 | + rank0_log(f"Saving a checkpoint in step {curr_step}.") |
| 113 | + begin = time.monotonic() |
| 114 | + dcp.save(self.states, checkpoint_id=self.create_checkpoint_id(curr_step)) |
| 115 | + self.reset() |
| 116 | + rank0_log( |
| 117 | + f"Finish saving the checkpoint in step {curr_step}. " |
| 118 | + f"{time.monotonic() - begin} seconds" |
| 119 | + ) |
| 120 | + |
| 121 | + def load(self, step: int = -1) -> bool: |
| 122 | + if not self.folder: |
| 123 | + return False |
| 124 | + if not os.path.isdir(self.folder): |
| 125 | + return False |
| 126 | + if step != -1 and not os.path.isdir(self.create_checkpoint_id(step)): |
| 127 | + return False |
| 128 | + |
| 129 | + if step == -1: |
| 130 | + step_counts = [] |
| 131 | + for filename in os.listdir(self.folder): |
| 132 | + match = re.search(r"step-(\d+)", filename) |
| 133 | + if match: |
| 134 | + step_counts.append(int(match.group(1))) |
| 135 | + if not step_counts: |
| 136 | + return False |
| 137 | + step = max(step_counts) |
| 138 | + |
| 139 | + rank0_log("Loading a checkpoint.") |
| 140 | + begin = time.monotonic() |
| 141 | + dcp.load( |
| 142 | + self.states, |
| 143 | + checkpoint_id=self.create_checkpoint_id(step), |
| 144 | + ) |
| 145 | + rank0_log(f"Finish loading a checkpoint. {time.monotonic() - begin} seconds.") |
| 146 | + return True |
0 commit comments