Bc-AI commited on
Commit
1ca35f0
Β·
verified Β·
1 Parent(s): d400524

Update train.py

Browse files
Files changed (1) hide show
  1. train.py +277 -159
train.py CHANGED
@@ -8,7 +8,7 @@
8
  # "datasets>=2.19",
9
  # "tokenizers>=0.20",
10
  # "bitsandbytes",
11
- # "torchao",
12
  # ]
13
  # ///
14
 
@@ -16,30 +16,39 @@
16
  Smilyai-G1 : Fast Sparse General-Assistant Transformer β€” FSDP2 EDITION (8xH200)
17
  ~20B total params | ~2B active per token
18
 
19
- FIXED EDITION v2. Changes in this pass:
20
-
21
- 1. MUON SCALE BUG (critical): the Newton-Schulz update multiplier was
22
- `0.2 * sqrt(max(rows, cols))` β€” for d_model=2048 matrices that's ~45x
23
- too large (sqrt(2048)β‰ˆ45.25). Correct Muon uses the ASPECT RATIO of the
24
- matrix: `max(1, rows/cols)**0.5`, which is ~1.0 for square-ish matrices.
25
- Every Muon-optimized weight (attention, MoE experts, router) was getting
26
- hammered with ~45x oversized updates every step β€” this produces fast
27
- early "progress" (coarse structure survives noisy updates) followed by a
28
- hard plateau because fine-grained learning gets destroyed by the noise
29
- floor. Fixed here; muon_lr raised 0.008 -> 0.02 to compensate for the
30
- ~45x smaller effective step (standard Muon LR for this model scale).
31
-
32
- 2. CHECKPOINT I/O WAS BLOCKING (caused a real NCCL watchdog crash): rank 0's
33
- torch.save() + upload_file() for an ~80-100GB checkpoint could take
34
- longer than the default 10-minute NCCL collective timeout, while ranks
35
- 1-7 sat idle at dist.barrier(). Fix: checkpoint save/upload now happens
36
- on a background thread on rank 0. All 8 ranks return to training
37
- immediately after the (fast) state-dict gather; the slow disk/network
38
- work no longer blocks any collective. The barrier that used to follow
39
- the checkpoint block has been removed since rank 0 no longer lags.
40
-
41
- 3. NCCL timeout raised from the 10-minute default to 60 minutes as a safety
42
- net for any other slow collective we haven't found yet.
 
 
 
 
 
 
 
 
 
43
 
44
  The load-bearing invariant of this file remains:
45
 
@@ -47,8 +56,8 @@ The load-bearing invariant of this file remains:
47
 
48
  RUN:
49
  export HF_TOKEN=your_hf_token_here
50
- export G1_SESSION_ID=2 # NEW session β€” see notes above
51
- export MAX_TRAINING_HOURS=144 # 6 days
52
  torchrun --nproc_per_node=8 train_g1_fsdp.py
53
  """
54
 
@@ -115,6 +124,21 @@ torch.backends.cudnn.allow_tf32 = True
115
  torch.backends.cuda.enable_flash_sdp(True)
116
  torch.backends.cuda.enable_mem_efficient_sdp(True)
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(message)s', datefmt='%H:%M:%S')
119
  log = logging.getLogger("smilyai-g1-fsdp")
120
  log.info(f"[env] flash_attn={HAS_FLASH} | bnb={HAS_BNB}")
@@ -123,8 +147,8 @@ log.info(f"[env] flash_attn={HAS_FLASH} | bnb={HAS_BNB}")
123
  # HF SETUP
124
  # ─────────────────────────────────────────────────────────────────────────────
125
  HF_TOKEN = os.environ.get("HF_TOKEN", "")
126
- SESSION_ID = int(os.environ.get("G1_SESSION_ID", "2"))
127
- REPO_PREFIX = "hugging-science/Smilyai-G1-20B-v2-session-"
128
  HF_MODEL_REPO = f"{REPO_PREFIX}{SESSION_ID:03d}"
129
 
130
  if not HF_TOKEN:
@@ -142,7 +166,7 @@ TEMP_CKPT_DIR = "/tmp/g1_ckpts"
142
  os.makedirs(LOCAL_CACHE, exist_ok=True)
143
  os.makedirs(TEMP_CKPT_DIR, exist_ok=True)
144
 
145
- MAX_HOURS = float(os.environ.get("MAX_TRAINING_HOURS", "110.0"))
146
  START_TIME = time.time()
147
  def elapsed_h(): return (time.time() - START_TIME) / 3600
148
  def remaining_h(): return MAX_HOURS - elapsed_h()
@@ -245,12 +269,6 @@ DOMAIN_TOKEN = ""
245
 
246
  @torch.no_grad()
247
  def make_sample(model, prompt="def fibonacci(n):", max_new=48, temp=0.8, top_p=0.95):
248
- """
249
- This runs a MODEL FORWARD, which under FSDP2 is a collective (all-gather
250
- per block). It therefore MUST be called by every rank. The sampling RNG
251
- is seeded identically on all ranks so every rank walks the same token
252
- sequence and issues an identical collective schedule.
253
- """
254
  try:
255
  tok = _get_tokenizer()
256
  if tok is None: return None
@@ -263,7 +281,7 @@ def make_sample(model, prompt="def fibonacci(n):", max_new=48, temp=0.8, top_p=0
263
  log.warning(f"[sample] tokenizer error: {e}"); return None
264
 
265
  gen = torch.Generator(device=device)
266
- gen.manual_seed(1234) # identical on all ranks -> identical trajectory
267
 
268
  was_training = model.training
269
  model.eval()
@@ -287,7 +305,6 @@ def make_sample(model, prompt="def fibonacci(n):", max_new=48, temp=0.8, top_p=0
287
  return None
288
 
289
  def record_sample(model, step, is_master: bool):
290
- """Collective on all ranks; only rank 0 persists the result."""
291
  txt = make_sample(model)
292
  if not is_master:
293
  return
@@ -352,7 +369,7 @@ class Config:
352
  n_shared_experts: int = 1
353
  aux_loss_coef: float = 0.01
354
  bias_update_rate: float = 0.001
355
- bias_update_every: int = 10 # in OPTIMIZER steps
356
  bias_cap: float = 2.0
357
  bias_decay: float = 0.0005
358
  usage_ema_decay: float = 0.99
@@ -360,8 +377,6 @@ class Config:
360
 
361
  tie_embeddings: bool = True
362
 
363
- # ── FIX #1: Muon LR raised to compensate for the corrected (~45x smaller)
364
- # update scale. 0.02 is the standard Muon LR at this model scale.
365
  muon_lr: float = 0.02
366
  muon_min_lr: float = 0.002
367
  muon_mom: float = 0.95
@@ -386,6 +401,11 @@ class Config:
386
  dpo_every: int = 500
387
  dpo_beta: float= 0.1
388
 
 
 
 
 
 
389
  dataset_sources: tuple = (
390
  ("HuggingFaceFW/fineweb-edu", "train", "text", 200_000_000_000),
391
  ("HuggingFaceCode/stack-v3-train", "train", "content", 100_000_000_000),
@@ -396,9 +416,13 @@ class Config:
396
  )
397
  tokenizer_repo: str = "Smilyai-labs/Smilyai-U1-B-Tokenizer"
398
  tokenizer_workers: int = 8
399
- prefetch_shards: int = 6
 
 
 
400
 
401
- use_compile: bool = False
 
402
  use_fp8: bool = False
403
 
404
  @property
@@ -407,6 +431,19 @@ class Config:
407
  def head_dim(self): return self.d_model // self.n_heads
408
  def tokens_per_step(self, bs, world_size=1): return bs * self.grad_accum * self.max_len * world_size
409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410
  # ─────────────────────────────────────────────────────────────────────────────
411
  # DISTRIBUTED HELPERS
412
  # ─────────────────────────────────────────────────────────────────────────────
@@ -421,16 +458,12 @@ def distributed_mean(value: float, device: torch.device) -> float:
421
  return t.item()
422
 
423
  def broadcast_flag(value: bool, device: torch.device) -> bool:
424
- """Rank 0 decides, everyone obeys. Used for anything that gates a
425
- collective (checkpointing, eval, stopping) so ranks can never diverge."""
426
  flag = torch.tensor(int(bool(value)), dtype=torch.int32, device=device)
427
  if dist_ready():
428
  dist.broadcast(flag, src=0)
429
  return bool(flag.item())
430
 
431
  def all_ok(ok: bool, device: torch.device) -> bool:
432
- """Collective AND. If ANY rank failed (OOM/NaN), every rank must take the
433
- same recovery branch, or the next collective deadlocks."""
434
  t = torch.tensor(int(bool(ok)), dtype=torch.int32, device=device)
435
  if dist_ready():
436
  dist.all_reduce(t, op=dist.ReduceOp.MIN)
@@ -549,7 +582,6 @@ def precompute_rope(head_dim, max_len, theta, device):
549
  return freqs.cos(), freqs.sin()
550
 
551
  def apply_rope(x, cos, sin):
552
- """Rotation math forced to fp32 β€” cos/sin tables must stay fp32 too."""
553
  dt = x.dtype
554
  L = x.shape[1]; h = x.shape[-1] // 2
555
  c = cos[:L].unsqueeze(0).unsqueeze(2); s = sin[:L].unsqueeze(0).unsqueeze(2)
@@ -650,8 +682,6 @@ def _moe_gemm_kernel(
650
 
651
 
652
  def _grouped_linear_raw(A, W, block_expert, M_padded, transpose, BM):
653
- """W is (E, OUT, IN) β€” nn.Linear convention. transpose=True computes the
654
- dA backward pass (A @ W instead of A @ W^T)."""
655
  E, OUT, IN = W.shape
656
  if not transpose:
657
  K, N = IN, OUT
@@ -749,8 +779,6 @@ class GroupedLinearFn(torch.autograd.Function):
749
 
750
 
751
  def moe_align_block_size(expert_ids, num_experts, block_size, device):
752
- """Sort tokens by expert, pad each expert's run up to block_size. No
753
- tokens are dropped."""
754
  counts = torch.bincount(expert_ids, minlength=num_experts)
755
  padded_counts = ((counts + block_size - 1) // block_size) * block_size
756
 
@@ -788,9 +816,9 @@ class MoEFFN(nn.Module):
788
  self.aux_loss_coef = cfg.aux_loss_coef
789
  self.block_m = cfg.moe_block_m
790
 
791
- self.gate_w = nn.Parameter(torch.empty(E, h, d)) # (E, OUT=h, IN=d)
792
  self.up_w = nn.Parameter(torch.empty(E, h, d))
793
- self.down_w = nn.Parameter(torch.empty(E, d, h)) # (E, OUT=d, IN=h)
794
  nn.init.normal_(self.gate_w, std=0.02)
795
  nn.init.normal_(self.up_w, std=0.02)
796
  nn.init.normal_(self.down_w, std=0.02 / math.sqrt(2 * cfg.n_layers))
@@ -823,7 +851,6 @@ class MoEFFN(nn.Module):
823
 
824
  @torch.no_grad()
825
  def update_bias(self):
826
- """COLLECTIVE β€” must be called by every rank on the same steps."""
827
  if dist_ready():
828
  dist.all_reduce(self.expert_usage_ema, op=dist.ReduceOp.AVG)
829
 
@@ -931,7 +958,14 @@ class SmilyaiG1(nn.Module):
931
  self._log_summary()
932
 
933
  def _raw_blocks(self):
934
- return [getattr(b, "_orig_mod", b) for b in self.blocks]
 
 
 
 
 
 
 
935
 
936
  def init_rope(self, device):
937
  c, s = precompute_rope(self.cfg.head_dim, self.cfg.max_len, self.cfg.rope_theta, device)
@@ -960,7 +994,8 @@ class SmilyaiG1(nn.Module):
960
  log.info(f" Total params: {total/1e9:.2f}B")
961
  log.info(f" Active/token (estimate): {active_est/1e9:.2f}B (target ~2B)")
962
  log.info(f" vocab={cfg.vocab_size} | Flash: {HAS_FLASH}")
963
- log.info(f" Muon LR: {cfg.muon_lr} (aspect-ratio scaling β€” FIXED)")
 
964
  log.info("=" * 70)
965
 
966
  def count_params(self): return sum(p.numel() for p in self.parameters())
@@ -1045,8 +1080,51 @@ def apply_fsdp(model: SmilyaiG1, cfg: Config) -> SmilyaiG1:
1045
  fully_shard(model, mp_policy=mp_policy)
1046
  return model
1047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1048
  # ─────────────────────────────────────────────────────────────────────────────
1049
- # MUON β€” DTensor-aware β€” *** SCALE BUG FIXED HERE ***
1050
  # ─────────────────────────────────────────────────────────────────────────────
1051
  def newton_schulz_5(G: torch.Tensor, steps: int = 5) -> torch.Tensor:
1052
  a, b, c = 3.4445, -4.7750, 2.0315
@@ -1063,7 +1141,6 @@ def newton_schulz_5(G: torch.Tensor, steps: int = 5) -> torch.Tensor:
1063
 
1064
  @torch.no_grad()
1065
  def stochastic_round_to(dtype: torch.dtype, x_fp32: torch.Tensor) -> torch.Tensor:
1066
- """Unbiased stochastic rounding fp32 -> bf16."""
1067
  if dtype != torch.bfloat16:
1068
  return x_fp32.to(dtype)
1069
  bits = x_fp32.contiguous().view(torch.int32)
@@ -1073,27 +1150,6 @@ def stochastic_round_to(dtype: torch.dtype, x_fp32: torch.Tensor) -> torch.Tenso
1073
 
1074
 
1075
  class Muon(torch.optim.Optimizer):
1076
- """
1077
- Memory: momentum buffer stays SHARDED (same layout as the local gradient
1078
- shard) β€” only the transient Newton-Schulz step gathers a full parameter,
1079
- one at a time, freed immediately after use.
1080
-
1081
- *** SCALE FIX ***
1082
- The Newton-Schulz output `u` is an (approximately) orthogonalized matrix
1083
- β€” its operator norm is ~1 regardless of the gradient's original
1084
- magnitude. The correct Muon update multiplier is the ASPECT RATIO of the
1085
- matrix:
1086
-
1087
- scale = max(1.0, rows / cols) ** 0.5 # ~1.0 for square-ish mats
1088
-
1089
- NOT `sqrt(max(rows, cols))`, which for a d_model=2048 square-ish matrix
1090
- evaluates to sqrt(2048) β‰ˆ 45.25 β€” roughly 45x too large. That bug was
1091
- silently blowing up every Muon-optimized weight (attention, MoE experts,
1092
- router) by ~45x every step, which produces fast-looking early loss drops
1093
- followed by a hard plateau because the true gradient signal gets
1094
- drowned out by oversized noise. muon_lr has been raised in Config to
1095
- compensate for the corrected (much smaller) effective step size.
1096
- """
1097
  def __init__(self, params, lr=0.02, momentum=0.95, wd=0.0):
1098
  super().__init__(list(params), dict(lr=lr, momentum=momentum, wd=wd))
1099
 
@@ -1113,30 +1169,23 @@ class Muon(torch.optim.Optimizer):
1113
  st['buf'] = torch.zeros_like(grad, dtype=torch.float32)
1114
  buf = st['buf']
1115
 
1116
- # --- step 1: elementwise momentum, on the shard ---
1117
  buf.mul_(mom).add_(grad.to(torch.float32))
1118
  gnest = grad.to(torch.float32).add(buf, alpha=mom)
1119
 
1120
- # --- step 2: gather only what NS actually needs ---
1121
  if is_dtensor:
1122
  full = gnest.full_tensor()
1123
  else:
1124
  full = gnest
1125
 
1126
- # --- step 3: orthogonalize + CORRECT aspect-ratio scale ---
1127
  if full.ndim in (2, 3):
1128
  u = newton_schulz_5(full)
1129
  rows, cols = full.shape[-2], full.shape[-1]
1130
- # *** FIX: was `sqrt(max(rows, cols))` β€” ~45x too large
1131
- # for d_model=2048 matrices. Correct Muon scale is the
1132
- # matrix aspect ratio, ~1.0 for square-ish weights. ***
1133
  scale = max(1.0, rows / cols) ** 0.5
1134
  update = u.to(torch.float32) * (lr * 0.2 * scale)
1135
  else:
1136
  update = full * lr
1137
  del full
1138
 
1139
- # --- steps 4+5: back to shard-local space, then round ---
1140
  if is_dtensor:
1141
  upd_local = distribute_tensor(
1142
  update, p.device_mesh, p.placements
@@ -1161,13 +1210,12 @@ def build_optimizers(model: SmilyaiG1, cfg: Config, is_master: bool):
1161
  adamw_p.append(p)
1162
 
1163
  muon_opt = Muon(muon_p, lr=cfg.muon_lr, momentum=cfg.muon_mom, wd=cfg.wd)
1164
-
1165
  groups = [{'params': adamw_p, 'lr': cfg.adamw_lr}]
1166
 
1167
  if dist_ready():
1168
  adamw_opt = torch.optim.AdamW(groups, betas=(cfg.beta1, cfg.beta2),
1169
  weight_decay=cfg.wd, foreach=True)
1170
- if is_master: log.info("[optim] Muon (gather-for-NS, FIXED scale) + foreach AdamW (DTensor-safe)")
1171
  elif HAS_BNB:
1172
  adamw_opt = bnb.optim.AdamW8bit(groups, betas=(cfg.beta1, cfg.beta2), weight_decay=cfg.wd)
1173
  if is_master: log.info("[optim] Muon (FIXED) + 8-bit AdamW (single GPU)")
@@ -1223,10 +1271,60 @@ def _resolve_eos(tok) -> int:
1223
  return 0
1224
 
1225
 
1226
- def _open_source_stream(repo_id: str, split: str, shard_index: int, num_shards: int):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1227
  ds = load_dataset(repo_id, split=split, streaming=True)
1228
  if num_shards > 1:
1229
  ds = ds.shard(num_shards=num_shards, index=shard_index)
 
 
 
 
 
1230
  return ds
1231
 
1232
 
@@ -1257,27 +1355,47 @@ class LiveStreamingDataset:
1257
  for t in self._workers:
1258
  t.start()
1259
  log.info(f"[stream] rank={rank}/{world_size}: {self.n_workers} tokenizer threads "
1260
- f"({self.total_shards} global shards) | {len(cfg.dataset_sources)} sources")
 
1261
 
1262
  def _fetch_loop(self, worker_id: int):
1263
  shard_index = self.rank * self.n_workers + worker_id
 
 
 
1264
  try:
1265
  streams = []
 
1266
  for repo_id, split, text_field, w in self.cfg.dataset_sources:
1267
  try:
1268
- streams.append([_open_source_stream(repo_id, split, shard_index, self.total_shards),
1269
- text_field, repo_id, split, float(w)])
 
 
 
 
1270
  except Exception as e:
1271
- log.warning(f"[stream] rank={self.rank}.w{worker_id} could not open {repo_id}: {e}")
 
 
 
 
 
 
1272
  if not streams:
1273
- log.error(f"[stream] rank={self.rank}.w{worker_id} no sources opened")
1274
  return
1275
 
1276
- rng = np.random.default_rng(1234 + shard_index)
1277
  iters = [iter(s[0]) for s in streams]
1278
  probs = np.array([s[4] for s in streams], dtype=np.float64)
1279
  probs = probs / probs.sum()
1280
 
 
 
 
 
 
1281
  buf: List[int] = []
1282
  buf_source = "?"
1283
  need = self.max_len * self.batch_size
@@ -1288,17 +1406,22 @@ class LiveStreamingDataset:
1288
  try:
1289
  row = next(iters[idx])
1290
  except StopIteration:
1291
- streams[idx][0] = _open_source_stream(repo_id, split, shard_index, self.total_shards)
 
 
 
1292
  iters[idx] = iter(streams[idx][0])
1293
  continue
1294
  except Exception as e:
1295
- log.warning(f"[stream] rank={self.rank}.w{worker_id} read error on {repo_id}: {e}")
 
1296
  time.sleep(1.0)
1297
  continue
1298
 
1299
- text = row.get(text_field)
 
1300
  if not text:
1301
- continue
1302
 
1303
  try:
1304
  ids = self.tok.encode(text).ids
@@ -1356,7 +1479,7 @@ def build_val_loader(cfg: Config) -> Optional[DataLoader]:
1356
  n_val_seqs = 128
1357
  try:
1358
  for row in ds:
1359
- text = row.get(text_field)
1360
  if not text:
1361
  continue
1362
  ids = tok.encode(text).ids
@@ -1385,18 +1508,11 @@ def build_val_loader(cfg: Config) -> Optional[DataLoader]:
1385
  shuffle=False, num_workers=0, pin_memory=True, drop_last=True)
1386
 
1387
  # ─────────────────────────────────────────────────────────────────────────────
1388
- # CHECKPOINTING β€” *** NOW ASYNC ON RANK 0 ***
1389
  # ─────────────────────────────────────────────────────────────────────────────
1390
  _ckpt_thread: Optional[threading.Thread] = None
1391
 
1392
  def _async_save_and_upload(model_sd, muon_sd, adamw_sd, step, epoch, cfg_dict, loss):
1393
- """
1394
- Runs entirely on a background thread on rank 0. Does NOT block the main
1395
- training loop, and since save_ckpt() already returns immediately after
1396
- kicking this off, it does NOT block any other rank either β€” the state-
1397
- dict gather (the actual collective) already finished before this thread
1398
- was started.
1399
- """
1400
  name = f"g1_s{SESSION_ID:03d}_step{step:07d}"
1401
  local = os.path.join(TEMP_CKPT_DIR, f"{name}.pt")
1402
  try:
@@ -1413,33 +1529,23 @@ def _async_save_and_upload(model_sd, muon_sd, adamw_sd, step, epoch, cfg_dict, l
1413
  except OSError: pass
1414
 
1415
  def save_ckpt(model, muon, adamw, step, epoch, cfg, loss, is_master: bool):
1416
- """
1417
- COLLECTIVE: get_model_state_dict / get_optimizer_state_dict must run on
1418
- EVERY rank (they gather DTensor shards into a full state dict on rank 0).
1419
- That part is fast (NVLINK all-gather). What used to be slow β€” writing
1420
- ~80-100GB to disk and uploading it β€” now happens on a background thread
1421
- AFTER this function has already returned. No rank blocks on I/O.
1422
- """
1423
  global _ckpt_thread
1424
  opts = StateDictOptions(full_state_dict=True, cpu_offload=True)
1425
- model_sd = get_model_state_dict(model, options=opts) # collective, all ranks
1426
  try:
1427
- muon_sd = get_optimizer_state_dict(model, muon, options=opts) # collective
1428
  except Exception as e:
1429
  log.warning(f"[ckpt] could not gather muon state: {e}"); muon_sd = {}
1430
  try:
1431
- adamw_sd = get_optimizer_state_dict(model, adamw, options=opts) # collective
1432
  except Exception as e:
1433
  log.warning(f"[ckpt] could not gather adamw state: {e}"); adamw_sd = {}
1434
 
1435
  if not is_master:
1436
- return # non-master ranks are done β€” no I/O, no waiting
1437
 
1438
- # If a previous async checkpoint is still uploading, wait for it here
1439
- # (on rank 0 only, off the collective path β€” cannot deadlock other ranks).
1440
  if _ckpt_thread is not None and _ckpt_thread.is_alive():
1441
- log.warning("[ckpt] previous checkpoint still uploading β€” waiting for it to finish "
1442
- "before starting the next one")
1443
  _ckpt_thread.join()
1444
 
1445
  _ckpt_thread = threading.Thread(
@@ -1449,7 +1555,6 @@ def save_ckpt(model, muon, adamw, step, epoch, cfg, loss, is_master: bool):
1449
  )
1450
  _ckpt_thread.start()
1451
  log.info(f"[ckpt] step={step} state gathered, upload started in background β€” training continues")
1452
- # returns immediately β€” rank 0 does NOT block on disk/network
1453
 
1454
  def _find_latest_ckpt():
1455
  for sid in range(SESSION_ID, 0, -1):
@@ -1464,10 +1569,18 @@ def _find_latest_ckpt():
1464
  return repo, ckpts[-1]
1465
  return None, None
1466
 
1467
- def load_ckpt(model, muon, adamw, device, is_master: bool):
 
 
 
 
 
 
 
1468
  ckpt = None
1469
- meta = torch.zeros(3, dtype=torch.float64, device=device) # [found, step, epoch] + loss
1470
  loss_t = torch.zeros(1, dtype=torch.float64, device=device)
 
1471
 
1472
  if is_master:
1473
  repo, ckpt_name = _find_latest_ckpt()
@@ -1477,12 +1590,31 @@ def load_ckpt(model, muon, adamw, device, is_master: bool):
1477
  try:
1478
  path = hf_hub_download(repo, ckpt_name, cache_dir=TEMP_CKPT_DIR, token=HF_TOKEN)
1479
  ckpt = torch.load(path, map_location="cpu", weights_only=False)
1480
- meta[0] = 1.0
1481
- meta[1] = float(ckpt['step'])
1482
- meta[2] = float(ckpt['epoch'])
1483
- loss_t[0] = float(ckpt['loss'])
1484
- if repo != HF_MODEL_REPO:
1485
- log.info(f"[ckpt] resuming from an EARLIER session's repo: {repo}/{ckpt_name}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1486
  except Exception as e:
1487
  log.error("=" * 66)
1488
  log.error(f"[ckpt] FOUND {repo}/{ckpt_name} BUT COULD NOT LOAD IT: {e}")
@@ -1493,6 +1625,13 @@ def load_ckpt(model, muon, adamw, device, is_master: bool):
1493
  if dist_ready():
1494
  dist.broadcast(meta, src=0)
1495
  dist.broadcast(loss_t, src=0)
 
 
 
 
 
 
 
1496
 
1497
  if meta[0].item() < 0.5:
1498
  return 0, 0, float('inf')
@@ -1516,14 +1655,12 @@ def load_ckpt(model, muon, adamw, device, is_master: bool):
1516
 
1517
  step, epoch, loss = int(meta[1].item()), int(meta[2].item()), float(loss_t[0].item())
1518
  if is_master:
1519
- log.info(f"[ckpt] resumed step={step} loss={loss:.4f}")
1520
  del ckpt
1521
  gc.collect()
1522
  return step, epoch, loss
1523
 
1524
  def save_final(model, cfg, step, epoch, loss, is_master: bool):
1525
- """Final save stays SYNCHRONOUS on purpose β€” it's the last thing the
1526
- process does, there's no more training to protect from blocking."""
1527
  opts = StateDictOptions(full_state_dict=True, cpu_offload=True)
1528
  model_sd = get_model_state_dict(model, options=opts)
1529
  if not is_master:
@@ -1578,10 +1715,6 @@ def train():
1578
  torch.cuda.set_device(local_rank)
1579
  device = torch.device("cuda", local_rank)
1580
  if world_size > 1 and not dist_ready():
1581
- # *** FIX: raised NCCL collective timeout from the 10-min default to
1582
- # 60 min as a safety net. This alone would have prevented the crash
1583
- # you hit, but the real fix is the async checkpoint below β€” this is
1584
- # just a backstop for anything else slow we haven't found yet. ***
1585
  dist.init_process_group(
1586
  backend="nccl", init_method="env://", device_id=device,
1587
  timeout=_dt.timedelta(minutes=60),
@@ -1617,20 +1750,11 @@ def train():
1617
 
1618
  model = apply_fp8(model, cfg, is_master)
1619
  model = apply_fsdp(model, cfg)
1620
-
1621
- if cfg.use_compile:
1622
- try:
1623
- for i, block in enumerate(model.blocks):
1624
- model.blocks[i] = torch.compile(block, dynamic=True)
1625
- log.info(f"[compile] compiled {len(model.blocks)} blocks")
1626
- except Exception as e:
1627
- log.warning(f"[compile] failed, running eager: {e}")
1628
- else:
1629
- if is_master: log.info("[compile] skipped")
1630
 
1631
  muon, adamw = build_optimizers(model, cfg, is_master)
1632
 
1633
- start_step, start_epoch, best_loss = load_ckpt(model, muon, adamw, device, is_master)
1634
  if dist_ready():
1635
  dist.barrier()
1636
 
@@ -1647,8 +1771,8 @@ def train():
1647
  log.info(f" micro_batch={bs}/GPU grad_accum={cfg.grad_accum} "
1648
  f"eff_batch={bs*cfg.grad_accum*world_size} max_len={cfg.max_len}")
1649
  log.info(f" {cfg.tokens_per_step(bs, world_size)/1e6:.1f}M tok/step | "
1650
- f"{MAX_HOURS}h budget | streaming=True")
1651
- log.info(f" Muon LR={cfg.muon_lr} (FIXED aspect-ratio scale)")
1652
  log.info("=" * 70)
1653
 
1654
  step, epoch = start_step, start_epoch
@@ -1769,10 +1893,6 @@ def train():
1769
  if dist_ready():
1770
  dist.barrier()
1771
 
1772
- # ── checkpoint: gate decided by rank 0, broadcast; SAVE IS NOW ASYNC ──
1773
- # No trailing barrier needed anymore β€” save_ckpt() returns as soon as
1774
- # the (fast) state-dict gather finishes; rank 0's disk write + HF
1775
- # upload happen on a background thread and never block training.
1776
  local_due = (step % cfg.ckpt_every == 0) or ((time.time() - last_ckpt) > 1800)
1777
  if broadcast_flag(local_due if is_master else False, device):
1778
  save_ckpt(model, muon, adamw, step, epoch, cfg,
@@ -1786,8 +1906,6 @@ def train():
1786
  log.info(f"[rank {rank}] DONE training loop")
1787
  stream.close()
1788
 
1789
- # Make sure any in-flight async checkpoint finishes before final save,
1790
- # so we don't have two big uploads racing at process exit.
1791
  if is_master and _ckpt_thread is not None and _ckpt_thread.is_alive():
1792
  log.info("[ckpt] waiting for final in-flight checkpoint upload to finish…")
1793
  _ckpt_thread.join()
 
8
  # "datasets>=2.19",
9
  # "tokenizers>=0.20",
10
  # "bitsandbytes",
11
+ # "torchao"
12
  # ]
13
  # ///
14
 
 
16
  Smilyai-G1 : Fast Sparse General-Assistant Transformer β€” FSDP2 EDITION (8xH200)
17
  ~20B total params | ~2B active per token
18
 
19
+ FIXED EDITION v3. Changes in this pass on top of v2:
20
+
21
+ 4. STACK-V3 SILENT DATA LOSS (critical): HuggingFaceCode/stack-v3-train has
22
+ ONE ROW PER REPOSITORY, with actual code nested under row["files"][i]
23
+ ["content"] β€” NOT under a top-level "content" field. The old code did
24
+ `row.get("content")`, which is None on every row of this dataset, so
25
+ 100% of stack-v3 rows were silently dropped for the entire run. Combined
26
+ with `if not text: continue`, this meant zero code tokens were ever fed
27
+ to the model despite stack-v3 being configured for 20% of the sampling
28
+ weight. Fixed with a dataset-aware _extract_text() that walks files[],
29
+ filters by language and size, and joins them into one training string.
30
+
31
+ 5. STREAMING DATASETS DO NOT SHUFFLE BY DEFAULT. `.shard()` just assigns
32
+ shard FILES to workers; rows within a shard are read in stored order.
33
+ Since stream position is never checkpointed, every session restart
34
+ re-reads the same opening rows of the same shard files before reaching
35
+ new content. Added `.shuffle(buffer_size=..., seed=session-dependent)`
36
+ to each opened stream so different sessions see different orderings β€”
37
+ this reduces (does not eliminate) repeat exposure across restarts.
38
+
39
+ 6. torch.compile WIRED IN: compiled per-block (after fully_shard, which is
40
+ the FSDP2-recommended order), dynamic=True to tolerate the MoE routing
41
+ dispatch's data-dependent shapes, dynamo cache size raised so the many
42
+ distinct (padded_total, expert-count) shape combinations don't blow the
43
+ recompile limit, and wrapped in try/except so a compile failure falls
44
+ back to eager instead of crashing a 6-day run.
45
+
46
+ 7. RESUME CONFIG-MISMATCH GUARD: on load, the checkpoint's saved config is
47
+ compared against the live Config() for architecture-critical fields
48
+ (d_model, n_layers, n_heads, n_kv_heads, n_experts, vocab_size). A
49
+ mismatch is fatal-loud instead of silently corrupting a load β€” dataset
50
+ mix changes are fine and expected across sessions, architecture changes
51
+ are not resumable.
52
 
53
  The load-bearing invariant of this file remains:
54
 
 
56
 
57
  RUN:
58
  export HF_TOKEN=your_hf_token_here
59
+ export G1_SESSION_ID=3
60
+ export MAX_TRAINING_HOURS=144
61
  torchrun --nproc_per_node=8 train_g1_fsdp.py
62
  """
63
 
 
124
  torch.backends.cuda.enable_flash_sdp(True)
125
  torch.backends.cuda.enable_mem_efficient_sdp(True)
126
 
127
+ # ── torch.compile / dynamo tuning ───────────────────────────────────────────
128
+ # MoE routing produces data-dependent shapes (total_padded varies with token
129
+ # distribution across experts each step). Automatic dynamic shapes will
130
+ # eventually stabilize these into symbolic dims, but only if we don't hit the
131
+ # recompile cache limit first. Raised well above default; suppress_errors so
132
+ # a rare compile edge case degrades to eager for that call instead of killing
133
+ # a 6-day unattended run.
134
+ try:
135
+ import torch._dynamo
136
+ torch._dynamo.config.cache_size_limit = 256
137
+ torch._dynamo.config.suppress_errors = True
138
+ torch._dynamo.config.capture_scalar_outputs = True
139
+ except Exception:
140
+ pass
141
+
142
  logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(message)s', datefmt='%H:%M:%S')
143
  log = logging.getLogger("smilyai-g1-fsdp")
144
  log.info(f"[env] flash_attn={HAS_FLASH} | bnb={HAS_BNB}")
 
147
  # HF SETUP
148
  # ─────────────────────────────────────────────────────────────────────────────
149
  HF_TOKEN = os.environ.get("HF_TOKEN", "")
150
+ SESSION_ID = int(os.environ.get("G1_SESSION_ID", "1"))
151
+ REPO_PREFIX = "hugging-science/Smilyai-G1-20B-session-"
152
  HF_MODEL_REPO = f"{REPO_PREFIX}{SESSION_ID:03d}"
153
 
154
  if not HF_TOKEN:
 
166
  os.makedirs(LOCAL_CACHE, exist_ok=True)
167
  os.makedirs(TEMP_CKPT_DIR, exist_ok=True)
168
 
169
+ MAX_HOURS = float(os.environ.get("MAX_TRAINING_HOURS", "24.0"))
170
  START_TIME = time.time()
171
  def elapsed_h(): return (time.time() - START_TIME) / 3600
172
  def remaining_h(): return MAX_HOURS - elapsed_h()
 
269
 
270
  @torch.no_grad()
271
  def make_sample(model, prompt="def fibonacci(n):", max_new=48, temp=0.8, top_p=0.95):
 
 
 
 
 
 
272
  try:
273
  tok = _get_tokenizer()
274
  if tok is None: return None
 
281
  log.warning(f"[sample] tokenizer error: {e}"); return None
282
 
283
  gen = torch.Generator(device=device)
284
+ gen.manual_seed(1234)
285
 
286
  was_training = model.training
287
  model.eval()
 
305
  return None
306
 
307
  def record_sample(model, step, is_master: bool):
 
308
  txt = make_sample(model)
309
  if not is_master:
310
  return
 
369
  n_shared_experts: int = 1
370
  aux_loss_coef: float = 0.01
371
  bias_update_rate: float = 0.001
372
+ bias_update_every: int = 10
373
  bias_cap: float = 2.0
374
  bias_decay: float = 0.0005
375
  usage_ema_decay: float = 0.99
 
377
 
378
  tie_embeddings: bool = True
379
 
 
 
380
  muon_lr: float = 0.02
381
  muon_min_lr: float = 0.002
382
  muon_mom: float = 0.95
 
401
  dpo_every: int = 500
402
  dpo_beta: float= 0.1
403
 
404
+ # ── FIX #4: repo name was already correct β€” the bug was the text field
405
+ # assumption, not the name. stack-v3-train stores code nested under
406
+ # row["files"][i]["content"], handled by _extract_text() below. The
407
+ # "content" placeholder here is now just documentation of what the
408
+ # extractor looks for at the leaf level.
409
  dataset_sources: tuple = (
410
  ("HuggingFaceFW/fineweb-edu", "train", "text", 200_000_000_000),
411
  ("HuggingFaceCode/stack-v3-train", "train", "content", 100_000_000_000),
 
416
  )
417
  tokenizer_repo: str = "Smilyai-labs/Smilyai-U1-B-Tokenizer"
418
  tokenizer_workers: int = 8
419
+ prefetch_shards: int = 20 # raised from 6 β€” more buffer against network hiccups
420
+
421
+ # ── FIX #5: shuffle buffer to reduce restart-repeat exposure ────────────
422
+ shuffle_buffer: int = 10_000
423
 
424
+ # ── FIX #6: compile now on by default, tuned for MoE's dynamic shapes ──
425
+ use_compile: bool = True
426
  use_fp8: bool = False
427
 
428
  @property
 
431
  def head_dim(self): return self.d_model // self.n_heads
432
  def tokens_per_step(self, bs, world_size=1): return bs * self.grad_accum * self.max_len * world_size
433
 
434
+ def arch_fingerprint(self) -> dict:
435
+ """Fields that MUST match across a checkpoint resume. Dataset mix,
436
+ LR schedule, batch size etc. are all safe to change between sessions
437
+ β€” these are not."""
438
+ return {
439
+ "vocab_size": self.vocab_size, "d_model": self.d_model,
440
+ "n_layers": self.n_layers, "n_heads": self.n_heads,
441
+ "n_kv_heads": self.n_kv_heads, "n_experts": self.n_experts,
442
+ "top_k": self.top_k, "expert_hidden_mult": self.expert_hidden_mult,
443
+ "shared_hidden_mult": self.shared_hidden_mult,
444
+ "tie_embeddings": self.tie_embeddings,
445
+ }
446
+
447
  # ─────────────────────────────────────────────────────────────────────────────
448
  # DISTRIBUTED HELPERS
449
  # ─────────────────────────────────────────────────────────────────────────────
 
458
  return t.item()
459
 
460
  def broadcast_flag(value: bool, device: torch.device) -> bool:
 
 
461
  flag = torch.tensor(int(bool(value)), dtype=torch.int32, device=device)
462
  if dist_ready():
463
  dist.broadcast(flag, src=0)
464
  return bool(flag.item())
465
 
466
  def all_ok(ok: bool, device: torch.device) -> bool:
 
 
467
  t = torch.tensor(int(bool(ok)), dtype=torch.int32, device=device)
468
  if dist_ready():
469
  dist.all_reduce(t, op=dist.ReduceOp.MIN)
 
582
  return freqs.cos(), freqs.sin()
583
 
584
  def apply_rope(x, cos, sin):
 
585
  dt = x.dtype
586
  L = x.shape[1]; h = x.shape[-1] // 2
587
  c = cos[:L].unsqueeze(0).unsqueeze(2); s = sin[:L].unsqueeze(0).unsqueeze(2)
 
682
 
683
 
684
  def _grouped_linear_raw(A, W, block_expert, M_padded, transpose, BM):
 
 
685
  E, OUT, IN = W.shape
686
  if not transpose:
687
  K, N = IN, OUT
 
779
 
780
 
781
  def moe_align_block_size(expert_ids, num_experts, block_size, device):
 
 
782
  counts = torch.bincount(expert_ids, minlength=num_experts)
783
  padded_counts = ((counts + block_size - 1) // block_size) * block_size
784
 
 
816
  self.aux_loss_coef = cfg.aux_loss_coef
817
  self.block_m = cfg.moe_block_m
818
 
819
+ self.gate_w = nn.Parameter(torch.empty(E, h, d))
820
  self.up_w = nn.Parameter(torch.empty(E, h, d))
821
+ self.down_w = nn.Parameter(torch.empty(E, d, h))
822
  nn.init.normal_(self.gate_w, std=0.02)
823
  nn.init.normal_(self.up_w, std=0.02)
824
  nn.init.normal_(self.down_w, std=0.02 / math.sqrt(2 * cfg.n_layers))
 
851
 
852
  @torch.no_grad()
853
  def update_bias(self):
 
854
  if dist_ready():
855
  dist.all_reduce(self.expert_usage_ema, op=dist.ReduceOp.AVG)
856
 
 
958
  self._log_summary()
959
 
960
  def _raw_blocks(self):
961
+ """Unwraps BOTH FSDP2 wrapping AND torch.compile's OptimizedModule
962
+ wrapping, so .ffn / .attn access always works regardless of which
963
+ wrappers are active."""
964
+ raw = []
965
+ for b in self.blocks:
966
+ m = getattr(b, "_orig_mod", b) # unwrap compile
967
+ raw.append(m)
968
+ return raw
969
 
970
  def init_rope(self, device):
971
  c, s = precompute_rope(self.cfg.head_dim, self.cfg.max_len, self.cfg.rope_theta, device)
 
994
  log.info(f" Total params: {total/1e9:.2f}B")
995
  log.info(f" Active/token (estimate): {active_est/1e9:.2f}B (target ~2B)")
996
  log.info(f" vocab={cfg.vocab_size} | Flash: {HAS_FLASH}")
997
+ log.info(f" Muon LR: {cfg.muon_lr} (aspect-ratio scaling)")
998
+ log.info(f" Compile: {cfg.use_compile}")
999
  log.info("=" * 70)
1000
 
1001
  def count_params(self): return sum(p.numel() for p in self.parameters())
 
1080
  fully_shard(model, mp_policy=mp_policy)
1081
  return model
1082
 
1083
+ def apply_compile(model: SmilyaiG1, cfg: Config, is_master: bool) -> SmilyaiG1:
1084
+ """
1085
+ *** FIX #6 ***
1086
+ Must run AFTER apply_fsdp β€” FSDP2's recommended composition order is
1087
+ shard-then-compile, applied per transformer block (not the whole model),
1088
+ because compiling the root model would try to trace across FSDP's
1089
+ all-gather/reduce-scatter boundaries.
1090
+
1091
+ dynamic=True because the MoE grouped-GEMM dispatch produces a different
1092
+ `total_padded` token count every step (depends on how tokens route to
1093
+ experts) β€” without this, every step with a new shape would trigger a
1094
+ full recompile. PyTorch's automatic dynamic shapes will still need a
1095
+ couple of steps to stabilize into symbolic dims; expect the first
1096
+ 20-50 steps after enabling compile to be slower (recompiling), then
1097
+ faster than eager once shapes settle.
1098
+
1099
+ Wrapped in try/except per block: a compile failure on one block falls
1100
+ back to eager for that block only, rather than crashing the whole run.
1101
+ The custom Triton autograd Functions (_TritonRMSNormFn, _FusedSwiGLUFn)
1102
+ are already marked @torch.compiler.disable, so compile treats them as
1103
+ opaque black-box calls β€” correct and intentional, no change needed
1104
+ there.
1105
+ """
1106
+ if not cfg.use_compile:
1107
+ if is_master: log.info("[compile] disabled")
1108
+ return model
1109
+ try:
1110
+ compiled = 0
1111
+ for i, block in enumerate(model.blocks):
1112
+ try:
1113
+ model.blocks[i] = torch.compile(block, dynamic=True, mode="max-autotune-no-cudagraphs")
1114
+ compiled += 1
1115
+ except Exception as e:
1116
+ if is_master:
1117
+ log.warning(f"[compile] block {i} failed to compile, staying eager: {e}")
1118
+ if is_master:
1119
+ log.info(f"[compile] compiled {compiled}/{len(model.blocks)} blocks "
1120
+ f"(dynamic=True β€” expect slower first ~50 steps while shapes stabilize)")
1121
+ except Exception as e:
1122
+ if is_master:
1123
+ log.warning(f"[compile] setup failed entirely, running eager: {e}")
1124
+ return model
1125
+
1126
  # ─────────────────────────────────────────────────────────────────────────────
1127
+ # MUON β€” DTensor-aware β€” CORRECT aspect-ratio scale
1128
  # ─────────────────────────────────────────────────────────────────────────────
1129
  def newton_schulz_5(G: torch.Tensor, steps: int = 5) -> torch.Tensor:
1130
  a, b, c = 3.4445, -4.7750, 2.0315
 
1141
 
1142
  @torch.no_grad()
1143
  def stochastic_round_to(dtype: torch.dtype, x_fp32: torch.Tensor) -> torch.Tensor:
 
1144
  if dtype != torch.bfloat16:
1145
  return x_fp32.to(dtype)
1146
  bits = x_fp32.contiguous().view(torch.int32)
 
1150
 
1151
 
1152
  class Muon(torch.optim.Optimizer):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1153
  def __init__(self, params, lr=0.02, momentum=0.95, wd=0.0):
1154
  super().__init__(list(params), dict(lr=lr, momentum=momentum, wd=wd))
1155
 
 
1169
  st['buf'] = torch.zeros_like(grad, dtype=torch.float32)
1170
  buf = st['buf']
1171
 
 
1172
  buf.mul_(mom).add_(grad.to(torch.float32))
1173
  gnest = grad.to(torch.float32).add(buf, alpha=mom)
1174
 
 
1175
  if is_dtensor:
1176
  full = gnest.full_tensor()
1177
  else:
1178
  full = gnest
1179
 
 
1180
  if full.ndim in (2, 3):
1181
  u = newton_schulz_5(full)
1182
  rows, cols = full.shape[-2], full.shape[-1]
 
 
 
1183
  scale = max(1.0, rows / cols) ** 0.5
1184
  update = u.to(torch.float32) * (lr * 0.2 * scale)
1185
  else:
1186
  update = full * lr
1187
  del full
1188
 
 
1189
  if is_dtensor:
1190
  upd_local = distribute_tensor(
1191
  update, p.device_mesh, p.placements
 
1210
  adamw_p.append(p)
1211
 
1212
  muon_opt = Muon(muon_p, lr=cfg.muon_lr, momentum=cfg.muon_mom, wd=cfg.wd)
 
1213
  groups = [{'params': adamw_p, 'lr': cfg.adamw_lr}]
1214
 
1215
  if dist_ready():
1216
  adamw_opt = torch.optim.AdamW(groups, betas=(cfg.beta1, cfg.beta2),
1217
  weight_decay=cfg.wd, foreach=True)
1218
+ if is_master: log.info("[optim] Muon (FIXED scale) + foreach AdamW (DTensor-safe)")
1219
  elif HAS_BNB:
1220
  adamw_opt = bnb.optim.AdamW8bit(groups, betas=(cfg.beta1, cfg.beta2), weight_decay=cfg.wd)
1221
  if is_master: log.info("[optim] Muon (FIXED) + 8-bit AdamW (single GPU)")
 
1271
  return 0
1272
 
1273
 
1274
+ # ── FIX #4: dataset-aware text extraction ────────────────────────────────────
1275
+ _STACK_KEEP_LANGS = {
1276
+ "Python", "JavaScript", "TypeScript", "Java", "C", "C++", "C#",
1277
+ "Go", "Rust", "Ruby", "PHP", "Swift", "Kotlin", "Scala", "Shell",
1278
+ "SQL", "HTML", "CSS", "Markdown", "R", "Julia", "Lua", "Haskell",
1279
+ "Elixir", "Erlang", "Dart", "Zig", "CUDA", "Fortran",
1280
+ }
1281
+ _MIN_CODE_CHARS = 64
1282
+ _MAX_CODE_CHARS = 65536
1283
+
1284
+ def _extract_text(row: dict, text_field: str, repo_id: str) -> Optional[str]:
1285
+ """
1286
+ Universal text extractor.
1287
+ - stack-v3-train: row["files"] is a list of {file_path, language,
1288
+ content, license_type, ...}. There is NO top-level "content" field β€”
1289
+ this was the bug that silently zeroed out all code training data.
1290
+ - everything else: plain row[text_field] string.
1291
+ """
1292
+ if "stack-v3" in repo_id:
1293
+ files = row.get("files")
1294
+ if not files:
1295
+ return None
1296
+ parts = []
1297
+ for f in files:
1298
+ content = f.get("content", "")
1299
+ if not content:
1300
+ continue
1301
+ lang = f.get("language", "")
1302
+ if lang and lang not in _STACK_KEEP_LANGS:
1303
+ continue
1304
+ if len(content) < _MIN_CODE_CHARS or len(content) > _MAX_CODE_CHARS:
1305
+ continue
1306
+ fpath = f.get("file_path", "")
1307
+ parts.append(f"# {fpath}\n{content}")
1308
+ if not parts:
1309
+ return None
1310
+ return "\n\n".join(parts)
1311
+
1312
+ text = row.get(text_field)
1313
+ if not text or not isinstance(text, str):
1314
+ return None
1315
+ return text
1316
+
1317
+
1318
+ def _open_source_stream(repo_id: str, split: str, shard_index: int, num_shards: int,
1319
+ shuffle_buffer: int = 0, shuffle_seed: int = 0):
1320
  ds = load_dataset(repo_id, split=split, streaming=True)
1321
  if num_shards > 1:
1322
  ds = ds.shard(num_shards=num_shards, index=shard_index)
1323
+ # FIX #5: session-seeded shuffle buffer β€” reduces (does not eliminate)
1324
+ # repeat exposure to the same opening rows every time a session restarts,
1325
+ # since streaming datasets have no persisted read position.
1326
+ if shuffle_buffer > 0:
1327
+ ds = ds.shuffle(buffer_size=shuffle_buffer, seed=shuffle_seed)
1328
  return ds
1329
 
1330
 
 
1355
  for t in self._workers:
1356
  t.start()
1357
  log.info(f"[stream] rank={rank}/{world_size}: {self.n_workers} tokenizer threads "
1358
+ f"({self.total_shards} global shards) | {len(cfg.dataset_sources)} sources | "
1359
+ f"shuffle_buffer={cfg.shuffle_buffer} session={SESSION_ID}")
1360
 
1361
  def _fetch_loop(self, worker_id: int):
1362
  shard_index = self.rank * self.n_workers + worker_id
1363
+ # session-dependent seed: different sessions get different shuffle
1364
+ # orderings out of the buffer window, reducing exact repeat-on-resume
1365
+ shuffle_seed = 1234 + shard_index + SESSION_ID * 97
1366
  try:
1367
  streams = []
1368
+ failed = []
1369
  for repo_id, split, text_field, w in self.cfg.dataset_sources:
1370
  try:
1371
+ streams.append([
1372
+ _open_source_stream(repo_id, split, shard_index, self.total_shards,
1373
+ shuffle_buffer=self.cfg.shuffle_buffer,
1374
+ shuffle_seed=shuffle_seed),
1375
+ text_field, repo_id, split, float(w)
1376
+ ])
1377
  except Exception as e:
1378
+ log.error(f"[stream] rank={self.rank}.w{worker_id} "
1379
+ f"FAILED TO OPEN {repo_id}: {e}")
1380
+ failed.append(repo_id)
1381
+
1382
+ if failed:
1383
+ log.error(f"[stream] rank={self.rank}.w{worker_id} "
1384
+ f"MISSING SOURCES (0% contribution, check repo name/access!): {failed}")
1385
  if not streams:
1386
+ log.error(f"[stream] rank={self.rank}.w{worker_id} NO SOURCES OPENED β€” worker is dead")
1387
  return
1388
 
1389
+ rng = np.random.default_rng(shuffle_seed)
1390
  iters = [iter(s[0]) for s in streams]
1391
  probs = np.array([s[4] for s in streams], dtype=np.float64)
1392
  probs = probs / probs.sum()
1393
 
1394
+ if worker_id == 0 and self.rank == 0:
1395
+ log.info("[stream] actual sampling weights after open:")
1396
+ for s, p in zip(streams, probs):
1397
+ log.info(f" {s[2]:55s} {p*100:5.1f}%")
1398
+
1399
  buf: List[int] = []
1400
  buf_source = "?"
1401
  need = self.max_len * self.batch_size
 
1406
  try:
1407
  row = next(iters[idx])
1408
  except StopIteration:
1409
+ streams[idx][0] = _open_source_stream(
1410
+ repo_id, split, shard_index, self.total_shards,
1411
+ shuffle_buffer=self.cfg.shuffle_buffer,
1412
+ shuffle_seed=shuffle_seed + 1) # vary seed on re-open
1413
  iters[idx] = iter(streams[idx][0])
1414
  continue
1415
  except Exception as e:
1416
+ log.warning(f"[stream] rank={self.rank}.w{worker_id} "
1417
+ f"read error on {repo_id}: {e}")
1418
  time.sleep(1.0)
1419
  continue
1420
 
1421
+ # FIX #4: dataset-aware extraction, handles stack-v3's files[]
1422
+ text = _extract_text(row, text_field, repo_id)
1423
  if not text:
1424
+ continue # fast β€” no I/O, no sleep, just next row
1425
 
1426
  try:
1427
  ids = self.tok.encode(text).ids
 
1479
  n_val_seqs = 128
1480
  try:
1481
  for row in ds:
1482
+ text = _extract_text(row, text_field, repo_id)
1483
  if not text:
1484
  continue
1485
  ids = tok.encode(text).ids
 
1508
  shuffle=False, num_workers=0, pin_memory=True, drop_last=True)
1509
 
1510
  # ─────────────────────────────────────────────────────────────────────────────
1511
+ # CHECKPOINTING β€” async on rank 0
1512
  # ─────────────────────────────────────────────────────────────────────────────
1513
  _ckpt_thread: Optional[threading.Thread] = None
1514
 
1515
  def _async_save_and_upload(model_sd, muon_sd, adamw_sd, step, epoch, cfg_dict, loss):
 
 
 
 
 
 
 
1516
  name = f"g1_s{SESSION_ID:03d}_step{step:07d}"
1517
  local = os.path.join(TEMP_CKPT_DIR, f"{name}.pt")
1518
  try:
 
1529
  except OSError: pass
1530
 
1531
  def save_ckpt(model, muon, adamw, step, epoch, cfg, loss, is_master: bool):
 
 
 
 
 
 
 
1532
  global _ckpt_thread
1533
  opts = StateDictOptions(full_state_dict=True, cpu_offload=True)
1534
+ model_sd = get_model_state_dict(model, options=opts)
1535
  try:
1536
+ muon_sd = get_optimizer_state_dict(model, muon, options=opts)
1537
  except Exception as e:
1538
  log.warning(f"[ckpt] could not gather muon state: {e}"); muon_sd = {}
1539
  try:
1540
+ adamw_sd = get_optimizer_state_dict(model, adamw, options=opts)
1541
  except Exception as e:
1542
  log.warning(f"[ckpt] could not gather adamw state: {e}"); adamw_sd = {}
1543
 
1544
  if not is_master:
1545
+ return
1546
 
 
 
1547
  if _ckpt_thread is not None and _ckpt_thread.is_alive():
1548
+ log.warning("[ckpt] previous checkpoint still uploading β€” waiting for it to finish")
 
1549
  _ckpt_thread.join()
1550
 
1551
  _ckpt_thread = threading.Thread(
 
1555
  )
1556
  _ckpt_thread.start()
1557
  log.info(f"[ckpt] step={step} state gathered, upload started in background β€” training continues")
 
1558
 
1559
  def _find_latest_ckpt():
1560
  for sid in range(SESSION_ID, 0, -1):
 
1569
  return repo, ckpts[-1]
1570
  return None, None
1571
 
1572
+ def load_ckpt(model, muon, adamw, cfg, device, is_master: bool):
1573
+ """
1574
+ FIX #7: architecture fingerprint check. Dataset mix / LR / batch size are
1575
+ all safe to change between sessions β€” but if d_model, n_layers, n_heads,
1576
+ n_experts etc. don't match the checkpoint, loading will either crash with
1577
+ a confusing shape-mismatch deep inside FSDP, or worse, partially succeed
1578
+ and silently corrupt the model. Caught loudly here instead.
1579
+ """
1580
  ckpt = None
1581
+ meta = torch.zeros(3, dtype=torch.float64, device=device)
1582
  loss_t = torch.zeros(1, dtype=torch.float64, device=device)
1583
+ mismatch_flag = torch.zeros(1, dtype=torch.int32, device=device)
1584
 
1585
  if is_master:
1586
  repo, ckpt_name = _find_latest_ckpt()
 
1590
  try:
1591
  path = hf_hub_download(repo, ckpt_name, cache_dir=TEMP_CKPT_DIR, token=HF_TOKEN)
1592
  ckpt = torch.load(path, map_location="cpu", weights_only=False)
1593
+
1594
+ # ── architecture fingerprint check ──────────────────────────
1595
+ saved_cfg = ckpt.get('config', {})
1596
+ live_fp = cfg.arch_fingerprint()
1597
+ mismatches = []
1598
+ for k, v in live_fp.items():
1599
+ if k in saved_cfg and saved_cfg[k] != v:
1600
+ mismatches.append(f"{k}: ckpt={saved_cfg[k]} vs live={v}")
1601
+ if mismatches:
1602
+ log.error("=" * 70)
1603
+ log.error("[ckpt] ARCHITECTURE MISMATCH β€” cannot safely resume!")
1604
+ for m in mismatches:
1605
+ log.error(f" {m}")
1606
+ log.error("[ckpt] refusing to load. Fix Config to match the "
1607
+ "checkpoint, or start a new model from scratch.")
1608
+ log.error("=" * 70)
1609
+ mismatch_flag[0] = 1
1610
+ ckpt = None
1611
+ else:
1612
+ meta[0] = 1.0
1613
+ meta[1] = float(ckpt['step'])
1614
+ meta[2] = float(ckpt['epoch'])
1615
+ loss_t[0] = float(ckpt['loss'])
1616
+ if repo != HF_MODEL_REPO:
1617
+ log.info(f"[ckpt] resuming from an EARLIER session's repo: {repo}/{ckpt_name}")
1618
  except Exception as e:
1619
  log.error("=" * 66)
1620
  log.error(f"[ckpt] FOUND {repo}/{ckpt_name} BUT COULD NOT LOAD IT: {e}")
 
1625
  if dist_ready():
1626
  dist.broadcast(meta, src=0)
1627
  dist.broadcast(loss_t, src=0)
1628
+ dist.broadcast(mismatch_flag, src=0)
1629
+
1630
+ if mismatch_flag.item() > 0:
1631
+ raise RuntimeError(
1632
+ "Checkpoint architecture mismatch β€” see rank 0 log above for details. "
1633
+ "Refusing to resume with corrupted/incompatible weights."
1634
+ )
1635
 
1636
  if meta[0].item() < 0.5:
1637
  return 0, 0, float('inf')
 
1655
 
1656
  step, epoch, loss = int(meta[1].item()), int(meta[2].item()), float(loss_t[0].item())
1657
  if is_master:
1658
+ log.info(f"[ckpt] resumed step={step} loss={loss:.4f} (architecture verified βœ…)")
1659
  del ckpt
1660
  gc.collect()
1661
  return step, epoch, loss
1662
 
1663
  def save_final(model, cfg, step, epoch, loss, is_master: bool):
 
 
1664
  opts = StateDictOptions(full_state_dict=True, cpu_offload=True)
1665
  model_sd = get_model_state_dict(model, options=opts)
1666
  if not is_master:
 
1715
  torch.cuda.set_device(local_rank)
1716
  device = torch.device("cuda", local_rank)
1717
  if world_size > 1 and not dist_ready():
 
 
 
 
1718
  dist.init_process_group(
1719
  backend="nccl", init_method="env://", device_id=device,
1720
  timeout=_dt.timedelta(minutes=60),
 
1750
 
1751
  model = apply_fp8(model, cfg, is_master)
1752
  model = apply_fsdp(model, cfg)
1753
+ model = apply_compile(model, cfg, is_master) # FIX #6 β€” after FSDP, per-block, dynamic
 
 
 
 
 
 
 
 
 
1754
 
1755
  muon, adamw = build_optimizers(model, cfg, is_master)
1756
 
1757
+ start_step, start_epoch, best_loss = load_ckpt(model, muon, adamw, cfg, device, is_master)
1758
  if dist_ready():
1759
  dist.barrier()
1760
 
 
1771
  log.info(f" micro_batch={bs}/GPU grad_accum={cfg.grad_accum} "
1772
  f"eff_batch={bs*cfg.grad_accum*world_size} max_len={cfg.max_len}")
1773
  log.info(f" {cfg.tokens_per_step(bs, world_size)/1e6:.1f}M tok/step | "
1774
+ f"{MAX_HOURS}h budget | streaming=True | compile={cfg.use_compile}")
1775
+ log.info(f" Muon LR={cfg.muon_lr} | resumed at step={start_step}")
1776
  log.info("=" * 70)
1777
 
1778
  step, epoch = start_step, start_epoch
 
1893
  if dist_ready():
1894
  dist.barrier()
1895
 
 
 
 
 
1896
  local_due = (step % cfg.ckpt_every == 0) or ((time.time() - last_ckpt) > 1800)
1897
  if broadcast_flag(local_due if is_master else False, device):
1898
  save_ckpt(model, muon, adamw, step, epoch, cfg,
 
1906
  log.info(f"[rank {rank}] DONE training loop")
1907
  stream.close()
1908
 
 
 
1909
  if is_master and _ckpt_thread is not None and _ckpt_thread.is_alive():
1910
  log.info("[ckpt] waiting for final in-flight checkpoint upload to finish…")
1911
  _ckpt_thread.join()