Skip to content

The best ChatGPT that $100 can buy.

Python

adding MuonEq and Muon+, both seem to be very slight improvements at both d12 and d24. contributed by @jn2clark

Andrej Karpathy4e014d31b1d5
diff --git a/nanochat/optim.py b/nanochat/optim.py
index 56e85e1..84bb2cc 100644
--- a/nanochat/optim.py
+++ b/nanochat/optim.py
@@ -72,6 +72,12 @@ NorMuon variance reduction: per-neuron/column adaptive learning rate that normal
update scales after orthogonalization (Muon's output has non-uniform scales across neurons).
https://arxiv.org/pdf/2510.05491
+Two more (very) slight and optional improvements:
+1) MuonEq row equilibration: rescale each row to the mean row norm so the spectrum
+entering orthogonalization is better conditioned (https://arxiv.org/abs/2603.28254)
+2) Muon+ renormalization: snap the Frobenius norm to sqrt(min(m, n)), the norm of an exactly
+semi-orthogonal matrix, correcting for under-convergence of the polar iteration (https://arxiv.org/abs/2602.21545)
+
Some of the changes in nanochat implementation:
- Uses a simpler, more general approach to parameter grouping and stacking
- Uses a single fused kernel for the momentum -> polar_express -> variance_reduction -> update step
@@ -88,6 +94,7 @@ polar_express_coeffs = [
(2.3465413258596377, -1.7097828382687081, 0.42323551169305323),
]
+
@torch.compile(dynamic=False, fullgraph=True)
def muon_step_fused(
stacked_grads: Tensor, # (12, 768, 3072) - stacked gradients
@@ -112,9 +119,15 @@ def muon_step_fused(
momentum_buffer.lerp_(stacked_grads, 1 - momentum)
g = stacked_grads.lerp_(momentum_buffer, momentum)
- # Polar express
# Cast to bf16 for speed when available; skip cast otherwise (fp16 is unstable here due to limited exponent range)
X = g.bfloat16() if COMPUTE_DTYPE == torch.bfloat16 else g
+
+ # MuonEq row equilibration: rescale each row to the mean row norm so the spectrum entering orthogonalization is better conditioned
+ target = X.float().norm(dim=(-2, -1), keepdim=True) / (X.size(-2) ** 0.5)
+ row_norm = X.float().norm(dim=-1, keepdim=True).clamp_min(1e-6)
+ X = X * (target / row_norm).to(X.dtype)
+
+ # Polar Express orthogonalization: replace each update with the nearest orthogonal matrix
X = X / (X.norm(dim=(-2, -1), keepdim=True) * 1.01 + 1e-6)
if g.size(-2) > g.size(-1): # Tall matrix
for a, b, c in polar_express_coeffs[:ns_steps]:
@@ -128,6 +141,11 @@ def muon_step_fused(
X = a * X + B @ X
g = X
+ # Muon+ renormalization: snap Frobenius norm to sqrt(min(m, n))
+ target_norm = min(g.size(-2), g.size(-1)) ** 0.5
+ current_norm = g.float().norm(dim=(-2, -1), keepdim=True).clamp_min(1e-6)
+ g = g * (target_norm / current_norm).to(g.dtype)
+
# Variance reduction
beta2 = beta2_t.to(g.dtype)
v_mean = g.float().square().mean(dim=red_dim, keepdim=True)