CLIWorks commited on
Commit
d22a1ff
·
verified ·
1 Parent(s): ced950d

Delete mythos-fineweb.py

Browse files
Files changed (1) hide show
  1. mythos-fineweb.py +0 -530
mythos-fineweb.py DELETED
@@ -1,530 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- OpenMythos pretraining on FineWeb-Edu with FSDP + AdamW.
4
-
5
- Single GPU:
6
- python training/3b_fine_web_edu.py
7
-
8
- Multi-GPU:
9
- torchrun --nproc_per_node=$(python -c "import torch; print(torch.cuda.device_count())") training/3b_fine_web_edu.py
10
- """
11
-
12
- import os
13
- import math
14
- import time
15
- import torch
16
- import torch.nn as nn
17
- import torch.distributed as dist
18
- from loguru import logger
19
- from torch.distributed.fsdp import (
20
- FullyShardedDataParallel as FSDP,
21
- ShardingStrategy,
22
- MixedPrecision,
23
- FullStateDictConfig,
24
- StateDictType,
25
- )
26
- from torch.distributed.fsdp.wrap import ModuleWrapPolicy
27
- from torch.utils.data import IterableDataset, DataLoader, get_worker_info
28
- from contextlib import nullcontext
29
-
30
- from datasets import load_dataset
31
-
32
- from open_mythos import OpenMythos
33
- from open_mythos.main import TransformerBlock, RecurrentBlock
34
- from open_mythos.variants import mythos_3b
35
- from open_mythos.tokenizer import MythosTokenizer
36
-
37
-
38
- # ---------------------------------------------------------------------------
39
- # Dataset
40
- # ---------------------------------------------------------------------------
41
-
42
-
43
- class FineWebEduDataset(IterableDataset):
44
- """
45
- Streaming FineWeb-Edu loader yielding fixed-length (input, target) pairs.
46
-
47
- FineWeb-Edu is trillions of tokens, so `streaming=True` pulls shards on
48
- demand instead of materializing to disk. Sharding is two-dimensional —
49
- `world_size` ranks × `num_workers` DataLoader workers per rank — and each
50
- `(rank, worker_id)` deterministically owns one shard of the global stream.
51
- That gives disjoint coverage without any cross-process coordination.
52
-
53
- Streaming datasets are not seekable, so a resumed run re-enters its shard
54
- from the beginning. Acceptable at pretraining scale: the chance of
55
- re-playing the same tokens before the run ends is negligible versus the
56
- cost of a true resumable loader.
57
- """
58
-
59
- def __init__(self, encoding, seq_len: int, subset: str, rank: int, world_size: int):
60
- """
61
- Args:
62
- encoding -- tokenizer exposing `.encode(str) -> list[int]`
63
- seq_len -- context length; every yielded pair has this many tokens
64
- subset -- FineWeb-Edu config name (e.g. "sample-10BT", "default")
65
- rank -- global rank of this process within the distributed job
66
- world_size -- total number of distributed processes
67
- """
68
- self.encoding = encoding
69
- self.seq_len = seq_len
70
- self.subset = subset
71
- self.rank = rank
72
- self.world_size = world_size
73
-
74
- def __iter__(self):
75
- """
76
- Yield `(input_ids, target_ids)` tensors of length `seq_len` forever.
77
-
78
- Inputs and targets are shifted by one for next-token prediction —
79
- `target[i] == input[i + 1]`. Documents are concatenated into a rolling
80
- buffer and sliced into fixed-length chunks, packing short docs together
81
- and splitting long ones. This keeps every step at the same shape,
82
- which under FSDP avoids recompute from variable-length inputs and
83
- removes the need for a pad-aware attention mask.
84
- """
85
- worker = get_worker_info()
86
- num_workers = worker.num_workers if worker else 1
87
- worker_id = worker.id if worker else 0
88
-
89
- total_shards = self.world_size * num_workers
90
- shard_index = self.rank * num_workers + worker_id
91
-
92
- ds = load_dataset(
93
- "HuggingFaceFW/fineweb-edu",
94
- name=self.subset,
95
- split="train",
96
- streaming=True,
97
- ).shard(num_shards=total_shards, index=shard_index)
98
-
99
- buf = []
100
- for sample in ds:
101
- buf.extend(self.encoding.encode(sample["text"]))
102
- while len(buf) >= self.seq_len + 1:
103
- chunk = buf[: self.seq_len + 1]
104
- buf = buf[self.seq_len + 1 :]
105
- yield (
106
- torch.tensor(chunk[:-1], dtype=torch.long),
107
- torch.tensor(chunk[1:], dtype=torch.long),
108
- )
109
-
110
-
111
- # ---------------------------------------------------------------------------
112
- # LR schedule: linear warmup → cosine decay
113
- # ---------------------------------------------------------------------------
114
-
115
-
116
- def get_lr(step: int, warmup: int, total: int, max_lr: float, min_lr: float) -> float:
117
- """
118
- Linear warmup → half-cosine decay to `min_lr`.
119
-
120
- Standard language-model pretraining schedule. The warmup phase prevents
121
- Adam's second-moment estimate from collapsing to a huge LR in the first
122
- few steps when gradients are noisy. The cosine tail lets the model make
123
- small, increasingly conservative updates near the end of training rather
124
- than crashing to `min_lr` at a fixed step.
125
-
126
- Behavior by region:
127
- step < warmup → linear ramp 0 → max_lr
128
- warmup ≤ step < total → cosine decay max_lr → min_lr
129
- step ≥ total → clamped at min_lr (safety for
130
- off-by-one step counters at the end
131
- of training)
132
-
133
- Args:
134
- step -- current global optimizer step (0-indexed)
135
- warmup -- number of warmup steps before cosine decay begins
136
- total -- step at which the cosine reaches `min_lr`
137
- max_lr -- peak learning rate reached at the end of warmup
138
- min_lr -- floor learning rate at and after `total` steps
139
-
140
- Returns:
141
- Scalar learning rate for this step.
142
- """
143
- if step < warmup:
144
- return max_lr * step / warmup
145
- if step >= total:
146
- return min_lr
147
- decay = (step - warmup) / (total - warmup)
148
- return min_lr + 0.5 * (max_lr - min_lr) * (1.0 + math.cos(math.pi * decay))
149
-
150
-
151
- # ---------------------------------------------------------------------------
152
- # Checkpointing — weights-only every 500 steps, full at epoch end + best
153
- # ---------------------------------------------------------------------------
154
-
155
-
156
- def save_weights_only(model, step, epoch, ckpt_dir, ddp):
157
- """Save model weights only (~1.3GB for 3B bf16). For testing/transfer."""
158
- if ddp:
159
- with FSDP.state_dict_type(
160
- model,
161
- StateDictType.FULL_STATE_DICT,
162
- FullStateDictConfig(offload_to_cpu=True, rank0_only=True),
163
- ):
164
- model_state = model.state_dict()
165
- else:
166
- model_state = model.state_dict()
167
-
168
- ckpt_path = os.path.join(ckpt_dir, f"spiderportal-v5-ep{epoch}-step{step}.pt")
169
- tmp_path = ckpt_path + ".tmp"
170
- torch.save(model_state, tmp_path)
171
- os.replace(tmp_path, ckpt_path)
172
- size_mb = os.path.getsize(ckpt_path) / (1024 * 1024)
173
- return ckpt_path, size_mb
174
-
175
-
176
- def save_full_checkpoint(model, optimizer, step, epoch, cfg, vocab_size, ckpt_dir, ddp, master, ckpt_name="full"):
177
- """Save model + optimizer state (~18GB for 3B bf16). For resume training."""
178
- if ddp:
179
- with FSDP.state_dict_type(
180
- model,
181
- StateDictType.FULL_STATE_DICT,
182
- FullStateDictConfig(offload_to_cpu=True, rank0_only=True),
183
- ):
184
- model_state = model.state_dict()
185
- optim_state = FSDP.optim_state_dict(model, optimizer)
186
- else:
187
- model_state = model.state_dict()
188
- optim_state = optimizer.state_dict()
189
-
190
- if not master:
191
- return None, 0
192
-
193
- os.makedirs(ckpt_dir, exist_ok=True)
194
- final_path = os.path.join(ckpt_dir, f"spiderportal-v5-{ckpt_name}.pt")
195
- tmp_path = final_path + ".tmp"
196
- torch.save(
197
- {
198
- "step": step,
199
- "epoch": epoch,
200
- "model_state_dict": model_state,
201
- "optimizer_state_dict": optim_state,
202
- "cfg": cfg,
203
- "vocab_size": vocab_size,
204
- },
205
- tmp_path,
206
- )
207
- os.replace(tmp_path, final_path)
208
- size_mb = os.path.getsize(final_path) / (1024 * 1024)
209
- return final_path, size_mb
210
-
211
-
212
- def delete_step_checkpoints(ckpt_dir):
213
- """Delete all weights-only step checkpoints to free disk space."""
214
- deleted = 0
215
- for f in os.listdir(ckpt_dir):
216
- if f.startswith("spiderportal-v5-ep") and "-step" in f and f.endswith(".pt"):
217
- path = os.path.join(ckpt_dir, f)
218
- try:
219
- os.remove(path)
220
- deleted += 1
221
- except OSError:
222
- pass
223
- return deleted
224
-
225
-
226
- def load_checkpoint(model, optimizer, path, ddp):
227
- """Restore model + optimizer from full checkpoint."""
228
- ckpt = torch.load(path, map_location="cpu", weights_only=False)
229
-
230
- if ddp:
231
- with FSDP.state_dict_type(
232
- model,
233
- StateDictType.FULL_STATE_DICT,
234
- FullStateDictConfig(offload_to_cpu=True, rank0_only=False),
235
- ):
236
- model.load_state_dict(ckpt["model_state_dict"])
237
- optim_state = FSDP.optim_state_dict_to_load(
238
- model=model,
239
- optim=optimizer,
240
- optim_state_dict=ckpt["optimizer_state_dict"],
241
- )
242
- optimizer.load_state_dict(optim_state)
243
- else:
244
- model.load_state_dict(ckpt["model_state_dict"])
245
- optimizer.load_state_dict(ckpt["optimizer_state_dict"])
246
-
247
- return int(ckpt["step"]), int(ckpt.get("epoch", 0))
248
-
249
-
250
- # ---------------------------------------------------------------------------
251
- # Main
252
- # ---------------------------------------------------------------------------
253
-
254
-
255
- def main():
256
- """
257
- End-to-end pretraining entry point.
258
-
259
- Order matters: distributed init must run before any CUDA allocation, the
260
- tokenizer must exist before the model is built (vocab_size flows into
261
- cfg), and FSDP must wrap the model before the optimizer is constructed
262
- (FSDP re-flattens parameters, so an optimizer built on the unwrapped
263
- model would track stale param objects). Resume then loads state into the
264
- already-constructed optimizer in-place.
265
-
266
- Lifecycle:
267
- 1. Initialize torch.distributed (NCCL) if launched under torchrun.
268
- 2. Build tokenizer → derive vocab_size.
269
- 3. Construct OpenMythos with the 3B variant config.
270
- 4. Wrap in FSDP with FULL_SHARD + bf16/fp16 mixed precision (multi-GPU)
271
- or move to device + autocast (single-GPU).
272
- 5. Build fused AdamW on (possibly sharded) parameters.
273
- 6. Resume from the latest checkpoint in `ckpt_dir` if one exists.
274
- 7. Stream FineWeb-Edu through grad-accumulation microbatches with
275
- cosine LR schedule, per-step logging, and periodic checkpoints.
276
- 8. Write a final checkpoint if the last save wasn't aligned to
277
- `ckpt_every`, then barrier + tear down the process group.
278
-
279
- All hyperparameters are literal constants in this function by design —
280
- pretraining runs are long-lived and each run pins exact settings; a
281
- CLI/config layer is deliberately avoided to keep the file self-auditable.
282
- """
283
- # ------------------------------------------------------------------
284
- # Distributed init
285
- # ------------------------------------------------------------------
286
- ddp = int(os.environ.get("RANK", -1)) != -1
287
- if ddp:
288
- dist.init_process_group("nccl")
289
- rank = int(os.environ["RANK"])
290
- local_rank = int(os.environ["LOCAL_RANK"])
291
- world_size = int(os.environ["WORLD_SIZE"])
292
- device = f"cuda:{local_rank}"
293
- torch.cuda.set_device(device)
294
- else:
295
- rank = local_rank = 0
296
- world_size = 1
297
- device = "cuda" if torch.cuda.is_available() else "cpu"
298
-
299
- master = rank == 0
300
-
301
- if master:
302
- logger.info(
303
- f"GPUs: {torch.cuda.device_count()} | World size: {world_size} | Device: {device}"
304
- )
305
-
306
- # ------------------------------------------------------------------
307
- # Tokenizer
308
- # ------------------------------------------------------------------
309
- encoding = MythosTokenizer()
310
- vocab_size = encoding.vocab_size
311
-
312
- if master:
313
- logger.info(f"Tokenizer: gpt-oss-20b | Vocab size: {vocab_size:,}")
314
-
315
- # ------------------------------------------------------------------
316
- # Hyperparameters
317
- # ------------------------------------------------------------------
318
- seq_len = 2048
319
- micro_batch = 32
320
- target_tokens = 1_000_000_000
321
- grad_accum = max(1, 256 // (world_size * micro_batch))
322
- global_batch_tok = world_size * micro_batch * grad_accum * seq_len
323
- total_steps = target_tokens // global_batch_tok
324
- warmup_steps = 200
325
- lr = 3e-4
326
- wd = 0.1
327
- log_every = 10
328
- ckpt_every = 500
329
- ckpt_dir = "checkpoints"
330
- dataset_subset = "sample-1BT"
331
-
332
- if master:
333
- logger.info(
334
- f"seq_len={seq_len} | micro_batch={micro_batch} | grad_accum={grad_accum} | "
335
- f"global_batch_tokens={global_batch_tok:,} | total_steps={total_steps:,}"
336
- )
337
-
338
- # ------------------------------------------------------------------
339
- # Model
340
- # ------------------------------------------------------------------
341
- cfg = mythos_3b()
342
- cfg.vocab_size = vocab_size
343
- cfg.max_seq_len = seq_len
344
-
345
- bf16_ok = torch.cuda.is_available() and torch.cuda.is_bf16_supported()
346
- amp_dtype = torch.bfloat16 if bf16_ok else torch.float16
347
-
348
- model = OpenMythos(cfg)
349
-
350
- if ddp:
351
- mp_policy = MixedPrecision(
352
- param_dtype=amp_dtype,
353
- reduce_dtype=amp_dtype,
354
- buffer_dtype=amp_dtype,
355
- )
356
- wrap_policy = ModuleWrapPolicy({TransformerBlock, RecurrentBlock})
357
- model = FSDP(
358
- model,
359
- sharding_strategy=ShardingStrategy.FULL_SHARD,
360
- mixed_precision=mp_policy,
361
- auto_wrap_policy=wrap_policy,
362
- device_id=local_rank,
363
- )
364
- else:
365
- model = model.to(device)
366
- amp_ctx = (
367
- torch.amp.autocast(device_type="cuda", dtype=amp_dtype)
368
- if "cuda" in device
369
- else nullcontext()
370
- )
371
-
372
- # FSDP handles its own mixed precision; only need autocast for single-GPU
373
- amp_ctx = nullcontext() if ddp else amp_ctx # type: ignore[possibly-undefined]
374
-
375
- if master:
376
- n_params = sum(p.numel() for p in model.parameters())
377
- logger.info(f"Parameters: {n_params:,} | AMP dtype: {amp_dtype}")
378
-
379
- # Compile for 20-30% speedup (requires PyTorch 2.0+)
380
- try:
381
- model = torch.compile(model, mode="reduce-overhead")
382
- if master:
383
- logger.info("torch.compile: enabled")
384
- except Exception:
385
- if master:
386
- logger.info("torch.compile: not available, using eager mode")
387
-
388
- # ------------------------------------------------------------------
389
- # Optimizer
390
- # ------------------------------------------------------------------
391
- optimizer = torch.optim.AdamW(
392
- model.parameters(), lr=lr, weight_decay=wd, betas=(0.9, 0.95), fused=True
393
- )
394
-
395
- # ------------------------------------------------------------------
396
- # Resume from latest checkpoint (if any)
397
- # ------------------------------------------------------------------
398
- start_step = 0
399
- start_epoch = 1
400
- best_loss = float("inf")
401
- existing_ckpts = [f for f in os.listdir(ckpt_dir) if f.startswith("spiderportal-v5-ep") and f.endswith(".pt") and "-step" not in f] if os.path.isdir(ckpt_dir) else []
402
- if existing_ckpts:
403
- latest = os.path.join(ckpt_dir, sorted(existing_ckpts)[-1])
404
- if master:
405
- logger.info(f"Resuming from checkpoint: {latest}")
406
- start_step, start_epoch = load_checkpoint(model, optimizer, latest, ddp)
407
- if master:
408
- logger.success(f"Resumed at step {start_step}, epoch {start_epoch}")
409
-
410
- # ------------------------------------------------------------------
411
- # Dataset + DataLoader
412
- # ------------------------------------------------------------------
413
- dataset = FineWebEduDataset(encoding, seq_len, dataset_subset, rank, world_size)
414
- loader = DataLoader(dataset, batch_size=micro_batch, num_workers=8, pin_memory=True, prefetch_factor=2)
415
-
416
- # ------------------------------------------------------------------
417
- # Training loop
418
- # ------------------------------------------------------------------
419
- if master:
420
- os.makedirs(ckpt_dir, exist_ok=True)
421
-
422
- model.train()
423
- data_iter = iter(loader)
424
- t0 = time.perf_counter()
425
- step = start_step
426
- epoch = start_epoch
427
- step_ckpt_files = []
428
- tokens_in_epoch = 0
429
- tokens_per_epoch = target_tokens
430
-
431
- while step < total_steps:
432
- cur_lr = get_lr(step, warmup_steps, total_steps, lr, lr * 0.1)
433
- for g in optimizer.param_groups:
434
- g["lr"] = cur_lr
435
-
436
- optimizer.zero_grad()
437
- loss_accum = 0.0
438
-
439
- for micro_step in range(grad_accum):
440
- try:
441
- x, y = next(data_iter)
442
- except StopIteration:
443
- data_iter = iter(loader)
444
- x, y = next(data_iter)
445
-
446
- x = x.to(device if not ddp else f"cuda:{local_rank}", non_blocking=True)
447
- y = y.to(device if not ddp else f"cuda:{local_rank}", non_blocking=True)
448
-
449
- sync = (
450
- nullcontext()
451
- if (not ddp or micro_step == grad_accum - 1)
452
- else model.no_sync()
453
- )
454
- with sync, amp_ctx:
455
- logits = model(x)
456
- loss = nn.functional.cross_entropy(
457
- logits.view(-1, vocab_size), y.view(-1)
458
- )
459
- loss = loss / grad_accum
460
-
461
- loss.backward()
462
- loss_accum += loss.item()
463
-
464
- if ddp:
465
- grad_norm = model.clip_grad_norm_(1.0)
466
- else:
467
- grad_norm = nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
468
- optimizer.step()
469
- step += 1
470
- tokens_in_epoch += global_batch_tok
471
-
472
- if master and step % log_every == 0:
473
- dt = time.perf_counter() - t0
474
- tok_per_sec = global_batch_tok * log_every / dt
475
- tokens_seen = step * global_batch_tok
476
- logger.info(
477
- f"Epoch {epoch} | step {step:6d}/{total_steps} | loss {loss_accum:.4f} "
478
- f"| gnorm {float(grad_norm):.2f} | lr {cur_lr:.2e} "
479
- f"| {tok_per_sec / 1e6:.2f}M tok/s "
480
- f"| {tokens_seen / 1e9:.2f}B tokens seen"
481
- )
482
- t0 = time.perf_counter()
483
-
484
- if step % ckpt_every == 0 and master:
485
- ckpt_path, size_mb = save_weights_only(model, step, epoch, ckpt_dir, ddp)
486
- step_ckpt_files.append(ckpt_path)
487
- logger.info(f"Saved weights-only: {os.path.basename(ckpt_path)} ({size_mb:.0f}MB)")
488
-
489
- if tokens_in_epoch >= tokens_per_epoch:
490
- epoch_loss = loss_accum
491
- if master:
492
- epoch_time = (time.perf_counter() - t0) / 60
493
- logger.info(f"Epoch {epoch} complete | loss={epoch_loss:.4f} | Time: {epoch_time:.1f}min")
494
-
495
- for f in step_ckpt_files:
496
- if os.path.exists(f):
497
- os.remove(f)
498
- logger.info(f" Deleted step checkpoint: {os.path.basename(f)}")
499
- step_ckpt_files.clear()
500
-
501
- ckpt_path, size_mb = save_full_checkpoint(model, optimizer, step, epoch, cfg, vocab_size, ckpt_dir, ddp, master, f"ep{epoch}")
502
- if ckpt_path:
503
- logger.info(f"Saved epoch checkpoint: {os.path.basename(ckpt_path)} ({size_mb:.0f}MB)")
504
-
505
- if epoch_loss < best_loss:
506
- best_loss = epoch_loss
507
- ckpt_path, size_mb = save_full_checkpoint(model, optimizer, step, epoch, cfg, vocab_size, ckpt_dir, ddp, master, "best")
508
- if ckpt_path:
509
- logger.info(f"Saved best checkpoint: {os.path.basename(ckpt_path)} ({size_mb:.0f}MB)")
510
-
511
- epoch += 1
512
- tokens_in_epoch = 0
513
-
514
- if step > start_step and master:
515
- ckpt_path, size_mb = save_full_checkpoint(model, optimizer, step, epoch, cfg, vocab_size, ckpt_dir, ddp, master, f"final-ep{epoch}")
516
- if ckpt_path:
517
- logger.info(f"Saved final checkpoint: {os.path.basename(ckpt_path)} ({size_mb:.0f}MB)")
518
-
519
- if ddp:
520
- # Barrier so no rank exits while another is still finishing its
521
- # checkpoint gather — avoids NCCL "process group destroyed" noise.
522
- dist.barrier()
523
- dist.destroy_process_group()
524
-
525
- if master:
526
- logger.success("Training complete.")
527
-
528
-
529
- if __name__ == "__main__":
530
- main()