checkpoint_manager.py 5 KB
Newer Older
chenych's avatar
chenych committed
1
2
3
4
5
6
7
8
9
10
11
12
13
# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
chenych's avatar
chenych committed
14

chenych's avatar
chenych committed
15
16
import os
import random
chenych's avatar
chenych committed
17
import re
chenych's avatar
chenych committed
18
19
import shutil
import tempfile
chenych's avatar
chenych committed
20
21
from abc import ABC, abstractmethod
from typing import Any, Dict, Optional, Union
chenych's avatar
chenych committed
22
23
24

import numpy as np
import torch
chenych's avatar
chenych committed
25
import torch.distributed as dist
chenych's avatar
chenych committed
26
27
28
29
30
from filelock import FileLock
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
from transformers import PreTrainedTokenizer, ProcessorMixin


chenych's avatar
chenych committed
31
32
33
34
CHECKPOINT_TRACKER = "latest_global_step.txt"


class BaseCheckpointManager(ABC):
chenych's avatar
chenych committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    """
    A checkpoint manager that saves and loads
    - model
    - optimizer
    - lr_scheduler
    - extra_states
    in a SPMD way.

    We save
    - sharded model states and optimizer states
    - full lr_scheduler states
    - huggingface tokenizer and config for ckpt merge
    """

    def __init__(
        self,
        model: FSDP,
        optimizer: torch.optim.Optimizer,
        lr_scheduler: torch.optim.lr_scheduler.LRScheduler,
chenych's avatar
chenych committed
54
        processing_class: Union[PreTrainedTokenizer, ProcessorMixin],
chenych's avatar
chenych committed
55
56
57
58
    ):
        self.model = model
        self.optimizer = optimizer
        self.lr_scheduler = lr_scheduler
chenych's avatar
chenych committed
59
        self.processing_class = processing_class
chenych's avatar
chenych committed
60
61

        assert isinstance(self.model, FSDP)
chenych's avatar
chenych committed
62
63
        self.rank = dist.get_rank()
        self.world_size = dist.get_world_size()
chenych's avatar
chenych committed
64

chenych's avatar
chenych committed
65
    @abstractmethod
chenych's avatar
chenych committed
66
67
68
    def load_checkpoint(self, *args, **kwargs):
        raise NotImplementedError

chenych's avatar
chenych committed
69
    @abstractmethod
chenych's avatar
chenych committed
70
71
72
73
    def save_checkpoint(self, *args, **kwargs):
        raise NotImplementedError

    @staticmethod
chenych's avatar
chenych committed
74
    def local_mkdir(path: str) -> str:
chenych's avatar
chenych committed
75
76
77
78
79
80
81
82
83
        if not os.path.isabs(path):
            working_dir = os.getcwd()
            path = os.path.join(working_dir, path)

        # Using hash value of path as lock file name to avoid long file name
        lock_filename = f"ckpt_{hash(path) & 0xFFFFFFFF:08x}.lock"
        lock_path = os.path.join(tempfile.gettempdir(), lock_filename)

        try:
chenych's avatar
chenych committed
84
            with FileLock(lock_path, timeout=60):
chenych's avatar
chenych committed
85
86
87
                os.makedirs(path, exist_ok=True)
        except Exception as e:
            print(f"Warning: Failed to acquire lock for {path}: {e}")
chenych's avatar
chenych committed
88
            os.makedirs(path, exist_ok=True)  # even if the lock is not acquired, try to create the directory
chenych's avatar
chenych committed
89
90
91
92

        return path

    @staticmethod
chenych's avatar
chenych committed
93
    def get_rng_state() -> Dict[str, Any]:
chenych's avatar
chenych committed
94
95
96
97
98
99
100
101
102
        rng_state = {
            "cpu": torch.get_rng_state(),
            "cuda": torch.cuda.get_rng_state(),
            "numpy": np.random.get_state(),
            "random": random.getstate(),
        }
        return rng_state

    @staticmethod
chenych's avatar
chenych committed
103
    def load_rng_state(rng_state: Dict[str, Any]):
chenych's avatar
chenych committed
104
105
106
107
108
109
        torch.set_rng_state(rng_state["cpu"])
        torch.cuda.set_rng_state(rng_state["cuda"])
        np.random.set_state(rng_state["numpy"])
        random.setstate(rng_state["random"])


chenych's avatar
chenych committed
110
def find_latest_ckpt_path(path: Optional[str] = None, directory_format: str = "global_step_{}") -> Optional[str]:
chenych's avatar
chenych committed
111
112
113
114
115
116
117
118
119
120
    if path is None:
        return None

    tracker_file = get_checkpoint_tracker_filename(path)
    if not os.path.exists(tracker_file):
        print("Checkpoint tracker file does not exist: %s", tracker_file)
        return None

    with open(tracker_file, "rb") as f:
        iteration = int(f.read().decode())
chenych's avatar
chenych committed
121

chenych's avatar
chenych committed
122
123
124
125
126
127
128
129
130
    ckpt_path = os.path.join(path, directory_format.format(iteration))
    if not os.path.exists(ckpt_path):
        print("Checkpoint does not exist: %s", ckpt_path)
        return None

    print("Found checkpoint: %s", ckpt_path)
    return ckpt_path


chenych's avatar
chenych committed
131
def get_checkpoint_tracker_filename(root_path: str) -> str:
chenych's avatar
chenych committed
132
133
134
    """
    Tracker file rescords the latest chckpoint during training to restart from.
    """
chenych's avatar
chenych committed
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
    return os.path.join(root_path, CHECKPOINT_TRACKER)


def remove_obsolete_ckpt(path: str, global_step: int, save_limit: int = -1, directory_format: str = "global_step_{}"):
    """
    Remove the obsolete checkpoints that exceed the save_limit.
    """
    if save_limit <= 0:
        return

    if not os.path.exists(path):
        return

    pattern = re.escape(directory_format).replace(r"\{\}", r"(\d+)")
    ckpt_folders = []
    for folder in os.listdir(path):
        if match := re.match(pattern, folder):
            step = int(match.group(1))
            if step < global_step:
                ckpt_folders.append((step, folder))

    ckpt_folders.sort(reverse=True)
    for _, folder in ckpt_folders[save_limit - 1 :]:
        folder_path = os.path.join(path, folder)
        shutil.rmtree(folder_path, ignore_errors=True)
        print(f"Removed obsolete checkpoint: {folder_path}")