efe-T's picture
update code/train/train_hgpt.py
2f3cb1c verified
Raw History Blame Contribute Delete
18 kB
"""HGpt pretraining on FineWeb-Edu (GPT-2 tokens) on one GPU, resumable on any VM.
Run (on the training VM; tools/launch_train.py starts it on Colab):
python train/train_hgpt.py --target-tokens 2000000000 --repo efe-T/HGpt --visibility public
python train/train_hgpt.py --smoke --run-dir /tmp/run (tiny model, synthetic data, CPU)
Recipe (EGITIM_PLANI.md, as Experiment-1-A where it applies): HybridConfig(attn_window=32768),
bf16 parameters, torch.compile, rows of 131,072 tokens x 4 accumulated = 524,288 tokens per
step, build_optimizers() learning rates, no warmup, constant LR then a linear cooldown over
the last 17% of the steps, Muon momentum 0.85 -> 0.95 over 300 steps, a fixed 32,768-token
attention window from the first step, delta memory and KV cache carried from
row to row (TBPTT), a finite-loss check before the first update.
Every token is read once (train/data.py). Checkpoints every 30 minutes, on demand
(tools/train_ctl.py) and at the end go to the run's store (train/store.py), so a restart on
any VM continues from the very next token; metrics go to metrics/metrics.jsonl in the same
store (tools/watch.py). --max-steps / --max-hours end a session with a checkpoint.
"""
import argparse
import math
import sys
import time
from pathlib import Path
import numpy as np
import torch
from torch.nn import functional as F
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "train"))
from HGpt import HybridConfig, HybridGPT, build_optimizers # noqa: E402
from checkpoint import CheckpointWriter, ControlChannel, resume, snapshot # noqa: E402
from data import TokenStream, write_shard # noqa: E402
from metrics import REMOTE_PATH, MetricsLogger # noqa: E402
from store import FolderStore, HubStore # noqa: E402
DATASET = "kjj0/finewebedu10B-gpt2"
SHARD_TOKENS = 100_000_000 # every train shard of DATASET
CODE_FILES = ["HGpt.py", "train/train_hgpt.py", "train/data.py", "train/checkpoint.py",
"train/store.py", "train/metrics.py"]
def parse_args(argv=None):
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
p.add_argument("--target-tokens", type=int, default=2_000_000_000)
p.add_argument("--row-tokens", type=int, help="tokens per training row (default: 131072)")
p.add_argument("--accum", type=int, help="rows per optimizer step (default: 4)")
p.add_argument("--attn-window", type=int, help="fixed local attention window in tokens (default: 32768)")
p.add_argument("--cooldown", type=float, default=0.17, help="fraction of the steps with LR going to 0")
p.add_argument("--repo", help="Hugging Face repo for checkpoints and metrics")
p.add_argument("--visibility", choices=("public", "private"), help="required with --repo")
p.add_argument("--store-dir", help="a local directory as the store instead of --repo")
p.add_argument("--run-dir", default="/content/run")
p.add_argument("--data-dir", default="/content/data")
p.add_argument("--val-tokens", type=int, default=2_097_152)
p.add_argument("--val-every-tokens", type=int, default=100_000_000)
p.add_argument("--ckpt-minutes", type=float, default=30.0)
p.add_argument("--log-every", type=int, default=10)
p.add_argument("--push-every", type=float, default=300.0, help="seconds between metrics pushes")
p.add_argument("--max-steps", type=int, help="end this session after this many steps (checkpoint)")
p.add_argument("--max-hours", type=float, help="end this session after this long (checkpoint)")
p.add_argument("--require-resume", action="store_true",
help="fail if there is no checkpoint to resume")
p.add_argument("--shutdown", action="store_true",
help="release the Colab VM when the session ends (target, --max-hours, --max-steps or a stop "
"request) and its last checkpoint reached the store")
p.add_argument("--no-compile", action="store_true")
p.add_argument("--baseline-kernels", action="store_true",
help="keep FlexAttention/Triton and fla instead of HybridGPT.select_backends (same math)")
p.add_argument("--seed", type=int, default=0)
p.add_argument("--smoke", action="store_true", help="tiny model and synthetic shards (CPU)")
args = p.parse_args(argv)
for name, regular, tiny in (("row_tokens", 131_072, 64), ("accum", 4, 2), ("attn_window", 32_768, 32)):
if getattr(args, name) is None:
setattr(args, name, tiny if args.smoke else regular)
elif getattr(args, name) < 1:
p.error(f"--{name.replace('_', '-')} must be positive")
if args.smoke: # small defaults for whatever was not given explicitly
smoke = {"target_tokens": 20 * 128, "val_tokens": 4 * args.row_tokens,
"val_every_tokens": 1024, "log_every": 2, "push_every": 0.0}
for name, value in smoke.items():
if getattr(args, name) == p.get_default(name):
setattr(args, name, value)
if args.repo and args.visibility is None:
p.error("--repo needs --visibility public|private")
if bool(args.repo) == bool(args.store_dir) and not args.smoke:
p.error("give exactly one of --repo or --store-dir")
return args
def model_config(args):
if args.smoke:
return HybridConfig(vocab_size=512, n_layer=12, n_head=2, n_embd=64, delta_heads=2, delta_head_dim=32,
attn_window=args.attn_window, eos_token=511, backout_layer=8)
return HybridConfig(attn_window=args.attn_window)
def smoke_files(data_dir: Path):
"""Deterministic synthetic shards for --smoke (documents of random tokens, EOS-led)."""
data_dir.mkdir(parents=True, exist_ok=True)
rng = np.random.default_rng(1234)
names = [f"smoke_train_{i:06d}.bin" for i in (1, 2, 3)] + ["smoke_val_000000.bin"]
for name in names:
tokens = rng.integers(1, 511, 6000)
tokens[::300] = 511
write_shard(data_dir / name, tokens)
return [data_dir / n for n in names[:3]], data_dir / names[3]
def fetch_shards(names, revision, data_dir: Path):
from huggingface_hub import hf_hub_download
return [Path(hf_hub_download(DATASET, name, repo_type="dataset", revision=revision, local_dir=str(data_dir)))
for name in names]
def delta_stats(model):
"""Half-lives (tokens) the decay biases give each delta layer, and the size of the
token-dependent gate, as a cheap trace of how fast the memory timescales move."""
out = {}
for i, block in enumerate(model.transformer.h):
if block.delta is not None:
half = (math.log(2) / F.softplus(block.delta.decay_bias.detach().float())).sort().values
q = [half[int(f * (len(half) - 1))].item() for f in (0.1, 0.5, 0.9)]
out[f"layer{i}"] = {"half_life_p10_p50_p90": [round(x, 1) for x in q],
"c_gate_norm": round(block.delta.c_gate.weight.float().norm().item(), 4)}
return out
@torch.no_grad()
def evaluate(runner, model, val_rows, window, device):
"""Each val row on its own (an empty memory), called the way training calls the model
(memory in, memory out), so torch.compile needs one extra graph (no grad) and nothing else."""
losses = [runner(row[:-1].to(device), row[1:].to(device), attn_blocksize=window,
memory=model.init_memory(1, device), return_memory=True)[0].float() for row in val_rows]
return torch.stack(losses).mean().item()
def main(argv=None) -> int:
args = parse_args(argv)
run_dir = Path(args.run_dir)
run_dir.mkdir(parents=True, exist_ok=True)
device = torch.device("cuda" if torch.cuda.is_available() and not args.smoke else "cpu")
torch.manual_seed(args.seed)
cfg = model_config(args)
model = HybridGPT(cfg).to(device)
kernels = None
if device.type == "cuda":
model.to_bf16_training()
if not args.baseline_kernels: # eagerly, before torch.compile; falls back per kernel
kernels = model.select_backends(device)
print(f"kernels: {kernels}", flush=True)
optimizers = build_optimizers(model, compile_ns=device.type == "cuda")
base_lrs = [[g["lr"] for g in o.param_groups] for o in optimizers]
muon = optimizers[2]
runner = model if (args.no_compile or device.type != "cuda") else torch.compile(model)
if args.repo:
store = HubStore(args.repo, private=args.visibility == "private")
else:
store = FolderStore(args.store_dir or run_dir / "store")
metrics_path = run_dir / "metrics.jsonl"
if not metrics_path.exists():
store.download_file(REMOTE_PATH, metrics_path) # continue the history of a run from another VM
metrics = MetricsLogger(metrics_path, store=store, push_every=args.push_every)
control = ControlChannel(run_dir)
upload_state = {"ok": None} # whether the newest checkpoint reached the store
def upload(path, manifest):
"""A failed upload must not end a long run: retry, then keep the local checkpoint
(the next checkpoint uploads in full again)."""
for attempt in range(1, 4):
try:
store.upload(path, manifest)
upload_state["ok"] = True
return
except Exception as error:
metrics.log("event", step=manifest["step"], message=f"upload failed ({attempt}/3): {error}")
time.sleep(30 * attempt)
upload_state["ok"] = False
writer = CheckpointWriter(run_dir / "checkpoints", keep=2, on_saved=[
upload, control.acknowledge,
lambda path, m: metrics.log("checkpoint", step=m["step"], tokens=m["tokens"], name=m["name"],
write_s=m.get("write_seconds"))])
tokens_per_step = args.row_tokens * args.accum
total_steps = args.target_tokens // tokens_per_step
info = resume(run_dir / "checkpoints", model, optimizers, store=store, device=device)
if args.require_resume and info is None:
raise RuntimeError("No checkpoint found. This session requires a checkpoint to resume.")
step = info["step"] if info else 0
tokens = info["tokens"] if info else 0
if tokens != step * tokens_per_step:
raise ValueError("resuming requires the checkpoint's tokens per optimizer step; adjust --row-tokens and --accum together")
if args.smoke:
train_files, val_file = smoke_files(run_dir / "smoke_data")
revision = "smoke"
else:
needed = total_steps * tokens_per_step + 1
names = [f"finewebedu_train_{i:06d}.bin" for i in range(1, math.ceil(needed / SHARD_TOKENS) + 2)]
if info is not None: # same order as before; more shards only if the target grew
revision = info["loader"]["revision"]
names = info["loader"]["files"] + [n for n in names if n not in info["loader"]["files"]]
else:
from huggingface_hub import HfApi
revision = HfApi().dataset_info(DATASET).sha # pinned for the whole run
train_files = fetch_shards(names, revision, Path(args.data_dir))
val_file = fetch_shards(["finewebedu_val_000000.bin"], revision, Path(args.data_dir))[0]
stream = TokenStream(train_files, args.row_tokens, state=info["loader"] if info else None, revision=revision,
allow_row_resize=info is not None)
if stream.consumed_tokens != tokens:
raise ValueError("checkpoint token count does not match its data cursor")
val_stream = TokenStream([val_file], args.row_tokens)
val_rows = [r for r in (val_stream.next_row() for _ in range(args.val_tokens // args.row_tokens)) if r is not None]
# An empty memory instead of None: the same computation (forward creates exactly this one),
# but one input structure for torch.compile from the first row on (one graph, not two).
window = cfg.attn_window
memory = info["memory"] if info else None
memory = model.init_memory(1, device) if memory is None else memory.resize_attention(window)
extra = {"config": {k: v for k, v in cfg.__dict__.items()}, "args": vars(args), "dataset": DATASET,
"revision": revision, "total_steps": total_steps}
for name in CODE_FILES: # the exact code of this run, next to its checkpoints
store.upload_file((ROOT / name).read_bytes(), f"code/{name}")
metrics.log("run", target_tokens=args.target_tokens, total_steps=total_steps, start_step=step,
start_tokens=tokens, row_tokens=args.row_tokens, attn_window=window, accum=args.accum, revision=revision,
device=torch.cuda.get_device_name(0) if device.type == "cuda" else "cpu", kernels=kernels)
print(f"start at step {step}/{total_steps} ({tokens:,} tokens), revision {revision}, window {window}", flush=True)
cooldown_steps = max(1, round(args.cooldown * total_steps))
loss_acc, loss_n = torch.zeros((), device=device), 0
session_start = last_ckpt = last_log = time.time()
tokens_at_log, steps_this_session = tokens, 0
val_bucket = tokens // args.val_every_tokens
saved_step = step if info else None
first_step = step
reason = None
while reason is None:
if step >= total_steps:
reason = "target reached"
break
lr_scale = 1.0 if step < total_steps - cooldown_steps else (total_steps - step) / cooldown_steps
for opt, lrs in zip(optimizers, base_lrs):
for group, lr in zip(opt.param_groups, lrs):
group["lr"] = lr * lr_scale
muon.param_groups[0]["momentum"] = 0.85 + 0.10 * min(step / 300, 1.0)
rows = [stream.next_row() for _ in range(args.accum)]
if any(r is None for r in rows):
reason = "data exhausted" # never reached with enough shards; the rows read are dropped
break
batch = torch.stack(rows) # one pinned, asynchronous copy per step instead of a blocking one per row
batch = batch.pin_memory().to(device, non_blocking=True) if device.type == "cuda" else batch
for row in batch:
loss, memory = runner(row[:-1], row[1:], attn_blocksize=window, memory=memory, return_memory=True)
if step == first_step and loss_n == 0 and not torch.isfinite(loss):
raise FloatingPointError(f"first loss is {loss.item()} before any update; stopping")
loss.backward()
memory = memory.detach()
loss_acc += loss.detach().float()
loss_n += 1
grads = [p.grad for p in model.parameters() if p.grad is not None]
torch._foreach_div_(grads, args.accum)
for opt in optimizers:
opt.step()
model.zero_grad(set_to_none=True)
step += 1
steps_this_session += 1
tokens += tokens_per_step
if step % args.log_every == 0 or step == total_steps:
mean_loss = (loss_acc / loss_n).item()
now = time.time()
mem = torch.cuda.max_memory_allocated() / 2**30 if device.type == "cuda" else None
metrics.log("train", step=step, tokens=tokens, loss=round(mean_loss, 5),
tok_s=round((tokens - tokens_at_log) / max(now - last_log, 1e-9), 1),
lr=round(lr_scale, 6), window=window, mem_gb=None if mem is None else round(mem, 2))
print(f"step {step}/{total_steps} loss {mean_loss:.4f} lr {lr_scale:.3f} window {window} "
f"{(tokens - tokens_at_log) / max(now - last_log, 1e-9):,.0f} tok/s", flush=True)
if not math.isfinite(mean_loss):
metrics.log("event", step=step, message="non-finite loss: stopped without a checkpoint")
metrics.close()
return 3 # resume from the last good checkpoint
loss_acc.zero_()
loss_n, last_log, tokens_at_log = 0, now, tokens
if device.type == "cuda":
torch.cuda.reset_peak_memory_stats()
if step % 100 == 0:
metrics.log("delta", step=step, **delta_stats(model))
if tokens // args.val_every_tokens > val_bucket or step == total_steps:
val_bucket = tokens // args.val_every_tokens
val_loss = evaluate(runner, model, val_rows, window, device)
metrics.log("val", step=step, tokens=tokens, val_loss=round(val_loss, 5))
action = control.poll()
if action == "stop":
reason = "stop requested"
elif args.max_steps is not None and steps_this_session >= args.max_steps:
reason = "max steps for this session"
elif args.max_hours is not None and time.time() - session_start >= args.max_hours * 3600:
reason = "max hours for this session"
if action or reason or step == total_steps or time.time() - last_ckpt >= args.ckpt_minutes * 60:
writer.submit(snapshot(model, optimizers, step=step, tokens=tokens, memory=memory,
loader=stream.state(), extra=extra))
saved_step, last_ckpt = step, time.time()
if reason == "target reached" and saved_step != step:
writer.submit(snapshot(model, optimizers, step=step, tokens=tokens, memory=memory,
loader=stream.state(), extra=extra))
writer.wait()
metrics.log("end", step=step, tokens=tokens, reason=reason)
metrics.close()
print(f"end: {reason} at step {step} ({tokens:,} tokens)", flush=True)
if args.shutdown:
if upload_state["ok"] is False: # keep the VM: its disk holds the only copy of the checkpoint
print("the last checkpoint upload failed, so the VM stays up; upload it or resume here", flush=True)
return 4
try:
from google.colab import runtime
runtime.unassign()
except Exception as error:
print(f"could not release the VM ({error}); stop it with `colab stop`", flush=True)
return 0
if __name__ == "__main__":
sys.exit(main())