Module contents
Lesson 27 of 27Research 110 min

The optimizer frontier: preconditioners at scale and rigorous evaluation

Explore approximate second-order optimizers for large networks (K-FAC, Shampoo, SOAP and Sophia), schedule-free methods, and rigorous evaluation of a new optimizer: tuning budgets, benchmarks such as AlgoPerf, and common pitfalls in optimizer papers.

After this lesson you can

  • Derive K-FAC’s Kronecker approximation for a linear layer and relate it to Gauss–Newton and Fisher information.
  • Explain Shampoo’s per-side preconditioner statistics and SOAP’s relationship to Adam in Shampoo’s eigenbasis.
  • Explain Sophia’s diagonal curvature estimator and coordinate clipping.
  • Explain schedule-free averaging and interpolation and why they remove the need to fix a horizon.
  • Design a fair optimizer comparison with fixed tuning budget, multiple seeds and time to target following AlgoPerf.

Before you start

Motivation: a new candidate to replace Adam each year

Since 2015 the default optimizer for most deep learning has been Adam, and since 2019 its AdamW variant. Hundreds of alternatives have been published, many claiming to be “twice as fast.” Few survived. Two that did appear here: in the first AlgoPerf competition, measuring actual training time to target across workloads on fixed hardware, Distributed Shampoo won with hyperparameter tuning and Schedule-Free AdamW without tuning (Kasimbeg et al., 2025). A systematic 2025 study of language-model pretraining from 0.1 to 1.2 billion parameters found advertised 1.4–2× speedups shrink to about 1.1× versus a well-tuned baseline at the largest scale, and the best methods (Muon and SOAP) use matrix preconditioners (Wen et al., 2025, Fantastic Pretraining Optimizers and Where to Find Them).

Those two observations summarize the lesson. The first half is technical: construct approximate second-order preconditioners that fit in memory and cost little more than Adam (K-FAC, Shampoo, SOAP, Sophia) and remove the learning-rate schedule without losing performance (schedule-free). The second half is methodological: what “faster” means, why tuning budget can change the winner, and how to read an optimizer paper critically. Both halves matter: a brilliant preconditioner with poor evaluation is indistinguishable from a useless one.

We build on familiar tools. Natural gradient preconditions with inverse Fisher and is reparameterization-invariant, but for pp parameters Fisher has p2p^2 entries. Adam’s diagonal costs O(p)\bigO(p) but sees only axes. L-BFGS stores a few vector pairs but struggles with minibatch noise. Muon’s spectral descent orthogonalizes each matrix update without examining curvature. The missing middle exploits that network parameters are a collection of matrices, not an arbitrary vector, and each matrix’s curvature has structure.

K-FAC: layer Fisher as a Kronecker product

Consider linear layer s=Wa\vb{s} = \mat{W}\vb{a} with W∈Rdout×din\mat{W} \in \R^{d_{\text{out}} \times d_{\text{in}}} (include bias by appending 1 to a\vb{a}). For one example let a\vb{a} be layer input and g=∂ℓ/∂s\vb{g} = \partial \ell / \partial \vb{s} the loss gradient with respect to output. The chain rule gives the weight gradient as an outer product:

∇W ℓ=g a⊤,vec⁡(g a⊤)=a⊗g,\nabla_{\mat{W}}\,\ell = \vb{g}\,\vb{a}\T, \qquad \operatorname{vec}(\vb{g}\,\vb{a}\T) = \vb{a} \otimes \vb{g},

where vec⁡\operatorname{vec} stacks columns (the vec operator) and ⊗\otimes is the Kronecker product. An entry of vec⁡(W)\operatorname{vec}(\mat{W}) is indexed by pair (i,k)(i, k): input ii, output kk. The layer’s Fisher matrix block is the expectation of these gradients’ outer product:

F=E[vec⁡(∇Wℓ)vec⁡(∇Wℓ)⊤]=E[(aa⊤)⊗(gg⊤)],F(i,k),(j,l)=E[aiaj gkgl].F = \E\big[\operatorname{vec}(\nabla_{\mat{W}}\ell)\operatorname{vec}(\nabla_{\mat{W}}\ell)\T\big] = \E\big[(\vb{a}\vb{a}\T) \otimes (\vb{g}\vb{g}\T)\big], \qquad F_{(i,k),(j,l)} = \E[a_i a_j\, g_k g_l].

A crucial precision: in true Fisher, the label used to compute g\vb{g} is sampled from the model, y^∼pθ(y∣x)\hat y \sim p_\theta(y \given \vb{x}), not taken from data. Real labels yield empirical Fisher, generally a poor curvature approximation that can point in bad directions (Kunstner, Hennig and Balles, 2019). For exponential-family log-likelihood losses with network output as natural parameter (softmax cross-entropy, squared error with Gaussian noise), true Fisher equals generalized Gauss–Newton E[J⊤HzJ]\E[\mat{J}\T \mat{H}_z \mat{J}], because Ey^[∇zℓ ∇zℓ⊤]=∇z2ℓ\E_{\hat y}[\nabla_z \ell\, \nabla_z \ell\T] = \nabla_z^2 \ell. Fisher preconditioning is therefore Gauss–Newton.

Martens and Grosse’s (2015) key step is one approximation: replace the expectation of a Kronecker product with the Kronecker product of expectations.

The approximation is exact when a\vb{a} and g\vb{g} are independent, because then E[aiajgkgl]=E[aiaj] E[gkgl]\E[a_i a_j g_k g_l] = \E[a_i a_j]\,\E[g_k g_l]. They are not in a real network (input determines which outputs receive gradient); the interactive measures how much this matters. The model is a layer with 3 inputs and 2 outputs: Gaussian inputs with correlation cc, and output gradient g=∑kzkwk(a) vk\vb{g} = \sum_k z_k w_k(\vb{a})\,\vb{v}_k with independent zkz_k and wk(a)2=(1−ρ)+ρ ak2/E[ak2]w_k(\vb{a})^2 = (1 - \rho) + \rho\, a_k^2 / \E[a_k^2]: with ρ=0\rho = 0 gradient is input-independent; with ρ=1\rho = 1 input kk determines gradient received in output direction vk\vb{v}_k. All moments are exact fourth-order Gaussian moments, without sampling.

InteractiveKronecker factorization
Block Fisher FF
K-FAC: A⊗G\mat{A}\otimes\mat{G}
Difference F−A⊗GF - \mat{A}\otimes\mat{G}
A=E[aa⊤]\mat{A} = \E[\vb{a}\vb{a}\T]
G=E[gg⊤]\mat{G} = \E[\vb{g}\vb{g}\T]
negativepositive2×22\times 2 blocks: Aij GA_{ij}\,\mat{G}
Layer 1024 × 1024
Full block
Factors A and G
Entries
1.1·10¹²
2.1·10⁶
Memory in fp32
4.00 TiB
8.00 MiB
Invert (∝ n³)
1.2·10¹⁸
2.1·10⁹
Layer statistics
0.60
0.50
Cost in a real layer
1024
Relative error ∥F−A⊗G∥F/∥F∥F\norm{F - \mat{A}\otimes\mat{G}}_F / \norm{F}_F0.504
κ(F)\kappa(F), unpreconditioned27.8
κ\kappa with diagonal of FF7.13
κ\kappa with K-FAC2.20
Cosine between F−1∇F^{-1}\nabla and the K-FAC direction0.991
The Frobenius error is large, but what matters for preconditioning is κ\kappa of (A⊗G)−1F(\mat{A}\otimes\mat{G})^{-1}F: raise correlation cc and compare with the diagonal.
The block Fisher (6 × 6), its K-FAC approximation and their difference on the same color scale; below, factors A\mat{A} and G\mat{G}. Each 2×22\times 2 block of A⊗G\mat{A}\otimes\mat{G} is Aij GA_{ij}\,\mat{G}: a scaled copy of the output factor. At ρ=0\rho = 0 the difference vanishes even with highly correlated inputs. Raise ρ\rho: Frobenius error exceeds 60 %, but the condition number of (A⊗G)−1F(\mat{A}\otimes\mat{G})^{-1}F reaches only 3, while the diagonal's explodes as ∣c∣\abs{c} grows. The table scales cost to a real layer.

Two readings. First, relative Frobenius error poorly measures preconditioner quality: what matters is preconditioned matrix condition κ((A⊗G)−1F)\kappa\big((\mat{A}\otimes\mat{G})^{-1}F\big), governing first-order speed on the local quadratic. Here it is exactly 1+2ρ1 + 2\rho for any correlation cc. To see this, write Σ=E[aa⊤]\mat{\Sigma} = \E[\vb{a}\vb{a}\T], uk=Σ1/2ek/Σkk\vb{u}_k = \mat{\Sigma}^{1/2}\vb{e}_k / \sqrt{\Sigma_{kk}} (unit) and wk=G−1/2vk\vb{w}_k = \mat{G}^{-1/2}\vb{v}_k. Since G=v1v1⊤+v2v2⊤\mat{G} = \vb{v}_1\vb{v}_1\T + \vb{v}_2\vb{v}_2\T, the wk\vb{w}_k are orthonormal, and the preconditioned matrix is ∑k(I+2ρ ukuk⊤)⊗wkwk⊤\sum_k (\mat{I} + 2\rho\,\vb{u}_k\vb{u}_k\T) \otimes \vb{w}_k\vb{w}_k\T, block diagonal in the wk\vb{w}_k basis with eigenvalues 11 and 1+2ρ1 + 2\rho. Second, K-FAC captures exactly what the diagonal misses: input correlations, huge in networks (layer activations are far from white). Thus the diagonal worsens as ∣c∣\abs{c} grows and K-FAC does not.

The inverse comes for free

Proof

The mixed-product property (A⊗B)(C⊗D)=(AC)⊗(BD)(\mat{A}\otimes\mat{B})(\mat{C}\otimes\mat{D}) = (\mat{A}\mat{C})\otimes(\mat{B}\mat{D}) follows block by block: block (i,j)(i, j) of the product is ∑k(aikB)(ckjD)=(AC)ij BD\sum_k (a_{ik}\mat{B})(c_{kj}\mat{D}) = (\mat{A}\mat{C})_{ij}\,\mat{B}\mat{D}. It gives (A⊗B)(A−1⊗B−1)=In⊗Im=Inm(\mat{A}\otimes\mat{B})(\mat{A}^{-1}\otimes\mat{B}^{-1}) = \mat{I}_n\otimes\mat{I}_m = \mat{I}_{nm}. For the second identity, column jj of BVA⊤\mat{B}\mat{V}\mat{A}\T is ∑kajk Bvk\sum_k a_{jk}\,\mat{B}\vb{v}_k, exactly block jj of (A⊗B)vec⁡(V)(\mat{A}\otimes\mat{B})\operatorname{vec}(\mat{V}).

∎

With symmetric A\mat{A} and G\mat{G}, (A⊗G)−1vec⁡(∇W)=vec⁡(G−1∇W A−1)(\mat{A}\otimes\mat{G})^{-1}\operatorname{vec}(\nabla\mat{W}) = \operatorname{vec}(\mat{G}^{-1}\nabla\mat{W}\,\mat{A}^{-1}): K-FAC never forms the large matrix. For layer 1024×10241024\times 1024 the Fisher block has 240≈1.1×10122^{40} \approx 1.1\times 10^{12} entries (4 TiB in float32), and inversion costs on the order of (220)3≈1018(2^{20})^3 \approx 10^{18} operations; the factors have 2⋅2202\cdot 2^{20} entries (8 MiB) and inversion costs 2⋅230≈2×1092\cdot 2^{30} \approx 2\times 10^{9}. The next cell calculates it.

[ ]Kronecker: identities and accountingBrowser
import time
import numpy as np

rng = np.random.default_rng(0)
vec = lambda M: M.reshape(-1, order="F")           # apila columnas (convención matemática)

d_in, d_out = 20, 20
X = rng.normal(size=(d_in, 4 * d_in)); A = X @ X.T / X.shape[1] + 0.1 * np.eye(d_in)
Y = rng.normal(size=(d_out, 4 * d_out)); G = Y @ Y.T / Y.shape[1] + 0.1 * np.eye(d_out)
V = rng.normal(size=(d_out, d_in))                 # un "gradiente" con la forma de W

# 1) (A ⊗ G) vec(V) = vec(G V A)   (A y G simétricas)
print("vec(GVA) = (A⊗G) vec(V):", np.allclose(np.kron(A, G) @ vec(V), vec(G @ V @ A)))

# 2) (A ⊗ G)^{-1} = A^{-1} ⊗ G^{-1}, y aplicarla no exige formarla
t0 = time.perf_counter()
K = np.kron(A, G)                                  # 400 × 400
paso_completo = np.linalg.solve(K, vec(V))
t_full = time.perf_counter() - t0
t0 = time.perf_counter()
paso_factores = vec(np.linalg.solve(G, np.linalg.solve(A.T, V.T).T))   # G^{-1} V A^{-1}
t_fac = time.perf_counter() - t0
print("mismo paso:", np.allclose(paso_completo, paso_factores))
print(f"resolver con el bloque {K.shape[0]}×{K.shape[1]}: {1e3 * t_full:.1f} ms;  con los factores: {1e3 * t_fac:.2f} ms")

# 3) contabilidad para una capa de 1024 × 1024
d = 1024
print(f"\ncapa {d}×{d}: entradas del bloque {d**4:.3e}, de los factores {2 * d**2:.3e}, cociente {d**4 // (2 * d**2)}")
print(f"memoria del bloque en fp32: {4 * d**4 / 2**40:.0f} TiB;  factores: {4 * 2 * d**2 / 2**20:.0f} MiB")
print(f"invertir: ~{(d * d)**3:.2e} frente a ~{2 * d**3:.2e} operaciones (cociente {(d * d)**3 / (2 * d**3):.2e})")

Damping and what K-FAC really does

Factors are semidefinite and often nearly singular: output-layer G\mat{G} with softmax always has eigenvalue 0 (rows of diag⁡(p)−pp⊤\operatorname{diag}(\vb{p}) - \vb{p}\vb{p}\T sum to zero), and A\mat{A} inherits activation correlations. Damping is needed, as in Levenberg–Marquardt. Natural (A⊗G+λI)−1(\mat{A}\otimes\mat{G} + \lambda\mat{I})^{-1} destroys Kronecker structure. Martens and Grosse propose factored Tikhonov damping,

(A+πλ I)⊗(G+λπ I)=A⊗G+λI+λ (π I⊗G+1πA⊗I),(\mat{A} + \pi\sqrt{\lambda}\,\mat{I}) \otimes (\mat{G} + \tfrac{\sqrt{\lambda}}{\pi}\,\mat{I}) = \mat{A}\otimes\mat{G} + \lambda\mat{I} + \sqrt{\lambda}\,\big(\pi\,\mat{I}\otimes\mat{G} + \tfrac{1}{\pi}\mat{A}\otimes\mat{I}\big),

which adds λI\lambda\mat{I} plus a cross term. Factor π=(tr⁡A/din)/(tr⁡G/dout)\pi = \sqrt{(\tr\mat{A}/d_{\text{in}})/(\tr\mat{G}/d_{\text{out}})} balances both scales to minimize that term. In practice K-FAC also estimates A\mat{A} and G\mat{G} via minibatch moving averages, recomputes inverses only every kk steps (the expensive part), and adapts λ\lambda by Levenberg–Marquardt. Later variant EKFAC (George et al., 2018) rescales in the eigenbasis of A⊗G\mat{A}\otimes\mat{G} using diagonal second moments: it returns under another name with SOAP.

Now K-FAC from scratch on a two-layer NumPy perceptron. The first cell computes exact Fisher blocks per layer (expectation over y^∼p\hat y \sim p analytically) and measures approximation quality like the figure.

[ ]Exact Fisher blocks versus K-FACBrowser
import numpy as np

rng = np.random.default_rng(1)
# datos: tres clases en espiral, entradas con escalas distintas
n, K = 600, 3
t = rng.uniform(0.2, 1, n); y = rng.integers(0, K, n)
ang = 4 * t + 2 * np.pi * y / K + 0.25 * rng.normal(size=n)
X = np.c_[3 * t * np.cos(ang), 0.5 * t * np.sin(ang)]          # la segunda coordenada, 6 veces más pequeña

def init(h=16, seed=0):
    r = np.random.default_rng(seed)
    return [r.normal(size=(h, 3)) / np.sqrt(3), r.normal(size=(K, h + 1)) / np.sqrt(h + 1)]   # [W | b]

def forward(P, X):
    a1 = np.c_[X, np.ones(len(X))]                  # entrada homogénea: el sesgo es la última columna de W
    h = np.tanh(a1 @ P[0].T)
    a2 = np.c_[h, np.ones(len(X))]
    s = a2 @ P[1].T
    p = np.exp(s - s.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
    return a1, h, a2, p

def loss_grad(P, X, y):
    a1, h, a2, p = forward(P, X)
    m = len(X)
    loss = -np.log(p[np.arange(m), y]).mean()
    g2 = p.copy(); g2[np.arange(m), y] -= 1                       # ∂ℓ/∂s por ejemplo
    g1 = (g2 @ P[1][:, :-1]) * (1 - h**2)
    return loss, [g1.T @ a1 / m, g2.T @ a2 / m]                   # ∇W = E[g aᵀ]

def fisher_blocks(P, X):
    """Bloque exacto de Fisher de cada capa (esperanza exacta sobre y ~ p) y sus factores A, G."""
    a1, h, a2, p = forward(P, X)
    m = len(X)
    S2 = np.einsum("ni,nj->nij", -p, p); S2[:, range(K), range(K)] += p   # Cov(g2 | x) = diag(p) − ppᵀ
    D = 1 - h**2
    W2 = P[1][:, :-1]
    S1 = np.einsum("ki,nkl,lj->nij", W2, S2, W2, optimize=True) * D[:, :, None] * D[:, None, :]   # Cov(g1 | x)
    out = []
    for a, S in [(a1, S1), (a2, S2)]:
        F = np.einsum("ni,nj,nkl->ikjl", a, a, S, optimize=True).reshape(a.shape[1] * S.shape[1], -1) / m   # índice (i, k) = i·dout + k
        A = a.T @ a / m
        G = S.mean(0)
        out.append((F, A, G))
    return out

P = init()
for _ in range(150):                                                 # un poco de entrenamiento: estadísticas no triviales
    _, gr = loss_grad(P, X, y)
    P = [W - 0.5 * g for W, g in zip(P, gr)]
lam = 1e-3
for capa, (F, A, G) in enumerate(fisher_blocks(P, X), start=1):
    Kf = np.kron(A, G)
    err = np.linalg.norm(F - Kf) / np.linalg.norm(F)
    I = np.eye(len(F))
    # condición de F + λI precondicionada con la diagonal o con K-FAC (amortiguado igual)
    def kappa(Pm):
        w = np.linalg.eigvals(np.linalg.solve(Pm, F + lam * I)).real
        return w.max() / w.min()
    print(f"capa {capa}: bloque {F.shape[0]}×{F.shape[1]}, error relativo de A⊗G = {err:.3f}, "
          f"κ(F+λI) = {kappa(I):.3g}, con la diagonal {kappa(np.diag(np.diag(F)) + lam * I):.3g}, con K-FAC {kappa(Kf + lam * I):.3g}")

At the output layer K-FAC takes condition number from 814814 to 25.625.6; the diagonal worsens it to 16901690 because hidden activations are highly correlated. Improvement is smaller in the first layer (1740→4841740 \to 484) but still much better than diagonal. Frobenius errors are similar (56 % and 50 %): again a poor measure. Now training, full-batch to isolate preconditioning:

[ ]K-FAC from scratch versus GD and AdamBrowser
import time
import numpy as np

def kfac_dir(P, gr, X, lam):
    """Dirección de K-FAC con amortiguamiento de Tikhonov factorizado: (A + π√λ I)⁻¹ y (G + √λ/π I)⁻¹."""
    out = []
    for (A, G), g in zip(factores(P, X), gr):
        pi_ = np.sqrt((np.trace(A) / len(A)) / max(np.trace(G) / len(G), 1e-12))
        Ad = A + pi_ * np.sqrt(lam) * np.eye(len(A))
        Gd = G + np.sqrt(lam) / pi_ * np.eye(len(G))
        out.append(np.linalg.solve(Gd, np.linalg.solve(Ad, g.T).T))        # G⁻¹ ∇W A⁻¹
    return out

def factores(P, X):
    """Solo los factores A y G (sin formar el bloque completo), como haría K-FAC de verdad."""
    a1, h, a2, p = forward(P, X)
    m = len(X)
    G2 = (np.diag(p.sum(0)) - p.T @ p) / m
    D = 1 - h**2
    W2 = P[1][:, :-1]
    # E[D Wᵀ(diag p − ppᵀ)W D] con productos de matrices: Σ_k R_kᵀ diag(p_k) R_k − ZᵀZ
    G1 = sum((D * W2[k]).T @ (p[:, [k]] * D * W2[k]) for k in range(K))
    Z = D * (p @ W2)
    G1 = (G1 - Z.T @ Z) / m
    return [(a1.T @ a1 / m, G1), (a2.T @ a2 / m, G2)]

def entrena(metodo, eta, pasos=200, lam=1e-3):
    P = init()
    m1 = [np.zeros_like(W) for W in P]; v1 = [np.zeros_like(W) for W in P]
    hist = []
    t0 = time.perf_counter()
    for t in range(1, pasos + 1):
        L, gr = loss_grad(P, X, y)
        hist.append(L)
        if metodo == "GD":
            d = gr
        elif metodo == "Adam":
            m1 = [0.9 * a + 0.1 * g for a, g in zip(m1, gr)]
            v1 = [0.999 * a + 0.001 * g * g for a, g in zip(v1, gr)]
            d = [(a / (1 - 0.9**t)) / (np.sqrt(b / (1 - 0.999**t)) + 1e-8) for a, b in zip(m1, v1)]
        else:
            d = kfac_dir(P, gr, X, lam)
        P = [W - eta * di for W, di in zip(P, d)]
        if not np.isfinite(L) or L > 20:
            return np.full(pasos, np.inf), np.nan
    return np.array(hist), (time.perf_counter() - t0) / pasos

def pasos_hasta(hist, objetivo=0.02):
    k = np.flatnonzero(hist <= objetivo)
    return int(k[0]) + 1 if len(k) else None

rejillas = [("GD", "GD", [1, 3, 10]),
            ("Adam, rejilla corta", "Adam", [0.003, 0.01, 0.03]),
            ("Adam, rejilla amplia", "Adam", [0.1, 0.3, 1, 3]),
            ("K-FAC", "K-FAC", [0.1, 0.3, 1])]
for nombre, metodo, etas in rejillas:
    corridas = {e: entrena(metodo, e) for e in etas}
    mejor = min(etas, key=lambda e: corridas[e][0][-1])            # mejor pérdida final de la rejilla
    hist, tps = corridas[mejor]
    borde = " (¡en el borde de la rejilla!)" if mejor in (etas[0], etas[-1]) else ""
    print(f"{nombre:21s} η = {mejor:<5} pérdida en 25/50/100/200: "
          + " ".join(f"{hist[k - 1]:.3f}" for k in (25, 50, 100, 200))
          + f"  pasos hasta 0.02: {pasos_hasta(hist)}  ({1e3 * tps:.2f} ms/paso){borde}")

Read rows two and three before four. With a short grid of “usual” Adam rates (3⋅10−33\cdot 10^{-3} to 3⋅10−23\cdot 10^{-2}, already above default 10−310^{-3}), Adam looks much worse than K-FAC; with a grid enclosing its optimum Adam reaches target before K-FAC (39 versus 59 steps) and each step costs less than half. The cell’s warning (best rate at the grid boundary) is the alarm to look for in every comparison. We return to this in evaluation.

Shampoo: a preconditioner on each side

K-FAC is tied to linear layers and Fisher structure. Shampoo (Gupta, Koren and Singer, 2018) reaches a similar form from online optimization. Full-matrix AdaGrad preconditions with (∑sgsgs⊤)−1/2\big(\sum_s \vb{g}_s\vb{g}_s\T\big)^{-1/2}, with optimal regret but p2p^2 entries. For matrix parameter W∈Rm×n\mat{W} \in \R^{m\times n} with gradients Gs\mat{G}_s, Shampoo accumulates one factor per side.

The correspondence to K-FAC is direct: GG⊤\mat{G}\mat{G}\T sums over inputs and resembles GK-FAC\mat{G}_{\text{K-FAC}} (output side, m×mm\times m); G⊤G\mat{G}\T\mat{G} resembles A\mat{A} (input side, n×nn\times n). Differences: Shampoo uses accumulated batch gradients, not per-example inputs and output gradients, permitting any tensor (hence the name: an order-kk tensor gets kk factors), and uses root −1/4-1/4 per side, so their product is AdaGrad’s root −1/2-1/2.

Why −1/4-1/4? The analysis hinges on a matrix inequality: if each Gs\mat{G}_s has rank at most rr,

∑svec⁡(Gs)vec⁡(Gs)⊤  ⪯  r (Rt1/2⊗Lt1/2),\sum_s \operatorname{vec}(\mat{G}_s)\operatorname{vec}(\mat{G}_s)\T \;\preceq\; r\,\big(\mat{R}_t^{1/2} \otimes \mat{L}_t^{1/2}\big),

and since square root is monotone in Loewner order, (Rt⊗Lt)1/4(\mat{R}_t\otimes\mat{L}_t)^{1/4} dominates full-matrix AdaGrad’s preconditioner up to factor r\sqrt{r}. This transfers AdaGrad’s regret bound to Shampoo (Gupta et al., 2018). One rank-1 gradient is a one-line example: with G=uv⊤\mat{G} = \vb{u}\vb{v}\T, GG⊤=∥v∥2uu⊤\mat{G}\mat{G}\T = \norm{\vb{v}}^2\vb{u}\vb{u}\T, G⊤G=∥u∥2vv⊤\mat{G}\T\mat{G} = \norm{\vb{u}}^2\vb{v}\vb{v}\T, so (G⊤G)1/2⊗(GG⊤)1/2=∥u∥∥v∥ vv⊤∥v∥⊗uu⊤∥u∥=(v⊗u)(v⊗u)⊤(\mat{G}\T\mat{G})^{1/2}\otimes(\mat{G}\mat{G}\T)^{1/2} = \norm{\vb{u}}\norm{\vb{v}}\,\frac{\vb{v}\vb{v}\T}{\norm{\vb{v}}}\otimes\frac{\vb{u}\vb{u}\T}{\norm{\vb{u}}} = (\vb{v}\otimes\vb{u})(\vb{v}\otimes\vb{u})\T: exact equality.

Shampoo without memory is Muon

Proof

L=UΣ2U⊤\mat{L} = \mat{U}\mat{\Sigma}^2\mat{U}\T and R=VΣ2V⊤\mat{R} = \mat{V}\mat{\Sigma}^2\mat{V}\T, so L−1/4=UΣ−1/2U⊤\mat{L}^{-1/4} = \mat{U}\mat{\Sigma}^{-1/2}\mat{U}\T and R−1/4=VΣ−1/2V⊤\mat{R}^{-1/4} = \mat{V}\mat{\Sigma}^{-1/2}\mat{V}\T (plus terms on orthogonal complements, annihilated by G\mat{G}). Multiplication gives UΣ−1/2ΣΣ−1/2V⊤=UV⊤\mat{U}\mat{\Sigma}^{-1/2}\mat{\Sigma}\mat{\Sigma}^{-1/2}\mat{V}\T = \mat{U}\mat{V}\T.

∎

This is exactly Muon’s orthogonalization, spectral-norm steepest descent from the previous lesson (Bernstein and Newhouse, 2024, explicitly observed it). Shampoo and Muon are extremes of one family: Muon forgets all history and equalizes only current gradient singular values; Shampoo accumulates statistics to estimate curvature on each side.

The price: inverse matrix roots

Every kk steps compute L−1/4\mat{L}^{-1/4} and R−1/4\mat{R}^{-1/4}. With eigendecomposition L=QΛQ⊤\mat{L} = \mat{Q}\mat{\Lambda}\mat{Q}\T the root is QΛ−1/4Q⊤\mat{Q}\mat{\Lambda}^{-1/4}\mat{Q}\T, costing about 9m39m^3 operations for symmetric decomposition with vectors (Golub and Van Loan) and parallelizing poorly on GPU. Three practical consequences:

  • Precision. Eigenvalues of L\mat{L} span many orders of magnitude and λ−1/4\lambda^{-1/4} amplifies small ones. In bfloat16, with 8 mantissa bits (relative error 2−8≈0.4 %2^{-8} \approx 0.4\,\%), an eigenvalue 10−410^{-4} times smaller than the largest is below its rounding error and its inverse root is garbage. Compute roots in float32 or float64 with relative damping L+ε λmax⁡I\mat{L} + \eps\,\lambda_{\max}\mat{I}.
  • Scale. Anil et al. (2020) made Shampoo practical at scale: roots computed asynchronously on CPU (with coupled Newton iteration), refreshed every few hundred steps, large matrices split into blocks, and update magnitude borrowed from AdaGrad or Adam (grafting) to avoid tuning a new rate. PyTorch Distributed Shampoo (Shi et al., 2023) won AlgoPerf.
  • Frequency. Between recalculations the preconditioner is stale. This is Shampoo’s main instability source and the problem SOAP addresses.

For layer d×dd\times d with BB tokens per batch, forward and backward cost about 6d2B6d^2B operations; Shampoo adds 8d38d^3 per step (statistics and application) plus 20d3/k20d^3/k (roots). Relative overhead is O(d/B)\bigO(d/B): negligible in LLM pretraining (BB of hundreds of thousands of tokens) and prohibitive for small batches. The zoo interactive quantifies it below.

SOAP: Adam in Shampoo’s eigenbasis

Vyas et al. (2024) observed an equivalence reorganizing the landscape. Take Shampoo with exponent −1/2-1/2 per side (instead of −1/4-1/4) and write L=QLΛLQL⊤\mat{L} = \mat{Q}_L\mat{\Lambda}_L\mat{Q}_L\T, R=QRΛRQR⊤\mat{R} = \mat{Q}_R\mat{\Lambda}_R\mat{Q}_R\T. With rotated gradient G′=QL⊤GQR\mat{G}' = \mat{Q}_L\T\mat{G}\mat{Q}_R,

L−1/2GR−1/2=QL(Gij′λL,i λR,j)ijQR⊤.\mat{L}^{-1/2}\mat{G}\mat{R}^{-1/2} = \mat{Q}_L\Big(\frac{G'_{ij}}{\sqrt{\lambda_{L,i}\,\lambda_{R,j}}}\Big)_{ij}\mat{Q}_R\T.

In the rotated basis each entry is divided by the square root of a “row times column” product. And λL,i=(QL⊤LQL)ii=∑jE[Gij′2]\lambda_{L,i} = (\mat{Q}_L\T\mat{L}\mat{Q}_L)_{ii} = \sum_j \E[G'^2_{ij}], λR,j=∑iE[Gij′2]\lambda_{R,j} = \sum_i \E[G'^2_{ij}] are row and column sums of the rotated second moment. Estimating E[Gij′2]≈λL,iλR,j/∑iλL,i\E[G'^2_{ij}] \approx \lambda_{L,i}\lambda_{R,j}/\sum_i\lambda_{L,i} is exactly Adafactor’s rank-1 factorization. Shampoo (with −1/2-1/2) is Adafactor in Shampoo’s eigenbasis, up to a scalar.

SOAP (ShampoO with Adam in the Preconditioner’s eigenbasis) takes the obvious step: in that basis use Adam’s entrywise second moment instead of Adafactor’s factored one.

The advantages are practical. Second moment updates each step even if the basis is recomputed every kk, so the preconditioner is never completely stale; SOAP is much less sensitive to kk than Shampoo and adds only that hyperparameter to Adam’s. Its authors report over 40 % fewer iterations and over 35 % less time than AdamW, and around 20 % versus Shampoo, in 360- and 660-million-parameter language-model pretraining and the large-batch regime. EKFAC already had the idea: precondition with diagonal moments in Kronecker factors’ eigenbasis.

The full map fits in a table:

MethodPreconditioning basisScalingExtra state (layer m×nm\times n)
Adamcanonical axes1/E[g2]1/\sqrt{\E[g^2]} per entry2mn2mn
Muoncurrent momentum singular vectorsequalizes all singular valuesmnmn
Shampooeigenbases of L\mat{L}, R\mat{R}λL−1/4λR−1/4\lambda_L^{-1/4}\lambda_R^{-1/4} (rank 1)2(m2+n2)+mn2(m^2 + n^2) + mn
SOAPeigenbases of L\mat{L}, R\mat{R}1/E[g′2]1/\sqrt{\E[g'^2]} per entry (Adam)2(m2+n2)+2mn2(m^2 + n^2) + 2mn
K-FACeigenbases of A\mat{A}, G\mat{G}inverse factored Fisher2(m2+n2)2(m^2 + n^2)

In the last column, matrix methods store factors and what is applied between recomputations (inverse roots, eigenbases or inverses); Adam grafting, if used, adds another 2mn2mn.

InteractivePreconditioner zoo
Relative loss Lt/L0L_t / L_0 with the best η\eta for each method; target 10−310^{-3}
Tuning each method’s rate…
Method
Best η
Steps
Per step
Total
SGD+m
…
…
…
…
Adam
…
…
…
…
Shampoo
…
…
…
…
SOAP
…
…
…
…
Muon
…
…
…
…
Curvature
100
100
0.00
0.0000
Cost per step
10
4096
16 k
Horizontal axis
Winner by iterations…
Winner by total cost…
Calculating…
Quadratic in W∈R6×8\mat{W}\in\R^{6\times 8} with Hessian (1−δ) A⊗G+δ A2⊗G2(1-\delta)\,\mat{A}\otimes\mat{G} + \delta\,\mat{A}_2\otimes\mat{G}_2. Each method uses its best η\eta from a logarithmic grid for ‘steps to divide loss by 1000’ (time to target). Raise both side condition numbers: SGD stops reaching target and Shampoo and SOAP win by much. Align bases with axes: Adam catches SOAP because SOAP is Adam in the right basis. Muon equalizes momentum singular values but sees no curvature. Switch to ‘Cost’ and lower BB: for small batches cheap methods lead at equal compute and at moderate condition reach target earlier too.

Three conclusions to check. First, with ill-conditioned rotated Kronecker curvature (default κA=κG=100\kappa_A = \kappa_G = 100), momentum SGD, Adam and Muon miss target in 400 steps, whereas Shampoo and SOAP reach it in under 100. Muon is instructive: equalizing momentum singular values is not inverting curvature. Second, with bases axis-aligned, Adam’s diagonal is already the right preconditioner and SOAP’s advantage vanishes; matrix methods’ advantage is precisely rotating into the right basis. Third, per-step cost depends on d/Bd/B. With d=4096d = 4096 and B=16 384B = 16\,384 tokens, Shampoo costs 42 % more per step than AdamW; with BB of half a million, 1.3 %. “X times faster in iterations” means nothing without that factor.

The same comparison from scratch on multi-output regression whose weighted loss has Hessian exactly Σx⊗Σy\mat{\Sigma}_x\otimes\mat{\Sigma}_y, with stochastic gradients from batches of 32:

[ ]Shampoo, SOAP and Muon from scratchBrowser
import time
import numpy as np

def raiz_inversa(S, p, rel=1e-6):
    """S^(-1/p) de una simétrica semidefinida, con amortiguamiento relativo al mayor autovalor."""
    w, Q = np.linalg.eigh(S)
    w = np.maximum(w, 0) + rel * max(w.max(), 1e-30)
    return (Q * w ** (-1 / p)) @ Q.T

# 0) Shampoo sin acumulación (una sola G) es la ortogonalización de Muon
r = np.random.default_rng(0)
Gm = r.normal(size=(6, 9))
U, s, Vt = np.linalg.svd(Gm, full_matrices=False)
sh = raiz_inversa(Gm @ Gm.T, 4, 1e-12) @ Gm @ raiz_inversa(Gm.T @ Gm, 4, 1e-12)
print("L^(-1/4) G R^(-1/4) = U Vᵀ:", np.allclose(sh, U @ Vt, atol=1e-5))

# 1) regresión multisalida con pérdida ponderada: hessiana exactamente Σ_x ⊗ Σ_y
m, d, n = 6, 10, 4000
KX, KY = 100, 30                                       # condición de cada lado: prueba 3, 3
def espd(k, kappa, seed):
    Q, _ = np.linalg.qr(np.random.default_rng(seed).normal(size=(k, k)))
    return Q @ np.diag(np.logspace(0, -np.log10(kappa), k)) @ Q.T
Sx, Sy = espd(d, KX, 1), espd(m, KY, 2)
Xd = np.random.default_rng(3).multivariate_normal(np.zeros(d), Sx, size=n)
Wv = np.random.default_rng(4).normal(size=(m, d))
Yd = Xd @ Wv.T + 0.05 * np.random.default_rng(5).normal(size=(n, m))
W_opt = np.linalg.lstsq(Xd, Yd, rcond=None)[0].T
Sx_hat = Xd.T @ Xd / n
def exceso(W):                                            # pérdida − mínima = ½ tr(Δ Σ̂x Δᵀ Σy), exacto
    D = W - W_opt
    return 0.5 * np.sum((Sy @ D) * (D @ Sx_hat))

# punto de partida difícil: el error inicial reparte la pérdida por igual entre las m·d direcciones propias
wx, Qx = np.linalg.eigh(Sx_hat); wy, Qy = np.linalg.eigh(Sy)
signos = np.sign(np.random.default_rng(6).normal(size=(m, d)))
W_ini = W_opt + Qy @ (signos / np.sqrt(np.outer(wy, wx))) @ Qx.T

def newton_schulz(M, pasos=5):
    X = M / (np.linalg.norm(M) + 1e-12)
    for _ in range(pasos):
        A = X @ X.T
        X = 3.4445 * X + (-4.7750 * A + 2.0315 * A @ A) @ X
    return X

def optimiza(nombre, eta, pasos=400, B=32, k=10, objetivo=1e-3, seed=0):
    r = np.random.default_rng(seed)
    W = W_ini.copy(); M = np.zeros_like(W); V = np.zeros_like(W)
    L, R = np.zeros((m, m)), np.zeros((d, d))
    L0 = exceso(W)
    for t in range(1, pasos + 1):
        idx = r.integers(0, n, B)
        E = Xd[idx] @ W.T - Yd[idx]
        g = Sy @ E.T @ Xd[idx] / B                        # gradiente estocástico: Σ_y Eᵀ X / B
        if nombre == "SGD+m":
            M = 0.9 * M + g; U = M
        elif nombre == "Adam":
            M = 0.9 * M + 0.1 * g; V = 0.99 * V + 0.01 * g * g
            U = (M / (1 - 0.9**t)) / (np.sqrt(V / (1 - 0.99**t)) + 1e-8)
        elif nombre == "Muon":
            M = 0.9 * M + g; U = newton_schulz(M)
        else:                                             # Shampoo y SOAP comparten estadísticas
            L = 0.99 * L + 0.01 * g @ g.T; R = 0.99 * R + 0.01 * g.T @ g
            M = 0.9 * M + 0.1 * g
            if t == 1 or t % k == 0:
                if nombre == "Shampoo":
                    PL, PR = raiz_inversa(L, 4, 1e-4), raiz_inversa(R, 4, 1e-4)
                else:
                    QL, QR = np.linalg.eigh(L)[1], np.linalg.eigh(R)[1]
            if nombre == "Shampoo":
                U = PL @ M @ PR
            else:                                         # SOAP: Adam en la base propia de L y R
                gr = QL.T @ g @ QR
                V = 0.99 * V + 0.01 * gr * gr
                U = QL @ ((QL.T @ M @ QR) / (np.sqrt(V / (1 - 0.99**t)) + 1e-8)) @ QR.T
        W = W - eta * U
        rel = exceso(W) / L0
        if not np.isfinite(rel) or rel > 1e3:
            return None
        if rel < objetivo:
            return t
    return None

rejillas = {nombre: np.logspace(-2.5, 1, 8) for nombre in ["SGD+m", "Adam", "Shampoo", "SOAP", "Muon"]}
t0 = time.perf_counter()
for nombre, etas in rejillas.items():
    res = [(optimiza(nombre, e), e) for e in etas]
    ok = [(t, e) for t, e in res if t is not None]
    if ok:
        t, e = min(ok)
        print(f"{nombre:8s} mejor η = {e:.3g}: {t} pasos hasta reducir el exceso de pérdida 1000 veces")
    else:
        print(f"{nombre:8s} no llega en 400 pasos con ningún η de la rejilla")
print(f"(tiempo total: {time.perf_counter() - t0:.1f} s)")

In the browser SOAP reaches target in 87 steps, Shampoo in 203 and Adam in 228 (the lab Python changes figures slightly because data and eigenbases use different LAPACK routines, but not order); momentum SGD and Muon miss target in 400. The first line numerically checks one-step Shampoo’s theorem. Change KX, KY to 3, 3 and well-conditioned differences nearly vanish, with SOAP even behind: its advantage is curvature, not general magic.

Stochastic diagonal curvature: Sophia

Another line abandons bases and returns to a diagonal, but the Hessian’s (or Gauss–Newton’s), not squared gradients as in Adam. Sophia (Liu et al., 2023) is the best-known example. It needs a cheap estimator of diag⁡(H)\diag(\mat{H}); two classical ones exist.

Proof

Hutchinson: (u⊙Hu)i=∑jHijuiuj(\vb{u}\odot\mat{H}\vb{u})_i = \sum_j H_{ij}u_iu_j, and E[uiuj]=δij\E[u_iu_j] = \delta_{ij}. Gauss–Newton–Bartlett: Bartlett’s identity gives Ey^[∇ℓ(θ;x,y^)]=0\E_{\hat y}[\nabla\ell(\theta;\vb{x},\hat y)] = \vb{0}, so the BB summands are independent and centered, and E[g^g^⊤]=1B2∑bE[∇ℓb∇ℓb⊤]=1BF\E[\hat{\vb{g}}\hat{\vb{g}}\T] = \frac{1}{B^2}\sum_b \E[\nabla\ell_b\nabla\ell_b\T] = \frac{1}{B}F. Take the diagonal and multiply by BB.

∎

Sophia estimates ht\vb{h}_t with one of these every k=10k = 10 steps and smooths it with a moving average, maintains gradient momentum mt\vb{m}_t, and updates

θt+1=θt−ηt clip⁡(mtmax⁡(γ ht,ε), 1),\theta_{t+1} = \theta_t - \eta_t\,\operatorname{clip}\Big(\frac{\vb{m}_t}{\max(\gamma\,\vb{h}_t, \eps)},\,1\Big),

with entrywise clipping clip⁡(z,1)=max⁡(−1,min⁡(1,z))\operatorname{clip}(z, 1) = \max(-1, \min(1, z)). This is a diagonal Newton step where curvature is reliable and a sign step of size η\eta (like sign descent) where estimated curvature is small, negative or noisy: clipping bounds each coordinate’s step. Hutchinson’s estimator may return negative entries; GNB cannot by construction.

[ ]Hessian diagonal: Hutchinson and GNBBrowser
import numpy as np

# regresión softmax lineal: la hessiana es (1/n) Σ (x xᵀ) ⊗ (diag p − p pᵀ) y coincide con la de Gauss-Newton
r = np.random.default_rng(0)
n, d, K = 2000, 8, 4
X = r.normal(size=(n, d)) * np.logspace(0, -1.5, d)            # rasgos de escalas muy distintas
Wv = r.normal(size=(K, d)) * 3
y = np.array([r.choice(K, p=q) for q in np.exp(X @ Wv.T) / np.exp(X @ Wv.T).sum(1, keepdims=True)])
W = 0.5 * Wv                                                    # un punto intermedio del entrenamiento

def probs(W, Xb):
    s = Xb @ W.T
    p = np.exp(s - s.max(1, keepdims=True))
    return p / p.sum(1, keepdims=True)

P = probs(W, X)
# diagonal exacta: H[(k,i),(k,i)] = mean_n x_i² p_k (1 − p_k)
diag_exacta = (P * (1 - P)).T @ (X**2) / n                       # forma K × d, como W

def hvp(V):                                                     # H v sin formar H: (1/n) Σ_n (S_n V x_n) x_nᵀ
    U = X @ V.T                                                 # n × K
    SU = P * U - P * (P * U).sum(1, keepdims=True)              # (diag p − ppᵀ) u, ejemplo a ejemplo
    return SU.T @ X / n

def hutchinson(k):
    acc = np.zeros_like(W)
    for _ in range(k):
        u = r.choice([-1.0, 1.0], size=W.shape)                 # Rademacher: E[u uᵀ] = I
        acc += u * hvp(u)
    return acc / k

def gnb(k, B=256):                                              # Gauss-Newton-Bartlett de Sophia
    acc = np.zeros_like(W)
    for _ in range(k):
        idx = r.integers(0, n, B)
        Pb = P[idx]
        yhat = (Pb.cumsum(1) > r.random((B, 1))).argmax(1)      # etiquetas muestreadas del propio modelo
        G = Pb.copy(); G[np.arange(B), yhat] -= 1
        g = G.T @ X[idx] / B                                    # gradiente del lote con esas etiquetas
        acc += B * g * g
    return acc / k

rel = lambda est: np.linalg.norm(est - diag_exacta) / np.linalg.norm(diag_exacta)
for k in (1, 10, 100):
    print(f"{k:4d} muestras: error relativo Hutchinson {rel(hutchinson(k)):.3f}   GNB {rel(gnb(k)):.3f}")
print("¿alguna entrada negativa en Hutchinson con 1 muestra?", bool((hutchinson(1) < 0).any()))

# el paso de Sophia: recorte por coordenada de m / max(γ h, ε)
m_grad = (P - np.eye(K)[y]).T @ X / n                          # el gradiente completo hace de momento
h = gnb(10)
for gamma in (0.01, 0.1, 1.0):
    paso = np.clip(m_grad / np.maximum(gamma * h, 1e-12), -1, 1)
    print(f"γ = {gamma:<4}: {np.mean(np.abs(paso) == 1):.0%} de las coordenadas recortadas (paso de signo)")

With one sample the two estimators have errors around 60 % and 110 %, and Hutchinson gives negative entries; averaging helps as 1/k1/\sqrt{k}, which Sophia gets free via the moving average. The last part shows γ\gamma‘s effect: with small γ\gamma almost all coordinates clip and Sophia is momentum sign descent; with large γ\gamma it resembles diagonal Newton.

Does it work? The authors report 2× acceleration over AdamW in steps, compute and time on GPT models from 125 million to 1500 million parameters. Independent evaluations were less favorable: Kaddour et al. (2023) found Lion and Sophia gains vanish under fixed compute and a fully decayed baseline rate; Zhao et al. (2024) found Adam, Adafactor, Lion and Sophia comparable when each is carefully tuned; and Sophia was not among the fastest in Wen et al. (2025). Sophia exemplifies a sound idea (safeguarded diagonal curvature) with disputed empirical results.

Schedule-free: averaging without a known horizon

Nearly all serious training uses a learning-rate schedule: warmup followed by cosine or linear decay to zero. Decay works well but requires fixing total step count TT in advance. If training is extended the cosine has already decayed and must restart; if stopped early the intermediate model is worse than a cosine tuned for that point. Polyak–Ruppert iterate averaging needs no TT, but lags in deep networks because it carries poor early iterates.

Defazio et al. (2024) combine the ideas with three sequences.

Both extremes are familiar. With β=0\beta = 0, yt=zty_t = z_t: constant-step SGD with Polyak–Ruppert average as output. With β=1\beta = 1, yt=xty_t = x_t: gradient evaluated at the average itself, called primal averaging. This extreme’s guarantee has a short instructive proof showing where “anytime” comes from.

Proof

By the average’s definition, t xt=(t−1) xt−1+ztt\,x_t = (t-1)\,x_{t-1} + z_t, i.e. zt−xt=(t−1)(xt−xt−1)z_t - x_t = (t-1)(x_t - x_{t-1}). Then

⟨gt,zt−x⋆⟩=⟨gt,xt−x⋆⟩+(t−1)⟨gt,xt−xt−1⟩≥(f(xt)−f(x⋆))+(t−1)(f(xt)−f(xt−1)),\inner{\vb{g}_t}{z_t - x^\star} = \inner{\vb{g}_t}{x_t - x^\star} + (t-1)\inner{\vb{g}_t}{x_t - x_{t-1}} \ge \big(f(x_t) - f(x^\star)\big) + (t-1)\big(f(x_t) - f(x_{t-1})\big),

using convexity inequality f(w)≥f(xt)+⟨gt,w−xt⟩f(w) \ge f(x_t) + \inner{\vb{g}_t}{w - x_t} twice, with w=x⋆w = x^\star and w=xt−1w = x_{t-1}. The right side is t (f(xt)−f⋆)−(t−1)(f(xt−1)−f⋆)t\,(f(x_t) - f^\star) - (t-1)(f(x_{t-1}) - f^\star), a telescoping sum: summing from t=1t = 1 to TT gives T (f(xT)−f⋆)T\,(f(x_T) - f^\star). For the second part, standard online gradient descent analysis gives ∑t⟨gt,zt−x⋆⟩≤∥z1−x⋆∥22γ+γ2∑t∥gt∥2\sum_t\inner{\vb{g}_t}{z_t - x^\star} \le \frac{\norm{z_1 - x^\star}^2}{2\gamma} + \frac{\gamma}{2}\sum_t\norm{\vb{g}_t}^2 (expand ∥zt+1−x⋆∥2\norm{z_{t+1} - x^\star}^2 and sum).

∎

The first part matters: the bound holds for every TT along the same sequence without the algorithm knowing when we stop. The second is more modest than it looks: rate DG/TDG/\sqrt{T} uses TT to choose γ\gamma, and with fixed γ\gamma the bound at tt is D2/(2γt)+γG2/2D^2/(2\gamma t) + \gamma G^2/2, plateauing at γG2/2\gamma G^2/2 (with γt∝1/t\gamma_t \propto 1/\sqrt{t} and projection onto a bounded domain the rate is recovered without knowing TT, up to constants). Averaging saves horizon-specific decay, not choice of step scale. This is Cutkosky’s (2019) conversion; the second part connects it to online convex optimization regret. Defazio et al. prove that for convex ff and GG-Lipschitz, schedule-free attains E[f(xT)−f⋆]≤DG/T\E[f(x_T) - f^\star] \le DG/\sqrt{T} for any β∈[0,1]\beta \in [0, 1], the optimal worst-case rate. Their practical β=0.9\beta = 0.9 choice is experimental, not theoretical: evaluating gradients near the average stabilizes large-step dynamics and makes xtx_t closely follow a tuned cosine.

InteractiveWithout a learning-rate schedule
One realization: ztz_t (gradient), yty_t (evaluation), xtx_t (average)
  • ztz_t
  • yty_t
  • xtx_t
Expected error E[f]−f⋆\E[f] - f^\star (exact), logarithmic scales
  • schedule-free, xtx_t
  • cosine, T=100T = 100
  • cosine, T=300T = 300
  • cosine, T=1000T = 1000
  • Constant SGD, η=γ\eta = \gamma
t = 1000
1.20
0.50
Schedule-free: E[f(xt)]−f⋆\E[f(x_t)] - f^\star4.24e−3
Cosine T=100T = 1000.0443
Cosine T=300T = 3000.0161
Cosine T=1000T = 10005.18e−3
Constant SGD0.2643
At t=1000t = 1000, schedule-free error is ×0.82\times0.82 that of the best of the three cosines, without fixing any horizon.
Noisy quadratic with curvatures 1 and 0.04. Left, one realization of the three sequences: ztz_t jumps with noise, xtx_t is its average and yty_t lies between. Right, exact expected error (propagated mean and covariance, no sampling) for schedule-free versus three cosines tuned to end at T=100T = 100, 300300 and 10001000. Each cosine is good only at its horizon; schedule-free stays near their envelope throughout. Pause at any tt and compare readings. Set β\beta to 0.9 or more: the mean oscillates around the minimum and error worsens for any γ\gamma.

On a noisy quadratic averaging alone is already very good: Bach and Moulines’s (2013) result for constant-step averaged SGD in least squares. Thus a moderate β\beta works well with large γ\gamma in the figure, and β\beta near 1 is worse for any γ\gamma: gradient is evaluated near a slowly moving average, ztz_t overshoots, and the average oscillates. In deep networks, where a uniform average carries poor iterates from a nonconvex phase, β=0.9\beta = 0.9 gives schedule-free its advantage. The cell reproduces the comparison with linear regression using batches of 8 and four seeds in parallel:

[ ]Schedule-free versus horizon-tuned cosinesBrowser
import numpy as np

# regresión lineal con ruido: f(w) = E[½ (xᵀw − y)²], gradientes con lotes de 8
r0 = np.random.default_rng(0)
d = 20
escalas = np.logspace(0, -1.3, d)
w_true = r0.normal(size=d)
S = 4                                             # semillas, simuladas en paralelo (una fila cada una)
def exceso(w):                                    # f(w) − f(w*) exacto por semilla: ½ Σ escala² (w − w*)²
    return 0.5 * np.sum((escalas * (w - w_true)) ** 2, axis=-1)
def grad(w, r, B=8):                              # w: S × d; un lote de B ejemplos por semilla
    X = r.normal(size=(S, B, d)) * escalas
    yv = X @ w_true + 0.5 * r.normal(size=(S, B))
    return np.einsum("sbd,sb->sd", X, np.einsum("sbd,sd->sb", X, w) - yv) / B

def sgd_coseno(eta0, T, Tmax, r):
    w = np.zeros((S, d)); out = []
    for t in range(1, Tmax + 1):
        eta = eta0 * 0.5 * (1 + np.cos(np.pi * (t - 1) / T)) if t <= T else 0.0
        w = w - eta * grad(w, r)
        out.append(exceso(w).mean())
    return np.array(out)

def schedule_free(gamma, beta, Tmax, r):
    z = np.zeros((S, d)); x = np.zeros((S, d)); out = []
    for t in range(1, Tmax + 1):
        y = (1 - beta) * z + beta * x             # punto donde se evalúa el gradiente
        z = z - gamma * grad(y, r)                # paso de SGD con tasa constante
        c = 1 / (t + 1)
        x = (1 - c) * x + c * z                   # promedio uniforme de los z
        out.append(exceso(x).mean())
    return np.array(out)

Tmax = 1000
paradas = [100, 300, 1000]
media = lambda f: f(np.random.default_rng(0))     # media sobre las S semillas

filas = {}
for T in paradas:                                  # cada coseno con su mejor η₀ para terminar en T
    mejor = min(((media(lambda r: sgd_coseno(e, T, Tmax, r)), e) for e in (0.6, 1.2, 2.4)), key=lambda c: c[0][T - 1])
    filas[f"coseno T={T} (η₀={mejor[1]})"] = mejor[0]
sf = media(lambda r: schedule_free(1.2, 0.5, Tmax, r))
filas["schedule-free (γ=1.2, β=0.5)"] = sf
filas["SGD constante (η=1.2)"] = media(lambda r: sgd_coseno(1.2, 10**9, Tmax, r))

print(f"{'exceso de pérdida en t =':34s}" + "".join(f"{t:>10d}" for t in paradas))
for nombre, curva in filas.items():
    print(f"{nombre:34s}" + "".join(f"{curva[t - 1]:10.4f}" for t in paradas))

Each cosine is best of the three at its own horizon and poor at others: at t=100t = 100, T=1000T = 1000‘s error is about eight times T=100T = 100‘s, and the latter no longer improves, so at t=1000t = 1000 its error exceeds the long cosine’s by over tenfold. Schedule-free is best in the table at all three times without knowing any. Constant-step SGD without averaging stalls at the noise floor.

Practice uses Schedule-Free AdamW: the zz step is Adam’s (division by vt\sqrt{\vb{v}_t}), warmup is used, average weights are ct+1=γt2/∑s≤tγs2c_{t+1} = \gamma_t^2/\sum_{s\le t}\gamma_s^2 so warmup steps count little, and weight decay is evaluated at yty_t. Two engineering details: model parameters store yty_t during training and must switch to xtx_t for evaluation (official implementation: optimizer.eval() and optimizer.train()), and BatchNorm statistics are computed at yty_t, so recompute them at xtx_t before evaluation.

Rigorous evaluation: what “faster” means

With methods on the table, how do we decide which is better? Choi et al. (2019) made a simple observation with large consequences. Optimizers form an inclusion hierarchy: SGD is momentum with β=0\beta = 0; momentum is the limit of Adam with very large ε\eps (if ε≫v\eps \gg \sqrt{v}, Adam’s step is η m/ε\eta\,\vb{m}/\eps: momentum as a moving average at rate η/ε\eta/\eps). If all hyperparameters are tuned, a more general method cannot lose to a special case. Yet literature was full of momentum SGD beating Adam: tuning protocol made the difference, not the optimizer. Schmidt, Schneider and Hennig (2021) compared 15 optimizers on 8 problems in about 50 000 runs, finding none dominant overall; trying several default optimizers did roughly as well as thoroughly tuning one.

AlgoPerf (Dahl et al., 2023; MLCommons) is the reference implementation. It has eight fixed workloads (image with ResNet-50 and ViT, MRI with U-Net, speech with Conformer and DeepSpeech, translation with Transformer, molecular graphs with a GNN, recommendation with DLRM on Criteo 1TB) and randomized variants revealed after submission. Validation targets come from well-tuned baselines; wall time is measured on fixed hardware (8 V100 GPUs in the first competition). Two tracks: with external tuning, each submission declares a workload-independent search space; the first competition ran five studies of five trials, taking each study’s fastest trial and the median of studies. With self-tuning, no external tuning was allowed and the time budget was triple (Kasimbeg et al., 2025). Later rules changed these numbers (three studies, 1.5× self-tuning budget, different hardware); the structure remains. Times are aggregated with performance profiles: if ts,wt_{s,w} is submission ss‘s time on workload ww, rs,w=ts,w/min⁡s′ts′,wr_{s,w} = t_{s,w}/\min_{s'}t_{s',w} and

ρs(τ)=1∣W∣ #{w:rs,w≤τ},\rho_s(\tau) = \frac{1}{\abs{W}}\,\#\{w : r_{s,w} \le \tau\},

the fraction of workloads on which ss is at most τ\tau times slower than the best. Score is normalized area under ρs\rho_s between τ=1\tau = 1 and τ=4\tau = 4. A submission failing a workload (r=∞r = \infty) loses that portion for every τ\tau.

InteractiveTuning budget changes the winner
Expected validation loss of the best of KK random trials (lower is better)
Search space
6
0.0040
Display
SGD with momentum: best of 6…
Adam: best of 6…
Method X: best of 6…
Best to worst at this KK…
X overtakes Adam fromnever (K ≤ 256)
The same wide space for all methods. With few trials the method with the widest valley wins; with many, the one with the best optimum.
Synthetic response surfaces (validation loss against log-scale hyperparameters) for momentum SGD (2 hyperparameters), Adam (4), and new method ‘X’ with the best optimum but a narrow valley. The curve is expected loss of the best of KK random trials, calculated exactly over a pool of 4000 configurations. With a wide space, X needs many trials to beat Adam; with the ‘as in paper’ space (narrow for X, wide for baselines), it wins with few. Under ‘Winner’s bias’, the dashed line is what selecting with one seed observes, the solid line that same configuration on other seeds: the gap grows with KK.

The interactive reproduces three arguments. Ranking depends on KK: few trials favor the broadest valley, many favor the best optimum (Sivaprasad et al., 2020, use this to explain Adam’s practical appeal). Ranking depends on search space, and giving one’s own method a narrower space effectively gives it free trials (Choi et al.). Finally, choosing the minimum of KK noisy values biases the reported value downward: winner’s bias. Honest correction is to reevaluate the chosen configuration with new seeds, as in multi-seed evaluation.

The next cell computes medians, a bootstrap percentile interval for speedup and performance-profile score on synthetic timings for three algorithms, four workloads and five seeds.

[ ]Time to target, bootstrap and performance profilesBrowser
import numpy as np
import matplotlib.pyplot as plt

# Datos SINTÉTICOS con forma realista: tiempo (en horas) hasta alcanzar el objetivo de validación,
# 3 algoritmos × 4 workloads × 5 semillas; inf = no lo alcanza dentro del presupuesto.
r = np.random.default_rng(7)
algos = ["AdamW", "Candidato A", "Candidato B"]
workloads = ["imagen", "texto", "habla", "grafos"]
base = np.array([[10.0, 20.0, 15.0, 6.0],      # mediana real de cada algoritmo en cada workload
                 [8.0, 17.0, 14.0, 7.5],
                 [6.5, 30.0, 11.0, 5.0]])
fallos = np.array([[0.0, 0.0, 0.0, 0.0],        # probabilidad de no llegar (inestabilidad)
                   [0.0, 0.0, 0.1, 0.0],
                   [0.0, 0.6, 0.0, 0.2]])
semillas = 5
t = base[:, :, None] * np.exp(0.08 * r.normal(size=(3, 4, semillas)))
t[r.random(t.shape) < fallos[:, :, None]] = np.inf

# 1) puntuación por workload: mediana sobre semillas (robusta a una semilla mala; inf si fallan la mayoría)
med = np.median(t, axis=2)
print("mediana de horas hasta el objetivo:")
for a, fila in zip(algos, med):
    print(f"  {a:12s}" + "".join(f"{v:9.1f}" for v in fila))

# 2) intervalo bootstrap del cociente de medianas frente a AdamW en un workload
def ic_cociente(x, y, B=4000, rr=np.random.default_rng(1)):
    xs = rr.choice(x, size=(B, len(x))); ys = rr.choice(y, size=(B, len(y)))
    q = np.median(xs, 1) / np.median(ys, 1)
    q = q[np.isfinite(q)]
    return np.percentile(q, [2.5, 97.5])
for i in (1, 2):
    lo, hi = ic_cociente(t[0, 0], t[i, 0])
    print(f"aceleración de {algos[i]} en «imagen» (AdamW / {algos[i]}): {med[0, 0] / med[i, 0]:.2f}, IC 95 % bootstrap [{lo:.2f}, {hi:.2f}]")

# 3) perfiles de rendimiento y puntuación tipo AlgoPerf (área normalizada hasta τ = 4)
ratio = med / med.min(axis=0)                      # r_{s,w} = t_{s,w} / mejor t_w
taus = np.linspace(1, 4, 601)
perfil = np.array([[np.mean(ratio[s] <= tau) for tau in taus] for s in range(3)])
trapecio = getattr(np, "trapezoid", None) or np.trapz        # numpy 2 renombró trapz
puntuacion = trapecio(perfil, taus, axis=1) / (taus[-1] - taus[0])
for a, p in zip(algos, puntuacion):
    print(f"puntuación de {a}: {p:.3f}")

for s, a in enumerate(algos):
    plt.step(taus, perfil[s], where="post", label=f"{a} ({puntuacion[s]:.2f})")
plt.xlabel("τ (veces más lento que el mejor en ese workload)")
plt.ylabel("fracción de workloads con r ≤ τ")
plt.ylim(-0.02, 1.02); plt.legend(); plt.show()

Candidate B is fastest on two of four workloads and nearly ties the best on a third (“graphs”), with up to 1.5× speedups and a confidence interval excluding 1, but fails “text” on most seeds and finishes last in aggregate score. More modest candidate A narrowly beats AdamW. AlgoPerf’s lesson: in the first competition many submissions fast on some workloads failed others, and cross-workload robustness mattered as much as speed.

Measuring time honestly

Time to target requires correct timing, easy to get wrong on GPU: kernels launch asynchronously, so without synchronization before reading the clock one measures enqueueing, not compute. Standard benchmarking methodology applies: warmup, repetitions, median, excluding nontraining work (evaluation in AlgoPerf). Memory also costs: SOAP stores 2(m2+n2)+2mn2(m^2 + n^2) + 2mn numbers per layer versus Adam’s 2mn2mn, and a large model may require smaller batches. Measure using memory profiling, not theoretical counts, because roots and decompositions create temporaries.

Critically reading an optimizer paper

Questions to ask of any result in the area:

  1. Iterations or time? If the method costs ×1.5\times 1.5 per step, 30 % fewer iterations loses in time. Find measured wall time or at least measured per-step cost.
  2. How were baselines tuned? Defaults, hyperparameters copied from a different model, or a grid whose optimum hits its edge signal weak baselines. Equal declared budgets are needed.
  3. What schedule does the baseline use? Much “optimizer” improvement vanishes when baseline rate decays to zero at the correct horizon (Kaddour et al., 2023). Intermediate training comparisons mislead: rankings reverse as rates decay (Wen et al., 2025).
  4. How many seeds and what intervals? A 2 % difference on one seed is not a result.
  5. How many workloads, selected before or after? One architecture and dataset say little about the next.
  6. At what scale? Best matrix-method speedups shrink from about 1.4× at 0.1 billion parameters to about 1.1× at 1.2 billion (Wen et al., 2025). Optimal hyperparameters shift with width unless using a transfer-preserving parameterization like μP (Yang et al., 2022).
  7. Are code and configurations available? If it cannot be reproduced, it cannot be believed.

These questions are not gratuitous skepticism. The Adam versus SGD debate lasted years partly because comparisons ignored them.

Lab: Shampoo, K-FAC and mini AlgoPerf in PyTorch

The next two cells run on your machine, sized for under a minute on CPU; on GPU increase H, B and PASOS to expose cost differences. The first implements Shampoo (float64 roots, relative damping and Adam-norm grafting) and K-FAC (an extra backward pass with labels sampled from the model to estimate true Fisher), comparing them with AdamW and previous-lesson Muon in time per step and memory.

[ ]Miniature Shampoo and K-FAC (PyTorch)Local GPU
import time, warnings, torch, torch.nn as nn, torch.nn.functional as F

warnings.filterwarnings("ignore", message="Full backward hook")

torch.manual_seed(0)
torch.set_num_threads(2)
device = "cuda" if torch.cuda.is_available() else "cpu"
D_IN, H, C, B, PASOS = 32, 128, 10, 128, 150

# tarea: imitar a una red «maestra» aleatoria (las etiquetas son su argmax), entradas con escalas desiguales
maestra = nn.Sequential(nn.Linear(D_IN, 128), nn.Tanh(), nn.Linear(128, C)).to(device)
escala = torch.logspace(0, -1.5, D_IN, device=device)
def lote(n, g):
    x = torch.randn(n, D_IN, generator=g, device=device) * escala
    with torch.no_grad():
        return x, maestra(x / escala).argmax(1)

def modelo():
    torch.manual_seed(1)
    return nn.Sequential(nn.Linear(D_IN, H), nn.ReLU(), nn.Linear(H, H), nn.ReLU(), nn.Linear(H, C)).to(device)

def raiz_inversa(S, p, rel=1e-6):
    """S^(-1/p) en float64 con amortiguamiento relativo: en fp16/bf16 los autovalores pequeños se pierden."""
    w, Q = torch.linalg.eigh(S.double())
    w = w.clamp(min=0) + rel * w.max().clamp(min=1e-30)
    return ((Q * w.pow(-1.0 / p)) @ Q.T).to(S.dtype)

class Shampoo(torch.optim.Optimizer):
    """Shampoo con estadísticas EMA, raíces cada k pasos e injerto (grafting) de la norma de Adam."""
    def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), b2_stats=0.999, k=10, eps=1e-8, wd=0.0):
        super().__init__(params, dict(lr=lr, betas=betas, b2_stats=b2_stats, k=k, eps=eps, wd=wd))
    @torch.no_grad()
    def step(self):
        for gr in self.param_groups:
            b1, b2 = gr["betas"]
            for p in gr["params"]:
                if p.grad is None: continue
                g, st = p.grad, self.state[p]
                if not st:
                    st.update(t=0, m=torch.zeros_like(p), v=torch.zeros_like(p))
                    if p.ndim == 2:
                        st.update(L=torch.zeros(p.shape[0], p.shape[0], device=p.device), R=torch.zeros(p.shape[1], p.shape[1], device=p.device),
                                  PL=torch.eye(p.shape[0], device=p.device), PR=torch.eye(p.shape[1], device=p.device))
                st["t"] += 1; t = st["t"]
                st["m"].mul_(b1).add_(g, alpha=1 - b1); st["v"].mul_(b2).addcmul_(g, g, value=1 - b2)
                m_hat = st["m"] / (1 - b1**t)
                adam = m_hat / ((st["v"] / (1 - b2**t)).sqrt() + gr["eps"])
                if p.ndim == 2:
                    c = gr["b2_stats"]
                    st["L"].mul_(c).add_(g @ g.T, alpha=1 - c); st["R"].mul_(c).add_(g.T @ g, alpha=1 - c)
                    if t == 1 or t % gr["k"] == 0:
                        st["PL"], st["PR"] = raiz_inversa(st["L"], 4), raiz_inversa(st["R"], 4)
                    d = st["PL"] @ m_hat @ st["PR"]
                    d = d * (adam.norm() / (d.norm() + 1e-30))      # injerto: dirección de Shampoo, tamaño de Adam
                else:
                    d = adam
                p.mul_(1 - gr["lr"] * gr["wd"]).add_(d, alpha=-gr["lr"])

class MuonFP32(torch.optim.Optimizer):
    """Muon de la lección anterior: momento de Nesterov ortogonalizado con Newton-Schulz en fp32.
    torch.optim.Muon (PyTorch ≥ 2.9) hace lo mismo en bfloat16, que en GPU es rápido y en CPU se emula y es lento."""
    def __init__(self, params, lr=1e-3, momentum=0.95, wd=0.0):
        super().__init__(params, dict(lr=lr, momentum=momentum, wd=wd))
    @torch.no_grad()
    def step(self):
        for gr in self.param_groups:
            for p in gr["params"]:
                if p.grad is None: continue
                st = self.state[p]
                buf = st.setdefault("buf", torch.zeros_like(p))
                buf.mul_(gr["momentum"]).add_(p.grad)
                X = p.grad + gr["momentum"] * buf                       # Nesterov
                X = X / (X.norm() + 1e-7)
                for _ in range(5):
                    A = X @ X.T
                    X = 3.4445 * X + (-4.7750 * A + 2.0315 * A @ A) @ X
                escala = 0.2 * max(p.shape) ** 0.5                       # mismo RMS de actualización que AdamW
                p.mul_(1 - gr["lr"] * gr["wd"]).add_(X, alpha=-gr["lr"] * escala)

class KFAC:
    """K-FAC para las capas nn.Linear: factores EMA con etiquetas muestreadas del modelo y amortiguamiento factorizado."""
    def __init__(self, net, lr=0.1, lam=1e-2, ema=0.95, k=10):
        self.capas = [m for m in net.modules() if isinstance(m, nn.Linear)]
        self.lr, self.lam, self.ema, self.k, self.t = lr, lam, ema, k, 0
        self.A, self.G, self.Ai, self.Gi = {}, {}, {}, {}
        for m in self.capas:
            m.register_forward_hook(lambda mod, i, o: setattr(mod, "_a", i[0].detach()))
            m.register_full_backward_hook(lambda mod, gi, go: setattr(mod, "_g", go[0].detach()))
    def factores(self, net, x):
        """Pasada extra con ŷ ~ p(y|x): sus gradientes de salida estiman la Fisher verdadera, no la empírica."""
        logits = net(x)
        if not torch.isfinite(logits).all():
            raise FloatingPointError
        yhat = torch.distributions.Categorical(logits=logits.detach()).sample()
        net.zero_grad(); F.cross_entropy(logits, yhat, reduction="sum").backward()
        for m in self.capas:
            a = torch.cat([m._a, torch.ones(len(m._a), 1, device=m._a.device)], 1)
            n = len(a)
            A, G = a.T @ a / n, m._g.T @ m._g / n
            self.A[m] = A if m not in self.A else self.ema * self.A[m] + (1 - self.ema) * A
            self.G[m] = G if m not in self.G else self.ema * self.G[m] + (1 - self.ema) * G
    @torch.no_grad()
    def step(self):
        self.t += 1
        for m in self.capas:
            if self.t == 1 or self.t % self.k == 0:
                A, G = self.A[m], self.G[m]
                pi = ((A.trace() / len(A)) / (G.trace() / len(G)).clamp(min=1e-12)).sqrt()
                self.Ai[m] = raiz_inversa(A + pi * self.lam**0.5 * torch.eye(len(A), device=A.device), 1, 0)
                self.Gi[m] = raiz_inversa(G + self.lam**0.5 / pi * torch.eye(len(G), device=G.device), 1, 0)
            gW = torch.cat([m.weight.grad, m.bias.grad[:, None]], 1)
            d = self.Gi[m] @ gW @ self.Ai[m]                       # G⁻¹ ∇W A⁻¹
            m.weight.add_(d[:, :-1], alpha=-self.lr); m.bias.add_(d[:, -1], alpha=-self.lr)

def bytes_estado(opt):
    if isinstance(opt, KFAC):
        return sum(4 * (t.numel()) for dd in (opt.A, opt.G, opt.Ai, opt.Gi) for t in dd.values())
    return sum(v.numel() * v.element_size() for st in opt.state.values() for v in st.values() if torch.is_tensor(v))

def entrena(nombre, lr):
    try:
        return _entrena(nombre, lr)
    except FloatingPointError:                              # diverge con este η
        return float("inf"), float("nan"), float("nan"), float("nan")

def _entrena(nombre, lr):
    net = modelo()
    if nombre == "AdamW":
        opt = torch.optim.AdamW(net.parameters(), lr=lr, weight_decay=0.0)
    elif nombre == "Muon":
        mats = [p for p in net.parameters() if p.ndim == 2 and p.shape[1] != D_IN and p.shape[0] != C]   # capas ocultas
        resto = [p for p in net.parameters() if all(p is not q for q in mats)]
        opt = [MuonFP32(mats, lr=lr),
               torch.optim.AdamW(resto, lr=lr, weight_decay=0.0)]
    elif nombre == "Shampoo":
        opt = Shampoo(net.parameters(), lr=lr)
    else:
        opt = KFAC(net, lr=lr)
    opts = opt if isinstance(opt, list) else [opt]
    g = torch.Generator(device=device).manual_seed(0)
    if device == "cuda": torch.cuda.reset_peak_memory_stats(); torch.cuda.synchronize()
    t0 = time.perf_counter()
    for paso in range(PASOS):
        x, y = lote(B, g)
        if nombre == "K-FAC": opt.factores(net, x)
        for o in opts:
            if hasattr(o, "zero_grad"): o.zero_grad()
        net.zero_grad()
        loss = F.cross_entropy(net(x), y); loss.backward()
        if not torch.isfinite(loss):
            raise FloatingPointError
        for o in opts: o.step()
    if device == "cuda": torch.cuda.synchronize()          # los núcleos son asíncronos: sin esto se mide mal
    ms = 1e3 * (time.perf_counter() - t0) / PASOS
    xv, yv = lote(4096, torch.Generator(device=device).manual_seed(123))
    with torch.no_grad():
        val = F.cross_entropy(net(xv), yv).item()
    mem = torch.cuda.max_memory_allocated() / 2**20 if device == "cuda" else float("nan")
    return val, ms, sum(bytes_estado(o) for o in opts) / 2**20, mem

print(f"dispositivo: {device}")
rejillas = {"AdamW": [3e-3, 1e-2, 3e-2], "Muon": [3e-3, 1e-2, 3e-2], "Shampoo": [3e-3, 1e-2, 3e-2], "K-FAC": [0.03, 0.1, 0.3]}
for nombre, etas in rejillas.items():
    res = [(entrena(nombre, e), e) for e in etas]
    (val, ms, mib, mem), e = min(res, key=lambda r: r[0][0])
    print(f"{nombre:8s} η = {e:<6} pérdida de validación {val:.3f}   {ms:6.2f} ms/paso   estado del optimizador {mib:5.2f} MiB"
          + (f"   pico de memoria {mem:.0f} MiB" if mem == mem else ""))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Timings depend on machine and are noisy on shared CPUs. The stable result is order of magnitude: on CPU a Shampoo or K-FAC step costs 1.5–3× AdamW on this tiny model (exact numbers vary), because d/Bd/B is large here and eigendecompositions matter. On GPU with such small matrices the factor is larger (5–10×): eigh parallelizes poorly and launches many small kernels, while AdamW is nearly free. K-FAC also pays for the extra backward pass. At equal steps neither ends better than AdamW: this regime does not justify them, while cheaper, stateless Muon is somewhat ahead. With hundreds of thousands of tokens per batch the ratio reverses.

The second cell is miniature AlgoPerf: two tasks with fixed validation targets, the same search space and four candidate configurations for AdamW (warmup and horizon-dependent cosine), Schedule-Free AdamW (official implementation if installed, pip install schedulefree; otherwise a custom paper-following implementation), and Muon; select by time to target on one seed and reevaluate on five new seeds.

[ ]A mini AlgoPerf (PyTorch)Local GPU
import time, math, numpy as np, torch, torch.nn as nn, torch.nn.functional as F

torch.set_num_threads(2)
dev = "cuda" if torch.cuda.is_available() else "cpu"
try:
    import schedulefree                                    # implementación oficial: pip install schedulefree
    SFAdamW = schedulefree.AdamWScheduleFree
    origen_sf = "oficial (schedulefree)"
except ImportError:
    class SFAdamW(torch.optim.Optimizer):
        """Schedule-free AdamW (algoritmo de Defazio et al., 2024). Los parámetros del modelo guardan y_t al entrenar
        y x_t al evaluar; z_t vive en el estado. Se llama a train() y eval() como en la implementación oficial."""
        def __init__(self, params, lr=2.5e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.0, warmup_steps=0):
            super().__init__(params, dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay,
                                          warmup_steps=warmup_steps, k=0, suma_pesos=0.0, modo="train"))
        @torch.no_grad()
        def eval(self):
            for gr in self.param_groups:
                if gr["modo"] == "train":
                    for p in gr["params"]:
                        st = self.state.get(p)
                        if st: p.lerp_(st["z"], 1 - 1 / gr["betas"][0])      # y → x = (y − (1−β₁) z) / β₁
                    gr["modo"] = "eval"
        @torch.no_grad()
        def train(self):
            for gr in self.param_groups:
                if gr["modo"] == "eval":
                    for p in gr["params"]:
                        st = self.state.get(p)
                        if st: p.lerp_(st["z"], 1 - gr["betas"][0])          # x → y = (1−β₁) z + β₁ x
                    gr["modo"] = "train"
        @torch.no_grad()
        def step(self):
            for gr in self.param_groups:
                b1, b2 = gr["betas"]
                gr["k"] += 1; k = gr["k"]
                lr = gr["lr"] * min(1.0, k / max(1, gr["warmup_steps"])) * math.sqrt(1 - b2**k)
                gr["suma_pesos"] += lr**2
                c = lr**2 / gr["suma_pesos"]                                   # c_{t+1} = γ_t² / Σ γ_i²
                for p in gr["params"]:
                    if p.grad is None: continue
                    st = self.state[p]
                    if not st:
                        st["z"] = p.clone(); st["v"] = torch.zeros_like(p)
                    z, v = st["z"], st["v"]
                    v.mul_(b2).addcmul_(p.grad, p.grad, value=1 - b2)
                    d = p.grad / (v.sqrt() + gr["eps"]) + gr["weight_decay"] * p   # decaimiento evaluado en y
                    x = (p - (1 - b1) * z) / b1                                   # x a partir de y y z
                    z.add_(d, alpha=-lr)
                    x.lerp_(z, c)                                                 # x ← (1 − c) x + c z
                    p.copy_((1 - b1) * z + b1 * x)                                # nuevo y
    origen_sf = "propia (no está instalado schedulefree)"
print("schedule-free:", origen_sf, "| dispositivo:", dev)

# ---- dos tareas pequeñas con un objetivo de validación fijo ----
def tarea_clasificacion():
    g = torch.Generator().manual_seed(100)
    Wt, Vt = torch.randn(32, 64, generator=g), torch.randn(64, 10, generator=g)
    esc = torch.logspace(0, -1.5, 32)
    def lote(n, gen):
        x = torch.randn(n, 32, generator=gen) * esc
        return x.to(dev), (torch.tanh((x / esc) @ Wt / 5.6) @ Vt).argmax(1).to(dev)
    red = lambda: nn.Sequential(nn.Linear(32, 128), nn.ReLU(), nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 10))
    return lote, red, F.cross_entropy, OBJETIVOS["clasificación"]

def tarea_regresion():
    g = torch.Generator().manual_seed(200)
    Wt = torch.randn(16, 8, generator=g)
    def lote(n, gen):
        x = torch.randn(n, 16, generator=gen)
        y = torch.sin(x @ Wt / 3).sum(1, keepdim=True) / 2 + 0.1 * torch.randn(n, 1, generator=gen)
        return x.to(dev), y.to(dev)
    red = lambda: nn.Sequential(nn.Linear(16, 128), nn.Tanh(), nn.Linear(128, 128), nn.Tanh(), nn.Linear(128, 1))
    return lote, red, F.mse_loss, OBJETIVOS["regresión"]

TAREAS = {"clasificación": tarea_clasificacion, "regresión": tarea_regresion}
OBJETIVOS = {"clasificación": 0.90, "regresión": 0.12}
PASOS, LOTE, CADA = 200, 128, 10

def corre(tarea, algo, hp, semilla):
    """(pasos, segundos) hasta alcanzar el objetivo de validación, o (inf, inf)."""
    lote, red, perdida, objetivo = TAREAS[tarea]()
    torch.manual_seed(semilla); net = red().to(dev)
    gen = torch.Generator().manual_seed(semilla)
    xv, yv = lote(2048, torch.Generator().manual_seed(999))
    if algo == "AdamW":
        opts = [torch.optim.AdamW(net.parameters(), lr=hp["lr"], weight_decay=hp["wd"])]
    elif algo == "SF-AdamW":
        opts = [SFAdamW(net.parameters(), lr=hp["lr"], weight_decay=hp["wd"], warmup_steps=20)]
    else:
        ocultas = [net[2].weight]                                       # Muon solo en la matriz oculta
        resto = [p for p in net.parameters() if p is not net[2].weight]
        opts = [MuonFP32(ocultas, lr=hp["lr"], wd=hp["wd"]), torch.optim.AdamW(resto, lr=hp["lr"], weight_decay=hp["wd"])]
    # AdamW y Muon: calentamiento y coseno, que necesitan conocer el horizonte PASOS; schedule-free, no
    prog = [] if algo == "SF-AdamW" else [torch.optim.lr_scheduler.LambdaLR(
        o, lambda t: min(1, (t + 1) / 20) * 0.5 * (1 + math.cos(math.pi * t / PASOS))) for o in opts]
    t0 = time.perf_counter()
    for paso in range(1, PASOS + 1):
        for o in opts:
            if hasattr(o, "train"): o.train()
            o.zero_grad()
        x, y = lote(LOTE, gen)
        loss = perdida(net(x), y)
        if not torch.isfinite(loss): return math.inf, math.inf
        loss.backward()
        for o in opts: o.step()
        for s in prog: s.step()
        if paso % CADA == 0:                         # la evaluación no cuenta en el tiempo, como en AlgoPerf
            if dev == "cuda": torch.cuda.synchronize()
            pausa = time.perf_counter()
            for o in opts:
                if hasattr(o, "eval"): o.eval()      # schedule-free: se evalúa en x, no en y
            with torch.no_grad():
                val = perdida(net(xv), yv).item()
            t0 += time.perf_counter() - pausa
            if val <= objetivo:
                return paso, time.perf_counter() - t0
    return math.inf, math.inf

# ---- el mismo presupuesto para todos: 4 pruebas de búsqueda aleatoria en el mismo espacio ----
ESPACIO = {"lr": (1e-4, 3e-2), "wd": (1e-5, 1e-1)}           # log-uniforme
def muestrea(r):
    return {k: float(np.exp(r.uniform(np.log(a), np.log(b)))) for k, (a, b) in ESPACIO.items()}

ALGOS = ["AdamW", "SF-AdamW", "Muon"]
resumen = {}
for tarea in TAREAS:
    for algo in ALGOS:
        r = np.random.default_rng(0)                          # las mismas 4 configuraciones candidatas para todos
        pruebas = [muestrea(r) for _ in range(4)]
        _, i = min((corre(tarea, algo, hp, semilla=0)[0], i) for i, hp in enumerate(pruebas))
        hp = pruebas[i]
        # el elegido, reevaluado con 5 semillas nuevas: no se informa el ruido que se seleccionó
        resumen[(tarea, algo)] = (hp, np.array([corre(tarea, algo, hp, semilla=s) for s in range(1, 6)]))

def ic_mediana(x, B=2000, rr=np.random.default_rng(0)):
    return np.percentile(np.median(rr.choice(x, size=(B, len(x))), axis=1), [2.5, 97.5])

for (tarea, algo), (hp, sem) in resumen.items():
    pasos, seg = sem[:, 0], sem[:, 1]
    lo, hi = ic_mediana(pasos)
    print(f"{tarea:14s} {algo:9s} η={hp['lr']:.1e} λ={hp['wd']:.0e}  pasos hasta el objetivo: mediana {np.median(pasos):4.0f} "
          f"[IC 95 % {lo:.0f}, {hi:.0f}]  segundos: {np.median(seg):.2f}  fallos: {int(np.isinf(pasos).sum())}/5")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Read the output as a paper. In classification medians differ by one evaluation point (every 10 steps, the resolution) and intervals touch: no clear winner. In regression Muon and Schedule-Free AdamW reach target before AdamW with nonoverlapping intervals, about 90 and 110 steps versus 130. Enough to conclude? Not yet: two small tasks, a coarse bootstrap interval from five-value medians, and all three chose the same configuration (η=10−2\eta = 10^{-2}) among four, indicating search space rather than optimizer decides much. Seconds on a shared CPU are mostly noise; dedicated hardware would be needed to claim timing differences. This is exactly the nuance the preceding checklist teaches.

Common mistakes

Exercises

ProofInverse of a Kronecker product and its cost
Prove: If A∈Rn×n\mat{A} \in \R^{n\times n} and B∈Rm×m\mat{B} \in \R^{m\times m} are invertible, then (A⊗B)−1=A−1⊗B−1(\mat{A}\otimes\mat{B})^{-1} = \mat{A}^{-1}\otimes\mat{B}^{-1}. Consequently, for a 1024×10241024\times 1024 layer, inverting the K-FAC approximation costs about 5×1085\times 10^{8} times less than inverting the full block.
0
Recall that A⊗B\mat{A}\otimes\mat{B} is the block matrix whose (i,j)(i, j) block is aijBa_{ij}\mat{B}.

Step 1 of 3. What tool is needed first?

NumericBlock entries versus factors
For a 1024×10241024\times 1024 linear layer (no bias), what is the ratio of full Fisher block entries to total entries in Kronecker factors A\mat{A} and G\mat{G}?
QuizA baseline at its default rate
A paper tunes a new optimizer's learning rate over 20 values and compares Adam at its default η=10−3\eta = 10^{-3} on three tasks. The new method reaches target earlier on all three. What conclusion is valid?
CodeRobust inverse matrix root
Implement matrix_inverse_root(M, p, eps), returning (Ms+ε λmax⁡I)−1/p(\mat{M}_s + \eps\,\lambda_{\max}\mat{I})^{-1/p} for symmetric positive semidefinite M (possibly with rounding noise), where Ms=(M+M⊤)/2\mat{M}_s = (\mat{M} + \mat{M}\T)/2, negative eigenvalues of Ms\mat{M}_s are clipped to 0 and λmax⁡\lambda_{\max} is the largest eigenvalue of Ms\mat{M}_s (use 1 if 0). Use a float64 eigendecomposition even for float32 M, and return the type of M. Shampoo repeats this calculation every kk steps.
import numpy as np

def matrix_inverse_root(M, p, eps=1e-6):
  """(sym(M) + eps * lambda_max * I)^(-1/p), calculado en float64."""
  M = np.asarray(M)
  # tu código: simetriza, pasa a float64, eigh, recorta autovalores negativos,
  # amortigua relativo a lambda_max, eleva a -1/p y reconstruye
  return np.eye(M.shape[0], dtype=M.dtype)
Shift+Enter to run
QuizWithout knowing the step count
You will train a model without knowing how many steps you can afford: perhaps 20 000, perhaps 80 000. What practical advantage does Schedule-Free AdamW have over AdamW with cosine decay?
NumericMuon overhead
Muon orthogonalizes a d×dd\times d layer update with 5 Newton–Schulz iterations, each using 3 d×dd\times d matrix products (2d32d^3 operations each). Forward and backward for BB tokens cost 6d2B6d^2B. For d=4096d = 4096 and B=219=524 288B = 2^{19} = 524\,288 tokens, what percentage overhead does Muon add?
QuizShampoo without accumulation
Apply one Shampoo step with L=GG⊤\mat{L} = \mat{G}\mat{G}\T and R=G⊤G\mat{R} = \mat{G}\T\mat{G} computed only from current gradient G=UΣV⊤\mat{G} = \mat{U}\mat{\Sigma}\mat{V}\T (reduced SVD), using −1/4-1/4 roots per side. What update results?
QuizThe fastest candidate that loses
In the evaluation cell, candidate B is fastest on two of four workloads and nearly ties on a third, with up to 1.5× speedup, but finishes last in performance-profile score. Why?

Summary

Key idea
Preconditioners that work at scale exploit matrix parameters: K-FAC and Shampoo approximate curvature with one factor per side, SOAP runs Adam in their eigenbasis, and Muon is memoryless Shampoo. An optimizer is better only if it wins in time to target with equal tuning budget, multiple seeds and multiple workloads.
  • K-FAC approximates a layer’s Fisher block by A⊗G\mat{A}\otimes\mat{G}, exact under independent inputs and output gradients. Its inverse is A−1⊗G−1\mat{A}^{-1}\otimes\mat{G}^{-1} and step G−1∇WA−1\mat{G}^{-1}\nabla\mat{W}\mat{A}^{-1}: from (dindout)3(d_{\text{in}}d_{\text{out}})^3 to din3+dout3d_{\text{in}}^3 + d_{\text{out}}^3. Use factored Tikhonov damping.
  • Shampoo accumulates L=∑GG⊤\mat{L} = \sum\mat{G}\mat{G}\T and R=∑G⊤G\mat{R} = \sum\mat{G}\T\mat{G} and updates with L−1/4GR−1/4\mat{L}^{-1/4}\mat{G}\mat{R}^{-1/4}; without accumulation it is Muon’s orthogonalization. Inverse roots are computed every kk steps in high precision with damping.
  • Shampoo with exponent −1/2-1/2 per side is Adafactor in its eigenbasis; SOAP puts Adam there, with more stability and less sensitivity to refresh frequency.
  • Sophia uses an estimated Hessian or Gauss–Newton diagonal (Hutchinson or GNB) with coordinate clipping; results have not been confirmed against well-tuned baselines.
  • Schedule-free evaluates gradients between SGD sequence and average, publishing the average; online-to-batch conversion guarantees an anytime bound, and in practice matches a tuned cosine without fixing a horizon.
  • Optimizer evaluation is experiment design: time to target on fixed hardware, equal tuning budgets, reevaluation on new seeds, confidence intervals and robust workload aggregation, as in AlgoPerf.