Download delta_train.py from Ilikemechuri/diloco_floating_point: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/Ilikemechuri/diloco_floating_point/resolve/main/delta_train.py
- Command line
-
hf download hf://Ilikemechuri/diloco_floating_point/delta_train.py
-
curl -L -o delta_train.py https://huggingface.co/Ilikemechuri/diloco_floating_point/resolve/main/delta_train.py
15.2 kB
| #!/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) |