efe-T's picture
update code/train/checkpoint.py
47283f9 verified
Raw History Blame Contribute Delete
12.2 kB
"""Checkpoints for HGpt training: periodic and on demand, at any optimizer-step boundary.
On demand, while training runs:
touch <run_dir>/control/checkpoint (or send SIGUSR1 to the trainer) -> save
touch <run_dir>/control/stop -> save, then stop
The trainer calls ControlChannel.poll() after every optimizer step (every ~12 s at
16 x 32K tokens on an L4), so the checkpoint is a consistent state: no half-accumulated
gradients. Each one reports itself in <run_dir>/control/last_checkpoint.json. From this
machine, for a run on Colab: python tools/train_ctl.py checkpoint --session NAME.
A checkpoint is taken in two parts. snapshot() copies every tensor to CPU (a second or two
of pause), then CheckpointWriter writes it in a background thread while training goes on:
model.safetensors and ema.safetensors (the weights), trainer.pt (optimizer states, RNG
states, the carried HybridMemory, data position), and manifest.json with sha256 sums. The
directory appears atomically, latest.json points to the newest one, older ones beyond `keep`
are deleted, and on_saved callbacks run (for example a Hugging Face upload).
load_checkpoint() verifies the sums and restores the whole state exactly. On CPU the resumed
run is bit-identical to an uninterrupted one (tested); on GPU, kernels with nondeterministic
reductions make the continuation equal only up to rounding.
Trainer loop sketch:
control = ControlChannel(run_dir)
writer = CheckpointWriter(run_dir / "checkpoints", on_saved=[upload, control.acknowledge])
for step in ...:
... # 16 micro-batches, optimizer steps
action = control.poll()
if action or periodic_due:
writer.submit(snapshot(model, optimizers, ema=ema, memory=memory, step=step + 1,
tokens=tokens, loader=loader.state(), extra=run_info))
if action == "stop":
writer.wait()
break
"""
import hashlib
import json
import os
import random
import shutil
import signal
import sys
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
import torch
from safetensors.torch import load_file, save_file
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from HGpt import DeltaCarry, HybridMemory, KVCarry # noqa: E402
CONTROL_DIR = "control"
def _cpu_copy(obj):
"""Deep copy with every tensor cloned to CPU (detached), so training can go on."""
if isinstance(obj, torch.Tensor):
return obj.detach().to("cpu", copy=True)
if isinstance(obj, dict):
return {k: _cpu_copy(v) for k, v in obj.items()}
if isinstance(obj, (list, tuple)):
return type(obj)(_cpu_copy(v) for v in obj)
return obj
def memory_to_dict(memory: HybridMemory | None):
if memory is None:
return None
return {"delta": [{"state": c.state, "last": c.last} for c in memory.delta],
"attn": [{"k": c.k, "v": c.v} for c in memory.attn],
"docs": memory.docs, "prev_token": memory.prev_token, "has_prev": memory.has_prev}
def memory_from_dict(data, device=None) -> HybridMemory | None:
if data is None:
return None
move = (lambda t: t.to(device)) if device is not None else (lambda t: t)
return HybridMemory(
tuple(DeltaCarry(move(c["state"]), move(c["last"])) for c in data["delta"]),
tuple(KVCarry(move(c["k"]), move(c["v"])) for c in data["attn"]),
move(data["docs"]), move(data["prev_token"]), move(data["has_prev"]),
)
def snapshot(model, optimizers, *, step: int, tokens: int, ema=None, memory=None,
loader=None, extra=None) -> dict:
"""Everything needed to resume, with all tensors copied to CPU. step is the next step
to run; loader is the data position (any picklable dict); extra must be JSON-able."""
rng = {"torch": torch.get_rng_state(), "python": random.getstate()}
if torch.cuda.is_available():
rng["cuda"] = torch.cuda.get_rng_state_all()
return {
"model": _cpu_copy(model.state_dict()),
"ema": _cpu_copy(dict(ema)) if ema is not None else None,
"trainer": {
"optimizers": [_cpu_copy(o.state_dict()) for o in optimizers],
"memory": _cpu_copy(memory_to_dict(memory)),
"loader": _cpu_copy(loader),
"rng": rng,
},
"meta": {"step": int(step), "tokens": int(tokens), "extra": extra or {},
"created_utc": datetime.now(timezone.utc).isoformat()},
}
def _sha256(path: Path) -> str:
digest = hashlib.sha256()
with open(path, "rb") as f:
for block in iter(lambda: f.read(1 << 22), b""):
digest.update(block)
return digest.hexdigest()
def _write_json(path: Path, value):
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8")
os.replace(tmp, path)
def write_checkpoint(snap: dict, directory: Path) -> dict:
"""Writes snap into directory (created atomically). Returns the manifest."""
directory = Path(directory)
tmp = directory.with_name(directory.name + ".tmp")
shutil.rmtree(tmp, ignore_errors=True)
tmp.mkdir(parents=True)
save_file(snap["model"], tmp / "model.safetensors")
if snap["ema"] is not None:
save_file(snap["ema"], tmp / "ema.safetensors")
torch.save(snap["trainer"], tmp / "trainer.pt")
manifest = {**snap["meta"], "name": directory.name,
"files": {p.name: _sha256(p) for p in sorted(tmp.iterdir())}}
_write_json(tmp / "manifest.json", manifest)
shutil.rmtree(directory, ignore_errors=True)
os.replace(tmp, directory)
return manifest
class CheckpointWriter:
"""Writes snapshots in a background thread, one at a time, keeping the newest `keep`."""
def __init__(self, root, keep: int = 2, on_saved=()):
self.root = Path(root)
self.root.mkdir(parents=True, exist_ok=True)
self.keep = keep
self.on_saved = list(on_saved) if isinstance(on_saved, (list, tuple)) else [on_saved]
self._thread = None
self._error = None
def submit(self, snap: dict) -> str:
"""Starts writing snap; waits first if the previous checkpoint is still being written."""
self.wait()
name = f"step-{snap['meta']['step']:07d}-tokens-{snap['meta']['tokens']}"
self._thread = threading.Thread(target=self._run, args=(snap, name), name=f"checkpoint-{name}")
self._thread.start()
return name
def wait(self):
"""Blocks until the current write is done; re-raises its error, if any."""
if self._thread is not None:
self._thread.join()
self._thread = None
if self._error is not None:
error, self._error = self._error, None
raise RuntimeError("checkpoint write failed") from error
def _run(self, snap, name):
try:
start = time.perf_counter()
path = self.root / name
manifest = write_checkpoint(snap, path)
manifest["write_seconds"] = round(time.perf_counter() - start, 1)
_write_json(self.root / "latest.json", {"name": name, "step": manifest["step"],
"tokens": manifest["tokens"]})
self._prune(keep_name=name)
for callback in self.on_saved:
callback(path, manifest)
except BaseException as error: # surfaced by the next submit() / wait()
self._error = error
def _prune(self, keep_name):
done = sorted((p for p in self.root.iterdir()
if p.is_dir() and p.name.startswith("step-") and not p.name.endswith(".tmp")),
key=lambda p: p.name)
for old in done[:-self.keep]:
if old.name != keep_name:
shutil.rmtree(old, ignore_errors=True)
def latest_checkpoint(root) -> Path | None:
pointer = Path(root) / "latest.json"
if not pointer.exists():
return None
return Path(root) / json.loads(pointer.read_text(encoding="utf-8"))["name"]
def load_checkpoint(directory, model, optimizers, *, ema=None, device=None, restore_rng=True) -> dict:
"""Verifies the sha256 sums, loads weights and optimizer states in place and returns
{"step", "tokens", "extra", "loader", "memory"} for the trainer (memory on `device`)."""
directory = Path(directory)
manifest = json.loads((directory / "manifest.json").read_text(encoding="utf-8"))
for name, digest in manifest["files"].items():
if _sha256(directory / name) != digest:
raise ValueError(f"checkpoint file {name} does not match its sha256 in manifest.json")
model.load_state_dict(load_file(directory / "model.safetensors"))
if ema is not None:
for key, value in load_file(directory / "ema.safetensors").items():
ema[key].copy_(value)
trainer = torch.load(directory / "trainer.pt", map_location="cpu", weights_only=True)
if len(trainer["optimizers"]) != len(optimizers):
raise ValueError("checkpoint has a different number of optimizers")
for opt, state in zip(optimizers, trainer["optimizers"]):
opt.load_state_dict(state)
if restore_rng:
torch.set_rng_state(trainer["rng"]["torch"])
random.setstate(trainer["rng"]["python"])
if "cuda" in trainer["rng"] and torch.cuda.is_available():
torch.cuda.set_rng_state_all(trainer["rng"]["cuda"])
return {"step": manifest["step"], "tokens": manifest["tokens"], "extra": manifest["extra"],
"loader": trainer["loader"], "memory": memory_from_dict(trainer["memory"], device)}
def resume(local_root, model, optimizers, *, store=None, ema=None, device=None) -> dict | None:
"""Continues a run from the newest checkpoint: this VM's own (local_root, the writer's
root) or, if newer or the only one, the store's (a run that stopped on another VM).
Returns load_checkpoint()'s dict plus "path", or None for a fresh start. Restore the
data stream from the returned "loader" state to continue with the very next token."""
local = latest_checkpoint(local_root)
remote_name = store.latest_name() if store is not None else None
if remote_name is not None and (local is None or remote_name > local.name): # zero-padded step names
local = store.download_latest(Path(local_root) / "from_store")
if local is None:
return None
info = load_checkpoint(local, model, optimizers, ema=ema, device=device)
info["path"] = str(local)
return info
class ControlChannel:
"""On-demand requests to a running trainer: files in <run_dir>/control or SIGUSR1."""
def __init__(self, run_dir, use_signal: bool = True):
self.dir = Path(run_dir) / CONTROL_DIR
self.dir.mkdir(parents=True, exist_ok=True)
self._signalled = False
if (use_signal and hasattr(signal, "SIGUSR1")
and threading.current_thread() is threading.main_thread()):
signal.signal(signal.SIGUSR1, self._on_signal)
def _on_signal(self, signum, frame):
self._signalled = True
def poll(self) -> str | None:
"""'stop' (save, then stop), 'checkpoint' (save) or None. Consumes the request."""
stop, ckpt = self.dir / "stop", self.dir / "checkpoint"
if stop.exists():
stop.unlink(missing_ok=True)
ckpt.unlink(missing_ok=True)
return "stop"
if self._signalled or ckpt.exists():
self._signalled = False
ckpt.unlink(missing_ok=True)
return "checkpoint"
return None
def acknowledge(self, path, manifest):
"""on_saved callback: records the newest checkpoint for train_ctl.py to read."""
_write_json(self.dir / "last_checkpoint.json",
{"name": manifest["name"], "path": str(path), "step": manifest["step"],
"tokens": manifest["tokens"], "created_utc": manifest["created_utc"],
"write_seconds": manifest.get("write_seconds")})