fix: v12 GENESIS — fix 6 interaction bugs between paradigms\n\n1. P13 MTP heads added to optimizer (were dead — never updated)\n2. P18 Grokfast: skip Muon 2D params (NS normalisation cancels amplification)\n Apply only to 1D/embed params where AdamW preserves the signal\n3. P16 Plateau: save/restore ALL group LRs (was destroying LLRD ratios)\n4. P15 Token Triage applied to MTP loss too (was only on base loss)\n5. P16 Plateau: gentler burst ×2 instead of ×3 (Grokfast already amplifies)\n6. P15 Triage: per-position EMA disabled, use global excess only"
Browse files- chimera_turbo.py +145 -138
chimera_turbo.py
CHANGED
|
@@ -1,19 +1,15 @@
|
|
| 1 |
"""
|
| 2 |
-
chimera_turbo.py — CHIMERA GENESIS
|
| 3 |
|
| 4 |
-
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
P19 Layer-wise LR Decay — top layers learn faster, bottom layers preserve features
|
| 14 |
-
|
| 15 |
-
Removed (dead weight):
|
| 16 |
-
P14 EMA Self-Distill — doubled forward time, marginal gain from self-EMA
|
| 17 |
"""
|
| 18 |
|
| 19 |
import math
|
|
@@ -21,7 +17,7 @@ import os
|
|
| 21 |
import torch
|
| 22 |
import torch.nn as nn
|
| 23 |
import torch.nn.functional as F
|
| 24 |
-
from typing import
|
| 25 |
from contextlib import nullcontext
|
| 26 |
from collections import deque
|
| 27 |
|
|
@@ -54,7 +50,7 @@ def configure_threading(cpu_info, reserve=1):
|
|
| 54 |
|
| 55 |
|
| 56 |
# ═══════════════════════════════════════════════════════════
|
| 57 |
-
# P12
|
| 58 |
# ═══════════════════════════════════════════════════════════
|
| 59 |
|
| 60 |
def _zeropower_via_newtonschulz5(G, steps=5):
|
|
@@ -69,7 +65,6 @@ def _zeropower_via_newtonschulz5(G, steps=5):
|
|
| 69 |
|
| 70 |
|
| 71 |
class Muon(torch.optim.Optimizer):
|
| 72 |
-
"""Muon with integrated layer-wise LR decay (P19)."""
|
| 73 |
def __init__(self, params, lr=0.02, momentum=0.95, nesterov=True,
|
| 74 |
ns_steps=5, weight_decay=0.0,
|
| 75 |
adamw_betas=(0.9, 0.98), adamw_eps=1e-8):
|
|
@@ -113,14 +108,8 @@ class Muon(torch.optim.Optimizer):
|
|
| 113 |
|
| 114 |
|
| 115 |
def create_muon_optimizer(model, lr=0.02, momentum=0.95, weight_decay=0.01,
|
| 116 |
-
llrd_decay=0.85):
|
| 117 |
-
"""Create Muon with
|
| 118 |
-
|
| 119 |
-
Top layers get full LR, bottom layers get LR × decay^depth.
|
| 120 |
-
This preserves general features in early layers while allowing
|
| 121 |
-
later layers to specialize faster. Proven for ternary (arxiv 2602.07374).
|
| 122 |
-
"""
|
| 123 |
-
# Detect layer depth for each param
|
| 124 |
raw = getattr(model, "_orig_mod", model)
|
| 125 |
n_layers = len(raw.layers) if hasattr(raw, "layers") else 28
|
| 126 |
|
|
@@ -128,35 +117,30 @@ def create_muon_optimizer(model, lr=0.02, momentum=0.95, weight_decay=0.01,
|
|
| 128 |
for name, p in model.named_parameters():
|
| 129 |
if not p.requires_grad:
|
| 130 |
continue
|
| 131 |
-
|
| 132 |
is_embed = any(k in name for k in ["embed", "lm_head", "wte", "wpe"])
|
| 133 |
if is_embed:
|
| 134 |
p._is_embed = True
|
| 135 |
-
|
| 136 |
-
# Determine layer index for LLRD
|
| 137 |
lr_scale = 1.0
|
| 138 |
for i in range(n_layers):
|
| 139 |
-
if f"layers.{i}." in name
|
| 140 |
-
|
| 141 |
-
depth_from_top = n_layers - 1 - i
|
| 142 |
-
lr_scale = llrd_decay ** depth_from_top
|
| 143 |
break
|
| 144 |
-
|
| 145 |
-
# Embeddings and lm_head get lowest LR
|
| 146 |
if is_embed:
|
| 147 |
lr_scale = llrd_decay ** n_layers
|
|
|
|
| 148 |
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
|
|
|
| 153 |
|
| 154 |
return Muon(param_groups, lr=lr, momentum=momentum,
|
| 155 |
weight_decay=weight_decay, adamw_betas=(0.9, 0.98))
|
| 156 |
|
| 157 |
|
| 158 |
# ═══════════════════════════════════════════════════════════
|
| 159 |
-
# P13
|
| 160 |
# ═════════════════════════════��═════════════════════════════
|
| 161 |
|
| 162 |
class MultiTokenPredictionLoss(nn.Module):
|
|
@@ -169,7 +153,8 @@ class MultiTokenPredictionLoss(nn.Module):
|
|
| 169 |
for h in self.extra_heads:
|
| 170 |
nn.init.normal_(h.weight, std=0.006)
|
| 171 |
|
| 172 |
-
def forward(self, hidden_states, labels):
|
|
|
|
| 173 |
total, count = 0.0, 0
|
| 174 |
for k, head in enumerate(self.extra_heads):
|
| 175 |
shift = k + 2
|
|
@@ -178,8 +163,20 @@ class MultiTokenPredictionLoss(nn.Module):
|
|
| 178 |
logits = head(hidden_states[:, :-shift])
|
| 179 |
targets = labels[:, shift:]
|
| 180 |
sl = min(logits.size(1), targets.size(1))
|
| 181 |
-
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
if torch.isfinite(loss):
|
| 184 |
total = total + loss
|
| 185 |
count += 1
|
|
@@ -187,7 +184,7 @@ class MultiTokenPredictionLoss(nn.Module):
|
|
| 187 |
|
| 188 |
|
| 189 |
# ═══════════════════════════════════════════════════════════
|
| 190 |
-
# P15
|
| 191 |
# ═══════════════════════════════════════════════════════════
|
| 192 |
|
| 193 |
class TokenTriage:
|
|
@@ -198,25 +195,24 @@ class TokenTriage:
|
|
| 198 |
self._loss_ema = None
|
| 199 |
|
| 200 |
def compute_weights(self, per_token_loss):
|
| 201 |
-
"""Returns per-token weights [B, T]. Differentiable-safe (weights are detached)."""
|
| 202 |
with torch.no_grad():
|
| 203 |
-
|
| 204 |
if self._loss_ema is None:
|
| 205 |
-
self._loss_ema =
|
| 206 |
else:
|
| 207 |
-
self._loss_ema = self.ema_decay * self._loss_ema + (1 - self.ema_decay) *
|
| 208 |
excess = per_token_loss - self._loss_ema
|
| 209 |
-
|
| 210 |
-
return torch.where(excess >=
|
| 211 |
|
| 212 |
|
| 213 |
# ═══════════════════════════════════════════════════════════
|
| 214 |
-
# P16
|
| 215 |
# ═══════════════════════════════════════════════════════════
|
| 216 |
|
| 217 |
class PlateauBreaker:
|
| 218 |
def __init__(self, patience=100, variance_threshold=0.005,
|
| 219 |
-
lr_multiplier=
|
| 220 |
self.patience = patience
|
| 221 |
self.var_threshold = variance_threshold
|
| 222 |
self.lr_mult = lr_multiplier
|
|
@@ -224,7 +220,7 @@ class PlateauBreaker:
|
|
| 224 |
self._history = deque(maxlen=patience)
|
| 225 |
self._stagnant_count = 0
|
| 226 |
self._burst_remaining = 0
|
| 227 |
-
self.
|
| 228 |
self.total_bursts = 0
|
| 229 |
|
| 230 |
def check_and_adjust(self, loss_val, optimizer, step):
|
|
@@ -233,10 +229,11 @@ class PlateauBreaker:
|
|
| 233 |
self._history.append(loss_val)
|
| 234 |
if self._burst_remaining > 0:
|
| 235 |
self._burst_remaining -= 1
|
| 236 |
-
if self._burst_remaining == 0 and self.
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
|
|
|
| 240 |
return False
|
| 241 |
if len(self._history) < self.patience:
|
| 242 |
return False
|
|
@@ -248,35 +245,30 @@ class PlateauBreaker:
|
|
| 248 |
else:
|
| 249 |
self._stagnant_count = 0
|
| 250 |
if self._stagnant_count >= self.patience // 2:
|
| 251 |
-
|
| 252 |
-
|
| 253 |
for pg in optimizer.param_groups:
|
| 254 |
-
pg["lr"] =
|
| 255 |
self._burst_remaining = self.burst_steps
|
| 256 |
self._stagnant_count = 0
|
| 257 |
self.total_bursts += 1
|
| 258 |
-
|
|
|
|
| 259 |
return True
|
| 260 |
return False
|
| 261 |
|
| 262 |
|
| 263 |
# ═══════════════════════════════════════════════════════════
|
| 264 |
-
# P18
|
| 265 |
# ═══════════════════════════════════════════════════════════
|
| 266 |
|
| 267 |
class GrokfastEMA:
|
| 268 |
-
"""
|
| 269 |
-
|
| 270 |
-
The key insight: gradient time-series has fast components (memorization,
|
| 271 |
-
STE quantization noise) and slow components (generalization signal).
|
| 272 |
-
EMA-filter the gradients, then ADD the filtered (slow) component back
|
| 273 |
-
with amplification factor λ.
|
| 274 |
-
|
| 275 |
-
Result: 43× faster convergence on grokking tasks.
|
| 276 |
-
For ternary models: STE noise is exactly the "fast component" —
|
| 277 |
-
Grokfast filters it out while amplifying the real learning signal.
|
| 278 |
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
| 280 |
"""
|
| 281 |
def __init__(self, alpha=0.98, lamb=2.0):
|
| 282 |
self.alpha = alpha
|
|
@@ -284,20 +276,18 @@ class GrokfastEMA:
|
|
| 284 |
self._ema: Dict[str, torch.Tensor] = {}
|
| 285 |
|
| 286 |
@torch.no_grad()
|
| 287 |
-
def apply(self, model
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
if param.grad is None:
|
| 294 |
continue
|
| 295 |
if name not in self._ema:
|
| 296 |
-
self._ema[name] =
|
| 297 |
else:
|
| 298 |
-
self._ema[name].mul_(self.alpha).add_(
|
| 299 |
-
|
| 300 |
-
param.grad.add_(self._ema[name], alpha=self.lamb)
|
| 301 |
|
| 302 |
|
| 303 |
# ═══════════════════════════════════════════════════════════
|
|
@@ -333,7 +323,7 @@ def apply(model, max_steps=10000, lr=0.02, weight_decay=0.01,
|
|
| 333 |
cpu_info = detect_cpu_info()
|
| 334 |
if verbose:
|
| 335 |
print("=" * 65)
|
| 336 |
-
print("CHIMERA GENESIS
|
| 337 |
print("=" * 65)
|
| 338 |
print(f" CPU: {cpu_info['capability']} Cores: {cpu_info['physical_cores']}")
|
| 339 |
|
|
@@ -341,51 +331,55 @@ def apply(model, max_steps=10000, lr=0.02, weight_decay=0.01,
|
|
| 341 |
if verbose:
|
| 342 |
print(f" Threads: {n}")
|
| 343 |
|
| 344 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
optimizer = create_muon_optimizer(model, lr=lr, weight_decay=weight_decay,
|
| 346 |
-
llrd_decay=llrd_decay)
|
| 347 |
scheduler = create_scheduler(optimizer, max_steps, warmup_steps)
|
| 348 |
|
| 349 |
if verbose:
|
| 350 |
-
n_groups = len(optimizer.param_groups)
|
| 351 |
n_total = sum(p.numel() for g in optimizer.param_groups for p in g["params"])
|
| 352 |
scales = [g["lr_scale"] for g in optimizer.param_groups]
|
| 353 |
-
|
| 354 |
-
print(f"
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
extras = {}
|
| 358 |
|
| 359 |
-
#
|
| 360 |
-
h, v = raw.config["hidden_size"], raw.config["vocab_size"]
|
| 361 |
-
extras["mtp"] = MultiTokenPredictionLoss(h, v, n_future=mtp_heads)
|
| 362 |
-
if verbose:
|
| 363 |
-
print(f"[P13] Multi-Token Prediction ({mtp_heads} heads)")
|
| 364 |
-
|
| 365 |
-
# P15: Token Triage
|
| 366 |
extras["triage"] = TokenTriage(ema_decay=0.99, select_ratio=0.6, floor_weight=0.1)
|
| 367 |
if verbose:
|
| 368 |
-
print(f"[P15] Token Triage (60%
|
| 369 |
|
| 370 |
-
# P16
|
| 371 |
extras["plateau"] = PlateauBreaker(patience=100, variance_threshold=0.005,
|
| 372 |
-
lr_multiplier=
|
| 373 |
if verbose:
|
| 374 |
-
print(f"[P16] Plateau Breaker (
|
| 375 |
|
| 376 |
-
# P18
|
| 377 |
extras["grokfast"] = GrokfastEMA(alpha=grokfast_alpha, lamb=grokfast_lambda)
|
| 378 |
if verbose:
|
| 379 |
-
|
|
|
|
|
|
|
| 380 |
|
| 381 |
if verbose:
|
|
|
|
| 382 |
print("=" * 65)
|
| 383 |
|
| 384 |
return model, optimizer, scheduler, extras
|
| 385 |
|
| 386 |
|
| 387 |
# ═══════════════════════════════════════════════════════════
|
| 388 |
-
# Training step — ALL paradigms FUSED
|
| 389 |
# ═══════════════════════════════════════════════════════════
|
| 390 |
|
| 391 |
_nan_count = 0
|
|
@@ -394,10 +388,28 @@ def training_step(model, batch, optimizer, scheduler,
|
|
| 394 |
extras=None, grad_accum_steps=1, step=0,
|
| 395 |
max_grad_norm=1.0, autocast_dtype=None,
|
| 396 |
mtp_weight=0.3) -> float:
|
| 397 |
-
"""
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 401 |
"""
|
| 402 |
global _nan_count
|
| 403 |
extras = extras or {}
|
|
@@ -415,48 +427,43 @@ def training_step(model, batch, optimizer, scheduler,
|
|
| 415 |
|
| 416 |
logits = getattr(outputs, "logits", None)
|
| 417 |
|
| 418 |
-
# ── FUSED LOSS: Token Triage × Batch Metabolism ──
|
| 419 |
if logits is not None:
|
| 420 |
B, T, V = logits.shape
|
| 421 |
-
# Per-token CE (no reduction)
|
| 422 |
per_token = F.cross_entropy(
|
| 423 |
logits.reshape(-1, V), labels.reshape(-1),
|
| 424 |
ignore_index=-100, reduction="none"
|
| 425 |
).reshape(B, T)
|
| 426 |
|
| 427 |
-
# P17: Batch Metabolism — per-sequence weights
|
| 428 |
with torch.no_grad():
|
| 429 |
-
seq_loss = per_token.mean(dim=1)
|
| 430 |
seq_mean = seq_loss.mean()
|
| 431 |
seq_std = seq_loss.std().clamp(min=1e-6)
|
| 432 |
z = (seq_loss - seq_mean) / seq_std
|
| 433 |
seq_weights = torch.sigmoid(z) * 1.5 + 0.5 # [0.5, 2.0]
|
| 434 |
|
| 435 |
-
# P15: Token Triage — per-token weights
|
| 436 |
triage = extras.get("triage")
|
| 437 |
-
|
| 438 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 439 |
else:
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
# Fuse: multiply token weights × sequence weights
|
| 443 |
-
combined_weights = tok_weights * seq_weights.unsqueeze(1) # [B, T]
|
| 444 |
-
base_loss = (per_token * combined_weights).sum() / combined_weights.sum()
|
| 445 |
-
else:
|
| 446 |
-
base_loss = outputs.loss if hasattr(outputs, "loss") else outputs
|
| 447 |
-
|
| 448 |
-
# P13: MTP auxiliary
|
| 449 |
-
mtp = extras.get("mtp")
|
| 450 |
-
hidden = getattr(outputs, "hidden_states", None)
|
| 451 |
-
if mtp is not None and hidden is not None:
|
| 452 |
-
mtp_loss = mtp(hidden, labels)
|
| 453 |
-
total_loss = base_loss + mtp_weight * mtp_loss
|
| 454 |
else:
|
| 455 |
-
total_loss =
|
| 456 |
|
| 457 |
loss_val = total_loss.item()
|
| 458 |
|
| 459 |
-
#
|
| 460 |
if not math.isfinite(loss_val):
|
| 461 |
_nan_count += 1
|
| 462 |
optimizer.zero_grad(set_to_none=True)
|
|
@@ -468,28 +475,28 @@ def training_step(model, batch, optimizer, scheduler,
|
|
| 468 |
return loss_val
|
| 469 |
_nan_count = 0
|
| 470 |
|
| 471 |
-
# P16: Plateau Breaker
|
| 472 |
plateau = extras.get("plateau")
|
| 473 |
-
if plateau
|
| 474 |
plateau.check_and_adjust(loss_val, optimizer, step)
|
| 475 |
|
| 476 |
if grad_accum_steps > 1:
|
| 477 |
total_loss = total_loss / grad_accum_steps
|
| 478 |
total_loss.backward()
|
| 479 |
|
| 480 |
-
# Sanitize
|
| 481 |
for p in model.parameters():
|
| 482 |
if p.grad is not None and not torch.isfinite(p.grad).all():
|
| 483 |
p.grad.nan_to_num_(nan=0.0, posinf=0.0, neginf=0.0)
|
| 484 |
|
| 485 |
-
# P18: Grokfast
|
| 486 |
grokfast = extras.get("grokfast")
|
| 487 |
-
if grokfast
|
| 488 |
grokfast.apply(model)
|
| 489 |
|
| 490 |
if is_accum:
|
| 491 |
torch.nn.utils.clip_grad_norm_(model.parameters(), max_grad_norm)
|
| 492 |
-
optimizer.step()
|
| 493 |
scheduler.step()
|
| 494 |
optimizer.zero_grad(set_to_none=True)
|
| 495 |
invalidate_all_caches(model)
|
|
|
|
| 1 |
"""
|
| 2 |
+
chimera_turbo.py — CHIMERA GENESIS v12
|
| 3 |
|
| 4 |
+
Interaction-audited paradigm stack. Every paradigm verified cumulative.
|
| 5 |
|
| 6 |
+
P12 Muon — NS-orthogonalized momentum for 2D matrices
|
| 7 |
+
P13 MTP — 3 aux heads (NOW in optimizer)
|
| 8 |
+
P15 Token Triage — focus on informative tokens (applied to ALL losses)
|
| 9 |
+
P16 Plateau Breaker — adaptive LR burst (LLRD-aware save/restore)
|
| 10 |
+
P17 Batch Metabolism — hard sequences weighted 2×
|
| 11 |
+
P18 Grokfast-EMA — amplify slow grads (1D params ONLY — NS cancels on 2D)
|
| 12 |
+
P19 LLRD — layer-wise LR decay for ternary
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
"""
|
| 14 |
|
| 15 |
import math
|
|
|
|
| 17 |
import torch
|
| 18 |
import torch.nn as nn
|
| 19 |
import torch.nn.functional as F
|
| 20 |
+
from typing import Dict
|
| 21 |
from contextlib import nullcontext
|
| 22 |
from collections import deque
|
| 23 |
|
|
|
|
| 50 |
|
| 51 |
|
| 52 |
# ═══════════════════════════════════════════════════════════
|
| 53 |
+
# P12 Muon + P19 LLRD
|
| 54 |
# ═══════════════════════════════════════════════════════════
|
| 55 |
|
| 56 |
def _zeropower_via_newtonschulz5(G, steps=5):
|
|
|
|
| 65 |
|
| 66 |
|
| 67 |
class Muon(torch.optim.Optimizer):
|
|
|
|
| 68 |
def __init__(self, params, lr=0.02, momentum=0.95, nesterov=True,
|
| 69 |
ns_steps=5, weight_decay=0.0,
|
| 70 |
adamw_betas=(0.9, 0.98), adamw_eps=1e-8):
|
|
|
|
| 108 |
|
| 109 |
|
| 110 |
def create_muon_optimizer(model, lr=0.02, momentum=0.95, weight_decay=0.01,
|
| 111 |
+
llrd_decay=0.85, extra_params=None):
|
| 112 |
+
"""Create Muon with LLRD. extra_params: additional nn.Module params to include."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
raw = getattr(model, "_orig_mod", model)
|
| 114 |
n_layers = len(raw.layers) if hasattr(raw, "layers") else 28
|
| 115 |
|
|
|
|
| 117 |
for name, p in model.named_parameters():
|
| 118 |
if not p.requires_grad:
|
| 119 |
continue
|
|
|
|
| 120 |
is_embed = any(k in name for k in ["embed", "lm_head", "wte", "wpe"])
|
| 121 |
if is_embed:
|
| 122 |
p._is_embed = True
|
|
|
|
|
|
|
| 123 |
lr_scale = 1.0
|
| 124 |
for i in range(n_layers):
|
| 125 |
+
if f"layers.{i}." in name:
|
| 126 |
+
lr_scale = llrd_decay ** (n_layers - 1 - i)
|
|
|
|
|
|
|
| 127 |
break
|
|
|
|
|
|
|
| 128 |
if is_embed:
|
| 129 |
lr_scale = llrd_decay ** n_layers
|
| 130 |
+
param_groups.append({"params": [p], "lr_scale": lr_scale})
|
| 131 |
|
| 132 |
+
# Add extra params (e.g. MTP heads) at full LR
|
| 133 |
+
if extra_params:
|
| 134 |
+
for p in extra_params:
|
| 135 |
+
if p.requires_grad:
|
| 136 |
+
param_groups.append({"params": [p], "lr_scale": 1.0})
|
| 137 |
|
| 138 |
return Muon(param_groups, lr=lr, momentum=momentum,
|
| 139 |
weight_decay=weight_decay, adamw_betas=(0.9, 0.98))
|
| 140 |
|
| 141 |
|
| 142 |
# ═══════════════════════════════════════════════════════════
|
| 143 |
+
# P13 MTP
|
| 144 |
# ═════════════════════════════��═════════════════════════════
|
| 145 |
|
| 146 |
class MultiTokenPredictionLoss(nn.Module):
|
|
|
|
| 153 |
for h in self.extra_heads:
|
| 154 |
nn.init.normal_(h.weight, std=0.006)
|
| 155 |
|
| 156 |
+
def forward(self, hidden_states, labels, token_weights=None):
|
| 157 |
+
"""Compute MTP loss, optionally weighted by token_weights from Triage."""
|
| 158 |
total, count = 0.0, 0
|
| 159 |
for k, head in enumerate(self.extra_heads):
|
| 160 |
shift = k + 2
|
|
|
|
| 163 |
logits = head(hidden_states[:, :-shift])
|
| 164 |
targets = labels[:, shift:]
|
| 165 |
sl = min(logits.size(1), targets.size(1))
|
| 166 |
+
|
| 167 |
+
if token_weights is not None:
|
| 168 |
+
# Apply token triage weights to MTP loss too
|
| 169 |
+
per_tok = F.cross_entropy(
|
| 170 |
+
logits[:, :sl].reshape(-1, logits.size(-1)),
|
| 171 |
+
targets[:, :sl].reshape(-1), ignore_index=-100, reduction="none"
|
| 172 |
+
).reshape(logits.size(0), sl)
|
| 173 |
+
tw = token_weights[:, :sl]
|
| 174 |
+
loss = (per_tok * tw).sum() / tw.sum()
|
| 175 |
+
else:
|
| 176 |
+
loss = F.cross_entropy(
|
| 177 |
+
logits[:, :sl].reshape(-1, logits.size(-1)),
|
| 178 |
+
targets[:, :sl].reshape(-1), ignore_index=-100)
|
| 179 |
+
|
| 180 |
if torch.isfinite(loss):
|
| 181 |
total = total + loss
|
| 182 |
count += 1
|
|
|
|
| 184 |
|
| 185 |
|
| 186 |
# ═══════════════════════════════════════════════════════════
|
| 187 |
+
# P15 Token Triage
|
| 188 |
# ═══════════════════════════════════════════════════════════
|
| 189 |
|
| 190 |
class TokenTriage:
|
|
|
|
| 195 |
self._loss_ema = None
|
| 196 |
|
| 197 |
def compute_weights(self, per_token_loss):
|
|
|
|
| 198 |
with torch.no_grad():
|
| 199 |
+
ml = per_token_loss.mean().item()
|
| 200 |
if self._loss_ema is None:
|
| 201 |
+
self._loss_ema = ml
|
| 202 |
else:
|
| 203 |
+
self._loss_ema = self.ema_decay * self._loss_ema + (1 - self.ema_decay) * ml
|
| 204 |
excess = per_token_loss - self._loss_ema
|
| 205 |
+
thr = torch.quantile(excess.flatten(), 1.0 - self.select_ratio)
|
| 206 |
+
return torch.where(excess >= thr, 1.0, self.floor_weight)
|
| 207 |
|
| 208 |
|
| 209 |
# ═══════════════════════════════════════════════════════════
|
| 210 |
+
# P16 Plateau Breaker (LLRD-aware)
|
| 211 |
# ═══════════════════════════════════════════════════════════
|
| 212 |
|
| 213 |
class PlateauBreaker:
|
| 214 |
def __init__(self, patience=100, variance_threshold=0.005,
|
| 215 |
+
lr_multiplier=2.0, burst_steps=50):
|
| 216 |
self.patience = patience
|
| 217 |
self.var_threshold = variance_threshold
|
| 218 |
self.lr_mult = lr_multiplier
|
|
|
|
| 220 |
self._history = deque(maxlen=patience)
|
| 221 |
self._stagnant_count = 0
|
| 222 |
self._burst_remaining = 0
|
| 223 |
+
self._saved_lrs = None # Save ALL group LRs, not just one
|
| 224 |
self.total_bursts = 0
|
| 225 |
|
| 226 |
def check_and_adjust(self, loss_val, optimizer, step):
|
|
|
|
| 229 |
self._history.append(loss_val)
|
| 230 |
if self._burst_remaining > 0:
|
| 231 |
self._burst_remaining -= 1
|
| 232 |
+
if self._burst_remaining == 0 and self._saved_lrs is not None:
|
| 233 |
+
# Restore ALL group LRs (preserves LLRD ratios)
|
| 234 |
+
for pg, saved_lr in zip(optimizer.param_groups, self._saved_lrs):
|
| 235 |
+
pg["lr"] = saved_lr
|
| 236 |
+
self._saved_lrs = None
|
| 237 |
return False
|
| 238 |
if len(self._history) < self.patience:
|
| 239 |
return False
|
|
|
|
| 245 |
else:
|
| 246 |
self._stagnant_count = 0
|
| 247 |
if self._stagnant_count >= self.patience // 2:
|
| 248 |
+
# Save ALL LRs before burst
|
| 249 |
+
self._saved_lrs = [pg["lr"] for pg in optimizer.param_groups]
|
| 250 |
for pg in optimizer.param_groups:
|
| 251 |
+
pg["lr"] *= self.lr_mult # Multiply, don't replace → LLRD preserved
|
| 252 |
self._burst_remaining = self.burst_steps
|
| 253 |
self._stagnant_count = 0
|
| 254 |
self.total_bursts += 1
|
| 255 |
+
base = self._saved_lrs[0]
|
| 256 |
+
print(f" [P16] Plateau! LR ×{self.lr_mult} for {self.burst_steps} steps (base {base:.2e})")
|
| 257 |
return True
|
| 258 |
return False
|
| 259 |
|
| 260 |
|
| 261 |
# ═══════════════════════════════════════════════════════════
|
| 262 |
+
# P18 Grokfast-EMA (1D params only — NS cancels on 2D)
|
| 263 |
# ═══════════════════════════════════════════════════════════
|
| 264 |
|
| 265 |
class GrokfastEMA:
|
| 266 |
+
"""Amplify slow gradient components for generalization.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
|
| 268 |
+
Applied ONLY to 1D params and embeddings (AdamW path).
|
| 269 |
+
Skipped for 2D matrices because Muon's Newton-Schulz normalisation
|
| 270 |
+
cancels the amplitude amplification — only direction survives,
|
| 271 |
+
which Muon already optimises via orthogonalisation.
|
| 272 |
"""
|
| 273 |
def __init__(self, alpha=0.98, lamb=2.0):
|
| 274 |
self.alpha = alpha
|
|
|
|
| 276 |
self._ema: Dict[str, torch.Tensor] = {}
|
| 277 |
|
| 278 |
@torch.no_grad()
|
| 279 |
+
def apply(self, model):
|
| 280 |
+
for name, p in model.named_parameters():
|
| 281 |
+
if p.grad is None:
|
| 282 |
+
continue
|
| 283 |
+
# Skip 2D Muon params — NS normalisation cancels amplitude
|
| 284 |
+
if p.ndim == 2 and not getattr(p, "_is_embed", False):
|
|
|
|
| 285 |
continue
|
| 286 |
if name not in self._ema:
|
| 287 |
+
self._ema[name] = p.grad.clone()
|
| 288 |
else:
|
| 289 |
+
self._ema[name].mul_(self.alpha).add_(p.grad, alpha=1 - self.alpha)
|
| 290 |
+
p.grad.add_(self._ema[name], alpha=self.lamb)
|
|
|
|
| 291 |
|
| 292 |
|
| 293 |
# ═══════════════════════════════════════════════════════════
|
|
|
|
| 323 |
cpu_info = detect_cpu_info()
|
| 324 |
if verbose:
|
| 325 |
print("=" * 65)
|
| 326 |
+
print("CHIMERA GENESIS v12 — Interaction-Audited Stack")
|
| 327 |
print("=" * 65)
|
| 328 |
print(f" CPU: {cpu_info['capability']} Cores: {cpu_info['physical_cores']}")
|
| 329 |
|
|
|
|
| 331 |
if verbose:
|
| 332 |
print(f" Threads: {n}")
|
| 333 |
|
| 334 |
+
raw = getattr(model, "_orig_mod", model)
|
| 335 |
+
extras = {}
|
| 336 |
+
|
| 337 |
+
# P13: Create MTP FIRST so we can add its params to optimizer
|
| 338 |
+
h, v = raw.config["hidden_size"], raw.config["vocab_size"]
|
| 339 |
+
mtp = MultiTokenPredictionLoss(h, v, n_future=mtp_heads)
|
| 340 |
+
extras["mtp"] = mtp
|
| 341 |
+
|
| 342 |
+
# P12+P19: Muon with LLRD + MTP head params included
|
| 343 |
+
mtp_params = list(mtp.parameters())
|
| 344 |
optimizer = create_muon_optimizer(model, lr=lr, weight_decay=weight_decay,
|
| 345 |
+
llrd_decay=llrd_decay, extra_params=mtp_params)
|
| 346 |
scheduler = create_scheduler(optimizer, max_steps, warmup_steps)
|
| 347 |
|
| 348 |
if verbose:
|
|
|
|
| 349 |
n_total = sum(p.numel() for g in optimizer.param_groups for p in g["params"])
|
| 350 |
scales = [g["lr_scale"] for g in optimizer.param_groups]
|
| 351 |
+
n_mtp = sum(p.numel() for p in mtp_params)
|
| 352 |
+
print(f"[P12] Muon (lr={lr}) + [P19] LLRD (decay={llrd_decay})")
|
| 353 |
+
print(f" {n_total:,} params, LR: {min(scales):.3f}× → {max(scales):.3f}×")
|
| 354 |
+
print(f"[P13] MTP ({mtp_heads} heads, {n_mtp:,} params — IN optimizer)")
|
|
|
|
| 355 |
|
| 356 |
+
# P15
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
extras["triage"] = TokenTriage(ema_decay=0.99, select_ratio=0.6, floor_weight=0.1)
|
| 358 |
if verbose:
|
| 359 |
+
print(f"[P15] Token Triage (60%→full, 40%→10%, applied to base+MTP)")
|
| 360 |
|
| 361 |
+
# P16
|
| 362 |
extras["plateau"] = PlateauBreaker(patience=100, variance_threshold=0.005,
|
| 363 |
+
lr_multiplier=2.0, burst_steps=50)
|
| 364 |
if verbose:
|
| 365 |
+
print(f"[P16] Plateau Breaker (×2 burst, LLRD-aware save/restore)")
|
| 366 |
|
| 367 |
+
# P18
|
| 368 |
extras["grokfast"] = GrokfastEMA(alpha=grokfast_alpha, lamb=grokfast_lambda)
|
| 369 |
if verbose:
|
| 370 |
+
n_1d = sum(p.numel() for p in model.parameters()
|
| 371 |
+
if p.requires_grad and (p.ndim < 2 or getattr(p, "_is_embed", False)))
|
| 372 |
+
print(f"[P18] Grokfast-EMA (α={grokfast_alpha}, λ={grokfast_lambda}, {n_1d:,} params — 1D only)")
|
| 373 |
|
| 374 |
if verbose:
|
| 375 |
+
print(f"[P17] Batch Metabolism (hard seq ×2, easy ×0.5)")
|
| 376 |
print("=" * 65)
|
| 377 |
|
| 378 |
return model, optimizer, scheduler, extras
|
| 379 |
|
| 380 |
|
| 381 |
# ═══════════════════════════════════════════════════════════
|
| 382 |
+
# Training step — ALL paradigms FUSED + VERIFIED CUMULATIVE
|
| 383 |
# ═══════════════════════════════════════════════════════════
|
| 384 |
|
| 385 |
_nan_count = 0
|
|
|
|
| 388 |
extras=None, grad_accum_steps=1, step=0,
|
| 389 |
max_grad_norm=1.0, autocast_dtype=None,
|
| 390 |
mtp_weight=0.3) -> float:
|
| 391 |
+
"""
|
| 392 |
+
Data flow (verified cumulative):
|
| 393 |
+
|
| 394 |
+
forward(batch) → logits, hidden_states
|
| 395 |
+
│
|
| 396 |
+
├─ per_token_loss = CE(logits, labels, reduction='none') [B,T]
|
| 397 |
+
│
|
| 398 |
+
├─ P17: seq_weights = sigmoid(z-score(per_seq_loss)) [B]
|
| 399 |
+
├─ P15: tok_weights = triage(excess_loss) [B,T]
|
| 400 |
+
├─ combined = tok_weights × seq_weights [B,T]
|
| 401 |
+
├─ base_loss = weighted_mean(per_token_loss, combined)
|
| 402 |
+
│
|
| 403 |
+
├─ P13: mtp_loss = MTP(hidden, labels, tok_weights) ← triage applied!
|
| 404 |
+
├─ total_loss = base + 0.3 × mtp
|
| 405 |
+
│
|
| 406 |
+
backward(total_loss) → param.grad for ALL params (model + MTP heads)
|
| 407 |
+
│
|
| 408 |
+
├─ P18: Grokfast amplifies grad on 1D params only (skip 2D/Muon)
|
| 409 |
+
│
|
| 410 |
+
optimizer.step() → P12 Muon (2D) + AdamW (1D), P19 LLRD scales per group
|
| 411 |
+
│
|
| 412 |
+
└─ P16: Plateau checks loss_val, burst preserves LLRD ratios
|
| 413 |
"""
|
| 414 |
global _nan_count
|
| 415 |
extras = extras or {}
|
|
|
|
| 427 |
|
| 428 |
logits = getattr(outputs, "logits", None)
|
| 429 |
|
|
|
|
| 430 |
if logits is not None:
|
| 431 |
B, T, V = logits.shape
|
|
|
|
| 432 |
per_token = F.cross_entropy(
|
| 433 |
logits.reshape(-1, V), labels.reshape(-1),
|
| 434 |
ignore_index=-100, reduction="none"
|
| 435 |
).reshape(B, T)
|
| 436 |
|
| 437 |
+
# P17: Batch Metabolism — per-sequence difficulty weights
|
| 438 |
with torch.no_grad():
|
| 439 |
+
seq_loss = per_token.mean(dim=1)
|
| 440 |
seq_mean = seq_loss.mean()
|
| 441 |
seq_std = seq_loss.std().clamp(min=1e-6)
|
| 442 |
z = (seq_loss - seq_mean) / seq_std
|
| 443 |
seq_weights = torch.sigmoid(z) * 1.5 + 0.5 # [0.5, 2.0]
|
| 444 |
|
| 445 |
+
# P15: Token Triage — per-token informativeness weights
|
| 446 |
triage = extras.get("triage")
|
| 447 |
+
tok_weights = triage.compute_weights(per_token) if triage else torch.ones_like(per_token)
|
| 448 |
+
|
| 449 |
+
# Fuse: multiplicative composition
|
| 450 |
+
combined = tok_weights * seq_weights.unsqueeze(1)
|
| 451 |
+
base_loss = (per_token * combined).sum() / combined.sum()
|
| 452 |
+
|
| 453 |
+
# P13: MTP with Token Triage weights passed through
|
| 454 |
+
mtp = extras.get("mtp")
|
| 455 |
+
hidden = getattr(outputs, "hidden_states", None)
|
| 456 |
+
if mtp is not None and hidden is not None:
|
| 457 |
+
mtp_loss = mtp(hidden, labels, token_weights=tok_weights)
|
| 458 |
+
total_loss = base_loss + mtp_weight * mtp_loss
|
| 459 |
else:
|
| 460 |
+
total_loss = base_loss
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
else:
|
| 462 |
+
total_loss = outputs.loss if hasattr(outputs, "loss") else outputs
|
| 463 |
|
| 464 |
loss_val = total_loss.item()
|
| 465 |
|
| 466 |
+
# NaN guard
|
| 467 |
if not math.isfinite(loss_val):
|
| 468 |
_nan_count += 1
|
| 469 |
optimizer.zero_grad(set_to_none=True)
|
|
|
|
| 475 |
return loss_val
|
| 476 |
_nan_count = 0
|
| 477 |
|
| 478 |
+
# P16: Plateau Breaker (before backward, uses loss_val only)
|
| 479 |
plateau = extras.get("plateau")
|
| 480 |
+
if plateau:
|
| 481 |
plateau.check_and_adjust(loss_val, optimizer, step)
|
| 482 |
|
| 483 |
if grad_accum_steps > 1:
|
| 484 |
total_loss = total_loss / grad_accum_steps
|
| 485 |
total_loss.backward()
|
| 486 |
|
| 487 |
+
# Sanitize
|
| 488 |
for p in model.parameters():
|
| 489 |
if p.grad is not None and not torch.isfinite(p.grad).all():
|
| 490 |
p.grad.nan_to_num_(nan=0.0, posinf=0.0, neginf=0.0)
|
| 491 |
|
| 492 |
+
# P18: Grokfast on 1D params only (2D handled by Muon NS)
|
| 493 |
grokfast = extras.get("grokfast")
|
| 494 |
+
if grokfast:
|
| 495 |
grokfast.apply(model)
|
| 496 |
|
| 497 |
if is_accum:
|
| 498 |
torch.nn.utils.clip_grad_norm_(model.parameters(), max_grad_norm)
|
| 499 |
+
optimizer.step() # P12 Muon (2D) + AdamW (1D), P19 LLRD via lr_scale
|
| 500 |
scheduler.step()
|
| 501 |
optimizer.zero_grad(set_to_none=True)
|
| 502 |
invalidate_all_caches(model)
|