File size: 24,924 Bytes
23c39b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import Optional
from dataclasses import dataclass
from pathlib import Path
from glob import glob
from types import SimpleNamespace
import json
import math
import os
import time
import yaml
import shutil

import torch
import torch.distributed as dist
import torch.distributed.checkpoint as dcp
from torch.distributed.checkpoint.state_dict import get_optimizer_state_dict, set_optimizer_state_dict
from torch.distributed.fsdp import fully_shard, FSDPModule, MixedPrecisionPolicy
from torch import Tensor, nn
from torch.utils.data import DataLoader

import tqdm
import wandb
import coolname
import hydra
import pydantic
from omegaconf import DictConfig, OmegaConf

from models.layers import Carry
from models.common import wrap_tensor
from models.transformer import TransformerBlock
from models.adam_atan2 import AdamATan2
from utils.functions import load_model_class, get_model_source_path
from dataset_new import V1Dataset, V1DatasetConfig, V1DatasetMeta


class ArchConfig(pydantic.BaseModel):
    model_config = pydantic.ConfigDict(extra='allow')

    name: str
    head: str


class DataConfig(pydantic.BaseModel):
    model_config = pydantic.ConfigDict(extra='allow')

    path: str
    target_only: bool = True  # Only supervise Answer.


class PretrainConfig(pydantic.BaseModel):
    # Config
    arch: ArchConfig
    data: DataConfig

    # Hyperparams
    global_batch_size: int
    epochs: int

    lr: float
    lr_min_ratio: float
    lr_warmup_steps: int

    weight_decay: float
    beta1: float
    beta2: float
    ema: Optional[float] = None
    fwd_bwd_dtype: str = "bfloat16"

    # Names
    project_name: Optional[str] = None
    run_name: Optional[str] = None
    checkpoint_path: Optional[str] = None

    # Resume / fine-tune from checkpoint
    resume_from: Optional[str] = None
    resume_epoch: Optional[int] = None
    weights_only_resume_from_ema: bool = False  # Swap EMA into model + reset optim
    # True mid-run continuation: restore step counter (LR schedule continues),
    # skip completed data, restore per-rank carry. Epoch granularity by
    # default; pass resume_step to continue from a mid-epoch step checkpoint.
    # Requires the SAME world size as the original run.
    resume_continue: bool = False
    resume_step: Optional[int] = None  # resume from fsdp2_step_<S> (requires resume_continue)

    # Save a rolling mid-epoch checkpoint (fsdp2_step_<S>) every N steps; only
    # the newest is kept, and all are pruned once an epoch checkpoint lands.
    # Enables making progress through wall-time limits shorter than an epoch.
    checkpoint_step_interval: Optional[int] = None

    # In-training held-out eval: every eval_interval steps, run the full eval
    # split (eval_data_path) on the LIVE raw weights and log eval/* metrics to
    # the training wandb run. The split is iterated with fixed_epoch=True so
    # every pass sees bit-identical batches (comparable across steps).
    eval_data_path: Optional[str] = None
    eval_interval: Optional[int] = None

    # Extras
    seed: int = 0
    checkpoint_interval: int = 1
    log_interval: int = 5


@dataclass
class TrainState:
    model: nn.Module
    carry: Optional[Carry]
    
    optim: AdamATan2

    step: int
    total_steps: int


def create_dataloader(config: PretrainConfig, local_batch_size: int, drop_last_batch: bool, rank: int, world_size: int, start_epoch: int = 0, start_batch: int = 0, fixed_epoch: bool = False):
    dataset = V1Dataset(V1DatasetConfig(
        seed=config.seed,

        dataset_path=config.data.path,
        drop_last_batch=drop_last_batch,

        target_only=config.data.target_only,

        batch_max_length=local_batch_size,
        rank=rank,
        num_replicas=world_size,

        start_epoch=start_epoch,
        start_batch=start_batch,
        fixed_epoch=fixed_epoch,
    ))
    dataloader = DataLoader(
        dataset,
        batch_size=None,

        num_workers=1,
        prefetch_factor=8,

        pin_memory=True,
        persistent_workers=True  # NOTE: Required for correct epoch handling
    )
    return dataloader, dataset.metadata


def apply_fsdp(module: nn.Module, param_dtype: torch.dtype):
    fully_shard(module,
                mp_policy=MixedPrecisionPolicy(param_dtype=param_dtype,
                                               reduce_dtype=torch.get_default_dtype()),  # Use master dtype for reduction
                reshard_after_forward=False)  # Trade off VRAM for less comms
    
    assert isinstance(module, FSDPModule)
    # Disable gradient division. Adams is scale invariant.
    module.set_gradient_divide_factor(1.0)
    module.set_force_sum_reduction_for_comms(True)


def create_model_and_carry(config: PretrainConfig, train_metadata: V1DatasetMeta, local_batch_size: int):
    model_cfg = config.arch.model_dump() | train_metadata.model_dump() | config.data.model_dump()
    fwd_bwd_dtype = getattr(torch, config.fwd_bwd_dtype)

    # Instantiate model with head
    model_cls = load_model_class(config.arch.name)
    head_cls = load_model_class(config.arch.head)

    with torch.device("cuda"):
        model: nn.Module = model_cls(model_cfg)
        carry = model.initial_carry(local_batch_size, dtype=fwd_bwd_dtype)  # pyright: ignore[reportCallIssue]
        # Attach loss head
        model = head_cls(model, model_cfg)

    # ----FSDP----
    # Broadcast buffers
    for buffer in model.buffers():
        dist.broadcast(buffer, src=0)

    # Detect TransformerBlock recursively and apply FSDP
    for module in model.modules():
        if isinstance(module, TransformerBlock):
            apply_fsdp(module, fwd_bwd_dtype)

    apply_fsdp(model, fwd_bwd_dtype)

    # ----Create optimizer----
    optim = AdamATan2(model.parameters(),
                      lr=torch.tensor(0.0, dtype=torch.get_default_dtype(), device="cpu"),
                      betas=(config.beta1, config.beta2),
                      weight_decay=config.weight_decay,
                      ema=config.ema)

    return model, carry, optim


def resolve_resume_epoch(config: PretrainConfig) -> int:
    """Epoch number of the checkpoint to resume from (explicit or latest)."""
    assert config.resume_from is not None
    if config.resume_epoch is not None:
        return config.resume_epoch
    ckpt_files = glob(os.path.join(config.resume_from, "fsdp2_epoch_*"))
    if not ckpt_files:
        raise FileNotFoundError(f"No checkpoint found in {config.resume_from}")
    return max(int(Path(f).stem.split("_")[-1]) for f in ckpt_files)


def load_step_state(config: PretrainConfig) -> dict:
    """Position record written alongside a fsdp2_step_<S> checkpoint."""
    assert config.resume_from is not None and config.resume_step is not None
    with open(os.path.join(config.resume_from, f"train_state_step_{config.resume_step}.json"), "rt") as f:
        return json.load(f)


def resolve_resume_position(config: PretrainConfig) -> tuple[int, int]:
    """(completed_epochs, batches_done_in_current_epoch) to resume at."""
    if not config.resume_continue:
        return 0, 0
    assert config.resume_from is not None, "resume_continue requires resume_from"
    if config.resume_step is not None:
        ss = load_step_state(config)
        return ss["epoch"] - 1, ss["batch_in_epoch"]
    return resolve_resume_epoch(config), 0


def init_train(config: PretrainConfig, rank: int, world_size: int):
    assert config.global_batch_size % world_size == 0, f"Global batch size {config.global_batch_size} must be divisible by world size {world_size}."
    local_batch_size = config.global_batch_size // world_size

    # Continuation: begin data iteration at the first uncompleted position
    start_epoch, start_batch = resolve_resume_position(config)

    # Dataset
    train_loader, train_metadata = create_dataloader(config, local_batch_size, drop_last_batch=True,  rank=rank, world_size=world_size, start_epoch=start_epoch, start_batch=start_batch)

    # Model
    model, carry, optim = create_model_and_carry(config, train_metadata, local_batch_size)

    # Train state
    # Estimated total training steps
    total_steps = int(config.epochs * train_metadata.total_length // config.global_batch_size)
    train_state = TrainState(
        model=model,
        carry=carry,
        optim=optim,
        
        step=0,
        total_steps=total_steps
    )
    return train_state, train_loader, train_metadata


def update_lr(config: PretrainConfig, train_state: TrainState) -> float:
    # Linear warmup cosine schedule
    if train_state.step < config.lr_warmup_steps:
        lr = config.lr * min(1.0, train_state.step / config.lr_warmup_steps)
    else:
        progress = (train_state.step - config.lr_warmup_steps) / (train_state.total_steps - config.lr_warmup_steps)
        lr = config.lr * (config.lr_min_ratio + max(0.0, (1 - config.lr_min_ratio) * 0.5 * (1.0 + math.cos(math.pi * progress))))

    tensor_lr = torch.tensor(lr, dtype=torch.get_default_dtype(), device="cpu")
    for param_group in train_state.optim.param_groups:
        param_group["lr"] = tensor_lr

    return lr


@torch.compile(dynamic=False)
def train_batch(train_state: TrainState, batch: dict[str, Tensor], **kwargs):
    train_state.carry, loss, metrics = train_state.model(batch=batch, carry=train_state.carry, **kwargs)
    loss.backward()
    train_state.optim.step()
    train_state.optim.zero_grad()
    return metrics


@torch.no_grad()
def evaluate_inline(train_state: TrainState, eval_loader: DataLoader, eval_carry, world_size: int) -> dict:
    """Held-out eval on the CURRENT raw weights, mid-training.

    Mirrors slurm/eval_loss.py::evaluate — eager forwards (uncompiled), fresh
    carry, token-weighted global mean via summed numerators/denominators —
    but needs NO reshard(): unlike eval_loss.py (which swaps weights under
    FSDP2's unsharded-param cache), here the cache IS the live weights. The
    multipack sampler yields the same batch count on every rank, so the
    all_reduce inside LMHead.forward stays collective-safe.
    """
    model = train_state.model
    model.eval()
    # Terminal-schedule extra args (e.g. final bp_steps); grads are off anyway.
    extra_args = model.compute_train_extra_args(SimpleNamespace(step=1 << 30, total_steps=1 << 30))  # pyright: ignore[reportCallIssue]

    t0 = time.time()
    agg: dict = {}
    carry = eval_carry
    for batch, batch_info in eval_loader:
        batch = batch | {k: wrap_tensor(torch.tensor(v, device="cpu")) for k, v in batch_info.items()}
        carry, _loss, metrics = model(batch=batch, carry=carry, **extra_args)
        for k, (num, den) in metrics.items():
            if k not in agg:
                agg[k] = [num.double().clone(), den.double().clone()]
            else:
                agg[k][0] += num.double()
                agg[k][1] += den.double()
    keys = sorted(agg.keys())
    flat = torch.stack([agg[k][0] for k in keys] + [agg[k][1] for k in keys])
    dist.all_reduce(flat)
    nums, dens = flat.chunk(2)
    results = {f"eval/{k}": (nums[i] / dens[i]).item() for i, k in enumerate(keys)}
    results["eval/seconds"] = time.time() - t0

    model.train()
    return results


@torch.inference_mode()
def reduce_metrics(local_metrics: dict[str, Tensor], prefix: str):
    metric_keys = list(sorted(local_metrics.keys()))  # Sort keys to guarantee all processes use the same order.
    # Reduce and reconstruct
    metric_values = torch.stack([local_metrics[k][0] for k in metric_keys] + [local_metrics[k][1] for k in metric_keys])
    dist.reduce(metric_values, dst=0)
    # Split and normalize
    metrics, metrics_div = metric_values.chunk(2, dim=-1)
    metrics = (metrics / metrics_div).cpu().numpy().tolist()
    return {prefix + name: metrics[idx] for idx, name in enumerate(metric_keys)}


def load_checkpoint(config: PretrainConfig, train_state: TrainState, train_metadata: V1DatasetMeta, rank: int):
    """Resume from a saved checkpoint.

    Loads both model weights and optimizer state (which carries EMA in
    AdamATan2). When weights_only_resume_from_ema=True, swaps the EMA buffer
    into the model and resets the optimizer state — typical for fine-tuning
    off a pretrain run with EMA-smoothed weights.

    When resume_continue=True, additionally restores the step counter (so the
    LR schedule continues instead of restarting) and the per-rank carry.
    """
    if config.resume_from is None:
        return

    if config.resume_step is not None:
        assert config.resume_continue, "resume_step requires resume_continue"
        checkpoint_id = os.path.join(config.resume_from, f"fsdp2_step_{config.resume_step}")
    else:
        epoch = resolve_resume_epoch(config)
        checkpoint_id = os.path.join(config.resume_from, f"fsdp2_epoch_{epoch}")
    print(f"[Resume] Loading model + optimizer from {checkpoint_id}")
    optim_state = get_optimizer_state_dict(train_state.model, train_state.optim)
    dcp.load(
        {"model": train_state.model.state_dict(), "optim": optim_state},
        checkpoint_id=checkpoint_id,
    )
    set_optimizer_state_dict(train_state.model, train_state.optim, optim_state)

    # set_optimizer_state_dict silently overwrites param_groups with the pretrain hyperparams
    # (lr, betas, weight_decay, ema). Restore the SFT cfg values so that overrides take effect.
    # (lr is also restored every step by update_lr() — these three are not.)
    for param_group in train_state.optim.param_groups:
        param_group["betas"] = (config.beta1, config.beta2)
        param_group["weight_decay"] = config.weight_decay
        param_group["ema"] = config.ema

    if config.weights_only_resume_from_ema:
        print("[Resume] Swapping EMA into model and resetting optimizer state")
        train_state.optim.swap_ema()
        train_state.optim._init_state()

    if config.resume_continue:
        assert not config.weights_only_resume_from_ema, "resume_continue keeps the optimizer; incompatible with weights_only_resume_from_ema"
        if config.resume_step is not None:
            train_state.step = load_step_state(config)["step"]
            carry_file = os.path.join(config.resume_from, f"carry_step_{config.resume_step}.{rank}.pt")
            print(f"[Resume] Continuing mid-epoch at step {train_state.step}")
        else:
            # Step counter: exact value if the checkpoint recorded it (new runs
            # do), otherwise estimate from the per-epoch step count.
            state_file = os.path.join(config.resume_from, f"train_state_epoch_{epoch}.json")
            if os.path.exists(state_file):
                with open(state_file, "rt") as f:
                    train_state.step = json.load(f)["step"]
                print(f"[Resume] Continuing at step {train_state.step} (recorded)")
            else:
                train_state.step = int(epoch * (train_metadata.total_length // config.global_batch_size))
                print(f"[Resume] Continuing at step {train_state.step} (estimated)")
            carry_file = os.path.join(config.resume_from, f"carry_epoch_{epoch}.{rank}.pt")
        # Per-rank carry (requires same world size as the original run)
        if os.path.exists(carry_file):
            train_state.carry = torch.load(carry_file, map_location="cuda", weights_only=False)
            print(f"[Resume] Restored carry from {carry_file}")
        else:
            print(f"[Resume] WARNING: no carry file {carry_file}; using fresh initial carry")

    print(f"[Resume] Done.")


def prune_step_checkpoints(config: PretrainConfig, keep_step: Optional[int]):
    """Remove step-checkpoint artifacts older than keep_step (all if None)."""
    for f in glob(os.path.join(config.checkpoint_path, "fsdp2_step_*")) + \
             glob(os.path.join(config.checkpoint_path, "carry_step_*.pt")) + \
             glob(os.path.join(config.checkpoint_path, "train_state_step_*.json")):
        s = int(Path(f).stem.split("_")[-1].split(".")[0])
        if keep_step is None or s < keep_step:
            shutil.rmtree(f) if os.path.isdir(f) else os.remove(f)


def save_step_checkpoint(config: PretrainConfig, train_state: TrainState, epoch: int, batch_in_epoch: int, rank: int, world_size: int):
    s = train_state.step
    dcp.save({"model": train_state.model.state_dict(), "optim": get_optimizer_state_dict(train_state.model, train_state.optim)},  # pyright: ignore[reportPrivateImportUsage]
             checkpoint_id=os.path.join(config.checkpoint_path, f"fsdp2_step_{s}"))
    torch.save(train_state.carry, os.path.join(config.checkpoint_path, f"carry_step_{s}.{rank}.pt"))
    if rank == 0:
        with open(os.path.join(config.checkpoint_path, f"train_state_step_{s}.json"), "wt") as f:
            json.dump({"step": s, "epoch": epoch, "batch_in_epoch": batch_in_epoch, "world_size": world_size}, f)
    dist.barrier()  # everyone finished writing before pruning older ones
    if rank == 0:
        prune_step_checkpoints(config, keep_step=s)


def save_code_and_config(config: PretrainConfig, train_metadata: V1DatasetMeta):
    if config.checkpoint_path is None or wandb.run is None:
        return

    os.makedirs(config.checkpoint_path, exist_ok=True)

    # Copy code
    code_list = [
        get_model_source_path(config.arch.name)
    ]
    for code_file in code_list:
        if code_file is not None:
            code_name = os.path.basename(code_file)

            shutil.copy(code_file, os.path.join(config.checkpoint_path, code_name))

    # Dump config as yaml
    with open(os.path.join(config.checkpoint_path, "all_config.yaml"), "wt") as f:
        yaml.dump(config.model_dump(), f)
    with open(os.path.join(config.checkpoint_path, "train_metadata.yaml"), "wt") as f:
        yaml.dump(train_metadata.model_dump(), f)

    # Log code (best-effort: artifact staging writes to wandb's data dir,
    # which can be a full/tiny node-local disk — never kill training over it)
    try:
        wandb.run.log_code(config.checkpoint_path)
    except OSError as exc:
        print(f"[W&B] log_code failed ({exc}); continuing without code artifact")


def load_synced_config(hydra_config: DictConfig, rank: int) -> PretrainConfig:
    objects = [None]
    if rank == 0:
        config = PretrainConfig(**OmegaConf.to_container(hydra_config, resolve=True))  # type: ignore

        # Naming
        if config.project_name is None:
            config.project_name = f"{Path(config.data.path).stem.capitalize()} HLM-torch"
        if config.run_name is None:
            config.run_name = os.environ.get("MLP_TASK_NAME", f"{config.arch.name.split('@')[-1]} {coolname.generate_slug(2)}")  # pyright: ignore[reportPrivateImportUsage]
        if config.checkpoint_path is None:
            config.checkpoint_path = os.path.join("checkpoints", config.project_name, config.run_name)

        objects = [config]

    dist.broadcast_object_list(objects, src=0)
    return objects[0]  # type: ignore


@hydra.main(config_path="config", config_name="cfg_pretrain", version_base=None)
def launch(hydra_config: DictConfig):
    WORLD_SIZE = 1
    RANK = 0
    DEVICE_ID = 0

    # Initialize distributed training if in distributed environment (e.g. torchrun)
    if "LOCAL_RANK" in os.environ:
        # Initialize distributed, default device and dtype
        dist.init_process_group(backend="nccl")

        WORLD_SIZE = dist.get_world_size()
        RANK = dist.get_rank()
        DEVICE_ID = int(os.environ["LOCAL_RANK"])

        torch.cuda.set_device(DEVICE_ID)

    # Load sync'ed config
    config = load_synced_config(hydra_config, rank=RANK)

    # Seed RNGs to ensure consistency
    torch.random.manual_seed(config.seed + RANK)

    # --- Training
    train_state, train_loader, train_metadata = init_train(config, rank=RANK, world_size=WORLD_SIZE)
    load_checkpoint(config, train_state, train_metadata, RANK)

    start_epoch, start_batch = resolve_resume_position(config)

    # --- In-training held-out eval (optional)
    eval_loader = None
    eval_carry = None
    if config.eval_interval is not None and config.eval_data_path is not None:
        local_batch_size = config.global_batch_size // WORLD_SIZE
        eval_cfg = config.model_copy(update={"data": config.data.model_copy(update={"path": config.eval_data_path})})
        eval_loader, eval_metadata = create_dataloader(eval_cfg, local_batch_size, drop_last_batch=False,
                                                       rank=RANK, world_size=WORLD_SIZE, fixed_epoch=True)
        with torch.device("cuda"):
            eval_carry = train_state.model.model.initial_carry(local_batch_size, dtype=getattr(torch, config.fwd_bwd_dtype))  # pyright: ignore[reportCallIssue]
        if RANK == 0:
            print(f"[Eval] every {config.eval_interval} steps on {eval_metadata.total_length:,} tokens from {config.eval_data_path}")

    # Progress bar and logger
    progress_bar = None
    if RANK == 0:
        progress_bar = tqdm.tqdm(total=train_state.total_steps)

        wandb.init(project=config.project_name, name=config.run_name, config=config.model_dump() | {"train_metadata": train_metadata.model_dump()},
                   settings=wandb.Settings(_disable_stats=True))  # type: ignore
        wandb.log({"num_params": sum(x.numel() for x in train_state.model.parameters())}, step=0)
        save_code_and_config(config, train_metadata)

    # Training Loop
    # epoch_base = global step count at the start of the current epoch, so
    # (step - epoch_base) is the batch offset inside it (used by mid-epoch
    # checkpoints). When resuming mid-epoch, the already-done batches count.
    pending_start_batch = start_batch
    for epoch in range(start_epoch + 1, config.epochs + 1):
        print (f"[Rank {RANK}, World Size {WORLD_SIZE}]: Epoch {epoch}")
        epoch_base = train_state.step - pending_start_batch
        pending_start_batch = 0

        # ############ Train Iter
        train_state.model.train()
        for batch, batch_info in train_loader:
            train_state.step += 1
            lr = update_lr(config, train_state)
            # Extra train arguments (such as BP warmup etc.)
            train_extra_args = train_state.model.compute_train_extra_args(train_state)  # pyright: ignore[reportCallIssue]

            metrics = train_batch(train_state, batch | {k: wrap_tensor(torch.tensor(v, device="cpu")) for k, v in batch_info.items()}, **train_extra_args)

            if train_state.step % config.log_interval == 0:
                metrics = reduce_metrics(metrics, prefix="train/")
                if RANK == 0:
                    progress_bar.update(train_state.step - progress_bar.n)  # type: ignore
                    wandb.log(metrics | train_extra_args | {"train/lr": lr}, step=train_state.step)

            del metrics

            # Periodic held-out eval on the live weights -> same wandb run
            if eval_loader is not None and train_state.step % config.eval_interval == 0:
                eval_metrics = evaluate_inline(train_state, eval_loader, eval_carry, WORLD_SIZE)
                if RANK == 0:
                    print(f"[Eval @ step {train_state.step}] " + "  ".join(f"{k.split('/')[-1]}={v:.4f}" for k, v in eval_metrics.items()), flush=True)
                    wandb.log(eval_metrics, step=train_state.step)

            # Rolling mid-epoch checkpoint
            if (config.checkpoint_step_interval is not None and config.checkpoint_path is not None
                    and train_state.step % config.checkpoint_step_interval == 0):
                save_step_checkpoint(config, train_state, epoch, train_state.step - epoch_base, RANK, WORLD_SIZE)

        ############ EVAL STACK: TBD TODO

        ############ Checkpointing
        if (epoch % config.checkpoint_interval == 0) or (epoch == config.epochs):
            if config.checkpoint_path is not None:
                # Save checkpoint
                dcp.save({"model": train_state.model.state_dict(), "optim": get_optimizer_state_dict(train_state.model, train_state.optim)},  # pyright: ignore[reportPrivateImportUsage]
                         checkpoint_id=os.path.join(config.checkpoint_path, f"fsdp2_epoch_{epoch}"))
                # Save carry on all ranks
                torch.save(train_state.carry, os.path.join(config.checkpoint_path, f"carry_epoch_{epoch}.{RANK}.pt"))
                # Record step counter for exact continuation (resume_continue)
                if RANK == 0:
                    with open(os.path.join(config.checkpoint_path, f"train_state_epoch_{epoch}.json"), "wt") as f:
                        json.dump({"step": train_state.step, "world_size": WORLD_SIZE}, f)
                    # Mid-epoch checkpoints are superseded by this epoch checkpoint
                    prune_step_checkpoints(config, keep_step=None)

    # finalize
    if dist.is_initialized():
        dist.destroy_process_group()
    wandb.finish()


if __name__ == "__main__":
    launch()