File size: 12,150 Bytes
47283f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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")})