AI/ML Optimization Muon Newton–Schulz PyTorch

Beyond AdamW: Matrix Orthogonalization (Muon), Newton–Schulz Iteration & RMS Scale Alignment at 16B+ Scale


For nearly a decade, AdamW (Loshchilov & Hutter, 2019) has remained the default optimizer for Transformer pretraining. Yet from a matrix-geometry perspective, elementwise second-moment preconditioning $m_t / (\sqrt{v_t} + \epsilon)$ treats a $d_{\text{out}} \times d_{\text{in}}$ linear projection weight matrix $W \in \mathbb{R}^{m \times n}$ as an unstructured flat vector – ignoring the fact that gradient matrices $G_t = \nabla_W \mathcal{L}$ in deep Transformers are overwhelmingly low-rank and dominated by a few top singular directions.

Muon (MomentUm Orthogonalized by Newton–Schulz) (Keller Jordan et al., 2024; scaled to $16\text{B}$ MoE in Moonlight, Liu et al., 2025, arXiv:2502.16982; GitHub) replaces coordinate-wise Adam scaling on hidden 2D weight matrices with spectral matrix orthogonalization: projecting the momentum matrix $M_t = U \Sigma V^\top$ onto its nearest semi-orthogonal polar factor $U V^\top = (M_t M_t^\top)^{-1/2} M_t$ using 5 Tensor-Core-friendly odd-polynomial Newton–Schulz iterations in bfloat16, achieving $\sim 2\times$ compute efficiency over AdamW along the Chinchilla scaling frontier.


0. Spectral Preconditioning: Why Orthogonalizing Momentum Beats Coordinate-Wise AdamW

Suppose a hidden linear layer receives activations $X \in \mathbb{R}^{B \times n}$ and upstream backpropagated gradients $\delta Y \in \mathbb{R}^{B \times m}$, producing the weight gradient $G = (\delta Y)^\top X = \sum_{i=1}^r \sigma_i u_i v_i^\top$. In standard SGD or AdamW, the update direction is heavily skewed toward the dominant singular value $\sigma_1 \gg \sigma_r$, starving rare semantic directions $(u_k, v_k)$ of learning signal. Replacing $M_t$ with its polar factor $\mathrm{Ortho}(M_t) = U V^\top$ snaps every non-zero singular value $\sigma_i \mapsto 1$:

Quintic Newton–Schulz Matrix Orthogonalization & Moonlight RMS Scale (Liu et al., 2025)
$$X_0 = \frac{M_t}{\|M_t\|_F + \epsilon}, \qquad X_{k+1} = a X_k + b X_k(X_k^\top X_k) + c X_k(X_k^\top X_k)^2 \quad (k = 0, \dots, 4)$$ $$W_{t+1} = (1 - \eta \lambda) W_t - \eta \cdot \underbrace{0.2\sqrt{\max(m, n)}}_{\text{Moonlight RMS Alignment}} \cdot X_5, \qquad (a, b, c) = (3.4445,\; -4.7750,\; 2.0315)$$

Why those exact quintic coefficients $(3.4445, -4.7750, 2.0315)$? Standard cubic Newton–Schulz $X_{k+1} = \frac{3}{2}X_k - \frac{1}{2}X_k(X_k^\top X_k)$ has linear derivative $f'(0) = 1.5$ near zero, requiring $12+$ steps to lift small singular values. Optimizing the odd 5th-degree polynomial $f(\sigma) = a\sigma + b\sigma^3 + c\sigma^5$ to maximize slope $f'(0) = 3.4445$ while keeping $|f(\sigma) - 1| \le 0.3$ on $(0, 1]$ pulls singular values as small as $10^{-2}$ into $[0.7, 1.2]$ in just 5 GEMM steps!

1. Quintic Polynomial Map f⁽⁵⁾(σ) on (0, 1] f(σ) = 3.4445σ − 4.7750σ³ + 2.0315σ⁵ (Steep slope at σ → 0) 1.0 5 steps in BF16 compress κ(G) = 1555.6 → [0.18, 1.20] without SVD 2. Moonlight Scaling Law Rules (arXiv:2502.16982) Why naive Muon stalls at >3B tokens without RMS alignment Rule A: Scale Orthogonal Update by 0.2 · √max(m, n) Matches AdamW coordinate RMS ≈ 0.2 across rectangular layers Rule B: Keep Embed, LM Head & RMSNorm on AdamW + Split fused QKV per-head before orthogonalizing
Figure 1: Quintic Newton–Schulz singular-value stabilization (left) and the two scaling invariants from Moonlight (Liu et al., 2025) that enable zero-tuning transfer of AdamW learning rates to 16B+ MoE training (right).
Three Critical Production Footguns When Training with Muon: (1) Why You Must Multiply by $0.2\sqrt{\max(m, n)}$: An orthogonal matrix $U V^\top \in \mathbb{R}^{m \times n}$ has Frobenius norm $\sqrt{\min(m, n)}$, so its per-element RMS is $\sqrt{\min(m,n)/(mn)} = 1/\sqrt{\max(m, n)}$. Without multiplying by $0.2\sqrt{\max(m, n)}$, wide MLP layers ($4d \times d$) receive $2\times$ smaller RMS updates than square layers! (2) Never Orthogonalize Fused wqkv Jointly: If $W_{QKV} \in \mathbb{R}^{3 d \times d}$ is orthogonalized as a single matrix, Newton–Schulz couples the singular subspaces of $Q$, $K$, and $V$ across all attention heads – always unbind or reshape per head ([H, d_head, d_model]) first. (3) Always Transpose Tall Matrices ($m \gt n$) Before Iteration: Compute $A = X^\top X \in \mathbb{R}^{n \times n}$ on the smaller dimension $\min(m, n)$ to save $m/n$ Tensor Core FLOPs.

1. Self-Contained PyTorch Implementation: Muon with Moonlight RMS Scaling

The runnable script below implements the exact 5-step quintic Newton–Schulz orthogonalizer and verifies how it compresses a badly ill-conditioned gradient matrix ($\kappa = 1555.6$) into a narrow singular spectrum in 5 iterations:

💻 Python: Quintic Newton–Schulz Orthogonalizer & Moonlight Muon StepPyTorch
import math
import torch

def zeropower_via_newtonschulz5(G: torch.Tensor, steps: int = 5, eps: float = 1e-7) -> torch.Tensor:
    """5-step quintic Newton-Schulz orthogonalization in BF16/FP32 (Liu et al., arXiv:2502.16982)."""
    assert G.ndim >= 2
    a, b, c = (3.4445, -4.7750, 2.0315)
    X = G.clone()
    # Transpose tall matrices (m > n) so Gram matrix A = X @ X^T has smaller shape [..., n, n]
    transposed = G.size(-2) > G.size(-1)
    if transposed:
        X = X.transpose(-2, -1)
    # Normalize Frobenius norm <= 1 so singular values start inside convergence basin (0, 1]
    X = X / (X.norm(dim=(-2, -1), keepdim=True) + eps)
    for _ in range(steps):
        A = X @ X.transpose(-2, -1)
        B = b * A + c * (A @ A)
        X = a * X + B @ X
    return X.transpose(-2, -1) if transposed else X

def muon_update(
    W: torch.Tensor, grad: torch.Tensor, buf: torch.Tensor,
    lr: float = 3e-4, wd: float = 0.1, momentum: float = 0.95
) -> torch.Tensor:
    """Single Muon parameter step with decoupled weight decay and Moonlight RMS alignment."""
    buf.mul_(momentum).add_(grad)
    g_ns = zeropower_via_newtonschulz5(grad.add(buf, alpha=momentum), steps=5)
    # Match AdamW coordinate RMS (~0.2) across arbitrary aspect ratios (m, n)
    rms_scale = 0.2 * math.sqrt(max(W.size(-2), W.size(-1)))
    W.mul_(1.0 - lr * wd).add_(g_ns, alpha=-lr * rms_scale)
    return W

if __name__ == "__main__":
    torch.manual_seed(42)
    # Construct ill-conditioned 64x32 gradient with singular values spanning [0.01, 10.0] (cond = 1000)
    G = torch.randn(64, 32) @ torch.diag(torch.logspace(-2, 1, 32))
    s_before = torch.linalg.svdvals(G)
    G_ortho = zeropower_via_newtonschulz5(G, steps=5)
    s_after = torch.linalg.svdvals(G_ortho)

    print(f"[PASS] Raw Gradient Condition Number       : {(s_before[0] / s_before[-1]).item():.1f}")
    print(f"[PASS] 5-Step Quintic NS Singular Range    : [{s_after.min().item():.3f}, {s_after.max().item():.3f}]")
    print(f"[PASS] Moonlight RMS Scale for (64, 32)    : {0.2 * math.sqrt(64):.4f}")
# Output:
# [PASS] Raw Gradient Condition Number       : 1555.6
# [PASS] 5-Step Quintic NS Singular Range    : [0.179, 1.202]
# [PASS] Moonlight RMS Scale for (64, 32)    : 1.6000

2. Large-Scale LLM Optimizers: Head-to-Head

Optimizer AdamW Distributed Shampoo / SOAP Muon (Moonlight, arXiv:2502.16982)
Preconditioning Geometry Diagonal coordinate-wise $v_t^{-1/2}$ Kronecker factors $(L_t^{-1/4} G_t R_t^{-1/4})$ Semi-orthogonal polar factor $U V^\top$ via 5-step NS
Optimizer State Memory $2\times$ parameter count ($m_t, v_t$) $3\text{–}4\times$ parameter count (Kronecker buffers + eigenbasis) $1\times$ parameter count (single momentum buffer $M_t$)
Compute Overhead & Precision Memory-bound elementwise kernel Requires FP32 matrix root inverse / eigendecomposition $\lt 1\%$ FLOP overhead; runs natively in bfloat16 GEMMs