File size: 15,208 Bytes
aed5b25 | 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 | #!/usr/bin/env python3
"""
Train GPT-2 on FineWeb-Edu for N steps (default 500) and upload the weight
difference (delta) before/after training to an HF Hub model repo, per
GPU model / precision (bf16, fp32).
- Deterministic mode ON (use_deterministic_algorithms + CUBLAS_WORKSPACE_CONFIG)
- GPU model is read via nvidia-smi (falls back to torch if that fails)
- bf16 only if the GPU supports it (Ampere or newer), fp32 always. Each is trained separately
- If a file for the same GPU model + precision already exists in the repo, print "exists"
(if all of them exist, exit right away; if only some exist, train only the missing ones)
- File name: {prefix}_{gpu slug}_{precision}.safetensors
e.g. delta_nvidia-geforce-rtx-4090_bf16.safetensors
Install:
pip install torch transformers datasets huggingface_hub safetensors numpy
Login:
huggingface-cli login (or the HF_TOKEN env var, or --token)
Run:
python delta_train.py --repo your-id/repo-name
"""
import os
# Must be set before importing torch (= before CUDA initialization)
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
import argparse
import gc
import hashlib
import math
import random
import re
import subprocess
import sys
import tempfile
from pathlib import Path
import numpy as np
import torch
# ----------------------------------------------------------------------------
# Arguments
# ----------------------------------------------------------------------------
def parse_args(argv=None):
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--repo", required=True, help="HF model repo to upload the deltas to (e.g. user/gpt2-deltas)")
p.add_argument("--token", default=None, help="HF token (if omitted, the HF_TOKEN env var / saved login is used)")
p.add_argument("--private", action="store_true", help="create the repo as private if it has to be newly created")
p.add_argument("--prefix", default="delta", help="file name prefix")
p.add_argument("--steps", type=int, default=500)
p.add_argument("--seq-len", type=int, default=512)
p.add_argument("--micro-batch", type=int, default=4)
p.add_argument("--grad-accum", type=int, default=4)
p.add_argument("--lr", type=float, default=None, help="default: 1e-4 pretrained / 6e-4 from scratch")
p.add_argument("--warmup", type=int, default=20)
p.add_argument("--weight-decay", type=float, default=0.1)
p.add_argument("--clip", type=float, default=1.0)
p.add_argument("--seed", type=int, default=1337)
p.add_argument("--from-scratch", action="store_true", help="start from random init (fixed seed) instead of pretrained gpt2")
p.add_argument("--dataset-config", default="sample-10BT", help="fineweb-edu config name")
p.add_argument("--cache-dir", default=".cache", help="cache folder for the tokenized data")
p.add_argument("--log-every", type=int, default=50)
args = p.parse_args(argv)
if args.lr is None:
args.lr = 6e-4 if args.from_scratch else 1e-4
return args
# ----------------------------------------------------------------------------
# GPU model / file name
# ----------------------------------------------------------------------------
def get_gpu_name() -> str:
"""Get the GPU name via nvidia-smi. Fall back to torch if that fails."""
first = os.environ.get("CUDA_VISIBLE_DEVICES", "").split(",")[0].strip()
if first and not first.isdigit(): # if given as a UUID etc., the index can't be determined
return torch.cuda.get_device_name(0)
idx = first if first else "0"
try:
out = subprocess.run(
["nvidia-smi", "-i", idx, "--query-gpu=name", "--format=csv,noheader"],
capture_output=True, text=True, check=True,
).stdout.strip()
name = out.splitlines()[0].strip()
if name:
return name
except (FileNotFoundError, subprocess.CalledProcessError, IndexError):
pass
print("[warning] nvidia-smi failed -> getting the GPU name via torch", file=sys.stderr)
return torch.cuda.get_device_name(0)
def slugify(name: str) -> str:
return re.sub(r"[^A-Za-z0-9]+", "-", name).strip("-").lower()
def tensor_name(prefix: str, gpu_slug: str, precision: str) -> str:
return f"{prefix}_{gpu_slug}_{precision}.safetensors"
def bf16_supported() -> bool:
# Only count native support (Ampere or newer, compute capability >= 8), not emulation
return torch.cuda.get_device_capability(0)[0] >= 8
# ----------------------------------------------------------------------------
# Reproducibility settings
# ----------------------------------------------------------------------------
def set_determinism(seed: int):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
# Turn TF32 off so fp32 training really runs in fp32
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
# ----------------------------------------------------------------------------
# Data: stream FineWeb-Edu -> GPT-2 tokenization (no shuffling, taken from the start -> identical data for everyone)
# ----------------------------------------------------------------------------
def load_tokens(args, n_tokens: int) -> np.ndarray:
cache = Path(args.cache_dir) / f"fwedu_{args.dataset_config}_{n_tokens}.npy"
if cache.exists():
print(f"[data] using cache: {cache}")
return np.load(cache)
from datasets import load_dataset
from transformers import AutoTokenizer
print(f"[data] streaming FineWeb-Edu ({args.dataset_config}) + tokenizing, tokens needed: {n_tokens:,}")
tok = AutoTokenizer.from_pretrained("gpt2")
tok.model_max_length = 10**9 # silence the long-document warning
eos = tok.eos_token_id
ds = load_dataset("HuggingFaceFW/fineweb-edu", name=args.dataset_config, split="train", streaming=True)
chunks, total, texts = [], 0, []
def flush():
nonlocal total
for ids in tok(texts)["input_ids"]:
arr = np.asarray(ids + [eos], dtype=np.int32)
chunks.append(arr)
total += len(arr)
texts.clear()
it = iter(ds)
try:
for ex in it:
texts.append(ex["text"])
if len(texts) == 256:
flush()
if total >= n_tokens:
break
finally:
# If the streaming iterator is cut off midway and just left there, the program sometimes
# hangs instead of finishing at exit, so clean it up
del it, ds
gc.collect()
if texts:
flush()
if total < n_tokens:
sys.exit(f"Not enough data: {total:,} < {n_tokens:,}")
tokens = np.concatenate(chunks)[:n_tokens]
cache.parent.mkdir(parents=True, exist_ok=True)
np.save(cache, tokens)
return tokens
# ----------------------------------------------------------------------------
# Model / optimizer
# ----------------------------------------------------------------------------
def build_model(args):
from transformers import AutoModelForCausalLM, GPT2Config
# dropout 0 + eager attention: minimize anything that varies by GPU type
drop = dict(attn_pdrop=0.0, resid_pdrop=0.0, embd_pdrop=0.0)
if args.from_scratch:
cfg = GPT2Config(**drop)
return AutoModelForCausalLM.from_config(cfg, attn_implementation="eager")
return AutoModelForCausalLM.from_pretrained("gpt2", attn_implementation="eager", **drop)
def make_optimizer(model, lr: float, wd: float):
params = [p for p in model.parameters() if p.requires_grad] # tied weights are picked up only once
decay = [p for p in params if p.ndim >= 2]
no_decay = [p for p in params if p.ndim < 2]
return torch.optim.AdamW(
[{"params": decay, "weight_decay": wd}, {"params": no_decay, "weight_decay": 0.0}],
lr=lr, betas=(0.9, 0.95), eps=1e-8,
)
def lr_factor(step: int, warmup: int, total: int) -> float:
if step < warmup:
return (step + 1) / warmup
prog = (step - warmup) / max(1, total - warmup)
return 0.1 + 0.9 * 0.5 * (1.0 + math.cos(math.pi * prog)) # cosine, minimum 10%
# ----------------------------------------------------------------------------
# One training run -> delta
# ----------------------------------------------------------------------------
def train_one(precision: str, batches: torch.Tensor, args, device: torch.device):
set_determinism(args.seed) # every precision starts from the same seed
model = build_model(args).to(device)
model.train()
init = {n: p.detach().float().cpu().clone() for n, p in model.named_parameters()}
opt = make_optimizer(model, args.lr, args.weight_decay)
sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: lr_factor(s, args.warmup, args.steps))
use_bf16 = precision == "bf16"
mb, accum = args.micro_batch, args.grad_accum
first_loss = last_loss = float("nan")
for step in range(args.steps):
loss_sum = torch.zeros((), device=device)
for k in range(accum):
i = (step * accum + k) * mb
x = batches[i:i + mb].to(device)
with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=use_bf16):
loss = model(input_ids=x, labels=x).loss
(loss / accum).backward()
loss_sum += loss.detach() / accum
torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)
opt.step()
sched.step()
opt.zero_grad(set_to_none=True)
if step == 0 or (step + 1) % args.log_every == 0 or step + 1 == args.steps:
last_loss = loss_sum.item()
if step == 0:
first_loss = last_loss
print(f" [{precision}] step {step + 1:>4}/{args.steps} loss {last_loss:.4f}")
# delta is always saved as fp32 (it comes from named_parameters, so the tied lm_head is left out)
delta = {n: (p.detach().float().cpu() - init[n]).contiguous() for n, p in model.named_parameters()}
delta_l2 = math.sqrt(sum(float(d.pow(2).sum()) for d in delta.values()))
del model, opt, sched
if device.type == "cuda":
torch.cuda.empty_cache()
return delta, {"loss_first": first_loss, "loss_last": last_loss, "delta_l2": delta_l2}
# ----------------------------------------------------------------------------
# HF Hub
# ----------------------------------------------------------------------------
def ensure_repo(api, repo: str, private: bool):
from huggingface_hub.utils import RepositoryNotFoundError
try:
api.repo_info(repo, repo_type="model")
except RepositoryNotFoundError:
print(f"[HF] repo not found, created a new one: {repo}")
api.create_repo(repo, repo_type="model", private=private, exist_ok=True)
def plan_runs(api, repo: str, prefix: str, gpu_slug: str, precisions):
"""Print "exists" for (GPU model, precision) pairs already uploaded and skip them. Return the remaining (precision, file name) list."""
todo = []
for prec in precisions:
name = tensor_name(prefix, gpu_slug, prec)
if api.file_exists(repo_id=repo, filename=name, repo_type="model"):
print(f"exists: {name}")
else:
todo.append((prec, name))
return todo
# ----------------------------------------------------------------------------
# main
# ----------------------------------------------------------------------------
def main(argv=None):
args = parse_args(argv)
if not torch.cuda.is_available():
sys.exit("A CUDA GPU is required")
device = torch.device("cuda:0")
from huggingface_hub import HfApi
from safetensors.torch import save_file
gpu = get_gpu_name()
slug = slugify(gpu)
precisions = (["bf16"] if bf16_supported() else []) + ["fp32"]
print(f"[GPU] {gpu} -> {slug}")
print(f"[precision] {', '.join(precisions)}" + ("" if "bf16" in precisions else " (this GPU does not support bf16)"))
api = HfApi(token=args.token)
ensure_repo(api, args.repo, args.private)
todo = plan_runs(api, args.repo, args.prefix, slug, precisions)
if not todo:
return # all of them already exist -> exit
# Data (every precision uses the same tokens)
n_seq = args.steps * args.grad_accum * args.micro_batch
tokens = load_tokens(args, n_seq * args.seq_len)
data_sha = hashlib.sha256(tokens.tobytes()).hexdigest()[:16]
batches = torch.from_numpy(tokens.astype(np.int64)).view(n_seq, args.seq_len)
import transformers
with tempfile.TemporaryDirectory() as tmp:
for prec, name in todo:
print(f"\n=== {prec} training started -> {name} ===")
delta, st = train_one(prec, batches, args, device)
meta = {
"gpu": gpu, "precision": prec, "deterministic": "true",
"init": "scratch" if args.from_scratch else "gpt2",
"steps": str(args.steps), "seq_len": str(args.seq_len),
"micro_batch": str(args.micro_batch), "grad_accum": str(args.grad_accum),
"lr": str(args.lr), "warmup": str(args.warmup), "weight_decay": str(args.weight_decay),
"clip": str(args.clip), "seed": str(args.seed),
"dataset": f"HuggingFaceFW/fineweb-edu:{args.dataset_config}", "data_sha256": data_sha,
"loss_first": f"{st['loss_first']:.6f}", "loss_last": f"{st['loss_last']:.6f}",
"delta_l2": f"{st['delta_l2']:.6f}",
"torch": torch.__version__, "cuda": str(torch.version.cuda),
"cudnn": str(torch.backends.cudnn.version()), "transformers": transformers.__version__,
}
path = Path(tmp) / name
save_file(delta, str(path), metadata=meta)
# Someone else may have uploaded it while we were training, so check once more right before uploading
if api.file_exists(repo_id=args.repo, filename=name, repo_type="model"):
print(f"exists: {name}")
continue
api.upload_file(
path_or_fileobj=str(path), path_in_repo=name, repo_id=args.repo,
repo_type="model", commit_message=f"add {name}",
)
print(f"[HF] upload complete: {args.repo}/{name} (loss {st['loss_first']:.3f} -> {st['loss_last']:.3f})")
if __name__ == "__main__":
# Using datasets streaming together with the tokenizer can leave background threads running, so the
# process sometimes hangs instead of exiting even after it's done (confirmed directly). Once all the
# work is finished, terminate immediately.
code = 0
try:
main()
except SystemExit as e:
if isinstance(e.code, str):
print(e.code, file=sys.stderr)
code = 1
else:
code = e.code or 0
except BaseException:
import traceback
traceback.print_exc()
code = 1
sys.stdout.flush()
sys.stderr.flush()
os._exit(code) |