Ilikemechuri commited on
Commit
aed5b25
·
verified ·
1 Parent(s): 046173d

Upload delta_train.py

Browse files
Files changed (1) hide show
  1. delta_train.py +369 -0
delta_train.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Train GPT-2 on FineWeb-Edu for N steps (default 500) and upload the weight
4
+ difference (delta) before/after training to an HF Hub model repo, per
5
+ GPU model / precision (bf16, fp32).
6
+
7
+ - Deterministic mode ON (use_deterministic_algorithms + CUBLAS_WORKSPACE_CONFIG)
8
+ - GPU model is read via nvidia-smi (falls back to torch if that fails)
9
+ - bf16 only if the GPU supports it (Ampere or newer), fp32 always. Each is trained separately
10
+ - If a file for the same GPU model + precision already exists in the repo, print "exists"
11
+ (if all of them exist, exit right away; if only some exist, train only the missing ones)
12
+ - File name: {prefix}_{gpu slug}_{precision}.safetensors
13
+ e.g. delta_nvidia-geforce-rtx-4090_bf16.safetensors
14
+
15
+ Install:
16
+ pip install torch transformers datasets huggingface_hub safetensors numpy
17
+ Login:
18
+ huggingface-cli login (or the HF_TOKEN env var, or --token)
19
+ Run:
20
+ python delta_train.py --repo your-id/repo-name
21
+ """
22
+ import os
23
+
24
+ # Must be set before importing torch (= before CUDA initialization)
25
+ os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
26
+
27
+ import argparse
28
+ import gc
29
+ import hashlib
30
+ import math
31
+ import random
32
+ import re
33
+ import subprocess
34
+ import sys
35
+ import tempfile
36
+ from pathlib import Path
37
+
38
+ import numpy as np
39
+ import torch
40
+
41
+
42
+ # ----------------------------------------------------------------------------
43
+ # Arguments
44
+ # ----------------------------------------------------------------------------
45
+ def parse_args(argv=None):
46
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
47
+ p.add_argument("--repo", required=True, help="HF model repo to upload the deltas to (e.g. user/gpt2-deltas)")
48
+ p.add_argument("--token", default=None, help="HF token (if omitted, the HF_TOKEN env var / saved login is used)")
49
+ p.add_argument("--private", action="store_true", help="create the repo as private if it has to be newly created")
50
+ p.add_argument("--prefix", default="delta", help="file name prefix")
51
+
52
+ p.add_argument("--steps", type=int, default=500)
53
+ p.add_argument("--seq-len", type=int, default=512)
54
+ p.add_argument("--micro-batch", type=int, default=4)
55
+ p.add_argument("--grad-accum", type=int, default=4)
56
+ p.add_argument("--lr", type=float, default=None, help="default: 1e-4 pretrained / 6e-4 from scratch")
57
+ p.add_argument("--warmup", type=int, default=20)
58
+ p.add_argument("--weight-decay", type=float, default=0.1)
59
+ p.add_argument("--clip", type=float, default=1.0)
60
+ p.add_argument("--seed", type=int, default=1337)
61
+ p.add_argument("--from-scratch", action="store_true", help="start from random init (fixed seed) instead of pretrained gpt2")
62
+
63
+ p.add_argument("--dataset-config", default="sample-10BT", help="fineweb-edu config name")
64
+ p.add_argument("--cache-dir", default=".cache", help="cache folder for the tokenized data")
65
+ p.add_argument("--log-every", type=int, default=50)
66
+
67
+ args = p.parse_args(argv)
68
+ if args.lr is None:
69
+ args.lr = 6e-4 if args.from_scratch else 1e-4
70
+ return args
71
+
72
+
73
+ # ----------------------------------------------------------------------------
74
+ # GPU model / file name
75
+ # ----------------------------------------------------------------------------
76
+ def get_gpu_name() -> str:
77
+ """Get the GPU name via nvidia-smi. Fall back to torch if that fails."""
78
+ first = os.environ.get("CUDA_VISIBLE_DEVICES", "").split(",")[0].strip()
79
+ if first and not first.isdigit(): # if given as a UUID etc., the index can't be determined
80
+ return torch.cuda.get_device_name(0)
81
+ idx = first if first else "0"
82
+ try:
83
+ out = subprocess.run(
84
+ ["nvidia-smi", "-i", idx, "--query-gpu=name", "--format=csv,noheader"],
85
+ capture_output=True, text=True, check=True,
86
+ ).stdout.strip()
87
+ name = out.splitlines()[0].strip()
88
+ if name:
89
+ return name
90
+ except (FileNotFoundError, subprocess.CalledProcessError, IndexError):
91
+ pass
92
+ print("[warning] nvidia-smi failed -> getting the GPU name via torch", file=sys.stderr)
93
+ return torch.cuda.get_device_name(0)
94
+
95
+
96
+ def slugify(name: str) -> str:
97
+ return re.sub(r"[^A-Za-z0-9]+", "-", name).strip("-").lower()
98
+
99
+
100
+ def tensor_name(prefix: str, gpu_slug: str, precision: str) -> str:
101
+ return f"{prefix}_{gpu_slug}_{precision}.safetensors"
102
+
103
+
104
+ def bf16_supported() -> bool:
105
+ # Only count native support (Ampere or newer, compute capability >= 8), not emulation
106
+ return torch.cuda.get_device_capability(0)[0] >= 8
107
+
108
+
109
+ # ----------------------------------------------------------------------------
110
+ # Reproducibility settings
111
+ # ----------------------------------------------------------------------------
112
+ def set_determinism(seed: int):
113
+ random.seed(seed)
114
+ np.random.seed(seed)
115
+ torch.manual_seed(seed)
116
+ torch.cuda.manual_seed_all(seed)
117
+ torch.use_deterministic_algorithms(True)
118
+ torch.backends.cudnn.deterministic = True
119
+ torch.backends.cudnn.benchmark = False
120
+ # Turn TF32 off so fp32 training really runs in fp32
121
+ torch.backends.cuda.matmul.allow_tf32 = False
122
+ torch.backends.cudnn.allow_tf32 = False
123
+
124
+
125
+ # ----------------------------------------------------------------------------
126
+ # Data: stream FineWeb-Edu -> GPT-2 tokenization (no shuffling, taken from the start -> identical data for everyone)
127
+ # ----------------------------------------------------------------------------
128
+ def load_tokens(args, n_tokens: int) -> np.ndarray:
129
+ cache = Path(args.cache_dir) / f"fwedu_{args.dataset_config}_{n_tokens}.npy"
130
+ if cache.exists():
131
+ print(f"[data] using cache: {cache}")
132
+ return np.load(cache)
133
+
134
+ from datasets import load_dataset
135
+ from transformers import AutoTokenizer
136
+
137
+ print(f"[data] streaming FineWeb-Edu ({args.dataset_config}) + tokenizing, tokens needed: {n_tokens:,}")
138
+ tok = AutoTokenizer.from_pretrained("gpt2")
139
+ tok.model_max_length = 10**9 # silence the long-document warning
140
+ eos = tok.eos_token_id
141
+
142
+ ds = load_dataset("HuggingFaceFW/fineweb-edu", name=args.dataset_config, split="train", streaming=True)
143
+
144
+ chunks, total, texts = [], 0, []
145
+
146
+ def flush():
147
+ nonlocal total
148
+ for ids in tok(texts)["input_ids"]:
149
+ arr = np.asarray(ids + [eos], dtype=np.int32)
150
+ chunks.append(arr)
151
+ total += len(arr)
152
+ texts.clear()
153
+
154
+ it = iter(ds)
155
+ try:
156
+ for ex in it:
157
+ texts.append(ex["text"])
158
+ if len(texts) == 256:
159
+ flush()
160
+ if total >= n_tokens:
161
+ break
162
+ finally:
163
+ # If the streaming iterator is cut off midway and just left there, the program sometimes
164
+ # hangs instead of finishing at exit, so clean it up
165
+ del it, ds
166
+ gc.collect()
167
+ if texts:
168
+ flush()
169
+
170
+ if total < n_tokens:
171
+ sys.exit(f"Not enough data: {total:,} < {n_tokens:,}")
172
+ tokens = np.concatenate(chunks)[:n_tokens]
173
+
174
+ cache.parent.mkdir(parents=True, exist_ok=True)
175
+ np.save(cache, tokens)
176
+ return tokens
177
+
178
+
179
+ # ----------------------------------------------------------------------------
180
+ # Model / optimizer
181
+ # ----------------------------------------------------------------------------
182
+ def build_model(args):
183
+ from transformers import AutoModelForCausalLM, GPT2Config
184
+
185
+ # dropout 0 + eager attention: minimize anything that varies by GPU type
186
+ drop = dict(attn_pdrop=0.0, resid_pdrop=0.0, embd_pdrop=0.0)
187
+ if args.from_scratch:
188
+ cfg = GPT2Config(**drop)
189
+ return AutoModelForCausalLM.from_config(cfg, attn_implementation="eager")
190
+ return AutoModelForCausalLM.from_pretrained("gpt2", attn_implementation="eager", **drop)
191
+
192
+
193
+ def make_optimizer(model, lr: float, wd: float):
194
+ params = [p for p in model.parameters() if p.requires_grad] # tied weights are picked up only once
195
+ decay = [p for p in params if p.ndim >= 2]
196
+ no_decay = [p for p in params if p.ndim < 2]
197
+ return torch.optim.AdamW(
198
+ [{"params": decay, "weight_decay": wd}, {"params": no_decay, "weight_decay": 0.0}],
199
+ lr=lr, betas=(0.9, 0.95), eps=1e-8,
200
+ )
201
+
202
+
203
+ def lr_factor(step: int, warmup: int, total: int) -> float:
204
+ if step < warmup:
205
+ return (step + 1) / warmup
206
+ prog = (step - warmup) / max(1, total - warmup)
207
+ return 0.1 + 0.9 * 0.5 * (1.0 + math.cos(math.pi * prog)) # cosine, minimum 10%
208
+
209
+
210
+ # ----------------------------------------------------------------------------
211
+ # One training run -> delta
212
+ # ----------------------------------------------------------------------------
213
+ def train_one(precision: str, batches: torch.Tensor, args, device: torch.device):
214
+ set_determinism(args.seed) # every precision starts from the same seed
215
+ model = build_model(args).to(device)
216
+ model.train()
217
+
218
+ init = {n: p.detach().float().cpu().clone() for n, p in model.named_parameters()}
219
+ opt = make_optimizer(model, args.lr, args.weight_decay)
220
+ sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: lr_factor(s, args.warmup, args.steps))
221
+
222
+ use_bf16 = precision == "bf16"
223
+ mb, accum = args.micro_batch, args.grad_accum
224
+ first_loss = last_loss = float("nan")
225
+
226
+ for step in range(args.steps):
227
+ loss_sum = torch.zeros((), device=device)
228
+ for k in range(accum):
229
+ i = (step * accum + k) * mb
230
+ x = batches[i:i + mb].to(device)
231
+ with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=use_bf16):
232
+ loss = model(input_ids=x, labels=x).loss
233
+ (loss / accum).backward()
234
+ loss_sum += loss.detach() / accum
235
+
236
+ torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)
237
+ opt.step()
238
+ sched.step()
239
+ opt.zero_grad(set_to_none=True)
240
+
241
+ if step == 0 or (step + 1) % args.log_every == 0 or step + 1 == args.steps:
242
+ last_loss = loss_sum.item()
243
+ if step == 0:
244
+ first_loss = last_loss
245
+ print(f" [{precision}] step {step + 1:>4}/{args.steps} loss {last_loss:.4f}")
246
+
247
+ # delta is always saved as fp32 (it comes from named_parameters, so the tied lm_head is left out)
248
+ delta = {n: (p.detach().float().cpu() - init[n]).contiguous() for n, p in model.named_parameters()}
249
+ delta_l2 = math.sqrt(sum(float(d.pow(2).sum()) for d in delta.values()))
250
+
251
+ del model, opt, sched
252
+ if device.type == "cuda":
253
+ torch.cuda.empty_cache()
254
+
255
+ return delta, {"loss_first": first_loss, "loss_last": last_loss, "delta_l2": delta_l2}
256
+
257
+
258
+ # ----------------------------------------------------------------------------
259
+ # HF Hub
260
+ # ----------------------------------------------------------------------------
261
+ def ensure_repo(api, repo: str, private: bool):
262
+ from huggingface_hub.utils import RepositoryNotFoundError
263
+
264
+ try:
265
+ api.repo_info(repo, repo_type="model")
266
+ except RepositoryNotFoundError:
267
+ print(f"[HF] repo not found, created a new one: {repo}")
268
+ api.create_repo(repo, repo_type="model", private=private, exist_ok=True)
269
+
270
+
271
+ def plan_runs(api, repo: str, prefix: str, gpu_slug: str, precisions):
272
+ """Print "exists" for (GPU model, precision) pairs already uploaded and skip them. Return the remaining (precision, file name) list."""
273
+ todo = []
274
+ for prec in precisions:
275
+ name = tensor_name(prefix, gpu_slug, prec)
276
+ if api.file_exists(repo_id=repo, filename=name, repo_type="model"):
277
+ print(f"exists: {name}")
278
+ else:
279
+ todo.append((prec, name))
280
+ return todo
281
+
282
+
283
+ # ----------------------------------------------------------------------------
284
+ # main
285
+ # ----------------------------------------------------------------------------
286
+ def main(argv=None):
287
+ args = parse_args(argv)
288
+
289
+ if not torch.cuda.is_available():
290
+ sys.exit("A CUDA GPU is required")
291
+ device = torch.device("cuda:0")
292
+
293
+ from huggingface_hub import HfApi
294
+ from safetensors.torch import save_file
295
+
296
+ gpu = get_gpu_name()
297
+ slug = slugify(gpu)
298
+ precisions = (["bf16"] if bf16_supported() else []) + ["fp32"]
299
+ print(f"[GPU] {gpu} -> {slug}")
300
+ print(f"[precision] {', '.join(precisions)}" + ("" if "bf16" in precisions else " (this GPU does not support bf16)"))
301
+
302
+ api = HfApi(token=args.token)
303
+ ensure_repo(api, args.repo, args.private)
304
+
305
+ todo = plan_runs(api, args.repo, args.prefix, slug, precisions)
306
+ if not todo:
307
+ return # all of them already exist -> exit
308
+
309
+ # Data (every precision uses the same tokens)
310
+ n_seq = args.steps * args.grad_accum * args.micro_batch
311
+ tokens = load_tokens(args, n_seq * args.seq_len)
312
+ data_sha = hashlib.sha256(tokens.tobytes()).hexdigest()[:16]
313
+ batches = torch.from_numpy(tokens.astype(np.int64)).view(n_seq, args.seq_len)
314
+
315
+ import transformers
316
+
317
+ with tempfile.TemporaryDirectory() as tmp:
318
+ for prec, name in todo:
319
+ print(f"\n=== {prec} training started -> {name} ===")
320
+ delta, st = train_one(prec, batches, args, device)
321
+
322
+ meta = {
323
+ "gpu": gpu, "precision": prec, "deterministic": "true",
324
+ "init": "scratch" if args.from_scratch else "gpt2",
325
+ "steps": str(args.steps), "seq_len": str(args.seq_len),
326
+ "micro_batch": str(args.micro_batch), "grad_accum": str(args.grad_accum),
327
+ "lr": str(args.lr), "warmup": str(args.warmup), "weight_decay": str(args.weight_decay),
328
+ "clip": str(args.clip), "seed": str(args.seed),
329
+ "dataset": f"HuggingFaceFW/fineweb-edu:{args.dataset_config}", "data_sha256": data_sha,
330
+ "loss_first": f"{st['loss_first']:.6f}", "loss_last": f"{st['loss_last']:.6f}",
331
+ "delta_l2": f"{st['delta_l2']:.6f}",
332
+ "torch": torch.__version__, "cuda": str(torch.version.cuda),
333
+ "cudnn": str(torch.backends.cudnn.version()), "transformers": transformers.__version__,
334
+ }
335
+ path = Path(tmp) / name
336
+ save_file(delta, str(path), metadata=meta)
337
+
338
+ # Someone else may have uploaded it while we were training, so check once more right before uploading
339
+ if api.file_exists(repo_id=args.repo, filename=name, repo_type="model"):
340
+ print(f"exists: {name}")
341
+ continue
342
+ api.upload_file(
343
+ path_or_fileobj=str(path), path_in_repo=name, repo_id=args.repo,
344
+ repo_type="model", commit_message=f"add {name}",
345
+ )
346
+ print(f"[HF] upload complete: {args.repo}/{name} (loss {st['loss_first']:.3f} -> {st['loss_last']:.3f})")
347
+
348
+
349
+ if __name__ == "__main__":
350
+ # Using datasets streaming together with the tokenizer can leave background threads running, so the
351
+ # process sometimes hangs instead of exiting even after it's done (confirmed directly). Once all the
352
+ # work is finished, terminate immediately.
353
+ code = 0
354
+ try:
355
+ main()
356
+ except SystemExit as e:
357
+ if isinstance(e.code, str):
358
+ print(e.code, file=sys.stderr)
359
+ code = 1
360
+ else:
361
+ code = e.code or 0
362
+ except BaseException:
363
+ import traceback
364
+
365
+ traceback.print_exc()
366
+ code = 1
367
+ sys.stdout.flush()
368
+ sys.stderr.flush()
369
+ os._exit(code)