Repository navigation
Expand file tree
/
Copy pathcheckpoint.py
More file actions
306 lines (254 loc) · 12.1 KB
/
Copy pathcheckpoint.py
File metadata and controls
306 lines (254 loc) · 12.1 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
304
305
306
import os
import json
import glob
import re
import random
import tempfile
import torch
import numpy as np
from typing import Any, Optional
CHECKPOINT_VERSION = 1
def capture_rng_states() -> dict:
rng = {
"python": random.getstate(),
"numpy": np.random.get_state(),
"torch_cpu": torch.random.get_rng_state(),
}
if torch.cuda.is_available():
rng["torch_cuda"] = torch.cuda.get_rng_state_all()
return rng
def restore_rng_states(rng: dict) -> None:
# torch RNG states must be CPU ByteTensors, but load_checkpoint maps every
# tensor to the training device (map_location="cuda:0" moves them to GPU).
random.setstate(rng["python"])
np.random.set_state(rng["numpy"])
torch.random.set_rng_state(rng["torch_cpu"].cpu())
if "torch_cuda" in rng and torch.cuda.is_available():
# Restore per device index; a checkpoint written with more visible
# GPUs than are visible now only restores the devices that exist.
for idx, state in enumerate(rng["torch_cuda"][: torch.cuda.device_count()]):
torch.cuda.set_rng_state(state.cpu(), idx)
def _atomic_write(path: str, write_fn) -> None:
"""Write via a temp file in the same directory, then ``os.replace``.
``os.replace`` is atomic on POSIX and Windows, so a crash mid-write
leaves the previous file intact instead of a truncated one.
"""
directory = os.path.dirname(path) or "."
os.makedirs(directory, exist_ok=True)
fd, tmp_path = tempfile.mkstemp(
dir=directory, prefix=f".{os.path.basename(path)}.", suffix=".tmp"
)
try:
with os.fdopen(fd, "wb") as f:
write_fn(f)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, path)
except BaseException:
if os.path.exists(tmp_path):
os.remove(tmp_path)
raise
def atomic_torch_save(obj, path: str) -> None:
"""``torch.save`` that never leaves a partially written file at ``path``."""
_atomic_write(path, lambda f: torch.save(obj, f))
def build_checkpoint_dict(model, optimizer, scheduler, epoch: int,
val_loss: float, metrics: dict,
early_stopping_state: Optional[dict] = None,
best_value: Optional[float] = None,
config_hash: str = "", scaler=None) -> dict:
"""Build a full training-state checkpoint dict.
``scaler`` is the fp16 ``torch.amp.GradScaler`` (or None); its loss
scale is saved so a resumed run does not restart from the initial scale.
"""
ckpt = {
"version": CHECKPOINT_VERSION,
"epoch": epoch,
"model_state_dict": model.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"val_loss": val_loss,
"metrics": metrics,
"config_hash": config_hash,
"rng_states": capture_rng_states(),
}
if hasattr(scheduler, "state_dict"):
ckpt["scheduler_state_dict"] = scheduler.state_dict()
if early_stopping_state is not None:
ckpt["early_stopping_state"] = early_stopping_state
if best_value is not None:
ckpt["best_value"] = best_value
if scaler is not None:
ckpt["scaler_state_dict"] = scaler.state_dict()
return ckpt
def save_checkpoint(path: str, model, optimizer, scheduler, epoch: int,
val_loss: float, metrics: dict,
early_stopping_state: Optional[dict] = None,
best_value: Optional[float] = None,
config_hash: str = "", scaler=None) -> None:
"""Persist a full training-state checkpoint to disk."""
ckpt = build_checkpoint_dict(
model, optimizer, scheduler, epoch, val_loss, metrics,
early_stopping_state, best_value, config_hash, scaler=scaler,
)
atomic_torch_save(ckpt, path)
def load_checkpoint(path: str, model, optimizer, scheduler,
device: str = "cpu", config_hash: str = "",
restore_rng: bool = True, scaler=None) -> dict:
"""Load checkpoint and restore model/optimizer/scheduler/RNG state."""
checkpoint = torch.load(path, map_location=device, weights_only=False)
if not isinstance(checkpoint, dict) or "model_state_dict" not in checkpoint:
raise ValueError(
f"{path} is not a full-state checkpoint (older templates wrote a "
"weights-only state_dict here). Delete it and start a fresh run, "
"or train at least one epoch with the current template before "
"using --resume."
)
saved_hash = checkpoint.get("config_hash", "")
if config_hash and saved_hash and saved_hash != config_hash:
raise ValueError(
f"Config hash mismatch: checkpoint={saved_hash[:12]}... "
f"vs current={config_hash[:12]}... "
"The config has changed since this checkpoint was saved."
)
model.load_state_dict(checkpoint["model_state_dict"])
optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
if "scheduler_state_dict" in checkpoint and hasattr(scheduler, "load_state_dict"):
scheduler.load_state_dict(checkpoint["scheduler_state_dict"])
if scaler is not None and "scaler_state_dict" in checkpoint:
scaler.load_state_dict(checkpoint["scaler_state_dict"])
if restore_rng and "rng_states" in checkpoint:
restore_rng_states(checkpoint["rng_states"])
return checkpoint
class CheckpointManager:
"""Manages periodic and best-model checkpoints during training.
The always-on `latest_model.pt` snapshot is written by
`LatestModelCallback`, not by this class. This class is only added
to the callback chain when `checkpoint_config.enabled = True` and
handles `best.pt` plus periodic `checkpoint_epoch_*.pt`.
"""
CHECKPOINT_VERSION = CHECKPOINT_VERSION
def __init__(self, run_dir: str, save_every_n: int = 10,
keep_last_k: int = 3, save_best: bool = True,
monitor: str = "val_loss", mode: str = "min"):
self.run_dir = run_dir
self.save_every_n = save_every_n
self.keep_last_k = keep_last_k
self.save_best = save_best
self.monitor = monitor
self.mode = mode
self.best_value: Optional[float] = None
def _is_better(self, current: float) -> bool:
if self.best_value is None:
return True
if self.mode == "min":
return current < self.best_value
return current > self.best_value
def save_checkpoint(self, path: str, model, optimizer, scheduler,
epoch: int, val_loss: float, metrics: dict,
early_stopping_state: Optional[dict] = None,
config_hash: str = "", scaler=None) -> None:
"""Save a complete training checkpoint (instance wrapper)."""
save_checkpoint(
path, model, optimizer, scheduler, epoch, val_loss, metrics,
early_stopping_state=early_stopping_state,
best_value=self.best_value,
config_hash=config_hash, scaler=scaler,
)
def load_checkpoint(self, path: str, model, optimizer, scheduler,
device: str = "cpu", config_hash: str = "",
scaler=None) -> dict:
"""Load a checkpoint and restore all state (instance wrapper)."""
return load_checkpoint(
path, model, optimizer, scheduler, device=device,
config_hash=config_hash, scaler=scaler,
)
def maybe_save(self, epoch: int, model, optimizer, scheduler,
val_loss: float, metrics: dict,
early_stopping_state: Optional[dict] = None,
config_hash: str = "", scaler=None,
monitor_value: Optional[float] = None) -> None:
"""Conditionally save best/periodic checkpoints. `latest_model.pt`
is handled by `LatestModelCallback`, not here. ``best.pt`` tracks
``monitor_value`` (the value of ``self.monitor``; ``val_loss`` when
not given)."""
value = val_loss if monitor_value is None else monitor_value
# Periodic checkpoint
if self.save_every_n > 0 and (epoch + 1) % self.save_every_n == 0:
path = os.path.join(self.run_dir, f"checkpoint_epoch_{epoch}.pt")
self.save_checkpoint(path, model, optimizer, scheduler,
epoch, val_loss, metrics,
early_stopping_state, config_hash, scaler=scaler)
self._cleanup_old_checkpoints()
# Best model checkpoint
if self.save_best and self._is_better(value):
self.best_value = value
path = os.path.join(self.run_dir, "best.pt")
self.save_checkpoint(path, model, optimizer, scheduler,
epoch, val_loss, metrics,
early_stopping_state, config_hash, scaler=scaler)
@staticmethod
def _epoch_of(path: str) -> int:
"""Extract the epoch number from ``checkpoint_epoch_{N}.pt``.
Unparseable names sort first (treated as oldest) so they are
cleaned up before any well-formed checkpoint.
"""
match = re.search(r"checkpoint_epoch_(\d+)\.pt$", os.path.basename(path))
return int(match.group(1)) if match else -1
def _cleanup_old_checkpoints(self) -> None:
"""Remove old periodic checkpoints, keeping only the last k.
Sorted numerically by epoch — a plain lexicographic sort would put
``checkpoint_epoch_9.pt`` after ``checkpoint_epoch_19.pt`` and delete
the wrong files once epoch numbers cross a digit boundary.
"""
pattern = os.path.join(self.run_dir, "checkpoint_epoch_*.pt")
checkpoints = sorted(glob.glob(pattern), key=self._epoch_of)
while len(checkpoints) > self.keep_last_k:
os.remove(checkpoints.pop(0))
def find_resume_checkpoint(run_path: str) -> Optional[str]:
"""Return path to `latest_model.pt` for the given run directory if it exists."""
path = os.path.join(run_path, "latest_model.pt")
return path if os.path.exists(path) else None
class SeedManifest:
"""Tracks completed seeds for multi-seed resume support."""
def __init__(self, group_path: str):
self.path = os.path.join(group_path, "seed_manifest.json")
self.completed_seeds: dict[str, dict[str, Any]] = {}
self._load()
def _load(self) -> None:
if os.path.exists(self.path):
with open(self.path, "r") as f:
data = json.load(f)
self.completed_seeds = data.get("completed_seeds", {})
def save(self) -> None:
payload = json.dumps({"completed_seeds": self.completed_seeds}, indent=2)
_atomic_write(self.path, lambda f: f.write(payload.encode("utf-8")))
def mark_complete(self, seed: int, val_loss: float,
wandb_run_id: str = "", metrics: dict | None = None) -> None:
self.completed_seeds[str(seed)] = {
"val_loss": val_loss,
"wandb_run_id": wandb_run_id,
"metrics": metrics or {},
}
self.save()
def is_complete(self, seed: int) -> bool:
return str(seed) in self.completed_seeds
def get_total_loss(self) -> float:
return sum(s["val_loss"] for s in self.completed_seeds.values())
def get_complete_count(self) -> int:
return len(self.completed_seeds)
def get_values(self, key: str) -> list[float]:
"""Per-seed values of ``key`` (e.g. ``final_val_loss``,
``best_val_r2``) over completed seeds, from each seed's ``metrics``.
Seeds recorded by an older template only have ``val_loss`` (final) and
``metrics.best_val_loss``; those keys are mapped. A seed without the
key gives NaN, which the objective treats as the worst value.
"""
values = []
for entry in self.completed_seeds.values():
metrics = entry.get("metrics", {})
if key in metrics:
values.append(float(metrics[key]))
elif key in ("final_val_loss", "best_val_loss"):
values.append(float(entry["val_loss"]))
else:
values.append(float("nan"))
return values