File size: 25,753 Bytes
1b13e1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Spider-FLEXITOKENS training pipeline with torchao FP8 + TileKernels.

Uses torchao's Float8Linear for FP8 training on Blackwell (sm_120)
and TileKernels for fused MoE routing (topk_gate, expand_to_fused,
reduce_fused, normalize_weight, get_fused_mapping, aux_fi).

Falls back to BF16 if torchao is unavailable.
Falls back to Python MoE loop if TileKernels is unavailable.

Architecture: SpiderForConditionalGeneration (RDT, MoE, MLA, FlexiTokens).
Byte-level vocab 272, pre-tokenized FineWeb-Edu shards at /fineweb_bytelevel/.

Usage:
python tk-train.py
python tk-train.py --mock_data --max_steps 50
python tk-train.py --micro_batch 64 --seq_len 128 --precision fp8
python tk-train.py --resume checkpoints-tk/spider-step50.pt
"""

import os
import gc
import math
import sys
import time
import argparse
import re
import enum
from contextlib import nullcontext

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
from torch.utils.data import IterableDataset, DataLoader, get_worker_info

from datasets import load_dataset

try:
    import bitsandbytes as bnb
    AdamW8bit = bnb.optim.AdamW8bit
    _HAS_8BIT = True
except ImportError:
    _HAS_8BIT = False
    AdamW8bit = None

try:
    from torchao.float8 import convert_to_float8_training, Float8LinearConfig
    _HAS_TORCHAO_FP8 = True
except ImportError:
    _HAS_TORCHAO_FP8 = False

import importlib
sys.path.insert(0, os.path.expanduser("~/TileKernels"))
_fp8_spider = importlib.import_module("tk-spider")
SpiderConfig = _fp8_spider.SpiderConfig
SpiderForConditionalGeneration = _fp8_spider.SpiderForConditionalGeneration
SENTINEL_TOKENS = _fp8_spider.SENTINEL_TOKENS

try:
    from loguru import logger
    logger.remove()
    logger.add(sys.stderr, format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}")
    logger.add("train_fp8.log", rotation="100 MB", retention="10 days",
               format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}")
except ImportError:
    import logging
    logging.basicConfig(level=logging.INFO)
    class _LoguruShim:
        def info(self, msg): logging.info(msg)
        def success(self, msg): logging.info(msg)
        def warning(self, msg): logging.warning(msg)
        def error(self, msg): logging.error(msg)
    logger = _LoguruShim()

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

BOS_ID = SENTINEL_TOKENS['BOS']
EOS_ID = SENTINEL_TOKENS['EOS']
PAD_ID = SENTINEL_TOKENS['PAD']


# ============================================================================
# Precision Mode
# ============================================================================

class PrecisionMode(enum.Enum):
    BF16 = "bf16"
    FP8 = "fp8"


def detect_precision_mode() -> PrecisionMode:
    if not torch.cuda.is_available():
        return PrecisionMode.BF16
    cc = torch.cuda.get_device_capability()
    if cc[0] >= 12 and _HAS_TORCHAO_FP8:
        return PrecisionMode.FP8
    if cc[0] >= 8 and _HAS_TORCHAO_FP8:
        return PrecisionMode.FP8
    return PrecisionMode.BF16


def configure_fp8_training(model, recipe_name="tensorwise"):
    base = Float8LinearConfig.from_recipe_name(recipe_name)
    config = Float8LinearConfig(
        cast_config_input=base.cast_config_input,
        cast_config_weight=base.cast_config_weight,
        cast_config_grad_output=base.cast_config_grad_output,
        cast_config_input_for_grad_weight=base.cast_config_input_for_grad_weight,
        cast_config_weight_for_grad_input=base.cast_config_weight_for_grad_input,
        cast_config_grad_output_for_grad_weight=base.cast_config_grad_output_for_grad_weight,
        gemm_config_output=base.gemm_config_output,
        gemm_config_grad_input=base.gemm_config_grad_input,
        gemm_config_grad_weight=base.gemm_config_grad_weight,
        enable_fsdp_float8_all_gather=base.enable_fsdp_float8_all_gather,
        round_scales_to_power_of_2=base.round_scales_to_power_of_2,
        pad_inner_dim=True,
    )

    def module_filter_fn(mod, fqn):
        skip = any(s in fqn for s in (
            "boundary_predictor",
            "loop_embedding",
            "engram",
            "layernorm",
            "norm",
            "embed_tokens",
            "lm_head",
            "halt_predictor",
            "router",
        ))
        return not skip

    model = convert_to_float8_training(
        model,
        module_filter_fn=module_filter_fn,
        config=config,
    )
    return model


# ============================================================================
# Byte-Level Datasets
# ============================================================================

class ByteLevelDataset(IterableDataset):
    def __init__(self, dataset_name="HuggingFaceFW/fineweb-edu",
                 subset="sample-10BT", split="train",
                 seq_len=2048, max_bytes=2048, rank=0, world_size=1):
        self.seq_len = seq_len
        self.max_bytes = max_bytes
        self.dataset_name = dataset_name
        self.subset = subset
        self.split = split
        self.rank = rank
        self.world_size = world_size

    def _encode_sample(self, text):
        byte_ids = list(text.encode('utf-8'))[:self.max_bytes]
        return [BOS_ID] + byte_ids + [EOS_ID]

    def __iter__(self):
        worker = get_worker_info()
        num_workers = worker.num_workers if worker else 1
        worker_id = worker.id if worker else 0
        total_shards = self.world_size * num_workers
        shard_index = self.rank * num_workers + worker_id
        ds = load_dataset(self.dataset_name, name=self.subset,
                          split=self.split, streaming=True
                          ).shard(num_shards=total_shards, index=shard_index)
        buf = []
        for sample in ds:
            text = sample.get("text", "")
            if not text:
                continue
            byte_ids = self._encode_sample(text)
            buf.extend(byte_ids)
            while len(buf) >= self.seq_len + 1:
                chunk = buf[:self.seq_len + 1]
                buf = buf[self.seq_len + 1:]
                x = torch.tensor(chunk[:-1], dtype=torch.long)
                y = torch.tensor(chunk[1:], dtype=torch.long)
                y[y == PAD_ID] = -100
                yield x, y


class LocalByteLevelDataset(IterableDataset):
    def __init__(self, data_dir, seq_len=2048, rank=0, world_size=1):
        self.seq_len = seq_len
        self.data_dir = data_dir
        self.rank = rank
        self.world_size = world_size
        self._files = self._discover_files()

    def _discover_files(self):
        import glob as _glob
        files = sorted(
            _glob.glob(os.path.join(self.data_dir, "**/*.bin"), recursive=True)
        )
        return [f for i, f in enumerate(files) if i % self.world_size == self.rank]

    def __iter__(self):
        import numpy as np
        worker = get_worker_info()
        num_workers = worker.num_workers if worker else 1
        worker_id = worker.id if worker else 0
        files = [f for i, f in enumerate(self._files) if i % num_workers == worker_id]
        token_buffer = []
        for filepath in files:
            if filepath.endswith(".bin"):
                arr = np.memmap(filepath, dtype=np.uint16, mode='r')
                pos = 0
                while pos + self.seq_len + 1 <= len(arr):
                    chunk = arr[pos:pos + self.seq_len + 1]
                    pos += self.seq_len + 1
                    x = torch.tensor(chunk[:-1], dtype=torch.long)
                    y = torch.tensor(chunk[1:], dtype=torch.long)
                    y[y == PAD_ID] = -100
                    yield x, y
                token_buffer.extend(arr[pos:].tolist())


class MockByteLevelDataset(IterableDataset):
    SAMPLES = [
        "Hello world, this is a test of the byte-level encoding system.",
        "The quick brown fox jumps over the lazy dog.",
        "Spider is a recurrent latent reasoning architecture with engram memory.",
        "Boundary predictors learn to merge byte sequences into meaningful tokens.",
        "FineWeb-Edu contains high-quality educational content for pretraining.",
        "\u042d\u0442\u043e \u0442\u0435\u043a\u0441\u0442 \u043d\u0430 \u0440\u0443\u0441\u0441\u043a\u043e\u043c \u044f\u0437\u044b\u043a\u0435.",
        "def fibonacci(n): return n if n <= 1 else fibonacci(n-1) + fibonacci(n-2)",
        "The integral of x^2 from 0 to 1 equals 1/3.",
    ]

    def __init__(self, seq_len=512, max_bytes=512, num_samples=1000):
        self.seq_len = seq_len
        self.max_bytes = max_bytes
        self.num_samples = num_samples

    def __iter__(self):
        buf = []
        count = 0
        while count < self.num_samples:
            for text in self.SAMPLES:
                byte_ids = list(text.encode('utf-8'))[:self.max_bytes]
                ids = [BOS_ID] + byte_ids + [EOS_ID]
                buf.extend(ids)
                while len(buf) >= self.seq_len + 1:
                    chunk = buf[:self.seq_len + 1]
                    buf = buf[self.seq_len + 1:]
                    x = torch.tensor(chunk[:-1], dtype=torch.long)
                    y = torch.tensor(chunk[1:], dtype=torch.long)
                    y[y == PAD_ID] = -100
                    yield x, y
                count += 1
                if count >= self.num_samples:
                    return


# ============================================================================
# Checkpointing
# ============================================================================

def save_step_checkpoint(model, optimizer, step, epoch, cfg, ckpt_dir, master,
                         ddp=False, current_best_loss=float("inf")):
    model_state = model.state_dict()
    optim_state = optimizer.state_dict()
    if not master:
        return None, 0
    os.makedirs(ckpt_dir, exist_ok=True)
    ckpt_path = os.path.join(ckpt_dir, f"spider-step{step}.pt")
    tmp_path = ckpt_path + ".tmp"
    torch.save({
        "step": step, "epoch": epoch,
        "model_state_dict": model_state,
        "optimizer_state_dict": optim_state,
        "cfg": cfg, "best_loss": current_best_loss,
    }, tmp_path)
    os.replace(tmp_path, ckpt_path)
    size_mb = os.path.getsize(ckpt_path) / (1024 * 1024)
    step_pattern = re.compile(r"spider-step\d+\.pt$")
    step_ckpts = sorted(
        [os.path.join(ckpt_dir, f) for f in os.listdir(ckpt_dir) if step_pattern.search(f)],
        key=os.path.getmtime,
    )
    while len(step_ckpts) > 2:
        old = step_ckpts.pop(0)
        os.remove(old)
    return ckpt_path, size_mb


def load_checkpoint(model, optimizer, path, ddp=False):
    ckpt = torch.load(path, map_location="cpu", weights_only=False)
    if "model_state_dict" not in ckpt:
        model.load_state_dict(ckpt, strict=False)
        return 0, 0, float("inf")
    model.load_state_dict(ckpt["model_state_dict"])
    try:
        optimizer.load_state_dict(ckpt["optimizer_state_dict"])
    except (ValueError, KeyError, RuntimeError) as e:
        logger.warning(f"Optimizer state mismatch: {e}. Skipping optimizer state.")
    saved_best_loss = ckpt.get("best_loss", float("inf"))
    return int(ckpt["step"]), int(ckpt.get("epoch", 0)), saved_best_loss


# ============================================================================
# LR Schedule
# ============================================================================

def get_lr(step, warmup, total, max_lr, min_lr):
    if step < warmup:
        return max_lr * step / warmup
    if step >= total:
        return min_lr
    decay = (step - warmup) / (total - warmup)
    return min_lr + 0.5 * (max_lr - min_lr) * (1.0 + math.cos(math.pi * decay))


# ============================================================================
# Main
# ============================================================================

def parse_args():
    parser = argparse.ArgumentParser(description="Spider-FLEXITOKENS FP8/BF16 training")
    parser.add_argument("--resume", type=str, default="")
    parser.add_argument("--reset_steps", action="store_true", help="Load weights but reset step/epoch to 0")
    parser.add_argument("--max_steps", type=int, default=0)
    parser.add_argument("--mock_data", action="store_true")
    parser.add_argument("--seq_len", type=int, default=0)
    parser.add_argument("--micro_batch", type=int, default=0)
    parser.add_argument("--grad_accum", type=int, default=0, help="Gradient accumulation steps (0=auto)")
    parser.add_argument("--n_loops", type=int, default=0)
    parser.add_argument("--lr", type=float, default=0)
    parser.add_argument("--ckpt_dir", type=str, default="checkpoints-tk")
    parser.add_argument("--data_dir", type=str, default="/home/lamcodealong/fineweb_bytelevel")
    parser.add_argument("--no_gradient_checkpointing", action="store_true")
    parser.add_argument("--precision", type=str, default="auto",
                        choices=["auto", "bf16", "fp8"],
                        help="Training precision: auto (detect), bf16, fp8 (torchao)")
    parser.add_argument("--compile", action="store_true",
                        help="torch.compile the model for optimized kernels")
    return parser.parse_args()


def main():
    args = parse_args()

    ddp = int(os.environ.get("RANK", -1)) != -1
    if ddp:
        import torch.distributed as dist
        dist.init_process_group("nccl")
        rank = int(os.environ["RANK"])
        local_rank = int(os.environ["LOCAL_RANK"])
        world_size = int(os.environ["WORLD_SIZE"])
        device = f"cuda:{local_rank}"
        torch.cuda.set_device(device)
    else:
        rank = local_rank = 0
        world_size = 1
        device = "cuda" if torch.cuda.is_available() else "cpu"
    master = rank == 0

    seq_len = args.seq_len or int(os.environ.get("SEQ_LEN", "2048"))
    micro_batch = args.micro_batch or int(os.environ.get("MICRO_BATCH", "64"))
    target_tokens = int(os.environ.get("TARGET_TOKENS", "10_000_000_000"))
    grad_accum = args.grad_accum if args.grad_accum and args.grad_accum > 0 else int(os.environ.get("GRAD_ACCUM", "1"))
    n_loops = args.n_loops or int(os.environ.get("N_LOOPS", "6"))
    lr = args.lr or float(os.environ.get("LR", "3e-4"))
    wd = 0.1
    warmup_steps = 200
    log_every = 10
    ckpt_every = int(os.environ.get("CKPT_EVERY", "50"))
    ckpt_dir = args.ckpt_dir

    global_batch_tok = world_size * micro_batch * grad_accum * seq_len
    total_steps = target_tokens // global_batch_tok
    if args.max_steps > 0:
        total_steps = min(total_steps, args.max_steps)

    cfg = SpiderConfig()
    bf16_ok = torch.cuda.is_available() and torch.cuda.is_bf16_supported()
    amp_dtype = torch.bfloat16 if bf16_ok else torch.float16

    if args.precision == "auto":
        prec_mode = detect_precision_mode()
    elif args.precision == "fp8":
        prec_mode = PrecisionMode.FP8
    else:
        prec_mode = PrecisionMode.BF16

    if prec_mode == PrecisionMode.FP8 and not _HAS_TORCHAO_FP8:
        logger.warning("torchao FP8 not available, falling back to BF16")
        prec_mode = PrecisionMode.BF16

    if master:
        logger.info(
            f"[Spider-FLEXITOKENS] hidden=2048 | 6 recurrent | 32 experts top-2 | "
            f"n_loops={n_loops} | seq_len={seq_len} | micro_batch={micro_batch} | "
            f"grad_accum={grad_accum} | global_batch_tokens={global_batch_tok:,} | "
            f"total_steps={total_steps:,}"
        )
        logger.info(
            f"Byte-level vocab: 272 | Precision: {prec_mode.value} | "
            f"Gradient checkpointing: {'disabled' if args.no_gradient_checkpointing else 'enabled'}"
        )

    model = SpiderForConditionalGeneration(cfg).to(amp_dtype)

    if prec_mode == PrecisionMode.FP8:
        try:
            recipe = "tensorwise"
            model = configure_fp8_training(model, recipe_name=recipe)
            if master:
                n_fp8 = sum(1 for m in model.modules() if m.__class__.__name__ == "Float8Linear")
                n_linear = sum(1 for m in model.modules() if isinstance(m, nn.Linear))
                logger.info(f"torchao FP8: {n_fp8} Float8Linear / {n_fp8 + n_linear} total linear layers (recipe={recipe})")
        except Exception as e:
            if master:
                logger.warning(f"FP8 setup failed ({e}), falling back to BF16")
            prec_mode = PrecisionMode.BF16

    if not args.no_gradient_checkpointing:
        model.gradient_checkpointing_enable()
    model.enable_input_require_grads()

    model = model.to(device)

    if args.compile:
        model = torch.compile(model, mode="default")
        if master:
            logger.info("Model compiled with torch.compile (default)")

    if ddp:
        model = torch.nn.parallel.DistributedDataParallel(
            model, device_ids=[local_rank], output_device=local_rank,
        )

    if master:
        n_params = sum(p.numel() for p in model.parameters())
        trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
        logger.info(
            f"Parameters: {n_params:,} total | {trainable:,} trainable | Precision: {prec_mode.value}"
        )

    if _HAS_8BIT:
        optimizer = AdamW8bit(
            model.parameters(), lr=lr, weight_decay=wd,
            betas=(0.9, 0.95), eps=1e-8,
        )
        if master:
            logger.info("Optimizer: 8-bit AdamW (saves ~50% optimizer VRAM)")
    else:
        optimizer = torch.optim.AdamW(
            model.parameters(), lr=lr, weight_decay=wd,
            betas=(0.9, 0.95), foreach=True, eps=1e-8,
        )
        if master:
            logger.info("Optimizer: standard AdamW")

    start_step = 0
    start_epoch = 1
    best_loss = float("inf")
    if args.resume and os.path.exists(args.resume):
        if master:
            logger.info(f"Resuming from checkpoint: {args.resume}")
        start_step, start_epoch, best_loss = load_checkpoint(model, optimizer, args.resume, ddp)
        if args.reset_steps:
            if master:
                logger.info(f"Reset steps: step {start_step} -> 0, epoch {start_epoch} -> 1")
            start_step = 0
            start_epoch = 1
            best_loss = float("inf")
            for group in optimizer.param_groups:
                for p in group['params']:
                    state = optimizer.state.get(p, {})
                    for k in ('exp_avg', 'exp_avg_sq', 'max_exp_avg_sq'):
                        if k in state:
                            state[k].zero_()
            if master:
                logger.info("Optimizer state reset (momentum/variance zeroed)")
        if master:
            logger.info(f"Resumed at step {start_step}, epoch {start_epoch}, best_loss={best_loss:.4f}")
    else:
        existing_ckpts = sorted(
            [os.path.join(ckpt_dir, f) for f in os.listdir(ckpt_dir)
             if f.startswith("spider-") and f.endswith(".pt") and not f.endswith(".tmp")]
        ) if os.path.isdir(ckpt_dir) else []
        if existing_ckpts:
            latest = existing_ckpts[-1]
            if master:
                logger.info(f"Auto-resuming from: {latest}")
            start_step, start_epoch, best_loss = load_checkpoint(model, optimizer, latest, ddp)
        if master:
            logger.info(f"Resumed at step {start_step}, epoch {start_epoch}, best_loss={best_loss:.4f}")

    if master:
        logger.info("Running FP8 warmup (2 fwd+bwd passes to compile kernels)...")
    model.train()
    for _w in range(2):
        _wx = torch.randint(4, 256, (2, seq_len), device=device)
        _wy = torch.randint(4, 256, (2, seq_len), device=device)
        _wo = model(_wx, labels=_wy, n_loops=n_loops)
        _wo['loss'].backward()
        optimizer.zero_grad(set_to_none=True)
        del _wx, _wy, _wo
    torch.cuda.synchronize()
    if master:
        peak_warmup = torch.cuda.max_memory_allocated() / 1024**3
        logger.info(f"Warmup done | Peak VRAM: {peak_warmup:.1f}GB")

    if args.mock_data:
        dataset = MockByteLevelDataset(seq_len=seq_len, num_samples=5000)
    elif args.data_dir and os.path.isdir(args.data_dir):
        dataset = LocalByteLevelDataset(
            data_dir=args.data_dir, seq_len=seq_len,
            rank=rank, world_size=world_size,
        )
    else:
        dataset = ByteLevelDataset(seq_len=seq_len, rank=rank, world_size=world_size)

    loader = DataLoader(
        dataset,
        batch_size=micro_batch,
        num_workers=4 if not args.mock_data else 0,
        pin_memory=True,
        prefetch_factor=4 if not args.mock_data else None,
        persistent_workers=True if not args.mock_data else False,
        drop_last=False,
    )

    class _Prefetcher:
        def __init__(self, loader, device):
            self.loader = loader
            self.device = device
            self._stream = torch.cuda.Stream()
            self._next_x = None
            self._next_y = None

        def _preload(self, data_iter):
            try:
                x, y = next(data_iter)
            except StopIteration:
                return None, None, data_iter
            with torch.cuda.stream(self._stream):
                self._next_x = x.to(self.device, non_blocking=True)
                self._next_y = y.to(self.device, non_blocking=True)
            return self._next_x, self._next_y, data_iter

        def next(self, data_iter):
            if self._next_x is not None:
                torch.cuda.current_stream().wait_stream(self._stream)
                x, y = self._next_x, self._next_y
            else:
                try:
                    x, y = next(data_iter)
                except StopIteration:
                    return None, None, data_iter
                x = x.to(self.device, non_blocking=True)
                y = y.to(self.device, non_blocking=True)
            self._next_x = None
            self._next_y = None
            nx, ny, data_iter = self._preload(data_iter)
            return x, y, data_iter

    prefetcher = _Prefetcher(loader, device)

    if prec_mode == PrecisionMode.FP8:
        amp_ctx = nullcontext()
    else:
        amp_ctx = (
            torch.amp.autocast(device_type="cuda", dtype=amp_dtype)
            if "cuda" in device
            else nullcontext()
        )

    if master:
        logger.info(f"Starting training from step {start_step} to {total_steps}")

    model.train()
    step = start_step
    tokens_seen = start_step * global_batch_tok
    t0_loop = time.time()
    data_iter = iter(loader)

    for epoch in range(start_epoch, 1000):
        while step < total_steps:
            current_lr = get_lr(step, warmup_steps, total_steps, lr, lr * 0.1)
            for pg in optimizer.param_groups:
                pg['lr'] = current_lr

            optimizer.zero_grad(set_to_none=True)
            loss_accum = 0.0

            for micro_step in range(grad_accum):
                x, y, data_iter = prefetcher.next(data_iter)
                if x is None:
                    data_iter = iter(loader)
                    x, y, data_iter = prefetcher.next(data_iter)

                sync = (
                    nullcontext()
                    if (not ddp or micro_step == grad_accum - 1)
                    else model.no_sync()
                ) if ddp else nullcontext()

                with sync, amp_ctx:
                    output = model(x, labels=y, n_loops=n_loops)
                    loss = output['loss'] / grad_accum
                    loss.backward()

                loss_accum += loss.item() * grad_accum

                if master and step == start_step and micro_step == 0:
                    peak_vram = torch.cuda.max_memory_allocated() / 1024**3
                    logger.info(f"First forward+backward | Peak VRAM: {peak_vram:.1f}GB")

            nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
            optimizer.step()

            step += 1
            tokens_seen += global_batch_tok

            if step % 10 == 0:
                gc.collect()
                torch.cuda.empty_cache()

            if (step % log_every == 0 or step == 1) and master:
                elapsed = time.time() - t0_loop
                tps = log_every * global_batch_tok / elapsed if elapsed > 0 else 0
                loss_val = loss_accum
                if loss_val < best_loss:
                    best_loss = loss_val
                logger.info(
                    f"Epoch {epoch} | step {step}/{total_steps} | loss {loss_val:.4f} | "
                    f"lr {current_lr:.2e} | {tps/1e3:.1f}k tok/s | "
                    f"prec {prec_mode.value} | tokens {tokens_seen/1e6:.2f}M"
                )
                t0_loop = time.time()

            if step % ckpt_every == 0 and master:
                ckpt_path, ckpt_mb = save_step_checkpoint(
                    model, optimizer, step, epoch, cfg, ckpt_dir, master,
                    ddp=ddp, current_best_loss=best_loss,
                )
                if ckpt_path:
                    logger.info(f"Checkpoint saved: {ckpt_path} ({ckpt_mb:.0f} MB)")

            if step >= total_steps:
                break

        if step >= total_steps:
            break

    if master:
        final_path = os.path.join(ckpt_dir, "spider-final.pt")
        os.makedirs(ckpt_dir, exist_ok=True)
        torch.save({
            "step": step, "epoch": epoch,
            "model_state_dict": model.state_dict(),
            "optimizer_state_dict": optimizer.state_dict(),
            "cfg": cfg, "best_loss": best_loss,
        }, final_path)
        logger.info(f"Final checkpoint saved: {final_path}")
        logger.info(f"Training complete. Total steps: {step}, Best loss: {best_loss:.4f}")


if __name__ == "__main__":
    main()