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
- 06Natural gradientSpectral steepest descent and MuonAdamW (decoupled weight decay)The Adam-SGD gapLearning-rate schedulesIterate averagingGauss-Newton methodLimited-memory BFGSAdaptive diagonal preconditioning
- 02Kronecker productVec operator and the vec trick
- 00Multi-seed evaluationCUDA asynchronous executionBenchmarking methodologyMemory profiling
- 05Confidence interval and coverage
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 parameters Fisher has entries. Adam’s diagonal costs 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 with (include bias by appending 1 to ). For one example let be layer input and the loss gradient with respect to output. The chain rule gives the weight gradient as an outer product:
where stacks columns (the vec operator) and is the Kronecker product. An entry of is indexed by pair : input , output . The layer’s Fisher matrix block is the expectation of these gradients’ outer product:
A crucial precision: in true Fisher, the label used to compute is sampled from the model, , 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 , because . 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 and are independent, because then . 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 , and output gradient with independent and : with gradient is input-independent; with input determines gradient received in output direction . All moments are exact fourth-order Gaussian moments, without sampling.
Two readings. First, relative Frobenius error poorly measures preconditioner quality: what matters is preconditioned matrix condition , governing first-order speed on the local quadratic. Here it is exactly for any correlation . To see this, write , (unit) and . Since , the are orthonormal, and the preconditioned matrix is , block diagonal in the basis with eigenvalues and . 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 grows and K-FAC does not.
The inverse comes for free
Proof
The mixed-product property follows block by block: block of the product is . It gives . For the second identity, column of is , exactly block of .
∎With symmetric and , : K-FAC never forms the large matrix. For layer the Fisher block has entries (4 TiB in float32), and inversion costs on the order of operations; the factors have entries (8 MiB) and inversion costs . The next cell calculates it.
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 with softmax always has eigenvalue 0 (rows of sum to zero), and inherits activation correlations. Damping is needed, as in Levenberg–Marquardt. Natural destroys Kronecker structure. Martens and Grosse propose factored Tikhonov damping,
which adds plus a cross term. Factor balances both scales to minimize that term. In practice K-FAC also estimates and via minibatch moving averages, recomputes inverses only every steps (the expensive part), and adapts by Levenberg–Marquardt. Later variant EKFAC (George et al., 2018) rescales in the eigenbasis of 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 analytically) and measures approximation quality like the figure.
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 to ; the diagonal worsens it to because hidden activations are highly correlated. Improvement is smaller in the first layer () but still much better than diagonal. Frobenius errors are similar (56 % and 50 %): again a poor measure. Now training, full-batch to isolate preconditioning:
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 ( to , already above default ), 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 , with optimal regret but entries. For matrix parameter with gradients , Shampoo accumulates one factor per side.
The correspondence to K-FAC is direct: sums over inputs and resembles (output side, ); resembles (input side, ). Differences: Shampoo uses accumulated batch gradients, not per-example inputs and output gradients, permitting any tensor (hence the name: an order- tensor gets factors), and uses root per side, so their product is AdaGrad’s root .
Why ? The analysis hinges on a matrix inequality: if each has rank at most ,
and since square root is monotone in Loewner order, dominates full-matrix AdaGrad’s preconditioner up to factor . This transfers AdaGrad’s regret bound to Shampoo (Gupta et al., 2018). One rank-1 gradient is a one-line example: with , , , so : exact equality.
Shampoo without memory is Muon
Proof
and , so and (plus terms on orthogonal complements, annihilated by ). Multiplication gives .
∎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 steps compute and . With eigendecomposition the root is , costing about operations for symmetric decomposition with vectors (Golub and Van Loan) and parallelizing poorly on GPU. Three practical consequences:
- Precision. Eigenvalues of span many orders of magnitude and amplifies small ones. In bfloat16, with 8 mantissa bits (relative error ), an eigenvalue 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 .
- 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 with tokens per batch, forward and backward cost about operations; Shampoo adds per step (statistics and application) plus (roots). Relative overhead is : negligible in LLM pretraining ( 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 per side (instead of ) and write , . With rotated gradient ,
In the rotated basis each entry is divided by the square root of a “row times column” product. And , are row and column sums of the rotated second moment. Estimating is exactly Adafactor’s rank-1 factorization. Shampoo (with ) 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 , so the preconditioner is never completely stale; SOAP is much less sensitive to 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:
| Method | Preconditioning basis | Scaling | Extra state (layer ) |
|---|---|---|---|
| Adam | canonical axes | per entry | |
| Muon | current momentum singular vectors | equalizes all singular values | |
| Shampoo | eigenbases of , | (rank 1) | |
| SOAP | eigenbases of , | per entry (Adam) | |
| K-FAC | eigenbases of , | inverse factored Fisher |
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 .
Three conclusions to check. First, with ill-conditioned rotated Kronecker curvature (default ), 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 . With and tokens, Shampoo costs 42 % more per step than AdamW; with 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 , with stochastic gradients from batches of 32:
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 ; two classical ones exist.
Proof
Hutchinson: , and . Gauss–Newton–Bartlett: Bartlett’s identity gives , so the summands are independent and centered, and . Take the diagonal and multiply by .
∎Sophia estimates with one of these every steps and smooths it with a moving average, maintains gradient momentum , and updates
with entrywise clipping . This is a diagonal Newton step where curvature is reliable and a sign step of size (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.
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 , which Sophia gets free via the moving average. The last part shows ‘s effect: with small almost all coordinates clip and Sophia is momentum sign descent; with large 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 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 , 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 , : constant-step SGD with Polyak–Ruppert average as output. With , : 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, , i.e. . Then
using convexity inequality twice, with and . The right side is , a telescoping sum: summing from to gives . For the second part, standard online gradient descent analysis gives (expand and sum).
∎The first part matters: the bound holds for every along the same sequence without the algorithm knowing when we stop. The second is more modest than it looks: rate uses to choose , and with fixed the bound at is , plateauing at (with and projection onto a bounded domain the rate is recovered without knowing , 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 and -Lipschitz, schedule-free attains for any , the optimal worst-case rate. Their practical choice is experimental, not theoretical: evaluating gradients near the average stabilizes large-step dynamics and makes closely follow a tuned cosine.
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 works well with large in the figure, and near 1 is worse for any : gradient is evaluated near a slowly moving average, overshoots, and the average oscillates. In deep networks, where a uniform average carries poor iterates from a nonconvex phase, gives schedule-free its advantage. The cell reproduces the comparison with linear regression using batches of 8 and four seeds in parallel:
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 , ‘s error is about eight times ‘s, and the latter no longer improves, so at 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 step is Adam’s (division by ), warmup is used, average weights are so warmup steps count little, and weight decay is evaluated at . Two engineering details: model parameters store during training and must switch to for evaluation (official implementation: optimizer.eval() and optimizer.train()), and BatchNorm statistics are computed at , so recompute them at 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 ; momentum is the limit of Adam with very large (if , Adam’s step is : momentum as a moving average at rate ). 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 is submission ‘s time on workload , and
the fraction of workloads on which is at most times slower than the best. Score is normalized area under between and . A submission failing a workload () loses that portion for every .
The interactive reproduces three arguments. Ranking depends on : 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 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.
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 numbers per layer versus Adam’s , 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:
- Iterations or time? If the method costs per step, 30 % fewer iterations loses in time. Find measured wall time or at least measured per-step cost.
- 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.
- 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).
- How many seeds and what intervals? A 2 % difference on one seed is not a result.
- How many workloads, selected before or after? One architecture and dataset say little about the next.
- 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).
- 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.
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 ""))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 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.
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")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 () 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
Step 1 of 3. What tool is needed first?
matrix_inverse_root(M, p, eps), returning for symmetric positive semidefinite M (possibly with rounding noise), where , negative eigenvalues of are clipped to 0 and is the largest eigenvalue of (use 1 if 0). Use a float64 eigendecomposition even for float32 M, and return the type of M. Shampoo repeats this calculation every 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)Summary
- K-FAC approximates a layer’s Fisher block by , exact under independent inputs and output gradients. Its inverse is and step : from to . Use factored Tikhonov damping.
- Shampoo accumulates and and updates with ; without accumulation it is Muon’s orthogonalization. Inverse roots are computed every steps in high precision with damping.
- Shampoo with exponent 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.