coderofpears commited on
Commit
31441cc
·
verified ·
1 Parent(s): 4e15292

publish portable stage runner + frozen sources

Browse files
Files changed (1) hide show
  1. pear15/cloud_checkpoint.py +338 -0
pear15/cloud_checkpoint.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Recoverable, single-writer checkpoints for local disks and Drive/FUSE mounts.
2
+
3
+ ``save_checkpoint(root, payload, keep_last=2)`` returns a unique snapshot directory.
4
+ Payload must be a dict with an integer ``step`` in 0..999999999999. Everything in
5
+ it is forwarded to torch.save: include model/optimizer/scheduler state_dicts,
6
+ Python and torch CPU/CUDA RNG states, counters and the data cursor yourself.
7
+ Only tensors and weights_only-compatible basic containers/scalars are supported;
8
+ encode NumPy RNG state as basic values/tensors rather than pickled NumPy objects.
9
+ Pause training while saving so the payload cannot change during serialization.
10
+
11
+ ``load_latest(root)`` returns ``(payload, info)`` or None. Tensors load onto CPU;
12
+ the caller restores training objects and RNGs. info is JSON-loggable and contains
13
+ path, step, manifest, and skipped [{path, reason}] recovery diagnostics. Rejected
14
+ snapshots also produce logger warnings, including when none can be recovered.
15
+ ``list_valid(root)`` returns fully verified directory Paths, newest first.
16
+
17
+ Each step_{step:012d}_{uuid_hex} directory contains checkpoint.pt, manifest.json,
18
+ and READY. Files are flushed/fsynced as .partial files before os.replace; READY
19
+ is written LAST and binds the manifest's SHA-256. The manifest binds the fixed
20
+ payload filename, size, digest, step, creation time and directory UUID. Recovery
21
+ scans directories, never a latest pointer, and verifies bytes AND weights-only
22
+ deserialization. Neither hardlinks, locks nor atomic directory operations are
23
+ needed. A process kill may leave partial files; these are ignored and preserved.
24
+ File fsync cannot guarantee a cloud provider has finished remote replication.
25
+
26
+ SINGLE WRITER REQUIRED: MUST NOT run two notebooks against the same RunDir.
27
+ Stop the old runtime before resuming in a new one. Readers should run between
28
+ saves; this is not a protocol for concurrent hostile filesystem mutation.
29
+ Symlinks/reparse points, including in root ancestors, are rejected.
30
+
31
+ Retention runs only after the new snapshot verifies. keep_last must be >= 2.
32
+ The newest keep_last valid snapshots and the newly saved snapshot are protected
33
+ (an out-of-order save can therefore temporarily exceed the limit). Only the
34
+ three known files of older complete, owned, verified snapshots are removed;
35
+ unknown files and incomplete/corrupt snapshots are never recursively deleted.
36
+ SHA-256 detects corruption, not malicious replacement/authenticity. No remote
37
+ code, unrestricted pickle fallback, or torch safe-global additions are used.
38
+ """
39
+
40
+ import hashlib
41
+ import json
42
+ import logging
43
+ import os
44
+ from pathlib import Path
45
+ import re
46
+ import stat
47
+ import time
48
+ import uuid
49
+
50
+
51
+ __all__ = ["save_checkpoint", "load_latest", "list_valid"]
52
+
53
+ _LOG = logging.getLogger(__name__)
54
+ _FORMAT = "pear15.cloud_checkpoint.v1"
55
+ _DIRECTORY = re.compile(r"step_([0-9]{12})_([0-9a-f]{32})\Z")
56
+ _DIGEST = re.compile(r"[0-9a-f]{64}\Z")
57
+ _FILES = ("READY", "manifest.json", "checkpoint.pt")
58
+ _FIELDS = {"format", "file", "sha256", "bytes", "step", "created_ns", "id"}
59
+ _CHUNK = 1024 * 1024
60
+
61
+
62
+ def _import_torch():
63
+ import torch
64
+ return torch
65
+
66
+
67
+ def _linked(status):
68
+ # Junctions and other Windows reparse points must not escape the RunDir.
69
+ return stat.S_ISLNK(status.st_mode) or bool(
70
+ getattr(status, "st_file_attributes", 0)
71
+ & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
72
+ )
73
+
74
+
75
+ def _directory(path):
76
+ status = path.lstat()
77
+ if _linked(status) or not stat.S_ISDIR(status.st_mode):
78
+ raise ValueError(f"not a plain directory (symlinks forbidden): {path}")
79
+
80
+
81
+ def _root(root, create=False):
82
+ # abspath deliberately does not resolve away symlinks before checking them.
83
+ path = Path(os.path.abspath(os.fspath(root)))
84
+ for parent in reversed((path, *path.parents)):
85
+ try:
86
+ _directory(parent)
87
+ except FileNotFoundError:
88
+ continue
89
+ if create:
90
+ path.mkdir(parents=True, exist_ok=True)
91
+ _directory(path)
92
+ return path
93
+
94
+
95
+ def _open_regular(path):
96
+ before = path.lstat()
97
+ if _linked(before) or not stat.S_ISREG(before.st_mode):
98
+ raise ValueError(f"not a plain file (symlinks forbidden): {path}")
99
+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0)
100
+ descriptor = os.open(path, flags)
101
+ try:
102
+ after = os.fstat(descriptor)
103
+ if not stat.S_ISREG(after.st_mode) or (before.st_dev, before.st_ino) != (after.st_dev, after.st_ino):
104
+ raise ValueError(f"file changed while opening: {path}")
105
+ handle = os.fdopen(descriptor, "rb")
106
+ except BaseException:
107
+ os.close(descriptor)
108
+ raise
109
+ return handle
110
+
111
+
112
+ def _small_file(path, limit):
113
+ with _open_regular(path) as handle:
114
+ content = handle.read(limit + 1)
115
+ if len(content) > limit:
116
+ raise ValueError(f"oversized metadata: {path.name}")
117
+ return content
118
+
119
+
120
+ def _json_object(pairs):
121
+ result = {}
122
+ for key, value in pairs:
123
+ if key in result:
124
+ raise ValueError(f"duplicate manifest field: {key}")
125
+ result[key] = value
126
+ return result
127
+
128
+
129
+ def _ready_bytes(manifest_bytes):
130
+ return (_FORMAT + "\n" + hashlib.sha256(manifest_bytes).hexdigest() + "\n").encode("ascii")
131
+
132
+
133
+ def _header(path):
134
+ _directory(path)
135
+ match = _DIRECTORY.fullmatch(path.name)
136
+ if match is None:
137
+ raise ValueError("not an owned checkpoint directory")
138
+ raw = _small_file(path / "manifest.json", 16384)
139
+ if _small_file(path / "READY", 256) != _ready_bytes(raw):
140
+ raise ValueError("incomplete or mismatched READY marker")
141
+ manifest = json.loads(raw, object_pairs_hook=_json_object)
142
+ if not isinstance(manifest, dict) or set(manifest) != _FIELDS:
143
+ raise ValueError("invalid manifest fields")
144
+ if manifest["format"] != _FORMAT or manifest["file"] != "checkpoint.pt":
145
+ raise ValueError("unsupported format or unsafe manifest file path")
146
+ if type(manifest["step"]) is not int or manifest["step"] != int(match[1]):
147
+ raise ValueError("manifest step does not match directory")
148
+ if manifest["id"] != match[2]:
149
+ raise ValueError("manifest id does not match directory")
150
+ if type(manifest["created_ns"]) is not int or manifest["created_ns"] < 0:
151
+ raise ValueError("invalid creation metadata")
152
+ if type(manifest["bytes"]) is not int or manifest["bytes"] <= 0:
153
+ raise ValueError("invalid payload byte count")
154
+ if not isinstance(manifest["sha256"], str) or not _DIGEST.fullmatch(manifest["sha256"]):
155
+ raise ValueError("invalid SHA-256 digest")
156
+ return {"path": str(path), "step": manifest["step"], "manifest": manifest}
157
+
158
+
159
+ def _reject(skipped, path, error):
160
+ entry = {"path": str(path), "reason": f"{type(error).__name__}: {error}"}
161
+ skipped.append(entry)
162
+ _LOG.warning("Skipping checkpoint %s: %s", entry["path"], entry["reason"])
163
+
164
+
165
+ def _headers(root, skipped):
166
+ root = _root(root)
167
+ try:
168
+ children = sorted(root.iterdir(), key=lambda path: path.name)
169
+ except FileNotFoundError:
170
+ return []
171
+ records = []
172
+ for path in children:
173
+ if not _DIRECTORY.fullmatch(path.name):
174
+ continue
175
+ try:
176
+ records.append(_header(path))
177
+ except Exception as exc:
178
+ _reject(skipped, path, exc)
179
+ # A UUID name is the final deterministic tie-breaker for equal timestamps.
180
+ records.sort(key=lambda item: (item["step"], item["manifest"]["created_ns"], item["path"]), reverse=True)
181
+ return records
182
+
183
+
184
+ def _digest_file(handle):
185
+ digest, size = hashlib.sha256(), 0
186
+ while True:
187
+ chunk = handle.read(_CHUNK)
188
+ if not chunk:
189
+ return digest.hexdigest(), size
190
+ digest.update(chunk)
191
+ size += len(chunk)
192
+
193
+
194
+ def _load_record(torch, record):
195
+ path, manifest = Path(record["path"]), record["manifest"]
196
+ _directory(path)
197
+ with _open_regular(path / "checkpoint.pt") as handle:
198
+ if os.fstat(handle.fileno()).st_size != manifest["bytes"]:
199
+ raise ValueError("payload size mismatch")
200
+ digest, size = _digest_file(handle)
201
+ if size != manifest["bytes"] or digest != manifest["sha256"]:
202
+ raise ValueError("payload SHA-256/size mismatch")
203
+ handle.seek(0)
204
+ payload = torch.load(handle, map_location="cpu", weights_only=True)
205
+ if not isinstance(payload, dict) or type(payload.get("step")) is not int or payload["step"] != record["step"]:
206
+ raise ValueError("payload step does not match manifest")
207
+ return payload
208
+
209
+
210
+ def load_latest(root):
211
+ """Return (unchanged payload, JSON-loggable info), falling back on corruption."""
212
+ skipped = []
213
+ records = _headers(root, skipped)
214
+ if not records:
215
+ return None
216
+ torch = _import_torch() # Missing/broken torch is an environment error, not corruption.
217
+ for record in records:
218
+ try:
219
+ payload = _load_record(torch, record)
220
+ except Exception as exc:
221
+ _reject(skipped, record["path"], exc)
222
+ continue
223
+ return payload, {**record, "skipped": skipped}
224
+ return None
225
+
226
+
227
+ def _valid_records(records, torch, skipped):
228
+ valid = []
229
+ for record in records:
230
+ try:
231
+ # Do not retain model/optimizer tensors from multiple snapshots in RAM.
232
+ payload = _load_record(torch, record)
233
+ del payload
234
+ except Exception as exc:
235
+ _reject(skipped, record["path"], exc)
236
+ else:
237
+ valid.append(record)
238
+ return valid, skipped
239
+
240
+
241
+ def list_valid(root):
242
+ """Fully verify snapshots and return Paths ordered by step, creation, then UUID."""
243
+ # Empty/missing roots do not require PyTorch to be installed.
244
+ skipped = []
245
+ records = _headers(root, skipped)
246
+ if not records:
247
+ return []
248
+ records, _ = _valid_records(records, _import_torch(), skipped)
249
+ return [Path(record["path"]) for record in records]
250
+
251
+
252
+ def _flush(handle):
253
+ handle.flush()
254
+ os.fsync(handle.fileno())
255
+
256
+
257
+ def _write_file(path, content):
258
+ partial = path.with_name(path.name + ".partial")
259
+ with partial.open("xb") as handle:
260
+ handle.write(content)
261
+ _flush(handle)
262
+ os.replace(partial, path)
263
+
264
+
265
+ def _invalidate(path):
266
+ try:
267
+ marker = path / "READY"
268
+ status = marker.lstat()
269
+ if not _linked(status) and stat.S_ISREG(status.st_mode):
270
+ marker.unlink()
271
+ except FileNotFoundError:
272
+ pass
273
+ except OSError as exc:
274
+ _LOG.warning("Could not remove failed checkpoint marker %s: %s", path, exc)
275
+
276
+
277
+ def _prune(records, keep_last, new_path):
278
+ protected = {record["path"] for record in records[:keep_last]} | {str(new_path)}
279
+ for record in records:
280
+ if record["path"] in protected:
281
+ continue
282
+ path = Path(record["path"])
283
+ try:
284
+ # Recheck ownership/completeness immediately before touching known files.
285
+ if _header(path) != record:
286
+ continue
287
+ for name in _FILES:
288
+ with _open_regular(path / name):
289
+ pass
290
+ # Invalidate first. An interrupted cleanup can never look complete.
291
+ for name in _FILES:
292
+ (path / name).unlink()
293
+ if not any(path.iterdir()):
294
+ path.rmdir()
295
+ except (OSError, ValueError) as exc:
296
+ _LOG.warning("Could not prune checkpoint %s: %s", path, exc)
297
+
298
+
299
+ def save_checkpoint(root, payload, keep_last=2):
300
+ """Publish and verify a unique snapshot, then conservatively retain >=2 copies.
301
+
302
+ Serialization/I/O/verification failures propagate; failed snapshots have no
303
+ READY marker and previous snapshots are untouched. Partial debris is retained
304
+ for diagnosis. Exceptions after commit during retention may leave extra copies.
305
+ """
306
+ if not isinstance(payload, dict) or type(payload.get("step")) is not int or not 0 <= payload["step"] < 10**12:
307
+ raise ValueError("payload must be a dict with integer step in 0..999999999999")
308
+ if type(keep_last) is not int or keep_last < 2:
309
+ raise ValueError("keep_last must be an integer >= 2")
310
+ torch = _import_torch()
311
+ root = _root(root, create=True)
312
+ identifier = uuid.uuid4().hex
313
+ path = root / f"step_{payload['step']:012d}_{identifier}"
314
+ path.mkdir() # Exclusive unique name, not an atomic directory publication.
315
+ try:
316
+ partial = path / "checkpoint.pt.partial"
317
+ with partial.open("xb") as handle:
318
+ torch.save(payload, handle)
319
+ _flush(handle)
320
+ os.replace(partial, path / "checkpoint.pt")
321
+ with _open_regular(path / "checkpoint.pt") as handle:
322
+ digest, size = _digest_file(handle)
323
+ manifest = {"format": _FORMAT, "file": "checkpoint.pt", "sha256": digest,
324
+ "bytes": size, "step": payload["step"], "created_ns": time.time_ns(), "id": identifier}
325
+ raw = json.dumps(manifest, sort_keys=True, allow_nan=False).encode("utf-8")
326
+ _write_file(path / "manifest.json", raw)
327
+ _write_file(path / "READY", _ready_bytes(raw))
328
+ # Verify deserialization as well as on-mount checksums before any retention.
329
+ skipped = []
330
+ records, skipped = _valid_records(_headers(root, skipped), torch, skipped)
331
+ if not any(record["path"] == str(path) for record in records):
332
+ reason = next((item["reason"] for item in skipped if item["path"] == str(path)), "snapshot disappeared")
333
+ raise ValueError(f"new checkpoint failed verification: {reason}")
334
+ except BaseException:
335
+ _invalidate(path) # Includes KeyboardInterrupt and ENOSPC, even after marker publication.
336
+ raise
337
+ _prune(records, keep_last, path)
338
+ return path