"""Multi-GPU training with FSDP2, with weight checkpointing + resume. Stage 2 is switched on by environment variables (see ar/train/stage2.py). Until step STAGE2_START everything runs exactly as Stage 1; from that step on, training uses the read-once loader on the Stage 2 files (with document masking), the Stage 2 LR schedule and no weight decay on 1-D (normalization) weights. No restart is needed at the switch. """ import os import shutil import time import argparse import torch import torch.nn.functional as F import torch.distributed as dist import torch.distributed.checkpoint as dcp from torch.distributed.checkpoint.state_dict import get_state_dict, set_state_dict from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( checkpoint_wrapper, ) from ar.model.config import ARConfig, small_config, tiny_config from ar.model.model import ARModel from ar.model.mask import build_doc_block_mask from ar.data.dataset import BinDataset from ar.data.readonce import ReadOnceDataset from ar.train.train_config import TrainConfig from ar.train.stage2 import ( Stage2Settings, lr_at, protected_ckpts, ckpts_to_delete, EOT_ID, ) from ar.model.rmsnorm import RMSNorm from ar.model.rope import build_rope_cache def setup(): dist.init_process_group(backend="nccl") rank = dist.get_rank() local_rank = int(os.environ["LOCAL_RANK"]) torch.cuda.set_device(local_rank) return rank, local_rank, dist.get_world_size() def _complete(ckpt_dir, d): # a checkpoint writes .metadata last, so its presence means the save finished return os.path.isfile(os.path.join(ckpt_dir, d, ".metadata")) def find_latest_ckpt(ckpt_dir): """Return path to the newest COMPLETE ckpt_ folder, or None.""" if not os.path.isdir(ckpt_dir): return None entries = [d for d in os.listdir(ckpt_dir) if d.startswith("ckpt_") and _complete(ckpt_dir, d)] if not entries: return None entries.sort(key=lambda d: int(d.split("_")[1])) return os.path.join(ckpt_dir, entries[-1]) def rotate_ckpts(ckpt_dir, keep=2, is_main=False): """Keep the newest `keep` complete checkpoints; delete older ones and any half-written leftovers. Folders named in PROTECT_CKPTS (e.g. the final Stage 1 one) are never touched.""" if not is_main or not os.path.isdir(ckpt_dir): return doomed = ckpts_to_delete(os.listdir(ckpt_dir), lambda d: _complete(ckpt_dir, d), keep, protected_ckpts()) for old in doomed: shutil.rmtree(os.path.join(ckpt_dir, old), ignore_errors=True) print(f"[ckpt] removed {old}", flush=True) def enough_disk(ckpt_dir, need_gb, device): """True if there's room for a checkpoint. Rank 0 decides and tells everyone, so either all GPUs save or none do (a split decision would hang training).""" ok = torch.tensor([int(shutil.disk_usage(ckpt_dir).free > need_gb * 1e9)], device=device) dist.broadcast(ok, src=0) return bool(ok.item()) # a test run can point this elsewhere, so it never reacts to the real run's flag RELOAD_FLAG = os.environ.get("RELOAD_FLAG", "/fsx/ajay-stu/AR/logs/RELOAD") def reload_requested(device): """Rank 0 checks for the reload flag and tells everyone, so all GPUs agree.""" flag = torch.tensor([int(os.path.exists(RELOAD_FLAG))], device=device) dist.broadcast(flag, src=0) return bool(flag.item()) def save_ckpt(model, opt, step, ckpt_dir, is_main): """Save FSDP-sharded model + optimizer + step atomically across all ranks.""" path = os.path.join(ckpt_dir, f"ckpt_{step}") # each rank writes its shards; DCP handles coordination model_sd, opt_sd = get_state_dict(model, opt) state = {"model": model_sd, "opt": opt_sd, "step": step} dcp.save(state_dict=state, checkpoint_id=path) dist.barrier() if is_main: print(f"[ckpt] saved step {step} -> {path}", flush=True) def load_ckpt(model, opt, ckpt_path, is_main): """Load a DCP checkpoint into the FSDP model/optimizer. Returns start_step.""" model_sd, opt_sd = get_state_dict(model, opt) state = {"model": model_sd, "opt": opt_sd, "step": 0} dcp.load(state_dict=state, checkpoint_id=ckpt_path) set_state_dict(model, opt, model_state_dict=state["model"], optim_state_dict=state["opt"]) start_step = int(state["step"]) if is_main: print(f"[ckpt] resumed from {ckpt_path} at step {start_step}", flush=True) return start_step @torch.no_grad() def init_weights(model, mcfg, device): """Re-fill every weight AND buffer after to_empty() (its memory is blank).""" resid_std = 0.02 * (2 * mcfg.n_layers) ** -0.5 for name, m in model.named_modules(): if isinstance(m, torch.nn.Linear): # residual-path outputs start smaller so the signal doesn't grow with depth std = resid_std if name.endswith(("o_proj", "down_proj")) else 0.02 torch.nn.init.normal_(m.weight, mean=0.0, std=std) elif isinstance(m, torch.nn.Embedding): torch.nn.init.normal_(m.weight, mean=0.0, std=0.02) elif isinstance(m, RMSNorm): for p in m.parameters(): torch.nn.init.ones_(p) # norms must start at 1 # RoPE tables are buffers, not weights, so recompute them for real cos, sin = build_rope_cache(mcfg.head_dim, mcfg.max_seq_len, mcfg.rope_theta) model.rope_cos.copy_(cos.to(device)) model.rope_sin.copy_(sin.to(device)) def train(bin_paths, weights, tcfg, mcfg): rank, local_rank, world = setup() is_main = rank == 0 device = torch.device("cuda", local_rank) s2 = Stage2Settings.from_env() # None = plain Stage 1, exactly as before if is_main and s2 is not None: print(f"[stage2] switch at step {s2.start}: {len(s2.bins)} files, LR " f"{s2.peak:g} -> {s2.min_lr:g} until step {tcfg.max_steps}", flush=True) mp_policy = MixedPrecisionPolicy( param_dtype=torch.bfloat16, reduce_dtype=torch.float32, ) with torch.device("meta"): model = ARModel(mcfg) for i, block in enumerate(model.blocks): model.blocks[i] = checkpoint_wrapper(block) for block in model.blocks: fully_shard(block, mp_policy=mp_policy) fully_shard(model, mp_policy=mp_policy) model.to_empty(device=device) model.train() # re-fill all weights and buffers (to_empty leaves memory blank) init_weights(model, mcfg, device) opt = torch.optim.AdamW(model.parameters(), lr=tcfg.peak_lr, betas=tcfg.betas, weight_decay=tcfg.weight_decay) # Stage 2 decays only matrices (embeddings, linears); 1-D norm gains are left alone decay_params = [p for p in model.parameters() if p.ndim >= 2] # resume from latest checkpoint if one exists os.makedirs(tcfg.ckpt_dir, exist_ok=True) start_step = 0 latest = find_latest_ckpt(tcfg.ckpt_dir) if latest is not None: start_step = load_ckpt(model, opt, latest, is_main) + 1 data1 = data2 = None # loaders are built when first needed t0 = time.time() for step in range(start_step, tcfg.max_steps): in_s2 = s2 is not None and step >= s2.start if in_s2 and data2 is None: data2 = ReadOnceDataset(s2.bins, tcfg.seq_len, s2.weights, s2.start, tcfg.max_steps, EOT_ID) if is_main: print(f"[stage2] read-once loader ready at step {step}", flush=True) if not in_s2 and data1 is None: data1 = BinDataset(bin_paths, tcfg.seq_len, weights) # Stage 1 loader, unchanged lr = lr_at(step, tcfg, s2) for g in opt.param_groups: g["lr"] = lr if in_s2: g["weight_decay"] = 0.0 # Stage 2: decay is applied by hand below # gradient accumulation: several micro-batches add up their gradients # before one weight update, so fewer GPUs can reproduce the same step opt.zero_grad(set_to_none=True) loss_sum = 0.0 for micro in range(tcfg.grad_accum): if in_s2: x, y, segment_ids = data2.get_batch(step, micro, tcfg.batch_size, rank, world, device) else: x, y, segment_ids = data1.get_batch(tcfg.batch_size, device) block_mask = build_doc_block_mask(segment_ids, tcfg.seq_len, device=device) logits = model(x, block_mask) # loss in fp32: bf16 scores over a 151,936-token vocab are too coarse loss = F.cross_entropy(logits.float().view(-1, logits.size(-1)), y.view(-1)) # divide so the summed gradient equals the average over all micro-batches (loss / tcfg.grad_accum).backward() loss_sum += loss.item() / tcfg.grad_accum grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), tcfg.grad_clip) if in_s2 and tcfg.weight_decay > 0: # same decoupled decay AdamW would apply, but on matrices only with torch.no_grad(): for p in decay_params: p.mul_(1.0 - lr * tcfg.weight_decay) opt.step() if step % tcfg.log_every == 0: # every rank joins: average loss over all GPUs, and the full gradient norm avg = torch.tensor([loss_sum], device=device) dist.all_reduce(avg) gn = grad_norm.full_tensor() if hasattr(grad_norm, "full_tensor") else grad_norm if is_main: dt = time.time() - t0 toks = ((step - start_step + 1) * tcfg.batch_size * tcfg.seq_len * world * tcfg.grad_accum) print(f"step {step:6d} | loss {avg.item() / world:.4f} | lr {lr:.2e} " f"| {toks/dt/1e3:.1f}k tok/s (all GPUs) | gnorm {gn.item():.3f}", flush=True) # save checkpoint every ckpt_every steps (and at the very end) if (step + 1) % tcfg.ckpt_every == 0 or step == tcfg.max_steps - 1: if enough_disk(tcfg.ckpt_dir, 150, device): save_ckpt(model, opt, step, tcfg.ckpt_dir, is_main) rotate_ckpts(tcfg.ckpt_dir, is_main=is_main, # keep 1 checkpoint when disk is tight keep=(2 if shutil.disk_usage(tcfg.ckpt_dir).free > 400e9 else 1)) # hot reload: stop right after a save when asked, so no work is lost if reload_requested(device): if is_main: print(f"[reload] stopping after step {step} to apply new settings", flush=True) break elif is_main: print(f"[ckpt] WARNING: disk nearly full, skipped save at step {step}", flush=True) dist.destroy_process_group() if __name__ == "__main__": p = argparse.ArgumentParser() p.add_argument("--bin", nargs="+", required=True) p.add_argument("--weights", nargs="+", type=float, default=None) p.add_argument("--max_steps", type=int, default=100) p.add_argument("--batch_size", type=int, default=1) p.add_argument("--seq_len", type=int, default=2048) p.add_argument("--warmup_steps", type=int, default=20) p.add_argument("--peak_lr", type=float, default=None) p.add_argument("--ckpt_every", type=int, default=None) p.add_argument("--ckpt_dir", type=str, default=None) p.add_argument("--model_size", choices=["small", "full", "tiny"], default="full") p.add_argument("--grad_accum", type=int, default=1) p.add_argument("--lr_horizon", type=int, default=None) p.add_argument("--log_every", type=int, default=None) args = p.parse_args() tcfg_kwargs = dict(max_steps=args.max_steps, batch_size=args.batch_size, seq_len=args.seq_len, warmup_steps=args.warmup_steps) tcfg_kwargs["grad_accum"] = args.grad_accum if args.lr_horizon is not None: tcfg_kwargs["lr_horizon"] = args.lr_horizon if args.peak_lr is not None: tcfg_kwargs["peak_lr"] = args.peak_lr tcfg_kwargs["min_lr"] = args.peak_lr * 0.1 if args.ckpt_every is not None: tcfg_kwargs["ckpt_every"] = args.ckpt_every if args.ckpt_dir is not None: tcfg_kwargs["ckpt_dir"] = args.ckpt_dir if args.log_every is not None: tcfg_kwargs["log_every"] = args.log_every tcfg = TrainConfig(**tcfg_kwargs) mcfg = {"small": small_config, "full": ARConfig, "tiny": tiny_config}[args.model_size]() train(args.bin, args.weights, tcfg, mcfg)