Bc-AI commited on
Commit
764da61
Β·
verified Β·
1 Parent(s): 0064e5d

Create train.py

Browse files
Files changed (1) hide show
  1. train.py +1846 -0
train.py ADDED
@@ -0,0 +1,1846 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11,<3.13"
3
+ # dependencies = [
4
+ # "torch>=2.8,<2.10",
5
+ # "numpy>=2.0",
6
+ # "huggingface-hub>=0.34",
7
+ # "safetensors>=0.5",
8
+ # "datasets>=2.19",
9
+ # "tokenizers>=0.20",
10
+ # ]
11
+ # ///
12
+
13
+ """
14
+ Smilyai-G1 : Fast Sparse General-Assistant Transformer β€” FSDP2 EDITION (8xH200)
15
+ ~20B total params | ~2B active per token
16
+
17
+ FIXED EDITION. See the notes at the top of the answer for the full bug list.
18
+ The load-bearing invariant of this file:
19
+
20
+ *** EVERY collective must be executed by EVERY rank, in the same order. ***
21
+
22
+ That means model forwards (validate, sampling), state-dict gathers
23
+ (checkpointing), and the decision to *do* any of those things must never be
24
+ gated behind `if is_master`. Rank 0 may be the only one that WRITES the file
25
+ or PRINTS the line, but all 8 ranks must run the collective that produced it.
26
+
27
+ RUN:
28
+ export HF_TOKEN=your_hf_token_here
29
+ export G1_SESSION_ID=1
30
+ torchrun --nproc_per_node=8 train_g1_fsdp.py
31
+ or just:
32
+ python train_g1_fsdp.py # self-launches 8 NCCL workers if 8 GPUs visible
33
+ """
34
+
35
+ import os, gc, json, time, math, random, logging, threading, queue, contextlib
36
+ from dataclasses import dataclass, asdict
37
+ from typing import Optional, Tuple, List, Iterator
38
+
39
+ import numpy as np
40
+ import torch
41
+ import torch.nn as nn
42
+ import torch.nn.functional as F
43
+ import torch.distributed as dist
44
+ import torch.multiprocessing as mp
45
+ from torch.utils.data import Dataset, DataLoader
46
+
47
+ # ── FSDP2 / DTensor imports ─────────────────────────────────────────────────
48
+ try:
49
+ from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
50
+ except ImportError:
51
+ from torch.distributed._composable.fsdp import fully_shard, MixedPrecisionPolicy
52
+
53
+ from torch.distributed.tensor import DTensor, distribute_tensor
54
+ from torch.distributed.checkpoint.state_dict import (
55
+ get_model_state_dict, set_model_state_dict,
56
+ get_optimizer_state_dict, set_optimizer_state_dict,
57
+ StateDictOptions,
58
+ )
59
+
60
+ import triton
61
+ import triton.language as tl
62
+
63
+ from huggingface_hub import HfApi, hf_hub_download, upload_file, login as hf_login
64
+
65
+ try:
66
+ import bitsandbytes as bnb
67
+ HAS_BNB = True
68
+ except ImportError:
69
+ HAS_BNB = False
70
+
71
+ try:
72
+ from safetensors.torch import save_file as st_save
73
+ HAS_ST = True
74
+ except ImportError:
75
+ HAS_ST = False
76
+
77
+ try:
78
+ from flash_attn import flash_attn_func
79
+ HAS_FLASH = True
80
+ except ImportError:
81
+ HAS_FLASH = False
82
+
83
+ try:
84
+ from torchao.float8 import convert_to_float8_training, Float8LinearConfig
85
+ HAS_FP8 = True
86
+ except ImportError:
87
+ HAS_FP8 = False
88
+ convert_to_float8_training = None
89
+ Float8LinearConfig = None
90
+
91
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
92
+ torch.set_float32_matmul_precision('high')
93
+ torch.backends.cuda.matmul.allow_tf32 = True
94
+ torch.backends.cudnn.allow_tf32 = True
95
+ torch.backends.cuda.enable_flash_sdp(True)
96
+ torch.backends.cuda.enable_mem_efficient_sdp(True)
97
+
98
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(message)s', datefmt='%H:%M:%S')
99
+ log = logging.getLogger("smilyai-g1-fsdp")
100
+ log.info(f"[env] flash_attn={HAS_FLASH} | bnb={HAS_BNB}")
101
+
102
+ # ─────────────────────────────────────────────────────────────────────────────
103
+ # HF SETUP
104
+ # ─────────────────────────────────────────────────────────────────────────────
105
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
106
+ SESSION_ID = int(os.environ.get("G1_SESSION_ID", "1"))
107
+ REPO_PREFIX = "hugging-science/Smilyai-G1-20B-session-"
108
+ HF_MODEL_REPO = f"{REPO_PREFIX}{SESSION_ID:03d}"
109
+
110
+ if not HF_TOKEN:
111
+ log.warning("[hf] HF_TOKEN not set β€” uploads/downloads will fail. export HF_TOKEN=...")
112
+ else:
113
+ try:
114
+ hf_login(token=HF_TOKEN)
115
+ log.info("[hf] logged in")
116
+ except Exception as e:
117
+ log.warning(f"[hf] login failed: {e}")
118
+
119
+ hf_api = HfApi()
120
+ LOCAL_CACHE = "/tmp/g1_cache"
121
+ TEMP_CKPT_DIR = "/tmp/g1_ckpts"
122
+ os.makedirs(LOCAL_CACHE, exist_ok=True)
123
+ os.makedirs(TEMP_CKPT_DIR, exist_ok=True)
124
+
125
+ MAX_HOURS = float(os.environ.get("MAX_TRAINING_HOURS", "24.0"))
126
+ START_TIME = time.time()
127
+ def elapsed_h(): return (time.time() - START_TIME) / 3600
128
+ def remaining_h(): return MAX_HOURS - elapsed_h()
129
+ def should_stop_local():
130
+ if elapsed_h() >= MAX_HOURS:
131
+ log.info("[time] budget done"); return True
132
+ return False
133
+ def vram_gb(): return torch.cuda.memory_allocated() / 1024**3
134
+ def vram_total_gb(): return torch.cuda.get_device_properties(torch.cuda.current_device()).total_memory / 1024**3
135
+ def vram_str(): return f"{vram_gb():.1f}/{vram_total_gb():.0f}GB"
136
+
137
+ def ensure_repo():
138
+ try:
139
+ hf_api.repo_info(repo_id=HF_MODEL_REPO, repo_type="model", token=HF_TOKEN)
140
+ except Exception:
141
+ hf_api.create_repo(repo_id=HF_MODEL_REPO, repo_type="model", private=False, token=HF_TOKEN)
142
+ log.info(f"[hf] created {HF_MODEL_REPO}")
143
+ log.info(f"[hf] USING REPO: {HF_MODEL_REPO}")
144
+
145
+ def upload_to_hf(local: str, remote: str) -> bool:
146
+ try:
147
+ upload_file(path_or_fileobj=local, path_in_repo=remote,
148
+ repo_id=HF_MODEL_REPO, repo_type="model", token=HF_TOKEN)
149
+ log.info(f"[hf] up {remote}")
150
+ return True
151
+ except Exception as e:
152
+ log.error(f"[hf] upload failed: {e}")
153
+ return False
154
+
155
+ METRICS_FILE = os.path.join(TEMP_CKPT_DIR, f"metrics_session_{SESSION_ID:03d}.jsonl")
156
+ def log_metrics(**kw):
157
+ m = {'timestamp': time.time(), 'elapsed_hours': elapsed_h(), 'session_id': SESSION_ID, **kw}
158
+ with open(METRICS_FILE, 'a') as f:
159
+ f.write(json.dumps(m) + '\n')
160
+ return m
161
+ def upload_metrics():
162
+ if os.path.exists(METRICS_FILE):
163
+ upload_to_hf(METRICS_FILE, f"metrics_session_{SESSION_ID:03d}.jsonl")
164
+
165
+ # ─────────────────────────────────────────────────────────────────────────────
166
+ # MOTIVATION / PROGRESS BOARD
167
+ # ─────────────────────────────────────────────────────────────────────────────
168
+ import datetime
169
+ try:
170
+ import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt
171
+ HAS_MPL = True
172
+ except ImportError:
173
+ HAS_MPL = False
174
+
175
+ SAMPLES_FILE = os.path.join(TEMP_CKPT_DIR, "samples.md")
176
+ SUMMARY_FILE = os.path.join(TEMP_CKPT_DIR, "summary.jsonl")
177
+ PROGRESS_MD = os.path.join(TEMP_CKPT_DIR, "PROGRESS.md")
178
+ _step_clock = []
179
+ _tok = None
180
+
181
+ def _real_steps_per_hour():
182
+ if len(_step_clock) < 2: return None
183
+ (s0, t0), (s1, t1) = _step_clock[0], _step_clock[-1]
184
+ if t1 - t0 < 30 or s1 <= s0: return None
185
+ return (s1 - s0) / (t1 - t0) * 3600
186
+
187
+ def sessions_left(step, total):
188
+ sph = _real_steps_per_hour()
189
+ if sph is None: return None
190
+ usable_h = max(MAX_HOURS - 0.75, 8.0)
191
+ return max(math.ceil((total - step) / max(sph * usable_h, 1)), 0)
192
+
193
+ def session_banner():
194
+ try:
195
+ files = hf_api.list_repo_files(repo_id=HF_MODEL_REPO, repo_type="model", token=HF_TOKEN)
196
+ pts = [f for f in files if f.endswith(".pt")]
197
+ latest = max([int(f.split("step")[-1].split(".")[0]) for f in pts]) if pts else 0
198
+ except Exception:
199
+ pts, latest = [], 0
200
+ log.info("🌱" * 25)
201
+ log.info(f"WELCOME BACK β€” feed #{len(pts)+1}. Smilyai survived {len(pts)} sessions.")
202
+ log.info(f"Latest checkpoint on the Hub: step {latest:,}")
203
+ log.info("🌱" * 25)
204
+
205
+ def _bootstrap_from_hub(local, remote):
206
+ try:
207
+ import shutil
208
+ src = hf_hub_download(HF_MODEL_REPO, remote, cache_dir=TEMP_CKPT_DIR, token=HF_TOKEN)
209
+ shutil.copy(src, local)
210
+ log.info(f"[motiv] restored {remote}")
211
+ except Exception:
212
+ pass
213
+
214
+ def _get_tokenizer():
215
+ global _tok
216
+ if _tok is None:
217
+ try:
218
+ _tok = get_tokenizer(Config())
219
+ except Exception as e:
220
+ log.warning(f"[tokenizer] failed: {e}")
221
+ _tok = None
222
+ return _tok
223
+
224
+ DOMAIN_TOKEN = ""
225
+
226
+ @torch.no_grad()
227
+ def make_sample(model, prompt="def fibonacci(n):", max_new=48, temp=0.8, top_p=0.95):
228
+ """
229
+ BUGFIX: this runs a MODEL FORWARD, which under FSDP2 is a collective
230
+ (all-gather per block). It therefore MUST be called by every rank. The
231
+ sampling RNG is seeded identically on all ranks so every rank walks the
232
+ same token sequence and issues an identical collective schedule.
233
+ """
234
+ try:
235
+ tok = _get_tokenizer()
236
+ if tok is None: return None
237
+ encoded = tok.encode(DOMAIN_TOKEN + prompt)
238
+ token_ids = encoded.ids[-128:]
239
+ if not token_ids: return None
240
+ device = next(model.parameters()).device
241
+ ids = torch.tensor([token_ids], device=device)
242
+ except Exception as e:
243
+ log.warning(f"[sample] tokenizer error: {e}"); return None
244
+
245
+ gen = torch.Generator(device=device)
246
+ gen.manual_seed(1234) # identical on all ranks -> identical trajectory
247
+
248
+ was_training = model.training
249
+ model.eval()
250
+ try:
251
+ for _ in range(max_new):
252
+ with torch.amp.autocast('cuda', dtype=model.cfg.dtype):
253
+ logits, _ = model(ids[:, -model.cfg.max_len:], None)
254
+ p = F.softmax(logits[:, -1].float() / temp, dim=-1)
255
+ sp, si = torch.sort(p, descending=True)
256
+ keep = (torch.cumsum(sp, -1) - sp) < top_p
257
+ sp = sp * keep
258
+ sp = sp / sp.sum(-1, keepdim=True).clamp_min(1e-9)
259
+ nxt = si.gather(-1, torch.multinomial(sp, 1, generator=gen))
260
+ ids = torch.cat([ids, nxt], dim=1)
261
+ finally:
262
+ if was_training: model.train()
263
+ try:
264
+ return tok.decode(ids[0].tolist())
265
+ except Exception as e:
266
+ log.warning(f"[sample] decode error: {e}")
267
+ return None
268
+
269
+ def record_sample(model, step, is_master: bool):
270
+ """Collective on all ranks; only rank 0 persists the result."""
271
+ txt = make_sample(model)
272
+ if not is_master:
273
+ return
274
+ with open(SAMPLES_FILE, "a") as f:
275
+ f.write(f"\n## step {step:,} β€” {datetime.datetime.now():%d %b %H:%M}\n> {txt or '(skipped)'}\n")
276
+ upload_to_hf(SAMPLES_FILE, "samples.md")
277
+ if txt: log.info(f"[motiv] sample Β» {txt[:120]!r}")
278
+
279
+ def make_loss_chart():
280
+ if not (HAS_MPL and os.path.exists(METRICS_FILE)): return
281
+ tr, va = [], []
282
+ for line in open(METRICS_FILE):
283
+ try: m = json.loads(line)
284
+ except Exception: continue
285
+ if "loss" in m and "step" in m: tr.append((m["step"], m["loss"]))
286
+ elif "val_loss" in m and "step" in m: va.append((m["step"], m["val_loss"]))
287
+ if not tr: return
288
+ fig, ax = plt.subplots(figsize=(10, 5))
289
+ ax.plot(*zip(*tr), lw=1, label="train")
290
+ if va: ax.plot(*zip(*va), "o-", color="tab:red", label="val")
291
+ ax.set_xlabel("step"); ax.set_ylabel("loss"); ax.grid(alpha=.3); ax.legend()
292
+ ax.set_title("Smilyai-G1 20B learning curve 🌱")
293
+ p = os.path.join(TEMP_CKPT_DIR, "loss_curve.png")
294
+ fig.savefig(p, dpi=110, bbox_inches="tight"); plt.close(fig)
295
+ upload_to_hf(p, "loss_curve.png"); os.remove(p)
296
+
297
+ def update_progress_md(cfg, step, epoch, tr_loss, val_loss):
298
+ rec = {"t": f"{datetime.datetime.now():%d %b %H:%M}", "step": step, "epoch": epoch,
299
+ "loss": round(tr_loss, 4) if tr_loss is not None else None,
300
+ "val": round(val_loss, 4) if (val_loss is not None and val_loss == val_loss) else None}
301
+ with open(SUMMARY_FILE, "a") as f: f.write(json.dumps(rec) + "\n")
302
+ sl = sessions_left(step, cfg.total_steps); sl = f"~{sl}" if sl is not None else "?"
303
+ lines = ["# Smilyai-G1 20B · live progress 🌱", "",
304
+ f"**{100*step/cfg.total_steps:.1f}% trained** Β· estimated clicks left: **{sl}** πŸ–±οΈ", "",
305
+ "| when | step | train loss | val loss |", "|---|---|---|---|"]
306
+ for line in open(SUMMARY_FILE):
307
+ try: r = json.loads(line)
308
+ except Exception: continue
309
+ lines.append(f"| {r['t']} | {r['step']:,} | {r['loss'] if r['loss'] is not None else 'β€”'} "
310
+ f"| {r['val'] if r['val'] is not None else 'β€”'} |")
311
+ with open(PROGRESS_MD, "w") as f: f.write("\n".join(lines) + "\n")
312
+ upload_to_hf(PROGRESS_MD, "PROGRESS.md")
313
+
314
+ # ─────────────────────────────────────────────────────────────────────────────
315
+ # CONFIG
316
+ # ─────────────────────────────────────────────────────────────────────────────
317
+ @dataclass
318
+ class Config:
319
+ vocab_size: int = 131_072
320
+
321
+ d_model: int = 2048
322
+ n_layers: int = 32
323
+ n_heads: int = 16
324
+ n_kv_heads: int = 4
325
+ max_len: int = 2048
326
+ rope_theta: float = 500_000.0
327
+
328
+ n_experts: int = 56
329
+ top_k: int = 2
330
+ expert_hidden_mult: float = 0.875
331
+ shared_hidden_mult: float = 2.0
332
+ n_shared_experts: int = 1
333
+ aux_loss_coef: float = 0.01
334
+ bias_update_rate: float = 0.001
335
+ bias_update_every: int = 10 # in OPTIMIZER steps
336
+ bias_cap: float = 2.0
337
+ bias_decay: float = 0.0005
338
+ usage_ema_decay: float = 0.99
339
+ moe_block_m: int = 64
340
+
341
+ tie_embeddings: bool = True
342
+
343
+ muon_lr: float = 0.008
344
+ muon_min_lr: float = 0.0008
345
+ muon_mom: float = 0.95
346
+ adamw_lr: float = 1.5e-4
347
+ adamw_min_lr:float = 1.5e-5
348
+ beta1: float = 0.9
349
+ beta2: float = 0.95
350
+ wd: float = 0.1
351
+ grad_clip: float = 1.0
352
+ warmup: int = 3000
353
+ total_steps: int = 300_000
354
+
355
+ micro_batch: int = 2
356
+ grad_accum: int = 16
357
+
358
+ log_every: int = 10
359
+ eval_every: int = 500
360
+ ckpt_every: int = 1000
361
+
362
+ enable_dpo_bursts: bool = False
363
+ dpo_start_step: int = 250_000
364
+ dpo_every: int = 500
365
+ dpo_beta: float= 0.1
366
+
367
+ dataset_sources: tuple = (
368
+ ("HuggingFaceFW/fineweb-edu", "train", "text", 200_000_000_000),
369
+ ("HuggingFaceCode/stack-v3-train", "train", "content", 100_000_000_000),
370
+ ("opencsg/chinese-fineweb-edu", "train", "text", 60_000_000_000),
371
+ ("hotchpotch/fineweb-2-edu-japanese", "train", "text", 40_000_000_000),
372
+ ("KORMo-Team/korean-web-collection", "train", "text", 30_000_000_000),
373
+ ("HuggingFaceFW/fineweb-2", "train", "text", 70_000_000_000),
374
+ )
375
+ tokenizer_repo: str = "Smilyai-labs/Smilyai-U1-B-Tokenizer"
376
+ # BUGFIX: 18 threads x 6 sources x 8 ranks = 864 concurrent HTTP streams,
377
+ # which will get you rate-limited and eat enormous host RAM in buffers.
378
+ # 8 is already plenty to keep a single H200 fed at this token rate.
379
+ tokenizer_workers: int = 8
380
+ prefetch_shards: int = 6
381
+
382
+ use_compile: bool = False
383
+ use_fp8: bool = False
384
+
385
+ @property
386
+ def dtype(self): return torch.bfloat16
387
+ @property
388
+ def head_dim(self): return self.d_model // self.n_heads
389
+ def tokens_per_step(self, bs, world_size=1): return bs * self.grad_accum * self.max_len * world_size
390
+
391
+ # ─────────────────────────────────────────────────────────────────────────────
392
+ # DISTRIBUTED HELPERS
393
+ # ─────────────────────────────────────────────────────────────────────────────
394
+ def dist_ready() -> bool:
395
+ return dist.is_available() and dist.is_initialized()
396
+
397
+ def distributed_mean(value: float, device: torch.device) -> float:
398
+ t = torch.tensor(float(value), dtype=torch.float64, device=device)
399
+ if dist_ready():
400
+ dist.all_reduce(t, op=dist.ReduceOp.SUM)
401
+ t /= dist.get_world_size()
402
+ return t.item()
403
+
404
+ def broadcast_flag(value: bool, device: torch.device) -> bool:
405
+ """Rank 0 decides, everyone obeys. Used for anything that gates a
406
+ collective (checkpointing, eval, stopping) so ranks can never diverge."""
407
+ flag = torch.tensor(int(bool(value)), dtype=torch.int32, device=device)
408
+ if dist_ready():
409
+ dist.broadcast(flag, src=0)
410
+ return bool(flag.item())
411
+
412
+ def all_ok(ok: bool, device: torch.device) -> bool:
413
+ """Collective AND. If ANY rank failed (OOM/NaN), every rank must take the
414
+ same recovery branch, or the next collective deadlocks."""
415
+ t = torch.tensor(int(bool(ok)), dtype=torch.int32, device=device)
416
+ if dist_ready():
417
+ dist.all_reduce(t, op=dist.ReduceOp.MIN)
418
+ return bool(t.item())
419
+
420
+ def distributed_should_stop(device: torch.device, is_master: bool, step: int, total_steps: int) -> bool:
421
+ stop = (should_stop_local() or step >= total_steps) if is_master else False
422
+ return broadcast_flag(stop, device)
423
+
424
+ # ─────────────────────────────────────────────────────────────────────────────
425
+ # TRITON KERNELS
426
+ # ─────────────────────────────────────────────────────────────────────────────
427
+ @triton.jit
428
+ def smilyai_rmsnorm_fwd(X, W, Y, RSTD, stride_row, N, eps, BLOCK_N: tl.constexpr):
429
+ row = tl.program_id(0)
430
+ X += row * stride_row; Y += row * stride_row
431
+ cols = tl.arange(0, BLOCK_N); mask = cols < N
432
+ x = tl.load(X + cols, mask=mask, other=0.0).to(tl.float32)
433
+ var = tl.sum(x * x, axis=0) / N
434
+ rstd = 1.0 / tl.sqrt(var + eps)
435
+ tl.store(RSTD + row, rstd)
436
+ w = tl.load(W + cols, mask=mask, other=0.0).to(tl.float32)
437
+ tl.store(Y + cols, (x * rstd * w).to(Y.dtype.element_ty), mask=mask)
438
+
439
+ @triton.jit
440
+ def smilyai_rmsnorm_bwd(X, W, DY, DX, DW_PARTIAL, RSTD, stride_row, N, BLOCK_N: tl.constexpr):
441
+ row = tl.program_id(0)
442
+ X += row * stride_row; DY += row * stride_row; DX += row * stride_row
443
+ cols = tl.arange(0, BLOCK_N); mask = cols < N
444
+ x = tl.load(X + cols, mask=mask, other=0.0).to(tl.float32)
445
+ dy = tl.load(DY + cols, mask=mask, other=0.0).to(tl.float32)
446
+ w = tl.load(W + cols, mask=mask, other=0.0).to(tl.float32)
447
+ rstd = tl.load(RSTD + row)
448
+ wdy = w * dy
449
+ s = tl.sum(x * wdy, axis=0)
450
+ dx = rstd * wdy - (rstd * rstd * rstd / N) * x * s
451
+ tl.store(DX + cols, dx.to(DX.dtype.element_ty), mask=mask)
452
+ tl.store(DW_PARTIAL + row * N + cols, dy * x * rstd, mask=mask)
453
+
454
+ @triton.jit
455
+ def smilyai_swiglu_fwd(GATE, UP, OUT, N, BLOCK: tl.constexpr):
456
+ pid = tl.program_id(0)
457
+ offs = pid * BLOCK + tl.arange(0, BLOCK); mask = offs < N
458
+ g = tl.load(GATE + offs, mask=mask, other=0.0).to(tl.float32)
459
+ u = tl.load(UP + offs, mask=mask, other=0.0).to(tl.float32)
460
+ tl.store(OUT + offs, (g * tl.sigmoid(g) * u).to(OUT.dtype.element_ty), mask=mask)
461
+
462
+ @triton.jit
463
+ def smilyai_swiglu_bwd(GATE, UP, DOUT, DGATE, DUP, N, BLOCK: tl.constexpr):
464
+ pid = tl.program_id(0)
465
+ offs = pid * BLOCK + tl.arange(0, BLOCK); mask = offs < N
466
+ g = tl.load(GATE + offs, mask=mask, other=0.0).to(tl.float32)
467
+ u = tl.load(UP + offs, mask=mask, other=0.0).to(tl.float32)
468
+ dout = tl.load(DOUT + offs, mask=mask, other=0.0).to(tl.float32)
469
+ s = tl.sigmoid(g); silu = g * s; dsilu = s * (1.0 + g * (1.0 - s))
470
+ tl.store(DGATE + offs, (dout * u * dsilu).to(DGATE.dtype.element_ty), mask=mask)
471
+ tl.store(DUP + offs, (dout * silu ).to(DUP.dtype.element_ty), mask=mask)
472
+
473
+ class _TritonRMSNormFn(torch.autograd.Function):
474
+ @staticmethod
475
+ @torch.compiler.disable
476
+ def forward(ctx, x, w, eps):
477
+ orig = x.shape; x2 = x.reshape(-1, orig[-1]).contiguous()
478
+ M, N = x2.shape; y = torch.empty_like(x2)
479
+ rstd = torch.empty(M, device=x.device, dtype=torch.float32)
480
+ BN = triton.next_power_of_2(N)
481
+ w = w.contiguous()
482
+ smilyai_rmsnorm_fwd[(M,)](x2, w, y, rstd, x2.stride(0), N, eps, BLOCK_N=BN)
483
+ ctx.save_for_backward(x2, w, rstd); ctx.BN = BN; ctx.orig = orig
484
+ return y.view(orig)
485
+
486
+ @staticmethod
487
+ @torch.compiler.disable
488
+ def backward(ctx, dy):
489
+ x2, w, rstd = ctx.saved_tensors; M, N = x2.shape
490
+ dy2 = dy.reshape(M, N).contiguous()
491
+ dx = torch.empty_like(x2)
492
+ dwp = torch.empty(M, N, device=x2.device, dtype=torch.float32)
493
+ smilyai_rmsnorm_bwd[(M,)](x2, w, dy2, dx, dwp, rstd, x2.stride(0), N, BLOCK_N=ctx.BN)
494
+ return dx.view(ctx.orig), dwp.sum(0).to(w.dtype), None
495
+
496
+ class RMSNorm(nn.Module):
497
+ def __init__(self, dim: int, eps: float = 1e-6):
498
+ super().__init__(); self.eps = eps; self.w = nn.Parameter(torch.ones(dim))
499
+ def forward(self, x):
500
+ if x.is_cuda: return _TritonRMSNormFn.apply(x, self.w, self.eps)
501
+ x32 = x.float()
502
+ return (x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + self.eps) * self.w).to(x.dtype)
503
+
504
+ class _FusedSwiGLUFn(torch.autograd.Function):
505
+ @staticmethod
506
+ @torch.compiler.disable
507
+ def forward(ctx, gate, up):
508
+ shape = gate.shape; g = gate.reshape(-1).contiguous(); u = up.reshape(-1).contiguous()
509
+ N = g.numel(); out = torch.empty_like(g); BLOCK = 1024
510
+ smilyai_swiglu_fwd[(triton.cdiv(N, BLOCK),)](g, u, out, N, BLOCK=BLOCK)
511
+ ctx.save_for_backward(g, u); ctx.shape = shape; ctx.BLOCK = BLOCK
512
+ return out.view(shape)
513
+
514
+ @staticmethod
515
+ @torch.compiler.disable
516
+ def backward(ctx, dout):
517
+ g, u = ctx.saved_tensors; N = g.numel()
518
+ dout_flat = dout.reshape(-1).contiguous()
519
+ dgate = torch.empty_like(g); dup = torch.empty_like(u)
520
+ smilyai_swiglu_bwd[(triton.cdiv(N, ctx.BLOCK),)](g, u, dout_flat, dgate, dup, N, BLOCK=ctx.BLOCK)
521
+ return dgate.view(ctx.shape), dup.view(ctx.shape)
522
+
523
+ def fused_swiglu(gate, up):
524
+ return _FusedSwiGLUFn.apply(gate, up) if gate.is_cuda else F.silu(gate) * up
525
+
526
+ def precompute_rope(head_dim, max_len, theta, device):
527
+ inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device, dtype=torch.float32) / head_dim))
528
+ pos = torch.arange(max_len, device=device, dtype=torch.float32)
529
+ freqs = torch.outer(pos, inv_freq)
530
+ return freqs.cos(), freqs.sin()
531
+
532
+ def apply_rope(x, cos, sin):
533
+ """Rotation math forced to fp32 β€” cos/sin tables must stay fp32 too."""
534
+ dt = x.dtype
535
+ L = x.shape[1]; h = x.shape[-1] // 2
536
+ c = cos[:L].unsqueeze(0).unsqueeze(2); s = sin[:L].unsqueeze(0).unsqueeze(2)
537
+ x32 = x.float()
538
+ x1, x2 = x32[..., :h], x32[..., h:]
539
+ return torch.cat([x1 * c - x2 * s, x2 * c + x1 * s], dim=-1).to(dt)
540
+
541
+ class GQAAttention(nn.Module):
542
+ def __init__(self, cfg: Config, layer_idx: int):
543
+ super().__init__()
544
+ self.n_heads = cfg.n_heads
545
+ self.n_kv_heads = cfg.n_kv_heads
546
+ self.hd = cfg.head_dim
547
+ d = cfg.d_model
548
+
549
+ self.wq = nn.Linear(d, self.n_heads * self.hd, bias=False)
550
+ self.wk = nn.Linear(d, self.n_kv_heads * self.hd, bias=False)
551
+ self.wv = nn.Linear(d, self.n_kv_heads * self.hd, bias=False)
552
+ self.wo = nn.Linear(self.n_heads * self.hd, d, bias=False)
553
+
554
+ self.q_norm = RMSNorm(self.hd)
555
+ self.k_norm = RMSNorm(self.hd)
556
+
557
+ std = 0.02
558
+ for m in [self.wq, self.wk, self.wv]: nn.init.normal_(m.weight, std=std)
559
+ nn.init.normal_(self.wo.weight, std=std / math.sqrt(2 * cfg.n_layers))
560
+
561
+ def _attend(self, q, k, v):
562
+ if HAS_FLASH and q.is_cuda and q.dtype in (torch.bfloat16, torch.float16):
563
+ return flash_attn_func(q, k, v, causal=True)
564
+ B, L, Hq, D = q.shape; Hkv = k.shape[2]
565
+ qt = q.transpose(1,2); kt = k.transpose(1,2); vt = v.transpose(1,2)
566
+ if Hq != Hkv:
567
+ rep = Hq // Hkv
568
+ kt = kt.repeat_interleave(rep, 1); vt = vt.repeat_interleave(rep, 1)
569
+ out = F.scaled_dot_product_attention(qt, kt, vt, is_causal=True)
570
+ return out.transpose(1, 2)
571
+
572
+ def forward(self, x, cos, sin):
573
+ B, L, _ = x.shape
574
+ q = self.wq(x).view(B, L, self.n_heads, self.hd)
575
+ k = self.wk(x).view(B, L, self.n_kv_heads, self.hd)
576
+ v = self.wv(x).view(B, L, self.n_kv_heads, self.hd)
577
+
578
+ q, k = self.q_norm(q), self.k_norm(k)
579
+ q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
580
+
581
+ out = self._attend(q, k, v)
582
+ return self.wo(out.reshape(B, L, -1))
583
+
584
+ # ─────────────���───────────────────────────────────────────────────────────────
585
+ # FUSED GROUPED-GEMM MOE DISPATCH
586
+ # ─────────────────────────────────────────────────────────────────────────────
587
+ _moe_autotune_configs = [
588
+ triton.Config({"BLOCK_N": 64, "BLOCK_K": 32}, num_warps=4, num_stages=3),
589
+ triton.Config({"BLOCK_N": 128, "BLOCK_K": 32}, num_warps=8, num_stages=3),
590
+ triton.Config({"BLOCK_N": 128, "BLOCK_K": 64}, num_warps=8, num_stages=4),
591
+ triton.Config({"BLOCK_N": 64, "BLOCK_K": 64}, num_warps=4, num_stages=4),
592
+ ]
593
+
594
+
595
+ @triton.autotune(configs=_moe_autotune_configs, key=["K", "N"])
596
+ @triton.jit
597
+ def _moe_gemm_kernel(
598
+ A_ptr, B_ptr, C_ptr, block_expert_ptr,
599
+ M_padded, K, N,
600
+ stride_am, stride_ak,
601
+ stride_be, stride_bk, stride_bn,
602
+ stride_cm, stride_cn,
603
+ BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr,
604
+ ):
605
+ pid_m = tl.program_id(0)
606
+ pid_n = tl.program_id(1)
607
+ e = tl.load(block_expert_ptr + pid_m).to(tl.int64)
608
+
609
+ offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
610
+ offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
611
+ offs_k = tl.arange(0, BLOCK_K)
612
+ m_mask = offs_m < M_padded
613
+ n_mask = offs_n < N
614
+
615
+ a_ptrs = A_ptr + offs_m[:, None] * stride_am + offs_k[None, :] * stride_ak
616
+ b_ptrs = B_ptr + e * stride_be + offs_k[:, None] * stride_bk + offs_n[None, :] * stride_bn
617
+
618
+ acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
619
+ for k0 in range(0, K, BLOCK_K):
620
+ k_mask = (k0 + offs_k) < K
621
+ a = tl.load(a_ptrs, mask=m_mask[:, None] & k_mask[None, :], other=0.0)
622
+ b = tl.load(b_ptrs, mask=k_mask[:, None] & n_mask[None, :], other=0.0)
623
+ acc = tl.dot(a, b, acc)
624
+ a_ptrs += BLOCK_K * stride_ak
625
+ b_ptrs += BLOCK_K * stride_bk
626
+
627
+ tl.store(
628
+ C_ptr + offs_m[:, None] * stride_cm + offs_n[None, :] * stride_cn,
629
+ acc.to(tl.bfloat16), mask=m_mask[:, None] & n_mask[None, :],
630
+ )
631
+
632
+
633
+ def _grouped_linear_raw(A, W, block_expert, M_padded, transpose, BM):
634
+ """W is (E, OUT, IN) β€” nn.Linear convention. transpose=True computes the
635
+ dA backward pass (A @ W instead of A @ W^T)."""
636
+ E, OUT, IN = W.shape
637
+ if not transpose:
638
+ K, N = IN, OUT
639
+ stride_bk = W.stride(2)
640
+ stride_bn = W.stride(1)
641
+ else:
642
+ K, N = OUT, IN
643
+ stride_bk = W.stride(1)
644
+ stride_bn = W.stride(2)
645
+
646
+ C = torch.empty((M_padded, N), device=A.device, dtype=torch.bfloat16)
647
+ grid = lambda META: (triton.cdiv(M_padded, BM), triton.cdiv(N, META["BLOCK_N"]))
648
+ _moe_gemm_kernel[grid](
649
+ A, W, C, block_expert, M_padded, K, N,
650
+ A.stride(0), A.stride(1),
651
+ W.stride(0), stride_bk, stride_bn,
652
+ C.stride(0), C.stride(1),
653
+ BLOCK_M=BM,
654
+ )
655
+ return C
656
+
657
+
658
+ # BUGFIX: this kernel accumulates with tl.atomic_add. triton.autotune runs the
659
+ # kernel once per candidate config to benchmark it, so WITHOUT reset_to_zero
660
+ # the very first call for each new (K,N) key would leave DW containing
661
+ # ~4 extra accumulations of the same gradient. Silent, non-deterministic,
662
+ # and only on the first step of each new shape β€” the worst kind of bug.
663
+ @triton.autotune(configs=_moe_autotune_configs, key=["K", "N"], reset_to_zero=["DW_ptr"])
664
+ @triton.jit
665
+ def _moe_dw_kernel(
666
+ A_ptr, DC_ptr, DW_ptr, block_expert_ptr,
667
+ M_padded, K, N,
668
+ stride_am, stride_ak,
669
+ stride_dcm, stride_dcn,
670
+ stride_dwe, stride_dwn, stride_dwk,
671
+ BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr,
672
+ ):
673
+ pid_m = tl.program_id(0)
674
+ pid_n = tl.program_id(1)
675
+ pid_k = tl.program_id(2)
676
+ e = tl.load(block_expert_ptr + pid_m).to(tl.int64)
677
+
678
+ offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
679
+ offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
680
+ offs_k = pid_k * BLOCK_K + tl.arange(0, BLOCK_K)
681
+ m_mask = offs_m < M_padded
682
+ n_mask = offs_n < N
683
+ k_mask = offs_k < K
684
+
685
+ a = tl.load(A_ptr + offs_m[:, None] * stride_am + offs_k[None, :] * stride_ak,
686
+ mask=m_mask[:, None] & k_mask[None, :], other=0.0)
687
+ dc = tl.load(DC_ptr + offs_m[:, None] * stride_dcm + offs_n[None, :] * stride_dcn,
688
+ mask=m_mask[:, None] & n_mask[None, :], other=0.0)
689
+
690
+ tl.atomic_add(
691
+ DW_ptr + e * stride_dwe + offs_n[:, None] * stride_dwn + offs_k[None, :] * stride_dwk,
692
+ tl.dot(tl.trans(dc), a),
693
+ mask=n_mask[:, None] & k_mask[None, :],
694
+ )
695
+
696
+
697
+ def _grouped_dw_raw(A, dC, block_expert, E, OUT, IN, M_padded, BM):
698
+ DW = torch.zeros((E, OUT, IN), device=A.device, dtype=torch.float32)
699
+ grid = lambda META: (
700
+ triton.cdiv(M_padded, BM),
701
+ triton.cdiv(OUT, META["BLOCK_N"]),
702
+ triton.cdiv(IN, META["BLOCK_K"]),
703
+ )
704
+ _moe_dw_kernel[grid](
705
+ A, dC, DW, block_expert, M_padded, IN, OUT,
706
+ A.stride(0), A.stride(1),
707
+ dC.stride(0), dC.stride(1),
708
+ DW.stride(0), DW.stride(1), DW.stride(2),
709
+ BLOCK_M=BM,
710
+ )
711
+ return DW
712
+
713
+
714
+ class GroupedLinearFn(torch.autograd.Function):
715
+ @staticmethod
716
+ def forward(ctx, A, W, block_expert, padded_offsets, M_padded, BM):
717
+ A = A.contiguous().to(torch.bfloat16)
718
+ W = W.contiguous()
719
+ C = _grouped_linear_raw(A, W, block_expert, M_padded, False, BM)
720
+ ctx.save_for_backward(A, W, block_expert, padded_offsets)
721
+ ctx.M_padded = M_padded
722
+ ctx.BM = BM
723
+ return C
724
+
725
+ @staticmethod
726
+ def backward(ctx, dC):
727
+ A, W, block_expert, _ = ctx.saved_tensors
728
+ dC = dC.contiguous().to(torch.bfloat16)
729
+ dA = _grouped_linear_raw(dC, W, block_expert, ctx.M_padded, True, ctx.BM) \
730
+ if ctx.needs_input_grad[0] else None
731
+ dW = _grouped_dw_raw(A, dC, block_expert, W.shape[0], W.shape[1], W.shape[2],
732
+ ctx.M_padded, ctx.BM).to(W.dtype) \
733
+ if ctx.needs_input_grad[1] else None
734
+ return dA, dW, None, None, None, None
735
+
736
+
737
+ def moe_align_block_size(expert_ids, num_experts, block_size, device):
738
+ """Sort tokens by expert, pad each expert's run up to block_size. No
739
+ tokens are dropped."""
740
+ counts = torch.bincount(expert_ids, minlength=num_experts)
741
+ padded_counts = ((counts + block_size - 1) // block_size) * block_size
742
+
743
+ padded_offsets = torch.zeros(num_experts + 1, dtype=torch.long, device=device)
744
+ padded_offsets[1:] = torch.cumsum(padded_counts, dim=0)
745
+ orig_offsets = torch.zeros(num_experts + 1, dtype=torch.long, device=device)
746
+ orig_offsets[1:] = torch.cumsum(counts, dim=0)
747
+
748
+ total_padded = int(padded_offsets[-1].item())
749
+ sort_idx = torch.argsort(expert_ids, stable=True)
750
+ num_blocks_per_expert = padded_counts // block_size
751
+ block_expert = torch.repeat_interleave(
752
+ torch.arange(num_experts, device=device), num_blocks_per_expert
753
+ )
754
+
755
+ n_rows = expert_ids.numel()
756
+ arange_total = torch.arange(n_rows, device=device)
757
+ sorted_expert_of_row = expert_ids[sort_idx]
758
+ row_within_expert = arange_total - orig_offsets[sorted_expert_of_row]
759
+ dest = padded_offsets[sorted_expert_of_row] + row_within_expert
760
+
761
+ perm = torch.full((total_padded,), -1, dtype=torch.long, device=device)
762
+ perm[dest] = sort_idx
763
+ return perm, block_expert, total_padded, padded_offsets
764
+
765
+
766
+ class MoEFFN(nn.Module):
767
+ def __init__(self, cfg: Config, layer_idx: int):
768
+ super().__init__()
769
+ d = cfg.d_model
770
+ h = int(d * cfg.expert_hidden_mult)
771
+ E = cfg.n_experts
772
+ self.E = E; self.d = d; self.h = h
773
+ self.top_k = cfg.top_k
774
+ self.aux_loss_coef = cfg.aux_loss_coef
775
+ self.block_m = cfg.moe_block_m
776
+
777
+ self.gate_w = nn.Parameter(torch.empty(E, h, d)) # (E, OUT=h, IN=d)
778
+ self.up_w = nn.Parameter(torch.empty(E, h, d))
779
+ self.down_w = nn.Parameter(torch.empty(E, d, h)) # (E, OUT=d, IN=h)
780
+ nn.init.normal_(self.gate_w, std=0.02)
781
+ nn.init.normal_(self.up_w, std=0.02)
782
+ nn.init.normal_(self.down_w, std=0.02 / math.sqrt(2 * cfg.n_layers))
783
+
784
+ self.router = nn.Linear(d, E, bias=False)
785
+ nn.init.normal_(self.router.weight, std=0.02)
786
+
787
+ sh = int(d * cfg.shared_hidden_mult)
788
+ self.shared_gate = nn.Linear(d, sh, bias=False)
789
+ self.shared_up = nn.Linear(d, sh, bias=False)
790
+ self.shared_down = nn.Linear(sh, d, bias=False)
791
+ nn.init.normal_(self.shared_gate.weight, std=0.02)
792
+ nn.init.normal_(self.shared_up.weight, std=0.02)
793
+ nn.init.normal_(self.shared_down.weight, std=0.02 / math.sqrt(2 * cfg.n_layers))
794
+
795
+ self.bias_update_rate = cfg.bias_update_rate
796
+ self.bias_cap = cfg.bias_cap
797
+ self.bias_decay = cfg.bias_decay
798
+ self.usage_ema_decay = cfg.usage_ema_decay
799
+ # BUGFIX: these MUST stay fp32. model.to(bfloat16) would otherwise
800
+ # convert them, and expert_usage_ema accumulates token COUNTS (values
801
+ # in the thousands) β€” bf16's 8 mantissa bits cannot represent those
802
+ # increments, so the EMA would stop moving and load balancing would
803
+ # silently become a no-op. force_fp32_balancing_buffers() re-fixes
804
+ # them after the .to() in train().
805
+ self.register_buffer('expert_bias', torch.zeros(E, dtype=torch.float32))
806
+ self.register_buffer('expert_usage_ema', torch.zeros(E, dtype=torch.float32))
807
+ self._bias_capped_warned = False
808
+
809
+ self.last_aux_loss = torch.tensor(0.0)
810
+
811
+ @torch.no_grad()
812
+ def accumulate_usage(self, topk_i):
813
+ counts = F.one_hot(topk_i, self.E).float().sum(dim=(0, 1))
814
+ self.expert_usage_ema.mul_(self.usage_ema_decay).add_(counts, alpha=1 - self.usage_ema_decay)
815
+
816
+ @torch.no_grad()
817
+ def update_bias(self):
818
+ """COLLECTIVE β€” must be called by every rank on the same steps."""
819
+ if dist_ready():
820
+ dist.all_reduce(self.expert_usage_ema, op=dist.ReduceOp.AVG)
821
+
822
+ usage = self.expert_usage_ema
823
+ avg = usage.mean().clamp_min(1e-6)
824
+ error = ((avg - usage) / avg).clamp(-1.0, 1.0)
825
+
826
+ self.expert_bias.add_(self.bias_update_rate * error)
827
+ self.expert_bias.mul_(1.0 - self.bias_decay)
828
+ self.expert_bias.clamp_(-self.bias_cap, self.bias_cap)
829
+
830
+ if not self._bias_capped_warned and bool((self.expert_bias.abs() >= self.bias_cap * 0.99).any()):
831
+ log.warning(f"[moe] expert_bias hit cap ({self.bias_cap}) on some expert")
832
+ self._bias_capped_warned = True
833
+
834
+ def dead_expert_count(self, threshold: float = 1e-6) -> int:
835
+ return int((self.expert_usage_ema < threshold).sum().item())
836
+
837
+ def capped_expert_count(self) -> int:
838
+ return int((self.expert_bias.abs() >= self.bias_cap * 0.99).sum().item())
839
+
840
+ def forward(self, x):
841
+ B, L, D = x.shape; T = B * L
842
+ x_flat = x.reshape(T, D)
843
+ E, top_k, BM = self.E, self.top_k, self.block_m
844
+ device = x.device
845
+
846
+ shared_out = self.shared_down(
847
+ fused_swiglu(self.shared_gate(x_flat), self.shared_up(x_flat)))
848
+
849
+ logits = self.router(x_flat).float()
850
+ probs = F.softmax(logits, dim=-1)
851
+
852
+ biased = logits + self.expert_bias.detach().float()
853
+ _, topk_i = torch.topk(biased, top_k, dim=-1)
854
+ topk_p = probs.gather(-1, topk_i)
855
+ topk_p = topk_p / topk_p.sum(-1, keepdim=True).clamp_min(1e-9)
856
+
857
+ with torch.no_grad():
858
+ f_i = F.one_hot(topk_i, E).float().sum(1).mean(0)
859
+ p_i = probs.mean(0)
860
+ self.last_aux_loss = (E * (f_i * p_i).sum()) * self.aux_loss_coef
861
+
862
+ if self.training:
863
+ self.accumulate_usage(topk_i)
864
+
865
+ expert_ids_flat = topk_i.reshape(-1)
866
+ gate_flat = topk_p.reshape(-1).to(x.dtype)
867
+ token_idx_flat = torch.arange(T, device=device).unsqueeze(1).expand(T, top_k).reshape(-1)
868
+
869
+ perm, block_expert, total_padded, padded_offsets = moe_align_block_size(
870
+ expert_ids_flat, E, BM, device
871
+ )
872
+
873
+ valid = perm >= 0
874
+ gather_idx = perm.clamp_min(0)
875
+ src_token = token_idx_flat[gather_idx]
876
+ A_padded = x_flat[src_token] * valid.unsqueeze(1).to(x_flat.dtype)
877
+
878
+ gate = GroupedLinearFn.apply(A_padded, self.gate_w, block_expert, padded_offsets, total_padded, BM)
879
+ up = GroupedLinearFn.apply(A_padded, self.up_w, block_expert, padded_offsets, total_padded, BM)
880
+ down = GroupedLinearFn.apply(fused_swiglu(gate, up), self.down_w, block_expert, padded_offsets, total_padded, BM)
881
+
882
+ gate_vals = (gate_flat[gather_idx] * valid.to(gate_flat.dtype)).unsqueeze(1)
883
+ routed_out = torch.zeros(T, D, dtype=down.dtype, device=device)
884
+ routed_out.index_add_(0, src_token, (down * gate_vals.to(down.dtype)))
885
+
886
+ return (routed_out.to(x.dtype) + shared_out).view(B, L, D)
887
+
888
+ class Block(nn.Module):
889
+ def __init__(self, cfg: Config, layer_idx: int):
890
+ super().__init__()
891
+ self.norm1 = RMSNorm(cfg.d_model)
892
+ self.norm2 = RMSNorm(cfg.d_model)
893
+ self.attn = GQAAttention(cfg, layer_idx)
894
+ self.ffn = MoEFFN(cfg, layer_idx)
895
+
896
+ def forward(self, x, cos, sin):
897
+ x = x + self.attn(self.norm1(x), cos, sin)
898
+ x = x + self.ffn (self.norm2(x))
899
+ return x
900
+
901
+ class SmilyaiG1(nn.Module):
902
+ def __init__(self, cfg: Config):
903
+ super().__init__()
904
+ self.cfg = cfg
905
+ self.embed = nn.Embedding(cfg.vocab_size, cfg.d_model)
906
+ nn.init.normal_(self.embed.weight, std=0.02)
907
+
908
+ self.blocks = nn.ModuleList([Block(cfg, i) for i in range(cfg.n_layers)])
909
+ self.final_norm = RMSNorm(cfg.d_model)
910
+
911
+ if not cfg.tie_embeddings:
912
+ self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
913
+ nn.init.normal_(self.lm_head.weight, std=0.02 / math.sqrt(cfg.n_layers))
914
+ else:
915
+ self.lm_head = None
916
+
917
+ self.register_buffer("rope_cos", torch.zeros(cfg.max_len, cfg.head_dim // 2, dtype=torch.float32), persistent=False)
918
+ self.register_buffer("rope_sin", torch.zeros(cfg.max_len, cfg.head_dim // 2, dtype=torch.float32), persistent=False)
919
+ self._rope_ready = False
920
+ self._step = 0
921
+ self._last_lm_loss = None
922
+ self._last_aux_loss = None
923
+ self._log_summary()
924
+
925
+ # BUGFIX: torch.compile replaces blocks with OptimizedModule, which has no
926
+ # `.ffn`. Everything that reaches into a block must go through this.
927
+ def _raw_blocks(self):
928
+ return [getattr(b, "_orig_mod", b) for b in self.blocks]
929
+
930
+ def init_rope(self, device):
931
+ """BUGFIX: was lazily done inside forward(), which mutates a buffer
932
+ mid-forward under FSDP/compile. Call this once, explicitly."""
933
+ c, s = precompute_rope(self.cfg.head_dim, self.cfg.max_len, self.cfg.rope_theta, device)
934
+ self.rope_cos = c.float()
935
+ self.rope_sin = s.float()
936
+ self._rope_ready = True
937
+
938
+ def force_fp32_balancing_buffers(self):
939
+ """Undo the damage of a blanket model.to(bfloat16) on the MoE
940
+ load-balancing statistics."""
941
+ for b in self._raw_blocks():
942
+ b.ffn.expert_bias = b.ffn.expert_bias.float()
943
+ b.ffn.expert_usage_ema = b.ffn.expert_usage_ema.float()
944
+
945
+ def _log_summary(self):
946
+ cfg = self.cfg
947
+ total = sum(p.numel() for p in self.parameters())
948
+ attn_p = sum(p.numel() for n, p in self.named_parameters() if 'attn' in n)
949
+ shared_p= sum(p.numel() for n, p in self.named_parameters() if 'shared' in n)
950
+ h_e = int(cfg.d_model * cfg.expert_hidden_mult)
951
+ routed_total = cfg.n_layers * cfg.n_experts * (2*cfg.d_model*h_e + h_e*cfg.d_model)
952
+ routed_active = routed_total * (cfg.top_k / cfg.n_experts)
953
+ active_est = attn_p + shared_p + routed_active + cfg.d_model * cfg.vocab_size
954
+ log.info("=" * 70)
955
+ log.info("Smilyai-G1 20B β€” plain GQA + Sparse MoE (FSDP2)")
956
+ log.info(f" d={cfg.d_model} L={cfg.n_layers} heads={cfg.n_heads} kv={cfg.n_kv_heads}")
957
+ log.info(f" MoE: {cfg.n_experts} experts, top_k={cfg.top_k}, shared_mult={cfg.shared_hidden_mult}")
958
+ log.info(f" Total params: {total/1e9:.2f}B")
959
+ log.info(f" Active/token (estimate): {active_est/1e9:.2f}B (target ~2B)")
960
+ log.info(f" vocab={cfg.vocab_size} | Flash: {HAS_FLASH}")
961
+ log.info("=" * 70)
962
+
963
+ def count_params(self): return sum(p.numel() for p in self.parameters())
964
+ def collect_aux_loss(self): return sum(b.ffn.last_aux_loss for b in self._raw_blocks())
965
+ def set_step(self, s: int): self._step = s
966
+
967
+ def update_expert_bias(self):
968
+ for b in self._raw_blocks():
969
+ b.ffn.update_bias()
970
+
971
+ def dead_expert_report(self):
972
+ raw = self._raw_blocks()
973
+ dead = [b.ffn.dead_expert_count() for b in raw]
974
+ capped = [b.ffn.capped_expert_count() for b in raw]
975
+ return dead, sum(dead), capped, sum(capped)
976
+
977
+ def forward(self, tokens, targets=None):
978
+ B, L = tokens.shape; device = tokens.device
979
+ if not self._rope_ready:
980
+ self.init_rope(device)
981
+ cos, sin = self.rope_cos[:L], self.rope_sin[:L]
982
+
983
+ x = self.embed(tokens)
984
+ for block in self.blocks:
985
+ x = block(x, cos, sin)
986
+
987
+ x = self.final_norm(x)
988
+ logits= F.linear(x, self.embed.weight) if self.lm_head is None else self.lm_head(x)
989
+
990
+ if targets is None:
991
+ return logits, None
992
+
993
+ lm_loss = F.cross_entropy(
994
+ logits[:, :-1].reshape(-1, self.cfg.vocab_size).float(),
995
+ targets[:, 1:].reshape(-1), ignore_index=-1)
996
+ aux_loss = self.collect_aux_loss()
997
+ total_loss = lm_loss + aux_loss
998
+ self._last_lm_loss = lm_loss.detach()
999
+ self._last_aux_loss = aux_loss.detach() if torch.is_tensor(aux_loss) \
1000
+ else torch.tensor(float(aux_loss), device=device)
1001
+
1002
+ return logits, total_loss
1003
+
1004
+ # ─────────────────────────────────────────────────────────────────────────────
1005
+ # FP8 (must run BEFORE fully_shard β€” it swaps nn.Linear modules in place)
1006
+ # ─────────────────────────────────────────────────────────────────────────────
1007
+ _FP8_SKIP = ("router", "lm_head", "embed")
1008
+
1009
+ def fp8_capable_gpu() -> bool:
1010
+ return torch.cuda.is_available() and \
1011
+ torch.cuda.get_device_capability(torch.cuda.current_device())[0] >= 9
1012
+
1013
+ def apply_fp8(model: SmilyaiG1, cfg: Config, is_master: bool) -> SmilyaiG1:
1014
+ if not cfg.use_fp8:
1015
+ if is_master: log.info("[fp8] disabled")
1016
+ return model
1017
+ if not HAS_FP8:
1018
+ if is_master: log.warning("[fp8] torchao not installed β€” staying bf16")
1019
+ return model
1020
+ if not fp8_capable_gpu():
1021
+ if is_master: log.warning("[fp8] pre-Hopper GPU β€” staying bf16")
1022
+ return model
1023
+ convert_to_float8_training(
1024
+ model,
1025
+ config=Float8LinearConfig.from_recipe_name("rowwise"),
1026
+ module_filter_fn=lambda m, fqn: (
1027
+ isinstance(m, nn.Linear) and not any(s in fqn for s in _FP8_SKIP)
1028
+ ),
1029
+ )
1030
+ if is_master:
1031
+ log.info("[fp8] converted dense nn.Linear layers to float8 (rowwise); MoE stays bf16")
1032
+ return model
1033
+
1034
+ def apply_fsdp(model: SmilyaiG1, cfg: Config) -> SmilyaiG1:
1035
+ """
1036
+ BUGFIX: fully_shard requires an initialized process group. Single-GPU
1037
+ debug runs previously died here with an opaque error.
1038
+
1039
+ reduce_dtype is fp32, not bf16: summing gradients across 8 ranks in bf16
1040
+ throws away most of the small-magnitude signal you spent the backward
1041
+ pass computing. The extra memory is a few GB per rank.
1042
+ """
1043
+ if not dist_ready():
1044
+ log.warning("[fsdp] no process group β€” running unsharded (single GPU)")
1045
+ return model
1046
+ mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16,
1047
+ reduce_dtype=torch.float32)
1048
+ for block in model.blocks:
1049
+ fully_shard(block, mp_policy=mp_policy)
1050
+ fully_shard(model, mp_policy=mp_policy)
1051
+ return model
1052
+
1053
+ # ─────────────────────────────────────────────────────────────────────────────
1054
+ # MUON β€” DTensor-aware
1055
+ # ─────────────────────────────────────────────────────────────────────────────
1056
+ def newton_schulz_5(G: torch.Tensor, steps: int = 5) -> torch.Tensor:
1057
+ a, b, c = 3.4445, -4.7750, 2.0315
1058
+ squeeze = (G.ndim == 2)
1059
+ X = (G.unsqueeze(0) if squeeze else G).bfloat16()
1060
+ transposed = X.size(-2) < X.size(-1)
1061
+ if transposed: X = X.transpose(-2,-1)
1062
+ X = X / (X.norm(dim=(-2,-1), keepdim=True) + 1e-7)
1063
+ for _ in range(steps):
1064
+ A = X @ X.transpose(-2,-1)
1065
+ X = a*X + (b*A + c*A@A) @ X
1066
+ if transposed: X = X.transpose(-2,-1)
1067
+ return X.squeeze(0) if squeeze else X
1068
+
1069
+ @torch.no_grad()
1070
+ def stochastic_round_to(dtype: torch.dtype, x_fp32: torch.Tensor) -> torch.Tensor:
1071
+ """Unbiased stochastic rounding fp32 -> bf16."""
1072
+ if dtype != torch.bfloat16:
1073
+ return x_fp32.to(dtype)
1074
+ bits = x_fp32.contiguous().view(torch.int32)
1075
+ noise = torch.randint(0, 1 << 16, bits.shape, device=bits.device, dtype=torch.int32)
1076
+ rounded = (bits + noise) & -65536
1077
+ return rounded.view(torch.float32).to(torch.bfloat16)
1078
+
1079
+
1080
+ class Muon(torch.optim.Optimizer):
1081
+ """
1082
+ BUGFIX (the big one): the previous version stored the momentum buffer as a
1083
+ FULL, UNSHARDED fp32 tensor on every rank. For this model that is roughly
1084
+ the entire 20B parameter set, in fp32, replicated 8 times β€” around 80GB
1085
+ per GPU on top of everything else. It would OOM immediately.
1086
+
1087
+ It was also unnecessary. Momentum is ELEMENTWISE, so it is perfectly
1088
+ correct to run it on the local shard. Only Newton-Schulz needs the whole
1089
+ matrix. So the order is now:
1090
+
1091
+ 1. momentum update -> on the SHARDED gradient (buffer stays sharded)
1092
+ 2. all-gather the momentum-adjusted gradient -> transient, one param
1093
+ at a time, freed immediately
1094
+ 3. Newton-Schulz on the full matrix -> mathematically correct
1095
+ 4. scatter the update back to this rank's shard
1096
+ 5. stochastic-round and apply, all in local shard space
1097
+
1098
+ Peak extra memory is now one full parameter, not the whole model.
1099
+ """
1100
+ def __init__(self, params, lr=0.01, momentum=0.95, wd=0.0):
1101
+ super().__init__(list(params), dict(lr=lr, momentum=momentum, wd=wd))
1102
+
1103
+ @torch.no_grad()
1104
+ def step(self, closure=None):
1105
+ for g in self.param_groups:
1106
+ lr, mom, wd = g['lr'], g['momentum'], g['wd']
1107
+ for p in g['params']:
1108
+ if p.grad is None:
1109
+ continue
1110
+
1111
+ grad = p.grad
1112
+ is_dtensor = isinstance(p, DTensor)
1113
+
1114
+ st = self.state[p]
1115
+ if 'buf' not in st:
1116
+ # zeros_like(grad) keeps the SAME (sharded) layout as the
1117
+ # gradient β€” this is the whole memory fix.
1118
+ st['buf'] = torch.zeros_like(grad, dtype=torch.float32)
1119
+ buf = st['buf']
1120
+
1121
+ # --- step 1: elementwise momentum, on the shard ---
1122
+ buf.mul_(mom).add_(grad.to(torch.float32))
1123
+ gnest = grad.to(torch.float32).add(buf, alpha=mom)
1124
+
1125
+ # --- step 2: gather only what NS actually needs ---
1126
+ if is_dtensor:
1127
+ full = gnest.full_tensor()
1128
+ else:
1129
+ full = gnest
1130
+
1131
+ # --- step 3: orthogonalize the complete matrix ---
1132
+ if full.ndim in (2, 3):
1133
+ u = newton_schulz_5(full)
1134
+ scale = 0.2 * math.sqrt(max(full.shape[-2:]))
1135
+ update = u.to(torch.float32) * (lr * scale)
1136
+ else:
1137
+ update = full * lr
1138
+ del full
1139
+
1140
+ # --- steps 4+5: back to shard-local space, then round ---
1141
+ if is_dtensor:
1142
+ upd_local = distribute_tensor(
1143
+ update, p.device_mesh, p.placements
1144
+ ).to_local()
1145
+ p_local = p.to_local()
1146
+ else:
1147
+ upd_local = update
1148
+ p_local = p.data
1149
+
1150
+ if wd > 0:
1151
+ p_local.mul_(1.0 - lr * wd)
1152
+ p_local.sub_(stochastic_round_to(p_local.dtype, upd_local.contiguous()))
1153
+
1154
+
1155
+ def build_optimizers(model: SmilyaiG1, cfg: Config, is_master: bool):
1156
+ muon_p, adamw_p = [], []
1157
+ for name, p in model.named_parameters():
1158
+ if not p.requires_grad: continue
1159
+ if p.ndim in (2, 3) and 'embed' not in name and 'lm_head' not in name:
1160
+ muon_p.append(p)
1161
+ else:
1162
+ adamw_p.append(p)
1163
+
1164
+ muon_opt = Muon(muon_p, lr=cfg.muon_lr, momentum=cfg.muon_mom, wd=cfg.wd)
1165
+
1166
+ # BUGFIX: the old code built a second param group for 'lambda1'/'lambda2'
1167
+ # parameters that no longer exist in this architecture β€” an always-empty
1168
+ # group whose LR was then scaled by 5x in the scheduler loop, silently
1169
+ # shifting which group index got which LR.
1170
+ groups = [{'params': adamw_p, 'lr': cfg.adamw_lr}]
1171
+
1172
+ # BUGFIX: neither bitsandbytes' 8-bit optimizers nor the fused AdamW
1173
+ # kernel handle DTensor parameters. Under FSDP2 they either throw or
1174
+ # silently operate on garbage. Use the plain foreach path.
1175
+ if dist_ready():
1176
+ adamw_opt = torch.optim.AdamW(groups, betas=(cfg.beta1, cfg.beta2),
1177
+ weight_decay=cfg.wd, foreach=True)
1178
+ if is_master: log.info("[optim] Muon (gather-for-NS) + foreach AdamW (DTensor-safe)")
1179
+ elif HAS_BNB:
1180
+ adamw_opt = bnb.optim.AdamW8bit(groups, betas=(cfg.beta1, cfg.beta2), weight_decay=cfg.wd)
1181
+ if is_master: log.info("[optim] Muon + 8-bit AdamW (single GPU)")
1182
+ else:
1183
+ adamw_opt = torch.optim.AdamW(groups, betas=(cfg.beta1, cfg.beta2),
1184
+ weight_decay=cfg.wd, fused=True)
1185
+ if is_master: log.info("[optim] Muon + fused AdamW (single GPU)")
1186
+
1187
+ if is_master:
1188
+ log.info(f"[optim] Muon={sum(p.numel() for p in muon_p)/1e6:.1f}M | "
1189
+ f"AdamW={sum(p.numel() for p in adamw_p)/1e6:.1f}M")
1190
+ return muon_opt, adamw_opt
1191
+
1192
+ def cosine_lr(step, warmup, total, peak, minimum):
1193
+ if step < warmup: return peak * (step + 1) / warmup
1194
+ if step >= total: return minimum
1195
+ t = (step - warmup) / (total - warmup)
1196
+ return minimum + 0.5 * (peak - minimum) * (1 + math.cos(math.pi * t))
1197
+
1198
+ # ─────────────────────────────────────────────────────────────────────────────
1199
+ # LIVE MULTI-SOURCE STREAMING
1200
+ # ─────────────────────────────────────────────────────────────────────────────
1201
+ try:
1202
+ from datasets import load_dataset
1203
+ HAS_DATASETS = True
1204
+ except ImportError:
1205
+ HAS_DATASETS = False
1206
+
1207
+ _g1_tokenizer = None
1208
+
1209
+ def get_tokenizer(cfg: Config):
1210
+ global _g1_tokenizer
1211
+ if _g1_tokenizer is not None:
1212
+ return _g1_tokenizer
1213
+ from tokenizers import Tokenizer
1214
+ tok_path = hf_hub_download(
1215
+ repo_id=cfg.tokenizer_repo, filename="tokenizer.json",
1216
+ cache_dir=LOCAL_CACHE, token=HF_TOKEN,
1217
+ )
1218
+ _g1_tokenizer = Tokenizer.from_file(tok_path)
1219
+ got_vocab = _g1_tokenizer.get_vocab_size()
1220
+ if got_vocab != cfg.vocab_size:
1221
+ log.warning(f"[tokenizer] loaded vocab_size={got_vocab} != cfg.vocab_size="
1222
+ f"{cfg.vocab_size} β€” fix Config.vocab_size to match the real tokenizer.")
1223
+ return _g1_tokenizer
1224
+
1225
+
1226
+ def _resolve_eos(tok) -> int:
1227
+ for cand in ("</s>", "<|endoftext|>", "<|end_of_text|>", "<eos>"):
1228
+ tid = tok.token_to_id(cand)
1229
+ if tid is not None:
1230
+ return tid
1231
+ return 0
1232
+
1233
+
1234
+ def _open_source_stream(repo_id: str, split: str, shard_index: int, num_shards: int):
1235
+ ds = load_dataset(repo_id, split=split, streaming=True)
1236
+ if num_shards > 1:
1237
+ ds = ds.shard(num_shards=num_shards, index=shard_index)
1238
+ return ds
1239
+
1240
+
1241
+ class LiveStreamingDataset:
1242
+ def __init__(self, cfg: Config, batch_size: int, rank: int, world_size: int):
1243
+ if not HAS_DATASETS:
1244
+ raise RuntimeError("the `datasets` package is required for live streaming")
1245
+ self.cfg = cfg
1246
+ self.batch_size = batch_size
1247
+ self.rank = rank
1248
+ self.world_size = world_size
1249
+ self.max_len = cfg.max_len
1250
+ self.n_workers = max(1, cfg.tokenizer_workers)
1251
+ self.total_shards = world_size * self.n_workers
1252
+ self.tok = get_tokenizer(cfg)
1253
+ self.eos_id = _resolve_eos(self.tok)
1254
+
1255
+ weights = np.array([float(s[3]) for s in cfg.dataset_sources], dtype=np.float64)
1256
+ self.probabilities = weights / weights.sum()
1257
+
1258
+ qsize = max(cfg.prefetch_shards, self.n_workers * 2)
1259
+ self._q: queue.Queue = queue.Queue(maxsize=qsize)
1260
+ self._stop = threading.Event()
1261
+ self._workers = [
1262
+ threading.Thread(target=self._fetch_loop, args=(w,), daemon=True)
1263
+ for w in range(self.n_workers)
1264
+ ]
1265
+ for t in self._workers:
1266
+ t.start()
1267
+ log.info(f"[stream] rank={rank}/{world_size}: {self.n_workers} tokenizer threads "
1268
+ f"({self.total_shards} global shards) | {len(cfg.dataset_sources)} sources")
1269
+
1270
+ def _fetch_loop(self, worker_id: int):
1271
+ shard_index = self.rank * self.n_workers + worker_id
1272
+ try:
1273
+ streams = []
1274
+ for repo_id, split, text_field, w in self.cfg.dataset_sources:
1275
+ try:
1276
+ streams.append([_open_source_stream(repo_id, split, shard_index, self.total_shards),
1277
+ text_field, repo_id, split, float(w)])
1278
+ except Exception as e:
1279
+ log.warning(f"[stream] rank={self.rank}.w{worker_id} could not open {repo_id}: {e}")
1280
+ if not streams:
1281
+ log.error(f"[stream] rank={self.rank}.w{worker_id} no sources opened")
1282
+ return
1283
+
1284
+ rng = np.random.default_rng(1234 + shard_index)
1285
+ iters = [iter(s[0]) for s in streams]
1286
+ # BUGFIX: np.random.choice rejects probability vectors that don't
1287
+ # sum to exactly 1.0 in floating point. Renormalize in float64
1288
+ # over only the sources that actually opened.
1289
+ probs = np.array([s[4] for s in streams], dtype=np.float64)
1290
+ probs = probs / probs.sum()
1291
+
1292
+ buf: List[int] = []
1293
+ buf_source = "?"
1294
+ need = self.max_len * self.batch_size
1295
+
1296
+ while not self._stop.is_set():
1297
+ idx = int(rng.choice(len(iters), p=probs))
1298
+ _, text_field, repo_id, split, _w = streams[idx]
1299
+ try:
1300
+ row = next(iters[idx])
1301
+ except StopIteration:
1302
+ streams[idx][0] = _open_source_stream(repo_id, split, shard_index, self.total_shards)
1303
+ iters[idx] = iter(streams[idx][0])
1304
+ continue
1305
+ except Exception as e:
1306
+ log.warning(f"[stream] rank={self.rank}.w{worker_id} read error on {repo_id}: {e}")
1307
+ time.sleep(1.0)
1308
+ continue
1309
+
1310
+ text = row.get(text_field)
1311
+ if not text:
1312
+ continue
1313
+
1314
+ try:
1315
+ ids = self.tok.encode(text).ids
1316
+ except Exception:
1317
+ continue
1318
+ ids.append(self.eos_id)
1319
+ buf.extend(ids)
1320
+ buf_source = repo_id
1321
+
1322
+ while len(buf) >= need:
1323
+ chunk = buf[:need]
1324
+ buf = buf[need:]
1325
+ arr = np.array(chunk, dtype=np.int64).reshape(self.batch_size, self.max_len)
1326
+ if self._stop.is_set():
1327
+ return
1328
+ self._q.put((torch.from_numpy(arr), buf_source))
1329
+ except Exception as e:
1330
+ log.error(f"[stream] rank={self.rank}.w{worker_id} fetch loop crashed: {e}")
1331
+
1332
+ def __iter__(self) -> Iterator[Tuple[torch.Tensor, str]]:
1333
+ return self
1334
+
1335
+ def __next__(self) -> Tuple[torch.Tensor, str]:
1336
+ while not self._stop.is_set():
1337
+ try:
1338
+ return self._q.get(timeout=60)
1339
+ except queue.Empty:
1340
+ log.warning(f"[stream] rank={self.rank} queue empty β€” waiting for data …")
1341
+ raise StopIteration
1342
+
1343
+ def close(self):
1344
+ self._stop.set()
1345
+ # drain so blocked producers can exit
1346
+ try:
1347
+ while True: self._q.get_nowait()
1348
+ except queue.Empty:
1349
+ pass
1350
+ for t in self._workers:
1351
+ t.join(timeout=5)
1352
+
1353
+
1354
+ def build_val_loader(cfg: Config) -> Optional[DataLoader]:
1355
+ """
1356
+ BUGFIX: this is now built on EVERY rank, not just rank 0, because
1357
+ validate() runs a model forward (= FSDP collectives) on every rank.
1358
+ The stream is deliberately NOT sharded, so every rank tokenizes the same
1359
+ first N rows and the loaders have identical length β€” otherwise ranks
1360
+ would issue different numbers of forwards and deadlock.
1361
+ """
1362
+ if not HAS_DATASETS:
1363
+ return None
1364
+ tok = get_tokenizer(cfg)
1365
+ repo_id, split, text_field, _ = max(cfg.dataset_sources, key=lambda s: s[3])
1366
+ try:
1367
+ ds = load_dataset(repo_id, split=split, streaming=True)
1368
+ except Exception as e:
1369
+ log.warning(f"[val] could not open {repo_id}: {e}")
1370
+ return None
1371
+
1372
+ eos_id = _resolve_eos(tok)
1373
+ buf: List[int] = []
1374
+ rows = []
1375
+ n_val_seqs = 128
1376
+ try:
1377
+ for row in ds:
1378
+ text = row.get(text_field)
1379
+ if not text:
1380
+ continue
1381
+ ids = tok.encode(text).ids
1382
+ ids.append(eos_id)
1383
+ buf.extend(ids)
1384
+ while len(buf) >= cfg.max_len:
1385
+ rows.append(np.array(buf[:cfg.max_len], dtype=np.int64))
1386
+ buf = buf[cfg.max_len:]
1387
+ if len(rows) >= n_val_seqs:
1388
+ break
1389
+ if len(rows) >= n_val_seqs:
1390
+ break
1391
+ except Exception as e:
1392
+ log.warning(f"[val] stream error: {e}")
1393
+
1394
+ if not rows:
1395
+ log.warning(f"[val] got no validation rows from {repo_id}")
1396
+ return None
1397
+ data = np.stack(rows, axis=0)
1398
+
1399
+ class _ValDS(Dataset):
1400
+ def __len__(self): return len(data)
1401
+ def __getitem__(self, i): return torch.from_numpy(data[i])
1402
+
1403
+ return DataLoader(_ValDS(), batch_size=min(cfg.micro_batch, 4),
1404
+ shuffle=False, num_workers=0, pin_memory=True, drop_last=True)
1405
+
1406
+ # ─────────────────────────────────────────────────────────────────────────────
1407
+ # CHECKPOINTING
1408
+ # get_/set_model_state_dict and the optimizer equivalents are COLLECTIVE.
1409
+ # Every rank calls them; only rank 0 touches the filesystem.
1410
+ # ─────────────────────────────────────────────────────────────────────────────
1411
+ def save_ckpt(model, muon, adamw, step, epoch, cfg, loss, is_master: bool):
1412
+ opts = StateDictOptions(full_state_dict=True, cpu_offload=True)
1413
+ model_sd = get_model_state_dict(model, options=opts)
1414
+ try:
1415
+ muon_sd = get_optimizer_state_dict(model, muon, options=opts)
1416
+ except Exception as e:
1417
+ log.warning(f"[ckpt] could not gather muon state: {e}"); muon_sd = {}
1418
+ try:
1419
+ adamw_sd = get_optimizer_state_dict(model, adamw, options=opts)
1420
+ except Exception as e:
1421
+ log.warning(f"[ckpt] could not gather adamw state: {e}"); adamw_sd = {}
1422
+
1423
+ if not is_master:
1424
+ return
1425
+ name = f"g1_s{SESSION_ID:03d}_step{step:07d}"
1426
+ local = os.path.join(TEMP_CKPT_DIR, f"{name}.pt")
1427
+ torch.save({'model': model_sd, 'muon': muon_sd, 'adamw': adamw_sd,
1428
+ 'step': step, 'epoch': epoch, 'loss': loss, 'config': asdict(cfg)}, local)
1429
+ upload_to_hf(local, f"{name}.pt")
1430
+ try: os.remove(local)
1431
+ except OSError: pass
1432
+
1433
+ def _find_latest_ckpt():
1434
+ for sid in range(SESSION_ID, 0, -1):
1435
+ repo = f"{REPO_PREFIX}{sid:03d}"
1436
+ try:
1437
+ files = hf_api.list_repo_files(repo_id=repo, repo_type="model", token=HF_TOKEN)
1438
+ except Exception:
1439
+ continue
1440
+ ckpts = sorted([f for f in files if f.endswith(".pt") and "step" in f],
1441
+ key=lambda x: int(x.split("step")[-1].split(".")[0]))
1442
+ if ckpts:
1443
+ return repo, ckpts[-1]
1444
+ return None, None
1445
+
1446
+ def load_ckpt(model, muon, adamw, device, is_master: bool):
1447
+ """
1448
+ BUGFIX: the previous version did broadcast_object_list() on the ENTIRE
1449
+ checkpoint dict β€” pickling a full ~20B-parameter state dict and shipping
1450
+ it to all 8 ranks over the object collective. That's tens of GB of host
1451
+ RAM per rank and would almost certainly die.
1452
+
1453
+ The correct FSDP2 pattern: only rank 0 loads the file, and
1454
+ StateDictOptions(full_state_dict=True, broadcast_from_rank0=True) makes
1455
+ set_*_state_dict broadcast-and-reshard it. Non-master ranks pass {}.
1456
+ Only the three scalars (step/epoch/loss) need a real broadcast.
1457
+ """
1458
+ ckpt = None
1459
+ meta = torch.zeros(3, dtype=torch.float64, device=device) # [found, step, epoch] + loss
1460
+ loss_t = torch.zeros(1, dtype=torch.float64, device=device)
1461
+
1462
+ if is_master:
1463
+ repo, ckpt_name = _find_latest_ckpt()
1464
+ if repo is None:
1465
+ log.warning("[ckpt] no checkpoint in this or any earlier session repo β€” fresh start")
1466
+ else:
1467
+ try:
1468
+ path = hf_hub_download(repo, ckpt_name, cache_dir=TEMP_CKPT_DIR, token=HF_TOKEN)
1469
+ ckpt = torch.load(path, map_location="cpu", weights_only=False)
1470
+ meta[0] = 1.0
1471
+ meta[1] = float(ckpt['step'])
1472
+ meta[2] = float(ckpt['epoch'])
1473
+ loss_t[0] = float(ckpt['loss'])
1474
+ if repo != HF_MODEL_REPO:
1475
+ log.info(f"[ckpt] resuming from an EARLIER session's repo: {repo}/{ckpt_name}")
1476
+ except Exception as e:
1477
+ log.error("=" * 66)
1478
+ log.error(f"[ckpt] FOUND {repo}/{ckpt_name} BUT COULD NOT LOAD IT: {e}")
1479
+ log.error("[ckpt] falling back to fresh start β€” check this before trusting the run")
1480
+ log.error("=" * 66)
1481
+ ckpt = None
1482
+
1483
+ if dist_ready():
1484
+ dist.broadcast(meta, src=0)
1485
+ dist.broadcast(loss_t, src=0)
1486
+
1487
+ if meta[0].item() < 0.5:
1488
+ return 0, 0, float('inf')
1489
+
1490
+ # BUGFIX: broadcast_from_rank0 REQUIRES full_state_dict=True. The old code
1491
+ # passed only broadcast_from_rank0 and would raise.
1492
+ opts = StateDictOptions(full_state_dict=True, broadcast_from_rank0=True)
1493
+ set_model_state_dict(model,
1494
+ model_state_dict=(ckpt['model'] if is_master else {}),
1495
+ options=opts)
1496
+ try:
1497
+ set_optimizer_state_dict(model, muon,
1498
+ optim_state_dict=(ckpt['muon'] if is_master else {}),
1499
+ options=opts)
1500
+ except Exception as e:
1501
+ log.warning(f"[ckpt] muon state not restored: {e}")
1502
+ try:
1503
+ set_optimizer_state_dict(model, adamw,
1504
+ optim_state_dict=(ckpt['adamw'] if is_master else {}),
1505
+ options=opts)
1506
+ except Exception as e:
1507
+ log.warning(f"[ckpt] adamw state not restored: {e}")
1508
+
1509
+ step, epoch, loss = int(meta[1].item()), int(meta[2].item()), float(loss_t[0].item())
1510
+ if is_master:
1511
+ log.info(f"[ckpt] resumed step={step} loss={loss:.4f}")
1512
+ del ckpt
1513
+ gc.collect()
1514
+ return step, epoch, loss
1515
+
1516
+ def save_final(model, cfg, step, epoch, loss, is_master: bool):
1517
+ opts = StateDictOptions(full_state_dict=True, cpu_offload=True)
1518
+ model_sd = get_model_state_dict(model, options=opts)
1519
+ if not is_master:
1520
+ return
1521
+ name = f"g1_final_s{SESSION_ID:03d}_step{step:07d}"
1522
+ mname = f"{name}.safetensors" if HAS_ST else f"{name}.pt"
1523
+ mpath = os.path.join(TEMP_CKPT_DIR, mname)
1524
+ cpath = os.path.join(TEMP_CKPT_DIR, f"{name}_config.json")
1525
+ if HAS_ST:
1526
+ st_save({k: v.contiguous() for k, v in model_sd.items()}, mpath)
1527
+ else:
1528
+ torch.save(model_sd, mpath)
1529
+ with open(cpath, 'w') as f:
1530
+ json.dump({**asdict(cfg), 'step': step, 'epoch': epoch,
1531
+ 'loss': loss, 'arch': 'Smilyai-G1-20B'}, f, indent=2)
1532
+ upload_to_hf(mpath, mname); upload_to_hf(cpath, os.path.basename(cpath))
1533
+ for p in (mpath, cpath):
1534
+ try: os.remove(p)
1535
+ except OSError: pass
1536
+
1537
+ @torch.no_grad()
1538
+ def validate(model, val_loader, device, cfg, n=100):
1539
+ """
1540
+ BUGFIX: COLLECTIVE β€” every rank must call this with an identically-sized
1541
+ loader. Previously it ran on rank 0 only and hung the other 7 on the
1542
+ following barrier while rank 0 waited forever inside an all-gather.
1543
+ """
1544
+ if val_loader is None:
1545
+ return float('nan')
1546
+ was_training = model.training
1547
+ model.eval(); losses = []
1548
+ for i, batch in enumerate(val_loader):
1549
+ if i >= n: break
1550
+ batch = batch.to(device, non_blocking=True)
1551
+ with torch.amp.autocast('cuda', dtype=cfg.dtype):
1552
+ _, loss = model(batch, batch)
1553
+ lm = getattr(model, '_last_lm_loss', None)
1554
+ lm = lm if lm is not None else loss
1555
+ if lm is not None and torch.isfinite(lm):
1556
+ losses.append(lm.item())
1557
+ if was_training: model.train()
1558
+ local = float(np.mean(losses)) if losses else float('nan')
1559
+ if math.isnan(local):
1560
+ return local
1561
+ return distributed_mean(local, device)
1562
+
1563
+ # ─────────────────────────────────────────────────────────────────────────────
1564
+ # TRAIN
1565
+ # ─────────────────────────────────────────────────────────────────────────────
1566
+ def train():
1567
+ if not torch.cuda.is_available():
1568
+ raise RuntimeError("this script requires CUDA GPUs")
1569
+
1570
+ local_rank = int(os.environ.get("LOCAL_RANK", "0"))
1571
+ rank = int(os.environ.get("RANK", "0"))
1572
+ world_size = int(os.environ.get("WORLD_SIZE", "1"))
1573
+ torch.cuda.set_device(local_rank)
1574
+ device = torch.device("cuda", local_rank)
1575
+ if world_size > 1 and not dist_ready():
1576
+ dist.init_process_group(backend="nccl", init_method="env://", device_id=device)
1577
+ is_master = (rank == 0)
1578
+
1579
+ # keep the log readable: non-master ranks only speak up when something breaks
1580
+ if not is_master:
1581
+ log.setLevel(logging.WARNING)
1582
+
1583
+ torch.manual_seed(42 + rank); np.random.seed(42 + rank); random.seed(42 + rank)
1584
+
1585
+ log.info(f"[env] rank={rank}/{world_size} device={device} | "
1586
+ f"GPU={torch.cuda.get_device_name(local_rank)} | VRAM={vram_total_gb():.0f}GB")
1587
+
1588
+ if is_master:
1589
+ ensure_repo()
1590
+ session_banner()
1591
+ _bootstrap_from_hub(METRICS_FILE, os.path.basename(METRICS_FILE))
1592
+ _bootstrap_from_hub(SAMPLES_FILE, "samples.md")
1593
+ _bootstrap_from_hub(SUMMARY_FILE, "summary.jsonl")
1594
+ if dist_ready():
1595
+ dist.barrier()
1596
+
1597
+ cfg = Config()
1598
+ try:
1599
+ get_tokenizer(cfg)
1600
+ except Exception as e:
1601
+ log.warning(f"[tokenizer] pre-load failed, will retry lazily: {e}")
1602
+
1603
+ model = SmilyaiG1(cfg).to(device).to(cfg.dtype)
1604
+ # BUGFIX: .to(bfloat16) above hits every buffer. RoPE tables and the MoE
1605
+ # load-balancing statistics must be fp32 β€” put them back before sharding.
1606
+ model.init_rope(device)
1607
+ model.force_fp32_balancing_buffers()
1608
+
1609
+ model = apply_fp8(model, cfg, is_master) # BEFORE fsdp β€” swaps nn.Linear in place
1610
+ model = apply_fsdp(model, cfg)
1611
+
1612
+ if cfg.use_compile:
1613
+ try:
1614
+ for i, block in enumerate(model.blocks):
1615
+ model.blocks[i] = torch.compile(block, dynamic=True)
1616
+ log.info(f"[compile] compiled {len(model.blocks)} blocks")
1617
+ except Exception as e:
1618
+ log.warning(f"[compile] failed, running eager: {e}")
1619
+ else:
1620
+ if is_master: log.info("[compile] skipped")
1621
+
1622
+ muon, adamw = build_optimizers(model, cfg, is_master)
1623
+
1624
+ start_step, start_epoch, best_loss = load_ckpt(model, muon, adamw, device, is_master)
1625
+ if dist_ready():
1626
+ dist.barrier()
1627
+
1628
+ last_val = float('nan')
1629
+ bs = cfg.micro_batch
1630
+
1631
+ stream = LiveStreamingDataset(cfg, batch_size=bs, rank=rank, world_size=world_size)
1632
+ # BUGFIX: built on ALL ranks β€” validate() is collective.
1633
+ val_loader = build_val_loader(cfg)
1634
+
1635
+ if is_master:
1636
+ log.info("=" * 70)
1637
+ log.info(f"Smilyai-G1 | {model.count_params()/1e9:.2f}B total params | "
1638
+ f"Session {SESSION_ID} | FSDP2 world={world_size}")
1639
+ log.info(f" micro_batch={bs}/GPU grad_accum={cfg.grad_accum} "
1640
+ f"eff_batch={bs*cfg.grad_accum*world_size} max_len={cfg.max_len}")
1641
+ log.info(f" {cfg.tokens_per_step(bs, world_size)/1e6:.1f}M tok/step | "
1642
+ f"{MAX_HOURS}h budget | streaming=True")
1643
+ log.info("=" * 70)
1644
+
1645
+ step, epoch = start_step, start_epoch
1646
+ losses = []
1647
+ aux_losses = []
1648
+ model.train(); model.zero_grad(set_to_none=True)
1649
+ t0 = time.time(); last_ckpt = time.time()
1650
+
1651
+ # BUGFIX: was master-only -> guaranteed hang on the first FSDP all-gather.
1652
+ try:
1653
+ record_sample(model, step, is_master)
1654
+ except Exception as e:
1655
+ log.warning(f"[sample] {e}")
1656
+
1657
+ # NOTE: gradient accumulation now reduce-scatters on EVERY micro-step.
1658
+ # The old code used set_requires_gradient_sync(False) for the first 15 of
1659
+ # 16 micro-steps, which makes FSDP2 keep gradients UNSHARDED for the whole
1660
+ # accumulation window β€” a full replica of every gradient on every rank
1661
+ # (~40GB at bf16 for this model). Syncing every micro-step costs extra
1662
+ # NVLink traffic but is the only version that fits.
1663
+
1664
+ accum_n = 0
1665
+ while not distributed_should_stop(device, is_master, step, cfg.total_steps):
1666
+ try:
1667
+ batch, folder = next(stream)
1668
+ except StopIteration:
1669
+ log.warning(f"[stream] rank={rank} exhausted β€” sleeping 60s")
1670
+ time.sleep(60); continue
1671
+ except Exception as e:
1672
+ log.error(f"[data] rank={rank} {e}"); time.sleep(5); continue
1673
+
1674
+ batch = batch.to(device, non_blocking=True)
1675
+
1676
+ micro_ok = True
1677
+ try:
1678
+ with torch.amp.autocast('cuda', dtype=cfg.dtype):
1679
+ _, loss = model(batch, batch)
1680
+ loss_s = loss / cfg.grad_accum
1681
+
1682
+ if not torch.isfinite(loss):
1683
+ micro_ok = False
1684
+ else:
1685
+ loss_s.backward()
1686
+ lm_only = getattr(model, '_last_lm_loss', loss)
1687
+ aux_only = getattr(model, '_last_aux_loss', None)
1688
+ losses.append(float(lm_only))
1689
+ aux_losses.append(float(aux_only) if aux_only is not None else 0.0)
1690
+ except RuntimeError as e:
1691
+ if "out of memory" in str(e).lower() or "memory" in str(e).lower():
1692
+ log.error(f"[oom] rank={rank} step={step}: {e}")
1693
+ micro_ok = False
1694
+ torch.cuda.empty_cache()
1695
+ else:
1696
+ raise
1697
+
1698
+ # BUGFIX: OOM/NaN recovery must be a COLLECTIVE decision. Previously
1699
+ # one rank could `continue` while the others walked into the optimizer
1700
+ # step, and the next collective would deadlock the whole job.
1701
+ if not all_ok(micro_ok, device):
1702
+ if is_master: log.error(f"[skip] step={step} micro-batch failed on >=1 rank")
1703
+ model.zero_grad(set_to_none=True); accum_n = 0
1704
+ continue
1705
+
1706
+ accum_n += 1
1707
+ if accum_n < cfg.grad_accum:
1708
+ continue
1709
+
1710
+ mlr = cosine_lr(step, cfg.warmup, cfg.total_steps, cfg.muon_lr, cfg.muon_min_lr)
1711
+ alr = cosine_lr(step, cfg.warmup, cfg.total_steps, cfg.adamw_lr, cfg.adamw_min_lr)
1712
+ for g in muon.param_groups: g['lr'] = mlr
1713
+ for g in adamw.param_groups: g['lr'] = alr
1714
+
1715
+ norm = torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
1716
+ # BUGFIX: with FSDP2 this returns a DTensor; isnan/isinf on it is not
1717
+ # a reliable python bool. Materialize it first.
1718
+ if isinstance(norm, DTensor):
1719
+ norm = norm.full_tensor()
1720
+ if not torch.isfinite(norm):
1721
+ if is_master: log.error("[nan] grad-norm non-finite β€” skipping step")
1722
+ model.zero_grad(set_to_none=True); accum_n = 0; continue
1723
+
1724
+ muon.step(); adamw.step(); model.zero_grad(set_to_none=True)
1725
+
1726
+ step += 1
1727
+ model.set_step(step)
1728
+ accum_n = 0
1729
+ if len(losses) > 500: losses = losses[-500:]
1730
+ if len(aux_losses) > 500: aux_losses = aux_losses[-500:]
1731
+
1732
+ # collective β€” every rank, every time it's due
1733
+ if step % cfg.bias_update_every == 0:
1734
+ model.update_expert_bias()
1735
+
1736
+ if step % cfg.log_every == 0 and losses:
1737
+ avg = distributed_mean(float(np.mean(losses[-50:])), device)
1738
+ avg_aux = distributed_mean(float(np.mean(aux_losses[-50:])), device) if aux_losses else 0.0
1739
+ _step_clock.append((step, time.time()))
1740
+ if len(_step_clock) > 300: _step_clock.pop(0)
1741
+ sph = _real_steps_per_hour()
1742
+ tps = (sph * cfg.tokens_per_step(bs, world_size) / 3600) if sph else \
1743
+ (max(step - start_step, 1) * cfg.tokens_per_step(bs, world_size) / max(time.time() - t0, 1))
1744
+ if is_master:
1745
+ log_metrics(step=step, loss=avg, aux=avg_aux, tok_s=tps, folder=folder)
1746
+ sl = sessions_left(step, cfg.total_steps)
1747
+ suffix = f" | ~{sl} more sessions" if sl is not None else ""
1748
+ log.info(f"step {step:06d} | ep {epoch+1} | lm {avg:.4f} | aux {avg_aux:.4f} | "
1749
+ f"ppl {math.exp(min(avg,20)):.1f} | {tps/1e3:.1f}K tok/s | "
1750
+ f"{vram_str()} | {remaining_h():.1f}h left | {folder}{suffix}")
1751
+
1752
+ # ── eval: COLLECTIVE, all ranks ───────────────────────────────────
1753
+ if step % cfg.eval_every == 0:
1754
+ vl = validate(model, val_loader, device, cfg)
1755
+ if is_master and vl == vl:
1756
+ marker = " *NEW BEST*" if vl < best_loss else ""
1757
+ if vl < best_loss: best_loss = vl
1758
+ last_val = vl
1759
+ log_metrics(step=step, val_loss=vl)
1760
+ log.info(f" [val] loss={vl:.4f} ppl={math.exp(min(vl,20)):.1f}{marker}")
1761
+
1762
+ dead, total_dead, capped, total_capped = model.dead_expert_report()
1763
+ total_experts = cfg.n_experts * cfg.n_layers
1764
+ if total_dead > 0:
1765
+ log.info(f" [experts] dead={total_dead}/{total_experts}")
1766
+ else:
1767
+ log.info(f" [experts] all {total_experts} experts alive βœ…")
1768
+ if total_capped > 0:
1769
+ log.info(f" [experts] bias-capped={total_capped}/{total_experts}")
1770
+
1771
+ try:
1772
+ record_sample(model, step, is_master) # collective on all ranks
1773
+ except Exception as e:
1774
+ log.warning(f"[sample] {e}")
1775
+ if dist_ready():
1776
+ dist.barrier()
1777
+
1778
+ # ── checkpoint: gate decided by rank 0 and broadcast ──────────────
1779
+ # BUGFIX: `(time.time() - last_ckpt) > 1800` is wall-clock and is NOT
1780
+ # identical across ranks. When it flipped on some ranks and not others,
1781
+ # the ones that entered save_ckpt() blocked forever in the state-dict
1782
+ # all-gather while the rest ran ahead. Rank 0 now decides for everyone.
1783
+ local_due = (step % cfg.ckpt_every == 0) or ((time.time() - last_ckpt) > 1800)
1784
+ if broadcast_flag(local_due if is_master else False, device):
1785
+ save_ckpt(model, muon, adamw, step, epoch, cfg,
1786
+ losses[-1] if losses else 0.0, is_master)
1787
+ if is_master:
1788
+ update_progress_md(cfg, step, epoch,
1789
+ float(np.mean(losses[-50:])) if losses else None, last_val)
1790
+ make_loss_chart(); upload_metrics()
1791
+ if dist_ready():
1792
+ dist.barrier()
1793
+ last_ckpt = time.time()
1794
+
1795
+ log.info(f"[rank {rank}] DONE training loop")
1796
+ stream.close()
1797
+
1798
+ # BUGFIX: final validate is collective too β€” all ranks, then rank 0 reports.
1799
+ vm = validate(model, val_loader, device, cfg, n=300)
1800
+ if vm != vm:
1801
+ vm = losses[-1] if losses else 0.0
1802
+ save_final(model, cfg, step, epoch, vm, is_master)
1803
+ if is_master:
1804
+ try:
1805
+ update_progress_md(cfg, step, epoch,
1806
+ float(np.mean(losses[-50:])) if losses else None, vm)
1807
+ make_loss_chart(); upload_metrics()
1808
+ except Exception as e:
1809
+ log.warning(f"[motiv] final refresh failed: {e}")
1810
+ log.info(f"Steps={step:,} | Epochs={epoch+1} | Time={elapsed_h():.2f}h | Final val={vm:.4f}")
1811
+
1812
+ if dist_ready():
1813
+ dist.barrier()
1814
+ dist.destroy_process_group()
1815
+
1816
+
1817
+ def _spawn_worker(local_rank: int, world_size: int):
1818
+ os.environ["LOCAL_RANK"] = str(local_rank)
1819
+ os.environ["RANK"] = str(local_rank)
1820
+ os.environ["WORLD_SIZE"] = str(world_size)
1821
+ train()
1822
+
1823
+
1824
+ def launch():
1825
+ if "RANK" in os.environ and "WORLD_SIZE" in os.environ:
1826
+ train()
1827
+ return
1828
+
1829
+ world_size = torch.cuda.device_count()
1830
+ if world_size < 1:
1831
+ raise RuntimeError("No CUDA GPUs are visible")
1832
+ expected_world = int(os.environ.get("EXPECTED_WORLD_SIZE", str(world_size)))
1833
+ if world_size != expected_world:
1834
+ raise RuntimeError(
1835
+ f"Expected {expected_world} visible GPUs, found {world_size}; "
1836
+ "refusing to run with the wrong allocation"
1837
+ )
1838
+
1839
+ os.environ.setdefault("MASTER_ADDR", "127.0.0.1")
1840
+ os.environ.setdefault("MASTER_PORT", "29500")
1841
+ os.environ.setdefault("TORCH_NCCL_ASYNC_ERROR_HANDLING", "1")
1842
+ mp.spawn(_spawn_worker, args=(world_size,), nprocs=world_size, join=True)
1843
+
1844
+
1845
+ if __name__ == "__main__":
1846
+ launch()