File size: 10,762 Bytes
6661fea | 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 | #!/usr/bin/env python3
"""Launch clean Base 1.10 (no non-commercial data, 10 slots, 10B positions) from k95 on one Linux GPU node.
This program never rents a VM.
INPUTS contains queue.json, train.bin, val.bin, tokenizer.json, wagi_95000.pt and
SHA256SUMS. The approved SHA256SUMS must list exactly queue.json, train.bin and
val.bin. Its SHA-256 is passed from the data handoff; code, tokenizer and k95 are
pinned below. OUT must be on persistent storage. --check does not start training.
"""
import argparse
from hashlib import file_digest
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
TRAINER_SHA = "592ac0552bff64c489aa1036143e94d591f29a19d55aa2f13ecccbafc0bd01a8"
K95_SHA = "ad675d0cd61b2291b4cfbfd93c8a5d28217a12498fef7c7f997728911ddb952b"
TOK_SHA = "0640d3bd3674d7a6e59c540d945a2ad275a12e1bcaeb6007c37a90751f9815dd"
RECEIPT_FILES = {"train.bin", "val.bin", "queue.json"}
BLOCK, BATCH, SLOTS = 4096, 256, 10
FIRST_TRAIN_TOKEN_CAP = 10_000_000_000
# Ten equal complete slots; each needs an extra block for the sampler's offset.
SLOT_STEPS = (FIRST_TRAIN_TOKEN_CAP // (SLOTS * BLOCK) - 1) // BATCH
LR_ARGS = ("--lr", "6e-4", "--min-lr", "6e-4", "--schedule", "wsd", "--decay-frac", "0")
HEX = re.compile(r"[0-9a-f]{64}")
ARCH = {"vocab": 32768, "block": BLOCK, "n_layer": 20, "n_embd": 2048, "n_head": 16,
"norm": "rmsnorm", "norm_eps": 1e-6, "pos": "rope", "rope_theta": 500000,
"ffn": "swiglu", "ffn_mult": 2.667, "attn_bias": 0,
"value_residual": True, "qk_norm": True, "logit_cap": 0, "z_loss": 0}
def digest(path):
with path.open("rb") as stream:
return file_digest(stream, "sha256").hexdigest()
def require_hash(path, expected):
if not HEX.fullmatch(expected) or digest(path) != expected:
raise ValueError(f"SHA-256 mismatch: {path.name}")
def validate_queue(queue, train_tokens):
if not 0 < train_tokens <= FIRST_TRAIN_TOKEN_CAP:
raise ValueError("train.bin exceeds the token cap or is empty")
schedule = [sid for rotation in queue["rotations"] for sid in rotation]
if queue["steps_per_shard"] != SLOT_STEPS or len(schedule) != SLOTS or len(set(schedule)) != SLOTS:
raise ValueError(f"queue must contain {SLOTS} distinct {SLOT_STEPS}-update slots")
if set(schedule) != set(queue["shards"]):
raise ValueError("queue shard IDs do not match the schedule")
spans = sorted((queue["shards"][sid]["lo"], queue["shards"][sid]["hi"], sid) for sid in schedule)
end = 0
for lo, hi, sid in spans:
if not (lo == end < hi <= train_tokens and hi - lo >= (SLOT_STEPS * BATCH + 1) * BLOCK
and HEX.fullmatch(queue["shards"][sid]["sha256"])):
raise ValueError(f"invalid, overlapping, or undersized shard: {sid}")
end = hi
if end != train_tokens:
raise ValueError("queue does not cover train.bin exactly")
def preflight(inputs, trainer, receipt_sha):
receipt = inputs / "SHA256SUMS"
require_hash(receipt, receipt_sha)
entries = {}
for line in receipt.read_text(encoding="ascii").splitlines():
sha, name = line.split(" ", 1)
if name not in RECEIPT_FILES or name in entries or not HEX.fullmatch(sha):
raise ValueError("invalid receipt entry")
entries[name] = sha
if entries.keys() != RECEIPT_FILES:
raise ValueError("incomplete data receipt")
require_hash(trainer, TRAINER_SHA)
require_hash(inputs / "wagi_95000.pt", K95_SHA)
require_hash(inputs / "tokenizer.json", TOK_SHA)
train_bytes = (inputs / "train.bin").stat().st_size
val_bytes = (inputs / "val.bin").stat().st_size
if train_bytes % 2 or val_bytes % 2 or val_bytes < 2 * (BLOCK + 2):
raise ValueError("expected uint16 train.bin and nonempty validation windows")
if train_bytes // 2 > FIRST_TRAIN_TOKEN_CAP:
raise ValueError("train.bin exceeds the token cap")
for name, pin in entries.items():
require_hash(inputs / name, pin)
validate_queue(json.loads((inputs / "queue.json").read_bytes()), train_bytes // 2)
print(f"PREFLIGHT-OK: trainer, k95, tokenizer and {SLOTS} data slots verified", flush=True)
def checkpoint_step(path):
import torch
c = torch.load(path, map_location="cpu", weights_only=True, mmap=True)
step = c["step"]
if type(step) is not int:
raise ValueError("checkpoint has invalid step")
return step
def checkpoint_sha(out, step):
expected = None
with (out / "events.jsonl").open(encoding="utf-8") as stream:
for line in stream:
event = json.loads(line)
if event.get("kind") == "checkpoint" and event.get("updates") == step:
expected = event["sha256"]
if expected is None:
raise ValueError("missing checkpoint event; do not advance the slot")
return expected
def snapshot(out, step):
ck = out / "ckpt.pt"
if checkpoint_step(ck) != step:
raise ValueError("checkpoint step differs from slot boundary")
expected = checkpoint_sha(out, step)
require_hash(ck, expected)
history = out / "history"
history.mkdir(exist_ok=True)
# r24.2 atomically replaces ckpt.pt; a hardlink preserves these bytes without copying weights.
target = history / f"ckpt_{step}.pt"
try:
os.link(ck, target)
except FileExistsError:
require_hash(target, expected)
print(f"CHECKPOINT-OK update={step} sha256={expected} file={target}", flush=True)
def train(args):
import fcntl
out, inputs = args.out, args.inputs
out.mkdir(parents=True, exist_ok=True)
with (out / "launch.lock").open("a") as lock:
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
ck = out / "ckpt.pt"
contract = json.dumps({"data_receipt": args.receipt_sha, "warmup": args.warmup,
"trainer_sha256": TRAINER_SHA,
"launcher_sha256": digest(Path(__file__))}, sort_keys=True) + "\n"
marker = out / "launch.json"
if marker.exists():
if marker.read_text(encoding="ascii") != contract:
raise ValueError("run directory is bound to different inputs or schedule")
else:
if ck.exists() or (out / "events.jsonl").exists():
raise ValueError("refusing to adopt an existing run without its launch record")
with marker.open("x", encoding="ascii") as stream:
stream.write(contract)
if checkpoint_step(inputs / "wagi_95000.pt") != 95000:
raise ValueError("unexpected parent checkpoint update")
step = checkpoint_step(ck) if ck.exists() else 0
if not 0 <= step <= SLOT_STEPS * SLOTS:
raise ValueError("recovery checkpoint is outside this run")
if step and step % SLOT_STEPS == 0:
snapshot(out, step)
elif step:
require_hash(ck, checkpoint_sha(out, step))
for prior in range(SLOT_STEPS, step, SLOT_STEPS):
if not (out / "history" / f"ckpt_{prior}.pt").is_file():
raise ValueError(f"missing preceding milestone {prior}")
while step < SLOT_STEPS * SLOTS:
gpu = subprocess.check_output(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], text=True).splitlines()
if len(gpu) != 8 or len(set(gpu)) != 1 or not any(kind in gpu[0] for kind in ("H200", "RTX PRO 6000")):
raise ValueError("expected eight identical H200 or RTX PRO 6000 GPUs")
busy = subprocess.check_output(["nvidia-smi", "--query-compute-apps=pid", "--format=csv,noheader"], text=True)
if busy.strip() or shutil.disk_usage(out).free < 24 * 2**30:
raise ValueError("GPU occupied or less than 24 GiB available for recovery writes")
expected = (step // SLOT_STEPS + 1) * SLOT_STEPS
env = {k: v for k, v in os.environ.items()
if k not in {"HF_TOKEN", "HUGGING_FACE_HUB_TOKEN", "HUGGINGFACE_HUB_TOKEN", "PYTHONPATH", "CUDA_VISIBLE_DEVICES"}}
env.update(HF_HUB_OFFLINE="1", HF_DATASETS_OFFLINE="1", OMP_NUM_THREADS="4",
CUDA_DEVICE_ORDER="PCI_BUS_ID", PYTHONUNBUFFERED="1")
if (Path.home() / ".cache/huggingface/token").exists() or (Path.home() / ".huggingface/token").exists():
raise ValueError("HF token file must not be present on the training node")
arch = []
for name, value in ARCH.items():
arch.append("--" + name.replace("_", "-"))
if value is not True:
arch.append(str(value))
cmd = [sys.executable, "-m", "torch.distributed.run", "--standalone", "--nproc-per-node", "8",
str(args.trainer), "--data-dir", str(inputs), "--out-dir", str(out),
"--run-id", "slayer1b_110c", "--dtype", "uint16", "--steps", str(SLOTS * SLOT_STEPS),
"--queue", str(inputs / "queue.json"), "--queue-one-slot", "--data-seed", "20261127", "--seed", "1",
"--batch", str(BATCH), "--grad-accum", "8", "--loss-chunk", "1024", "--compile",
"--optimizer", "muon", "--muon-lr", "0.02",
"--wd", "0.1", "--grad-clip", "1.0", *LR_ARGS,
"--warmup", str(args.warmup), "--log-every", "10", "--eval-every", "200",
"--eval-iters", "20", "--eval-batch", "4",
"--events-jsonl", str(out / "events.jsonl"), "--ckpt-every", "400", *arch]
cmd += ["--resume"] if ck.exists() else ["--init-from", str(inputs / "wagi_95000.pt")]
subprocess.run(cmd, check=True, env=env)
snapshot(out, expected)
step = expected
print(f"RUN-DONE update={SLOT_STEPS * SLOTS}", flush=True)
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("inputs", type=lambda s: Path(s).resolve())
p.add_argument("trainer", type=lambda s: Path(s).resolve())
p.add_argument("out", type=lambda s: Path(s).resolve())
p.add_argument("receipt_sha")
p.add_argument("--check", action="store_true")
p.add_argument("--warmup", type=int, help="warmup steps selected after the stability probe")
args = p.parse_args()
if not args.check and (args.warmup is None or not 1 <= args.warmup <= 1000):
p.error("training requires --warmup in [1, 1000] after the stability probe")
try:
preflight(args.inputs, args.trainer, args.receipt_sha)
if not args.check:
train(args)
except (OSError, ValueError, KeyError, TypeError, subprocess.CalledProcessError) as exc:
p.exit(2, f"STOP: {exc}\n")
if __name__ == "__main__":
main()
|