Repository navigation
Expand file tree
/
Copy pathcheckpoint.py
More file actions
303 lines (253 loc) · 11.3 KB
/
Copy pathcheckpoint.py
File metadata and controls
303 lines (253 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
"""Per-hyperparameter training checkpoints.
A checkpoint here is a single file on disk holding everything needed
to resume training from a specific step: the model weights, the
optimizer state, the random number generator state, and the step
number itself. Saving and loading those four things is enough to make
training bit-exactly reproducible across an interruption.
Checkpoints are organized as::
checkpoints/
<16-character hash>/
config.json <- human-readable hyperparameters
step_000010.pt <- saved snapshot at step 10
step_000020.pt <- saved snapshot at step 20
...
The directory name is the first 16 hex characters of a SHA-256 hash
of the ``TrainingConfig`` dataclass below. The hash includes every
hyperparameter that affects the trained weights -- but NOT the total
number of training steps. That deliberate omission means a longer
run can resume from a shorter one's saved snapshots: when ``train.py``
asks for 6000 steps and the cache has a step_5000.pt sitting in the
matching directory, the loader picks that up and continues training
from step 5000.
The corpus is identified by a SHA-256 of the cleaned text. Two runs
that pretend to share hyperparameters but use different corpus text
will land in different cache directories, so they cannot accidentally
contaminate each other.
A ``config.json`` sidecar file is written next to the snapshots so
you can browse the cache directory by eye and tell which run is
which without having to decode the hash.
Glossary
--------
checkpoint: one ``step_<N>.pt`` file. Holds enough state to resume
training from step N as if no interruption had ever happened.
cache key: the 16-character hash that names the directory holding
a family of checkpoints sharing all hyperparameters except step
count.
state_dict (PyTorch): a dictionary of tensors that fully describes
the internal state of a model or optimizer. Used by PyTorch's
serialization helpers.
"""
from __future__ import annotations
import hashlib
import json
import os
import random
from dataclasses import asdict, dataclass
import torch
from torch import Tensor
from model import GPT
# Default root directory for all checkpoints. Per-config subdirectories
# are created under here.
CACHE_ROOT = "checkpoints"
@dataclass(frozen=True)
class TrainingConfig:
"""The set of inputs that uniquely identifies a training run.
Two runs that share the same TrainingConfig will produce the same
sequence of model weights step for step (assuming the same code).
Two runs whose configs differ in any one field will land in
different cache directories, so their checkpoints cannot collide.
``NUM_TRAINING_STEPS`` is intentionally NOT a field here: it is a
"stop after" target, not an input that changes the training
trajectory. Excluding it lets you resume a 1000-step run as part
of a longer 5000-step run.
"""
# Width of every Vector flowing through the model trunk.
embedding_dim: int
# Number of attention heads per layer.
n_head: int
# Number of stacked transformer layers.
n_layer: int
# Maximum sequence length the model is built to handle.
block_size: int
# Number of independent sequences drawn in one training step.
batch_size: int
# Initial Adam learning rate (decayed across training).
learning_rate: float
# Seed used to initialize every random number generator.
random_seed: int
# Number of TokenIds the model knows about. Derived from the
# tokenizer; included here so vocabulary changes invalidate the
# cache.
vocab_size: int
# SHA-256 of the cleaned corpus text. Pins the training data so
# we cannot resume across a corpus change.
corpus_sha256: str
def corpus_sha256(text: str) -> str:
"""SHA-256 hex digest of ``text``.
Used as the ``corpus_sha256`` field of ``TrainingConfig``.
"""
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def _cache_key(config: TrainingConfig) -> str:
"""Compute the 16-character cache key for ``config``.
The full config is JSON-encoded with sorted keys so the
serialization is deterministic, then hashed with SHA-256. We use
only the first 16 hex characters (64 bits): vastly more than
enough to avoid collisions across the number of distinct configs
a human will ever try.
"""
payload = json.dumps(asdict(config), sort_keys=True).encode("utf-8")
return hashlib.sha256(payload).hexdigest()[:16]
def ensure_cache_dir(config: TrainingConfig, root: str = CACHE_ROOT) -> str:
"""Return the cache directory for ``config``, creating it if needed.
Also writes ``config.json`` inside the directory on first use so
the human reading the checkpoints folder can see which
hyperparameter set corresponds to which hash. We do NOT rewrite
``config.json`` if it already exists; the file is informational
and any reasonable later run with the same hash must have the
same config by construction.
"""
path = os.path.join(root, _cache_key(config))
os.makedirs(path, exist_ok=True)
config_path = os.path.join(path, "config.json")
if not os.path.exists(config_path):
with open(config_path, "w") as handle:
json.dump(asdict(config), handle, indent=2, sort_keys=True)
handle.write("\n")
return path
def _step_filename(step: int) -> str:
"""Filename for the snapshot at training step ``step``.
Zero-padded to six digits so an ASCII sort of the directory
listing also sorts by step number, which is convenient when
eyeballing the cache.
"""
return f"step_{step:06d}.pt"
def _parse_step(filename: str) -> int | None:
"""Inverse of ``_step_filename``: extract N from ``step_<N>.pt``.
Returns None for any filename that does not match the pattern
(e.g. ``config.json`` or a ``.tmp`` leftover from an interrupted
save).
"""
if not filename.startswith("step_") or not filename.endswith(".pt"):
return None
try:
return int(filename[len("step_") : -len(".pt")])
except ValueError:
return None
def latest_checkpoint_step(path: str, max_step: int) -> int | None:
"""Highest saved step N in ``path`` such that ``N <= max_step``.
Returns ``None`` if the directory does not exist, is empty, or
contains no checkpoint at or below ``max_step``. Used by the
training entry point to decide where to resume from (or whether
to skip training entirely if N already equals the requested
step count).
"""
if not os.path.isdir(path):
return None
best: int | None = None
for name in os.listdir(path):
step = _parse_step(name)
if step is None or step > max_step:
continue
if best is None or step > best:
best = step
return best
def save(
path: str,
step: int,
model: GPT,
optimizer: torch.optim.Optimizer,
) -> None:
"""Write a snapshot of (parameters, optimizer, RNG state) to disk.
The snapshot file is named ``step_<step>.pt`` inside ``path``.
Contents:
* ``step`` -- the step number, for self-description.
* ``parameters`` -- a list of CPU tensors, one per entry of
``model.parameters()`` in order. We move
to CPU before saving so the file is
portable between devices.
* ``optimizer`` -- the optimizer's state_dict.
* ``torch_rng`` -- ``torch.get_rng_state()`` for the CPU
generator (controls all CPU randomness
including ``torch.randint`` calls done
with a CPU default device).
* ``torch_cuda_rng`` -- per-device CUDA RNG states, or None if
CUDA is not available.
* ``python_rng`` -- ``random.getstate()`` for the standard
``random`` module's generator.
Atomic write: we write to ``step_<N>.pt.tmp`` first and then
rename. A crash mid-save will leave only the ``.tmp`` file behind,
not a partially written ``.pt`` that ``load`` might accept.
"""
payload = {
"step": step,
"parameters": [p.detach().cpu() for p in model.parameters()],
"optimizer": optimizer.state_dict(),
"torch_rng": torch.get_rng_state(),
"torch_cuda_rng": (
torch.cuda.get_rng_state_all()
if torch.cuda.is_available()
else None
),
"python_rng": random.getstate(),
}
final = os.path.join(path, _step_filename(step))
tmp = final + ".tmp"
torch.save(payload, tmp)
os.replace(tmp, final)
def load(
path: str,
step: int,
model: GPT,
optimizer: torch.optim.Optimizer,
) -> None:
"""Restore the snapshot at ``step`` into ``model`` and ``optimizer``.
Both ``model`` and ``optimizer`` must already exist and be of the
same shape/structure they had when the snapshot was saved
(matching ``TrainingConfig``). The model's parameters are copied
over in place (no replacement of tensors -- the same tensor
objects' ``.data`` is overwritten), so any outside references to
them remain valid.
Side effects beyond ``model`` and ``optimizer``:
the torch CPU RNG, every torch CUDA RNG (if CUDA is available),
and the standard ``random`` module's RNG are restored to the
state they had when the snapshot was saved. After this call,
continuing the training loop produces a bit-exact continuation
of the original run.
"""
filename = os.path.join(path, _step_filename(step))
# weights_only=False because the payload includes non-tensor
# objects (optimizer state dict, Python RNG tuple). The file was
# written by this same project so unpickling it is safe.
payload = torch.load(filename, map_location="cpu", weights_only=False)
# Copy saved parameter values back into the model. We do not
# replace the parameter tensors themselves because the optimizer
# holds references to them.
saved_parameters = payload["parameters"]
live_parameters = model.parameters()
if len(saved_parameters) != len(live_parameters):
raise RuntimeError(
f"checkpoint has {len(saved_parameters)} parameter tensors "
f"but model has {len(live_parameters)}"
)
with torch.no_grad():
for live, saved in zip(live_parameters, saved_parameters):
live.copy_(saved.to(live.device))
device = live_parameters[0].device
optimizer.load_state_dict(payload["optimizer"])
# ``load_state_dict`` reinstates optimizer state tensors on CPU
# (matching ``map_location='cpu'`` above). Move each one onto the
# device the live parameters are on, so subsequent
# ``optimizer.step()`` calls can combine them with parameter
# gradients without a device mismatch.
for state in optimizer.state.values():
for key, value in state.items():
if isinstance(value, Tensor):
state[key] = value.to(device)
# Restore the random number generators. ``torch.set_rng_state``
# affects the CPU generator; CUDA generators are restored
# separately if both saver and loader have CUDA available.
torch.set_rng_state(payload["torch_rng"])
cuda_rng = payload.get("torch_cuda_rng")
if cuda_rng is not None and torch.cuda.is_available():
torch.cuda.set_rng_state_all(cuda_rng)
random.setstate(payload["python_rng"])