File size: 35,640 Bytes
b2a6e0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
"""Pretrain RecurrentGraphLM (A100_40GB preset) on FineWeb-Edu GPT-2 shards in Colab.

Each run trains for at most `session_minutes`, pushes checkpoints and metrics to a
Hugging Face model repo, and on the next run resumes from that repo, continuing on
data the checkpointed model has not seen. Training is stateful TBPTT: each batch row
is a contiguous token stream, and the detached GraphMemory carry persists between
updates, so the long-memory heads see context beyond one window.

Settings: edit CFG below, or pass a JSON dict of overrides in $RG_CFG_JSON.
"""

import gc
import json
import math
import os
import queue
import shutil
import sys
import threading
import time
import traceback

os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")

import numpy as np
import torch
from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download

import recurrent_graph as rg
from recurrent_graph import A100_40GB, RecurrentGraphLM, optimizer_groups

CFG = dict(
    repo_name="RecurrentGraphLM-fineweb-edu",  # created as <your HF user>/<repo_name>
    private=False,
    data_repo="kjj0/finewebedu10B-gpt2",  # modded-nanogpt shards: 99 train (~9.9B tokens) + 1 val
    vocab_size=50304,
    seq_len=1024,          # TBPTT window; memory carries across windows
    rows=64,               # parallel token streams = global batch rows (65.5K tokens per update)
    micro_rows=16,         # rows per forward/backward; lowered automatically on OOM
    lr=1e-3,
    base_fan_in=512,       # optimizer_groups: scales lr down for wider inputs (encoder, 4096-in readout)
    weight_decay=0.1,
    betas=(0.9, 0.95),
    grad_clip=1.0,
    warmup_steps=500,
    total_tokens=2_000_000_000,  # schedule length; linear cooldown to 0 over the last cooldown_frac
    cooldown_frac=0.2,
    session_minutes=115,   # wall clock of train.py, including setup and the final upload
    reserve_minutes=6,     # stop training this long before the session limit
    eval_every_minutes=15,
    ckpt_every_minutes=30,
    log_every=20,          # updates
    val_rows=16,           # validation: 16 streams x 128 windows x 1024 = 2.1M tokens, memory carried
    val_chunks=128,
    ce_chunk=4096,         # tokens per vocabulary-projection chunk
    seed=1337,
    work_dir="/content/rg_run",
    data_dir="/content/fineweb_edu",
)
MODEL_CFG = dict(A100_40GB)
CFG.update(json.loads(os.environ.get("RG_CFG_JSON") or "{}"))
MODEL_CFG.update(json.loads(os.environ.get("RG_MODEL_JSON") or "{}"))

CKPT_PATH = "checkpoints/latest.pt"
# Training FLOPs per token quoted in recurrent_graph.py for the A100_40GB preset at vocab 50304.
FLOPS_PER_TOKEN = 675e6 if (MODEL_CFG == A100_40GB and CFG["vocab_size"] == 50304) else None
PEAK_BF16 = {"H100": 989e12, "H200": 989e12, "A100": 312e12, "L4": 121e12, "A10": 125e12}


class Log:
    def __init__(self):
        self.file = None
        self.path = None

    def open(self, path):
        self.path = path
        self.file = open(path, "a", buffering=1)

    def __call__(self, *parts):
        line = time.strftime("[%H:%M:%S] ") + " ".join(str(p) for p in parts)
        print(line, flush=True)
        if self.file:
            self.file.write(line + "\n")


log = Log()


def fmt_time(seconds):
    seconds = int(max(seconds, 0))
    return f"{seconds // 3600}:{seconds % 3600 // 60:02d}:{seconds % 60:02d}"


# ----------------------------------------------------------------------------- uploads

class Uploader:
    """One background thread, so commits never race and training never waits on the network."""

    class Job:
        def __init__(self, files, message, delete_after):
            self.files, self.message, self.delete_after = files, message, delete_after
            self.done = threading.Event()
            self.ok = False

    def __init__(self, api, repo_id):
        self.api, self.repo_id = api, repo_id
        self.jobs = queue.Queue()
        threading.Thread(target=self._run, daemon=True).start()

    def submit(self, files, message, delete_after=()):
        job = self.Job(files, message, delete_after)
        self.jobs.put(job)
        return job

    def _run(self):
        while True:
            job = self.jobs.get()
            try:
                for attempt in range(5):
                    try:
                        ops = [CommitOperationAdd(path_in_repo=r, path_or_fileobj=l) for l, r in job.files]
                        self.api.create_commit(self.repo_id, ops, commit_message=job.message)
                        job.ok = True
                        break
                    except Exception as error:
                        log(f"upload '{job.message}' failed ({attempt + 1}/5): {error!r}")
                        if attempt < 4:
                            time.sleep(15 * 2**attempt)
                if job.ok:
                    for path in job.delete_after:
                        shutil.rmtree(path, ignore_errors=True) if os.path.isdir(path) else _remove(path)
            finally:
                job.done.set()
                self.jobs.task_done()

    def wait(self):
        self.jobs.join()


def _remove(path):
    try:
        os.remove(path)
    except OSError:
        pass


# ----------------------------------------------------------------------------- data

def fetch_data(name):
    return hf_hub_download(CFG["data_repo"], name, repo_type="dataset", local_dir=CFG["data_dir"])


def read_shard(path):
    header = np.fromfile(path, dtype=np.int32, count=256)
    if header.size != 256 or header[0] != 20240520 or header[1] != 1:
        raise ValueError(f"{path} is not a modded-nanogpt token shard")
    count = int(header[2])
    tokens = np.fromfile(path, dtype=np.uint16, count=count, offset=256 * 4)
    if tokens.size != count:
        raise ValueError(f"{path} is truncated")
    return tokens


class StreamLoader:
    """Each shard is cut into `rows` contiguous slices; row r walks slice r window by window.

    State (shard_index, window) fully determines the next batch, so a resumed run
    continues exactly after the last update the checkpointed model trained on.
    """

    def __init__(self, shards, rows, seq_len, shard_index=0, window=0):
        self.shards, self.rows, self.seq_len = shards, rows, seq_len
        self.shard_index, self.window = shard_index, window
        self.offsets = np.arange(seq_len + 1, dtype=np.int64)
        self._open()

    def _open(self):
        self.tokens = None
        if self.shard_index >= len(self.shards):
            return
        self.tokens = read_shard(fetch_data(self.shards[self.shard_index]))
        span = (self.tokens.size - 1) // self.rows
        self.starts = np.arange(self.rows, dtype=np.int64)[:, None] * span
        self.windows = span // self.seq_len
        following = self.shard_index + 1
        if following < len(self.shards):  # download the next shard while this one trains
            name = self.shards[following]
            threading.Thread(target=lambda: _quiet(fetch_data, name), daemon=True).start()

    def next(self):
        while self.tokens is not None and self.window >= self.windows:
            self.shard_index, self.window = self.shard_index + 1, 0
            self._open()
        if self.tokens is None:
            return None
        index = self.starts + self.window * self.seq_len + self.offsets
        self.window += 1
        return torch.from_numpy(self.tokens[index].astype(np.int64))

    def state(self):
        return dict(shard_index=self.shard_index, window=self.window)

    def where(self):
        if self.tokens is None:
            return "data exhausted"
        return f"shard {self.shard_index + 1}/{len(self.shards)} {100 * self.window / max(self.windows, 1):.0f}%"


def _quiet(fn, *args):
    try:
        fn(*args)
    except Exception as error:
        log(f"prefetch failed (will retry when needed): {error!r}")


# ----------------------------------------------------------------------------- loss

class LinearCrossEntropy(torch.autograd.Function):
    """Mean cross entropy of hidden @ weight.T + bias without materializing all logits.

    Gradients are computed chunk by chunk during forward, so peak memory is one
    [chunk, vocab] block instead of several [tokens, vocab] tensors, with no recompute.
    """

    @staticmethod
    def forward(ctx, hidden, weight, bias, targets, chunk):
        count = hidden.size(0)
        w = weight.to(torch.bfloat16)
        h = hidden.to(torch.bfloat16)
        b = bias.float()
        grad_h = torch.empty_like(h)
        grad_w = torch.zeros(weight.shape, dtype=torch.float32, device=weight.device)
        grad_b = torch.zeros(bias.shape, dtype=torch.float32, device=bias.device)
        total = torch.zeros((), dtype=torch.float32, device=hidden.device)
        for start in range(0, count, chunk):
            hc, tc = h[start:start + chunk], targets[start:start + chunk]
            logits = (hc @ w.t()).float() + b
            lse = logits.logsumexp(-1)
            total += (lse - logits.gather(1, tc[:, None]).squeeze(1)).sum()
            probs = logits.sub_(lse[:, None]).exp_()
            probs[torch.arange(tc.size(0), device=tc.device), tc] -= 1
            probs.mul_(1.0 / count)
            grad_b += probs.sum(0)
            g = probs.to(torch.bfloat16)
            grad_h[start:start + chunk] = g @ w
            grad_w += (g.t() @ hc).float()
            del logits, probs, g
        ctx.save_for_backward(grad_h, grad_w, grad_b)
        ctx.hidden_dtype = hidden.dtype
        return total / count

    @staticmethod
    def backward(ctx, grad_out):
        grad_h, grad_w, grad_b = ctx.saved_tensors
        return (grad_h * grad_out).to(ctx.hidden_dtype), grad_w * grad_out, grad_b * grad_out, None, None


@torch.no_grad()
def cross_entropy_sum(hidden, weight, bias, targets, chunk):
    w, b, total = weight.to(torch.bfloat16), bias.float(), 0.0
    h = hidden.to(torch.bfloat16)
    for start in range(0, h.size(0), chunk):
        logits = (h[start:start + chunk] @ w.t()).float() + b
        tc = targets[start:start + chunk]
        total += (logits.logsumexp(-1) - logits.gather(1, tc[:, None]).squeeze(1)).sum().item()
    return total


# ----------------------------------------------------------------------------- reporting

def plot_curves(metrics, path):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    train = [m for m in metrics if m["type"] == "train"]
    val = [m for m in metrics if m["type"] == "val"]
    fig, (ax_loss, ax_speed) = plt.subplots(1, 2, figsize=(12, 4.2))
    if train:
        x = np.array([m["tokens"] for m in train]) / 1e9
        y = np.array([m["loss"] for m in train])
        ax_loss.plot(x, y, color="#9bb7d4", lw=0.8, label="train")
        if len(y) > 10:
            k = min(25, len(y) // 5)
            smooth = np.convolve(y, np.ones(k) / k, mode="valid")
            ax_loss.plot(x[k - 1:], smooth, color="#1f5fa8", lw=1.6, label=f"train ({k}-pt mean)")
        ax_speed.plot(x, [m["tok_per_s"] / 1e3 for m in train], color="#2a8c5a", lw=1)
    if val:
        xv = np.array([m["tokens"] for m in val]) / 1e9
        ax_loss.plot(xv, [m["val_loss"] for m in val], "o-", color="#c0392b", ms=3, label="val")
        ax_loss.plot(xv, [m["val_loss_first"] for m in val], "--", color="#e08e79", lw=1,
                     label="val, first window (no memory)")
    if train or val:
        low = min([m["loss"] for m in train[len(train) // 10:]] + [m["val_loss"] for m in val] or [2.5])
        ax_loss.set_ylim(max(low - 0.3, 0), min(low + 3.5, 11.5))
    ax_loss.set(xlabel="tokens (B)", ylabel="loss (nats)", title="Loss")
    ax_loss.grid(alpha=0.3)
    ax_loss.legend(fontsize=8)
    ax_speed.set(xlabel="tokens (B)", ylabel="K tokens/s", title="Throughput")
    ax_speed.grid(alpha=0.3)
    fig.tight_layout()
    fig.savefig(path, dpi=110)
    plt.close(fig)


def readme(repo_id, info, metrics):
    train = [m for m in metrics if m["type"] == "train"]
    val = [m for m in metrics if m["type"] == "val"]
    rows = [("tokens seen", f"{info['tokens'] / 1e9:.3f} B ({100 * info['tokens'] / CFG['total_tokens']:.1f}% of schedule)"),
            ("updates", f"{info['step']:,}"), ("sessions", info["session"]),
            ("data position", info["where"]), ("updated", time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime()))]
    if train:
        rows += [("train loss", f"{train[-1]['loss']:.4f}"), ("tokens/s", f"{train[-1]['tok_per_s']:,.0f}")]
        if train[-1].get("mfu") is not None:
            rows.append(("MFU (approx.)", f"{100 * train[-1]['mfu']:.1f}%"))
    if val:
        best = min(m["val_loss"] for m in val)
        rows += [("val loss", f"{val[-1]['val_loss']:.4f} (best {best:.4f})"),
                 ("val loss, first window", f"{val[-1]['val_loss_first']:.4f}")]
    table = "\n".join(f"| {k} | {v} |" for k, v in rows)
    status = "complete" if info.get("complete") else "in progress"
    return f"""---
tags: [recurrent, language-model, fineweb-edu]
datasets: [HuggingFaceFW/fineweb-edu]
---
# {repo_id.split('/')[-1]}

`RecurrentGraphLM(50304, **A100_40GB)` ({info['params'] / 1e6:.1f}M parameters) pretrained from scratch on
FineWeb-Edu (GPT-2 tokens, `{CFG['data_repo']}`). Training is **{status}**; this card is rewritten by the
training script at every evaluation.

| | |
|---|---|
{table}

![training curves](plots/curves.png)

Stateful TBPTT: {info['rows']} contiguous streams x {info['seq_len']}-token windows per update, memory carried
(detached) across windows. Validation streams {CFG['val_rows'] * CFG['val_chunks'] * info['seq_len'] / 1e6:.1f}M val
tokens the same way from an empty memory; "first window" is the loss before any memory has accumulated.
AdamW, lr {CFG['lr']} (fan-in scaled from {CFG['base_fan_in']}), warmup {CFG['warmup_steps']} updates, linear cooldown
over the last {int(100 * CFG['cooldown_frac'])}% of {CFG['total_tokens'] / 1e9:.1f}B tokens.
Full metrics: `metrics.jsonl`. Logs: `logs/`.

```python
import sys, torch
from huggingface_hub import hf_hub_download
sys.path.insert(0, hf_hub_download("{repo_id}", "recurrent_graph.py").rsplit("/", 1)[0])
from recurrent_graph import RecurrentGraphLM, A100_40GB
ckpt = torch.load(hf_hub_download("{repo_id}", "{CKPT_PATH}"), map_location="cpu", weights_only=False)
model = RecurrentGraphLM(50304, **A100_40GB)
model.load_state_dict(ckpt["model"])
```
Earlier checkpoints are in the commit history of `{CKPT_PATH}`.
"""


# ----------------------------------------------------------------------------- training

class Trainer:
    def __init__(self, t_start):
        self.t_start = t_start
        self.deadline = t_start + (CFG["session_minutes"] - CFG["reserve_minutes"]) * 60
        self.work = CFG["work_dir"]
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.dirty = False      # trained since the last saved checkpoint
        self.status = dict(safe_to_disconnect=False, reason="setup")
        self.uploader = None
        self.stage_count = 0

    # --- setup

    def setup(self):
        device = self.device
        if device.type == "cuda":
            name = torch.cuda.get_device_name()
            if not torch.cuda.is_bf16_supported():
                raise RuntimeError(f"{name} has no bf16 support; pick an A100/L4/H100 runtime")
            total = torch.cuda.get_device_properties(0).total_memory / 2**30
            log(f"GPU: {name}, {total:.0f} GiB")
            torch.backends.cuda.matmul.allow_tf32 = True
            torch.backends.cudnn.allow_tf32 = True
            self.peak = next((v for k, v in PEAK_BF16.items() if k in name), None)
        else:
            log("WARNING: no GPU, running on CPU (only useful for testing)")
            self.peak = None
        fla = rg._fla_delta_rule is not None
        log(f"fla kernels: {'available' if fla else 'NOT available, using the PyTorch scans (slower)'}")

        token = os.environ.get("HF_TOKEN") or None
        api = HfApi(token=token)
        user = api.whoami()["name"]
        self.repo_id = f"{user}/{CFG['repo_name']}"
        api.create_repo(self.repo_id, private=CFG["private"], exist_ok=True)
        log(f"repo: https://huggingface.co/{self.repo_id}")
        self.api = api
        self.uploader = Uploader(api, self.repo_id)

        ckpt = None
        if api.file_exists(self.repo_id, CKPT_PATH):
            log("found checkpoint on the Hub, downloading")
            path = hf_hub_download(self.repo_id, CKPT_PATH, local_dir=os.path.join(self.work, "resume"))
            ckpt = torch.load(path, map_location="cpu", weights_only=False)
        self.metrics = []
        if ckpt is not None and api.file_exists(self.repo_id, "metrics.jsonl"):
            path = hf_hub_download(self.repo_id, "metrics.jsonl", local_dir=os.path.join(self.work, "resume"))
            with open(path) as f:  # drop entries logged after the checkpoint we resume from
                self.metrics = [m for m in map(json.loads, filter(str.strip, f)) if m["tokens"] <= ckpt["tokens"]]
        self.metrics_path = os.path.join(self.work, "metrics.jsonl")
        with open(self.metrics_path, "w") as f:
            f.writelines(json.dumps(m) + "\n" for m in self.metrics)

        if ckpt is not None and ckpt.get("complete"):
            log(f"training already complete at {ckpt['tokens'] / 1e9:.2f}B tokens; nothing to do")
            self.status = dict(safe_to_disconnect=True, reason="already complete")
            return False

        self.rows = ckpt["rows"] if ckpt else CFG["rows"]
        self.seq_len = ckpt["seq_len"] if ckpt else CFG["seq_len"]
        if ckpt and (self.rows, self.seq_len) != (CFG["rows"], CFG["seq_len"]):
            log(f"keeping rows={self.rows}, seq_len={self.seq_len} from the checkpoint so data order is preserved")

        torch.manual_seed(CFG["seed"])
        model = RecurrentGraphLM(CFG["vocab_size"], **MODEL_CFG).to(device)
        groups = optimizer_groups(model, CFG["weight_decay"], lr=CFG["lr"], base_fan_in=CFG["base_fan_in"])
        self.group_defaults = [(g["lr"], g["weight_decay"]) for g in groups]
        opt = torch.optim.AdamW(groups, betas=tuple(CFG["betas"]), eps=1e-8, fused=device.type == "cuda")

        files = api.list_repo_files(CFG["data_repo"], repo_type="dataset")
        shards = sorted(f for f in files if f.startswith("finewebedu_train_") and f.endswith(".bin"))
        val_name = sorted(f for f in files if f.startswith("finewebedu_val_") and f.endswith(".bin"))[0]

        if ckpt:
            model.load_state_dict(ckpt["model"])
            opt.load_state_dict(ckpt["optimizer"])
            self.step, self.tokens, self.session = ckpt["step"], ckpt["tokens"], ckpt["session"] + 1
            self.loader = StreamLoader(shards, self.rows, self.seq_len, **ckpt["data"])
            log(f"resumed: step {self.step:,}, {self.tokens / 1e9:.3f}B tokens, session {self.session}, "
                f"{self.loader.where()}")
        else:
            self.step, self.tokens, self.session = 0, 0, 1
            self.loader = StreamLoader(shards, self.rows, self.seq_len)
            counts = np.bincount(self.loader.tokens, minlength=CFG["vocab_size"])[:CFG["vocab_size"]]
            model.init_output_prior(torch.from_numpy(counts))
            log("fresh start: output bias set to the unigram prior of the first train shard")
        for group, (lr, wd) in zip(opt.param_groups, self.group_defaults):
            group["lr"], group["weight_decay"] = lr, wd
        self.model, self.opt = model, opt
        self.params = list(model.parameters())
        self.params_count = sum(p.numel() for p in self.params)
        log(f"model: {self.params_count / 1e6:.1f}M parameters; {self.rows} rows x {self.seq_len} tokens "
            f"= {self.rows * self.seq_len:,} tokens/update")

        span = CFG["val_chunks"] * self.seq_len
        val = read_shard(fetch_data(val_name))
        index = np.arange(CFG["val_rows"], dtype=np.int64)[:, None] * span + np.arange(span + 1)
        self.val = torch.from_numpy(val[index].astype(np.int64)).to(device)

        # Ladder of (micro_rows, recompute) settings tried in order when memory runs out.
        sizes = [m for m in (CFG["micro_rows"] >> i for i in range(8)) if m >= 1 and self.rows % m == 0]
        no_recompute = [m for m in sizes if m >= 4] or sizes[:1]
        self.ladder = [(m, False) for m in no_recompute] + [(m, True) for m in sizes]
        rung = ckpt.get("rung", 0) if ckpt else 0
        self.rung = min(rung, len(self.ladder) - 1)
        self._apply_rung()
        self.fla_fallback_used = False
        self.carries = None

        self.push_code()
        return True

    def _apply_rung(self):
        self.micro, recompute = self.ladder[self.rung]
        self.model.graph.checkpoint_steps = recompute
        self.carries = None

    # --- one update

    def lr_mult(self):
        if self.step < CFG["warmup_steps"]:
            return (self.step + 1) / CFG["warmup_steps"]
        total = CFG["total_tokens"]
        cooldown_start = total * (1 - CFG["cooldown_frac"])
        if self.tokens < cooldown_start:
            return 1.0
        return max(0.0, (total - self.tokens) / max(total - cooldown_start, 1))

    def update(self, batch):
        model, micro = self.model, self.micro
        groups = self.rows // micro
        carries = self.carries or [None] * groups
        inputs, targets = batch[:, :-1], batch[:, 1:]
        weight, bias = model.graph.readout.weight, model.graph.readout.bias
        self.opt.zero_grad(set_to_none=True)
        total = torch.zeros((), device=self.device)
        new_carries = []
        for g in range(groups):
            rows = slice(g * micro, (g + 1) * micro)
            with torch.autocast(self.device.type, dtype=torch.bfloat16):
                state, memory = model.encode_chunk(inputs[rows], carries[g])
                hidden = model.graph.pool(state)
            del state
            loss = LinearCrossEntropy.apply(hidden.flatten(0, 1), weight, bias,
                                            targets[rows].reshape(-1), CFG["ce_chunk"])
            (loss / groups).backward()
            new_carries.append(memory.detach())
            total += loss.detach()
            del hidden, loss, memory
        loss = (total / groups).item()
        grad_norm = torch.nn.utils.clip_grad_norm_(self.params, CFG["grad_clip"]).item()
        if not (math.isfinite(loss) and math.isfinite(grad_norm)):
            self.opt.zero_grad(set_to_none=True)
            self.carries = None
            return loss, grad_norm, False
        self.carries = new_carries
        mult = self.lr_mult()
        for group, (lr, _) in zip(self.opt.param_groups, self.group_defaults):
            group["lr"] = lr * mult
        self.opt.step()
        return loss, grad_norm, True

    def _free(self):
        self.opt.zero_grad(set_to_none=True)
        gc.collect()
        if self.device.type == "cuda":
            torch.cuda.empty_cache()

    def robust_update(self, batch):
        while True:
            try:
                return self.update(batch)
            except torch.cuda.OutOfMemoryError:
                self._free()
                if self.rung + 1 >= len(self.ladder):
                    raise
                self.rung += 1
                self._apply_rung()
                log(f"out of memory -> micro_rows={self.micro}, recompute={self.model.graph.checkpoint_steps}")
            except Exception as error:
                uses_fla = (self.device.type == "cuda" and rg._fla_delta_rule is not None
                            and self.model.graph.memory_backend != "torch")
                if not uses_fla or self.fla_fallback_used:
                    raise
                self._free()
                self.fla_fallback_used = True
                self.model.graph.memory_backend = "torch"
                self.carries = None
                log(f"fla kernel failed ({error!r}); switching to the PyTorch delta scan")

    # --- evaluation

    @torch.no_grad()
    def evaluate(self):
        model, T, chunks = self.model, self.seq_len, CFG["val_chunks"]
        weight, bias = model.graph.readout.weight, model.graph.readout.bias
        rows = self.val.size(0)
        micro = min(self.micro, rows)
        per_window = np.zeros(chunks)
        for start in range(0, rows, micro):
            stream = self.val[start:start + micro]
            carry = None
            for c in range(chunks):
                window = stream[:, c * T:c * T + T + 1]
                with torch.autocast(self.device.type, dtype=torch.bfloat16):
                    state, carry = model.encode_chunk(window[:, :-1], carry)
                    hidden = model.graph.pool(state)
                per_window[c] += cross_entropy_sum(hidden.flatten(0, 1), weight, bias,
                                                   window[:, 1:].reshape(-1), CFG["ce_chunk"])
                del state, hidden
        per_window /= rows * T
        return float(per_window.mean()), float(per_window[0])

    def run_eval(self):
        t0 = time.time()
        try:
            val_loss, val_first = self.evaluate()
        except Exception as error:  # never let evaluation kill a night of training
            self._free()
            log(f"evaluation failed: {error!r}")
            return
        record = dict(type="val", step=self.step, tokens=self.tokens, val_loss=val_loss,
                      val_loss_first=val_first, time=time.time())
        self.record(record)
        log(f"VAL step {self.step:,} | {self.tokens / 1e9:.3f}B tok | val loss {val_loss:.4f} "
            f"| first window {val_first:.4f} | {time.time() - t0:.0f}s")

    # --- persistence

    def record(self, entry):
        self.metrics.append(entry)
        with open(self.metrics_path, "a") as f:
            f.write(json.dumps(entry) + "\n")

    def info(self, complete=False):
        return dict(step=self.step, tokens=self.tokens, session=self.session, where=self.loader.where(),
                    params=self.params_count, rows=self.rows, seq_len=self.seq_len, complete=complete)

    def stage_reports(self, complete=False):
        """Snapshot metrics, card, plot and log into a fresh folder the uploader owns."""
        self.stage_count += 1
        stage = os.path.join(self.work, "stage", str(self.stage_count))
        os.makedirs(os.path.join(stage, "plots"), exist_ok=True)
        files = []
        shutil.copy(self.metrics_path, os.path.join(stage, "metrics.jsonl"))
        files.append((os.path.join(stage, "metrics.jsonl"), "metrics.jsonl"))
        with open(os.path.join(stage, "README.md"), "w") as f:
            f.write(readme(self.repo_id, self.info(complete), self.metrics))
        files.append((os.path.join(stage, "README.md"), "README.md"))
        try:
            plot_curves(self.metrics, os.path.join(stage, "plots", "curves.png"))
            files.append((os.path.join(stage, "plots", "curves.png"), "plots/curves.png"))
        except Exception as error:
            log(f"plot failed: {error!r}")
        if log.path:
            shutil.copy(log.path, os.path.join(stage, "session.log"))
            files.append((os.path.join(stage, "session.log"), f"logs/{os.path.basename(log.path)}"))
        return stage, files

    def push_reports(self, message):
        stage, files = self.stage_reports()
        return self.uploader.submit(files, message, delete_after=[stage])

    def push_code(self):
        stage = os.path.join(self.work, "stage", "code")
        os.makedirs(stage, exist_ok=True)
        with open(os.path.join(stage, "config.json"), "w") as f:
            json.dump(dict(model=MODEL_CFG, vocab_size=CFG["vocab_size"], train=CFG), f, indent=2)
        files = [(rg.__file__, "recurrent_graph.py"), (os.path.abspath(__file__), "train.py"),
                 (os.path.join(stage, "config.json"), "config.json")]
        self.uploader.submit(files, f"session {self.session}: code and config")

    def save_checkpoint(self, complete=False, final=False):
        if not all(torch.isfinite(p).all() for p in self.params):
            log("parameters are not finite; NOT saving a checkpoint")
            return None
        path = os.path.join(self.work, f"ckpt_step{self.step}.pt")
        torch.save(dict(model=self.model.state_dict(), optimizer=self.opt.state_dict(), step=self.step,
                        tokens=self.tokens, session=self.session, data=self.loader.state(), rows=self.rows,
                        seq_len=self.seq_len, rung=self.rung, complete=complete, cfg=CFG, model_cfg=MODEL_CFG),
                   path + ".tmp")
        os.replace(path + ".tmp", path)
        self.dirty = False
        stage, files = self.stage_reports(complete)
        files.append((path, CKPT_PATH))
        message = f"step {self.step} ({self.tokens / 1e9:.3f}B tokens){' final' if final else ''}"
        log(f"checkpoint saved locally, uploading in the background: {message}")
        return self.uploader.submit(files, message, delete_after=[stage] + ([] if final else [path]))

    # --- main loop

    def train(self):
        now = time.time()
        last_eval = last_ckpt = now
        window_tokens, window_time, window_loss, window_n = 0, 0.0, 0.0, 0
        bad_in_a_row = 0
        complete, reason = False, "time limit"
        log(f"training until {time.strftime('%H:%M', time.localtime(self.deadline))} "
            f"({fmt_time(self.deadline - now)}); first updates include kernel compilation")
        while True:
            if time.time() >= self.deadline:
                break
            if self.tokens >= CFG["total_tokens"]:
                complete, reason = True, "token budget reached"
                break
            batch = self.loader.next()
            if batch is None:
                complete, reason = True, "dataset exhausted"
                break
            t0 = time.time()
            loss, grad_norm, ok = self.robust_update(batch.to(self.device, non_blocking=True))
            elapsed = time.time() - t0
            self.step += 1
            self.tokens += self.rows * self.seq_len
            self.dirty = True
            if self.step == 1 or (self.step <= 3 and elapsed > 5):
                peak = torch.cuda.max_memory_allocated() / 2**30 if self.device.type == "cuda" else 0
                log(f"update {self.step}: {elapsed:.1f}s, peak memory {peak:.1f} GiB, "
                    f"micro_rows={self.micro}, recompute={self.model.graph.checkpoint_steps}")
            if not ok:
                bad_in_a_row += 1
                log(f"non-finite loss/grad at step {self.step} (loss {loss}, grad norm {grad_norm}); update skipped")
                if bad_in_a_row >= 20:
                    reason = "diverged (20 non-finite updates in a row)"
                    self.dirty = False  # never save over the last good checkpoint
                    break
                continue
            bad_in_a_row = 0
            if self.step > 3:  # leave compilation out of the throughput numbers
                window_tokens += self.rows * self.seq_len
                window_time += elapsed
            window_loss += loss
            window_n += 1
            if self.step % CFG["log_every"] == 0:
                tok_s = window_tokens / window_time if window_time else 0.0
                mfu = tok_s * FLOPS_PER_TOKEN / self.peak if (FLOPS_PER_TOKEN and self.peak) else None
                entry = dict(type="train", step=self.step, tokens=self.tokens, loss=window_loss / window_n,
                             lr=self.opt.param_groups[0]["lr"], grad_norm=grad_norm, tok_per_s=tok_s, mfu=mfu,
                             time=time.time())
                self.record(entry)
                left = self.deadline - time.time()
                log(f"step {self.step:,} | {self.tokens / 1e6:,.1f}M tok | loss {entry['loss']:.4f} "
                    f"| lr {entry['lr']:.2e} | gnorm {grad_norm:.2f} | {tok_s / 1e3:.1f}K tok/s"
                    + (f" | mfu {100 * mfu:.1f}%" if mfu is not None else "")
                    + f" | {self.loader.where()} | session left {fmt_time(left)}")
                window_tokens, window_time, window_loss, window_n = 0, 0.0, 0.0, 0
            now = time.time()
            if now - last_eval >= CFG["eval_every_minutes"] * 60:
                self.run_eval()
                last_eval = time.time()
                if time.time() - last_ckpt < CFG["ckpt_every_minutes"] * 60:
                    self.push_reports(f"metrics at step {self.step}")
            if time.time() - last_ckpt >= CFG["ckpt_every_minutes"] * 60:
                self.save_checkpoint()
                last_ckpt = time.time()
        return complete, reason

    def finish(self, complete, reason):
        log(f"stopping: {reason}")
        job = None
        if self.dirty or complete:
            self.run_eval()
            job = self.save_checkpoint(complete=complete, final=True)
        else:
            self.push_reports(f"session {self.session} end: {reason}")
        log("waiting for uploads to finish")
        self.uploader.wait()
        uploaded = job is None or job.ok
        if job is not None and not job.ok:
            log(f"FINAL CHECKPOINT UPLOAD FAILED; it is still at {job.files[-1][0]}")
        self.status = dict(safe_to_disconnect=uploaded, reason=reason, complete=complete,
                           step=self.step, tokens=self.tokens)
        log(f"session done: step {self.step:,}, {self.tokens / 1e9:.3f}B tokens, "
            f"{'uploaded' if uploaded else 'NOT uploaded'}. https://huggingface.co/{self.repo_id}")

    def emergency(self, error):
        """Something raised mid-training: keep whatever finite progress there is."""
        log("training stopped by an error:\n" + "".join(traceback.format_exception(error)))
        if self.uploader is None or not hasattr(self, "model"):
            return
        interrupted = isinstance(error, KeyboardInterrupt)
        job = None
        try:
            self._free()
            if self.dirty:
                job = self.save_checkpoint(final=True)
            else:
                self.push_reports(f"session {self.session}: stopped by {type(error).__name__}")
        except BaseException as inner:
            log(f"emergency save failed: {inner!r}")
        self.uploader.wait()
        saved = job is None or job.ok
        # A person pressed stop: leave the runtime to them. Otherwise nothing useful remains here.
        self.status = dict(safe_to_disconnect=saved and not interrupted,
                           reason=f"error: {type(error).__name__}: {error}", step=self.step, tokens=self.tokens)


def main():
    t_start = time.time()
    os.makedirs(os.path.join(CFG["work_dir"], "logs"), exist_ok=True)
    status_path = os.path.join(CFG["work_dir"], "status.json")
    _remove(status_path)
    log.open(os.path.join(CFG["work_dir"], "logs", time.strftime("session_%Y%m%d_%H%M%S.log")))
    trainer = Trainer(t_start)
    code = 0
    try:
        if trainer.setup():
            trainer.finish(*trainer.train())
    except BaseException as error:
        if not hasattr(trainer, "step"):  # failed during setup: the person is probably still watching
            log("setup failed:\n" + "".join(traceback.format_exception(error)))
            trainer.status = dict(safe_to_disconnect=False, reason=f"setup failed: {error!r}")
        else:
            trainer.emergency(error)
        code = 1
    with open(status_path, "w") as f:
        json.dump(trainer.status, f)
    log(f"status: {trainer.status}")
    return code


if __name__ == "__main__":
    sys.exit(main())