Steepest descent in other geometries: sign, natural gradient and Muon
Unify modern optimizers under a classical idea: steepest descent in a chosen norm. The ℓ∞ norm gives sign descent (signSGD, Lion), the Fisher metric gives natural gradient, and spectral norm on weight matrices gives Muon’s orthogonalized update, computed with Newton–Schulz iterations.
After this lesson you can
- Derive steepest-descent steps for an arbitrary norm using its dual norm.
- Obtain signSGD as ℓ∞ steepest descent and analyze Lion as the sign of interpolated momentum.
- Derive natural gradient as steepest descent in the Fisher metric (local quadratic KL approximation) and explain reparameterization invariance.
- Derive orthogonalized UVᵀ as spectral-norm steepest descent and implement Newton–Schulz without an SVD.
- Implement Muon for hidden network matrices and explain its combination with AdamW for embeddings, biases and output.
Before you start
- 06Gradient descentDescent directionMirror descentBregman divergenceAdaptive diagonal preconditioningStochastic momentumAdamAdamW (decoupled weight decay)Newton's method
- 02Singular value decompositionOperator normDual norm
- 05Fisher informationFisher information matrix
- 07Kullback-Leibler divergence (relative entropy)Local Fisher approximation of KL
- 09IEEE 754 and deep learning formats
- 00Automatic mixed precision in PyTorchPyTorch optimizer API
Motivation: the same algorithm with a different measure
Recent optimizers have very different names and formulas: signSGD, Lion, natural gradient and K-FAC, Shampoo, Muon. Read separately they look like a bag of tricks. This lesson argues a more economical thesis, stated clearly by Bernstein and Newhouse (2024) in “Old Optimizer, New Norm”: almost all are the same algorithm, steepest descent, using a different norm to measure step size.
The idea is old (Boyd and Vandenberghe devote section 9.4 to it) and begins with an observation hidden by gradient descent. Calling “the steepest descent direction” presupposes a way to compare equal-size steps, namely Euclidean norm. Measure steps differently and the steepest direction changes. There is no reason Euclidean norm must be the right one:
- Coordinates at different scales. If one parameter is a rate from 0 to 1 and another a bias around 100, a Euclidean-length 0.1 step means different things for each. Measuring coordinates separately () leads to gradient sign, then Adam and Lion.
- Parameters describing distributions. If parameterizes a probabilistic model, what matters is not how far moves but how much the distribution changes. Measuring with Kullback–Leibler divergence leads to natural gradient.
- Matrices acting on vectors. A linear layer is not a vector of unrelated numbers: it is an operator. What matters about change is how much it can change the output, measured by the operator norm. This leads to Muon’s orthogonalized update .
That is the lesson’s program: a general theorem, three norms and three optimizers, with proofs, from-scratch implementations and honest evidence of when they work.
Steepest descent for any norm
Let be differentiable, , and any norm on . Near , . “Which unit-size step most reduces the linear model?” is an optimization problem cleanly answered by dual norm .
Verify the second equality by separating size and direction. Write with and . For fixed the best is and the objective is , a parabola in minimized at . The versions differ: normalized steps have fixed size (gradient magnitude does not matter), while unnormalized steps scale by . Modern optimizers usually use the normalized version, with rate and momentum controlling size. The minimizer set is always nonempty (a linear function on a compact set) and, if , is a face of the unit ball: a point if strictly convex in that direction, otherwise an edge or whole face.
The chosen norm’s version of the descent lemma explains why this step.
Proof
By the fundamental theorem of calculus, . Inequality (the dual-norm definition) and the assumption bound the integrand by , so
The right side is exactly the definition’s objective with ; its minimum occurs at and equals . Summing from to telescopes to , and the minimum is at most the mean.
∎The theorem identifies what makes a method good: the ratio of its gain to its cost, constant measured in the same norm. Choosing a norm chooses pair . A norm suited to the problem’s geometry gives small and steps long where possible, short where necessary. The same idea applied to a trust region rather than linear model underlies Newton’s method and mirror descent, which replaces norm by Bregman divergence.
A catalog of norms
| Step norm | Dual norm | Direction | Resulting method |
|---|---|---|---|
| gradient descent | |||
| sign descent (signSGD, Lion, Adam without averages) | |||
| , | greedy coordinate descent (Gauss–Southwell rule) | ||
| , | preconditioned gradient; Newton if | ||
| Fisher metric | natural gradient | ||
| spectral on matrices | nuclear | spectral descent (Muon) |
The elliptical row deserves more. With diagonal , step is AdaGrad, RMSProp and Adam’s diagonal preconditioning. With equal to the Hessian, it is Newton’s direction. The adaptive-methods lesson’s catalog fits in row four; rows five and six are this lesson’s focus.
Two readings matter. First: the optimal direction is parallel to only in Euclidean norm. In any other norm, the angle between and can be large: with and only the first coordinate moves, nearly from , and in dimension with all similar the angle approaches , almost . Yet is always a descent direction, because . Second: balls with vertices give “discrete” steps. In and the optimum lies at vertices, so small gradient changes either do nothing or abruptly change direction. This causes both sign robustness and its noise.
ℓ∞ and sign descent
In the AdamW lesson you proved sign is steepest descent in and Adam with is exactly that method. With the general framework in place, the definition is immediate.
Three properties distinguish it from gradient descent:
- Each coordinate moves exactly . The step depends only on each gradient component’s sign, not scale. Tiny-gradient coordinates (deep layers, rare parameters) advance as much as others. This is Adam’s invariance to separately rescaling each gradient.
- The geometry follows the axes. Sign is not rotation-invariant: rotating the problem truly changes the step. The second cell shows sign going from winning to losing merely by rotating the Hessian.
- Sign is a biased nonlinearity. in magnitude: for a Gaussian gradient of mean and standard deviation , , almost at high signal and at low signal. With noise, sign automatically damps coordinates whose mean gradient is small relative to noise. It also clips extremes: a huge stochastic gradient from an outlier counts as much as a normal one. Thus sign is robust to heavy-tailed noise, as you will measure.
Lion: the sign of interpolated momentum
Lion (EvoLved Sign Momentum) was not designed by hand. Chen et al. (2023) found it via symbolic program search over update rules, evaluating candidates on real tasks. The result is surprisingly simple:
with default and . There are two moving averages of the same gradient, and the distinction matters. The stored one, , has long memory (, about 100 steps); the one used for the step, , weights the current gradient more ( versus ). This resembles Nesterov momentum: look a little ahead of the slow average. Term is decoupled weight decay as in AdamW.
Two practical consequences recommended by the paper. Since all entries have magnitude 1, Lion’s step norm is larger than Adam’s at the same rate (Adam’s is usually well below 1). Lion’s rate is therefore typically 3 to 10 times smaller than AdamW’s and decay 3 to 10 times larger to preserve product . Lion stores one state vector versus Adam’s two: real memory savings when optimizer state is a large fraction of total memory.
Fisher metric and natural gradient
Now parameters describe a distribution. Let be a model with and a loss, e.g. mean negative log likelihood. Very different values can yield the same distribution (consider simultaneous rescaling of two ReLU layers), and very close values can yield very different distributions (near in a Gaussian). Euclidean distance in sees neither. KL divergence does, and its local form is a metric.
If is sufficiently regular, the second-order Taylor expansion of KL around is
where is the Fisher information matrix: the zeroth-order term is 0, first order vanishes because the score has zero mean, and KL’s Hessian at is (information theory’s Fisher metric). Thus KL measures elliptical norm to second order, and the catalog’s fourth row gives the answer.
Fisher information appears as KL curvature rather than estimator variance. Both views yield the same matrix. For a well-specified model’s negative log likelihood, equals the expected Hessian at the optimum, so natural gradient resembles Newton; with exponential-family outputs it equals the generalized Gauss–Newton Hessian (Martens, 2020), positive semidefinite even far from optimum.
Invariance to reparameterization
Natural gradient became famous because it does not depend on how parameters are written.
Proof
By the chain rule , and taking the expected outer product gives . Likewise . Then . For the discrete step, with , and is the natural step in . For the flow, , the same differential equation with the same initial condition.
∎The smallest example is fitting a Gaussian. Take and loss , expected negative log likelihood on data minus its minimum. Its gradient and Fisher are
The natural gradient in is : factors and making ordinary gradient explode near and stall for large disappear. In parameterization , , and the theorem guarantees the natural step in mapped to is the same to first order.
True versus empirical Fisher
is an expectation under the model: in supervised learning, , with labels sampled from the model. Substituting real labels is tempting because the matrix then uses the same per-example gradients already available:
This is empirical Fisher, and approximates Fisher only in one case: at the optimum of a well-specified model, where real labels follow the model distribution. Far away it can be arbitrarily poor (Kunstner, Balles and Hennig, 2019). One-line example: estimate mean of using data from . True Fisher is 1 for every ; empirical Fisher is . The empirical “natural step” is , which from gets smaller farther from the optimum: it tends to zero as , while the true natural step is . Empirical Fisher is the gradient second-moment matrix, and far from optimum those gradients are large because the model errs, not because the surface is curved.
Natural gradient has an obvious cost: is , and with it cannot be stored or inverted. Practical methods approximate in Kronecker-product-structured blocks, one per layer: K-FAC, next lesson. The same idea with an explicit KL constraint instead of a penalty underlies TRPO in reinforcement learning.
Weight matrices as operators
Return to a network. A linear layer’s parameter is matrix and gradient another. Gradient descent treats it as a long vector under Frobenius norm. But the layer does , and change changes its output by , whose worst case is
with the spectral norm, largest singular value. To control how much a layer’s output can change for any input, spectral norm is natural for the step. Its dual under inner product is nuclear norm .
An exercise proves it step by step; the idea fits in one line. and each , so the sum is at least , with equality when for all .
Four useful views of :
- It is the sign of singular values. . If is diagonal, : spectral descent is sign descent in the gradient-diagonalizing basis. It preserves gradient input and output directions and discards magnitudes.
- It is the semiorthogonal matrix closest to in Frobenius norm (orthogonal Procrustes).
- It is Shampoo without accumulation. With and , . Shampoo accumulates and over time; with zero memory it is spectral descent.
- It is rotation-equivariant. For orthogonal , . Rotating layer inputs or outputs does not change the algorithm, as in SGD and unlike Adam or sign, which depend on the coordinate basis.
Why discard magnitudes? Network-layer gradients have very low stable rank : almost all energy lies in a few directions. A minibatch gradient sums outer products , so rank is at most , and in practice a few directions dominate. SGD spends almost its entire step there; Muon weights all gradient-visible directions equally, including weak ones potentially important for learning but drowned out by SGD.
Newton–Schulz: polynomials taking singular values to 1
An SVD at every step of every layer is expensive and, above all, parallelizes poorly on a GPU. The answer is elementary: an odd matrix polynomial acts separately on each singular value.
Proof
because , so . Summing with coefficients yields the result. Even powers would not work: lives in space and lacks form .
∎Thus to approximate , iterate a polynomial sending each toward 1 a few times. Each iteration costs three matrix products: , and . In wide orientation (), is and iteration costs about operations, all dense products GPUs run at full throughput.
The classical cubic
Newton–Schulz polar-factor iteration uses , namely . Its properties follow from the polynomial:
- and : 1 is a superattracting fixed point and nearby convergence is quadratic (error becomes ).
- , and for , : iteration works only in . Therefore normalize , guaranteeing because .
- Near 0, : a small singular value grows only 50 % per step. From it takes 19 iterations to reach .
The last point is the issue. After Frobenius normalization most singular values of a real gradient are tiny (consider with a hundred singular values). Five cubic steps barely move them: they multiply by , and remains .
Muon’s quintic
Keller Jordan proposed changing the goal. Singular values need not end exactly at 1; near 1 quickly suffices. With , slope at the origin is (over double the cubic), at the cost of 1 no longer being fixed: . Iterated five times, this polynomial takes any into band , oscillating there. The result is not but with diagonal in that band, and empirical experience is that this does not hurt training.
Muon performs five iterations in bfloat16, with products in modern GPUs’ 16-bit format (see IEEE 754 formats and relatives). This is safe for two reasons: rounding error at one step acts as a small singular-value perturbation that the next returns to the band, and the result need only be inside the band, not exact. This is mixed precision’s logic in autocast training: use low precision where errors do not accumulate.
Muon
Muon (MomentUm Orthogonalized by Newton-Schulz, Jordan et al., 2024) combines the pieces. For each hidden matrix with gradient :
with , five quintic steps (after Frobenius normalization), decoupled weight decay and shape factor . Momentum is orthogonalized after accumulation: the recent-gradient mean best estimates direction, and orthogonalization decides how to allocate the step among its directions.
Shape scaling
Without factor the same rate produces very different step sizes in different-sized layers. of a full-rank matrix has singular values equal to 1, so and its entries’ root-mean-square is
Two conventions are used:
- Original uses . It measures the step by operator norm between unit-RMS vectors, , whose steepest descent is : the rate transfers between wide and narrow layers. is a practical adjustment: it does not reduce steps for layers wider than tall.
- Moonshot (Liu et al., 2025) uses , giving each step RMS , typical of AdamW updates. Muon can thereby reuse the rate and weight decay tuned for AdamW.
Forgetting the factor is a silent error: training works, but each layer has a different optimal rate and no global value works for all.
Parameters excluded from Muon
Muon optimizes hidden-layer weight matrices. Other parameters use AdamW in separate parameter groups (see PyTorch’s optimizer API):
- Biases, normalization gains and scalars. These are vectors. For a vector : orthogonalization degenerates to normalization and no operator structure remains to exploit.
- Embedding table. Its input is a one-hot vector: the layer selects a column rather than mixing input directions. The appropriate operator norm from one-hot vectors measures columns separately, and its steepest descent normalizes column by column, not orthogonalizes. Also a rare token’s gradient is tiny and orthogonalization would amplify it to the same size as frequent ones.
- Output layer. It produces softmax logits, which do not behave like unit-RMS activations. Empirically applying Muon worsens results, and Jordan and later work recommend AdamW instead.
- Convolutions. Muon does handle them, flattening the filter of shape into matrix .
Implementation from scratch
First, steepest descent under the catalog’s norms, checked by brute force: among two hundred thousand boundary points per ball, none should reduce the linear model more than .
import numpy as np
def paso_mas_pronunciado(g, norma, P=None):
"""Minimizador d de <g, d> en la bola unidad de la norma y valor de la norma dual ||g||_* = -<g, d>."""
if norma == "l2":
d = -g / np.linalg.norm(g)
elif norma == "linf":
d = -np.sign(g)
elif norma == "l1":
i = np.argmax(np.abs(g))
d = np.zeros_like(g)
d[i] = -np.sign(g[i])
elif norma == "P": # ||d||_P = sqrt(d' P d)
h = np.linalg.solve(P, g)
d = -h / np.sqrt(g @ h)
return d, -(g @ d)
def norma_de(Z, norma, P=None):
if norma == "l2":
return np.linalg.norm(Z, axis=1)
if norma == "linf":
return np.abs(Z).max(axis=1)
if norma == "l1":
return np.abs(Z).sum(axis=1)
return np.sqrt(np.einsum("ij,jk,ik->i", Z, P, Z))
rng = np.random.default_rng(0)
n = 6
g = rng.standard_normal(n)
A = rng.standard_normal((n, n))
P = A @ A.T + 0.5 * np.eye(n)
# puntos aleatorios llevados a la frontera de cada bola: ninguno debe mejorar a d
Z = rng.standard_normal((200_000, n)) * rng.exponential(size=(200_000, 1)) ** 3
print("norma ||g||_* mejor muestra ||d||")
for norma in ["l2", "linf", "l1", "P"]:
d, dual = paso_mas_pronunciado(g, norma, P)
U = Z / norma_de(Z, norma, P)[:, None]
print(f"{norma:5s} {dual:8.4f} {-(U @ g).min():12.4f} {norma_de(d[None], norma, P)[0]:.3f}")The sample approaches the optimum without exceeding it. Now the guarantee theorem in action. For , the smoothness constant under norm is , computed at vertices for and and by variable substitution for ellipses. Each method takes step ; measure iteration count and worst ratio of actual to guaranteed decrease, which the theorem says never falls below 1.
import itertools
def constante_L(H, norma, P=None):
"""L = max_{||d|| <= 1} d' H d para H semidefinida positiva: la suavidad de x'Hx/2 en esa norma."""
if norma == "l2":
return np.linalg.eigvalsh(H).max()
if norma == "l1": # el máximo de una forma convexa en la bola l1 está en un vértice ±e_i
return np.diag(H).max()
if norma == "linf": # ... y en la bola l-infinito, en un vértice (±1, ..., ±1)
V = np.array(list(itertools.product([-1.0, 1.0], repeat=H.shape[0])))
return np.einsum("ij,jk,ik->i", V, H, V).max()
R = np.linalg.cholesky(np.linalg.inv(P)) # d = R u con ||u||_2 = 1 recorre la bola de ||.||_P
return np.linalg.eigvalsh(R.T @ H @ R).max()
def descenso(H, x0, norma, P=None, tol=1e-10, max_iter=100_000):
L = constante_L(H, norma, P)
f = lambda x: 0.5 * x @ H @ x
x, f0, peor = x0.copy(), f(x0), np.inf
for k in range(max_iter):
d, dual = paso_mas_pronunciado(H @ x, norma, P)
x_nuevo = x + (dual / L) * d
peor = min(peor, (f(x) - f(x_nuevo)) / (dual**2 / (2 * L)))
x = x_nuevo
if f(x) <= tol * f0:
return k + 1, peor
return max_iter, peor
n = 8
h = np.logspace(0, 2, n) # curvaturas de 1 a 100
Q, _ = np.linalg.qr(np.random.default_rng(1).standard_normal((n, n)))
x0 = np.random.default_rng(2).standard_normal(n)
for nombre, H in {"alineada con los ejes": np.diag(h), "girada": Q @ np.diag(h) @ Q.T}.items():
print(f"hessiana {nombre}:")
for etiqueta, norma, P in [("l2", "l2", None), ("linf (signo)", "linf", None), ("l1 (coordenada)", "l1", None),
("P = diag(H)", "P", np.diag(np.diag(H))), ("P = H (Newton)", "P", H)]:
it, peor = descenso(H, x0, norma, P)
print(f" {etiqueta:16s} iteraciones: {it:6d} min(descenso / garantía) = {peor:.2f}")The table summarizes the lesson. With axis-aligned Hessian, sign needs 135 iterations versus gradient’s 719: its geometry fits the problem. Rotate the Hessian without changing eigenvalues and sign rises to 2778, worse than gradient, unaffected by rotation (903). Diagonal norm matches Newton in the aligned case and helps less when rotated (539), and solves both in one step. The minimum ratio never falls below 1, as promised.
Sign, Signum and Lion with noise
Now stochastic gradients on a 100-dimensional quadratic with curvatures to 1. Each method uses the same rate schedule (linear decay to zero) and its best rate among eleven. Compare no noise, Gaussian noise and Student noise with 1.5 degrees of freedom, which has infinite variance.
import numpy as np
d, T = 100, 400
h = np.logspace(-3, 0, d) # curvaturas de 0.001 a 1, alineadas con los ejes
x_ini = 3 * np.random.default_rng(5).standard_normal(d)
f = lambda x: 0.5 * np.sum(h * x * x)
def entrenar(regla, lr, sigma, colas=False, seed=0):
rng = np.random.default_rng(seed)
x, m = x_ini.copy(), np.zeros(d)
for t in range(T):
ruido = rng.standard_t(1.5, d) if colas else rng.standard_normal(d)
g = h * x + sigma * ruido
eta = lr * (1 - t / T) # decaimiento lineal hasta 0, igual para todos
if regla == "SGD+mom.":
m = 0.9 * m + g
x = x - eta * m
elif regla == "signSGD":
x = x - eta * np.sign(g)
elif regla == "Signum": # signo del momentum
m = 0.9 * m + 0.1 * g
x = x - eta * np.sign(m)
elif regla == "Lion":
c = 0.9 * m + 0.1 * g # beta1 = 0.9: interpolación para el paso
x = x - eta * np.sign(c)
m = 0.99 * m + 0.01 * g # beta2 = 0.99: memoria más larga
if not np.all(np.abs(x) < 1e6):
return np.inf
return f(x)
tasas = np.logspace(-4, 1, 11)
print(f"f inicial = {f(x_ini):.1f}; mejor f final tras ajustar la tasa en {len(tasas)} valores")
print(f"{'ruido':22s}" + "".join(f"{r:>12s}" for r in ["SGD+mom.", "signSGD", "Signum", "Lion"]))
for sigma, colas, nombre in [(0.0, False, "sin ruido"), (0.5, False, "gaussiano, σ = 0.5"), (0.5, True, "t de Student (ν = 1.5)")]:
fila = [min(entrenar(regla, lr, sigma, colas) for lr in tasas) for regla in ["SGD+mom.", "signSGD", "Signum", "Lion"]]
print(f"{nombre:22s}" + "".join(f"{v:12.2e}" for v in fila))The result cautions against sweeping claims. On an aligned quadratic with Gaussian noise, momentum SGD beats all sign methods. With heavy-tailed noise the story reverses: SGD barely drops from 47.8 to 6.7 because its optimal rate must be tiny to survive occasional huge gradients, while signSGD reaches 1.8 by clipping each coordinate to . Lion is last: its long moving average () absorbs an outlier and retains it for tens of steps, so the sign of a mean can be less robust than the mean of signs. Zhang et al. (2020) argued transformer gradient noise is heavy-tailed; Kunstner et al. (2023) later noted sign advantages persist even without noise. This experiment shows one mechanism favoring sign under heavy tails, not that this mechanism acts in your model.
A Gaussian’s natural gradient
The next cell checks invariance numerically: traverse the same total time at progressively smaller rates in both parameterizations, measuring KL between final Gaussians. Then compare natural and empirical-Fisher steps.
import numpy as np
def grad_mu_sigma(mu, sig): # gradiente de KL(N(0,1) || N(mu, sig^2))
r = mu**2 + 1.0
return np.array([mu / sig**2, 1 / sig - r / sig**3])
def kl(p, q): # KL(N(p) || N(q)), con p = (mu, sigma)
return np.log(q[1] / p[1]) + (p[1]**2 + (p[0] - q[0])**2) / (2 * q[1]**2) - 0.5
def natural(theta0, eta, pasos, coords):
mu, sig = theta0
for _ in range(pasos):
g = grad_mu_sigma(mu, sig)
if coords == "sigma": # F = diag(1/sig^2, 2/sig^2)
mu, sig = mu - eta * sig**2 * g[0], sig - eta * sig**2 / 2 * g[1]
else: # s = log sig: F = diag(1/sig^2, 2), grad_s = sig * grad_sig
mu, sig = mu - eta * sig**2 * g[0], sig * np.exp(-eta * 0.5 * sig * g[1])
return np.array([mu, sig])
def ordinario(theta0, eta, pasos, coords):
mu, sig = theta0
for _ in range(pasos):
g = grad_mu_sigma(mu, sig)
if coords == "sigma":
mu, sig = mu - eta * g[0], sig - eta * g[1]
else:
mu, sig = mu - eta * g[0], sig * np.exp(-eta * sig * g[1])
return np.array([mu, sig])
theta0 = (-2.0, 2.5)
print("tiempo total eta * pasos = 2 en todos los casos")
print(" eta KL entre naturales KL entre ordinarios")
for eta in [0.2, 0.1, 0.05, 0.025, 0.0125]:
pasos = round(2 / eta)
a, b = natural(theta0, eta, pasos, "sigma"), natural(theta0, eta, pasos, "log")
c, d = ordinario(theta0, eta, pasos, "sigma"), ordinario(theta0, eta, pasos, "log")
print(f" {eta:<7} {kl(a, b):.3e} {kl(c, d):.3e}")
# Fisher verdadera frente a Fisher empírica para la media de N(mu, 1) con datos de N(0, 1)
x = np.random.default_rng(0).normal(0.0, 1.0, size=10_000)
print("\n mu gradiente Fisher verdadera Fisher empírica paso natural paso con la empírica")
for mu in [0.5, 2.0, 5.0, 20.0]:
puntuaciones = x - mu # d/dmu log p(x | mu) en cada dato, con las etiquetas reales
g = -puntuaciones.mean() # gradiente de la log-verosimilitud negativa media
F_emp = np.mean(puntuaciones**2) # media de los gradientes por ejemplo al cuadrado
print(f" {mu:4.1f} {g:8.3f} {1.0:6.2f} {F_emp:8.2f} {-g:8.3f} {-g / F_emp:8.4f}")The first table separates dynamics clearly. KL between natural gradients falls from to , roughly a factor of 4 each time rate halves: parameter difference is and KL, quadratic in it, . In the limit they are the same curve. Ordinary-gradient KL stays at : different flows, not discretization error. The second table shows empirical Fisher’s failure: with the natural step is (reaching optimum in one step with ), and empirical step .
Newton–Schulz versus SVD
import numpy as np
def newton_schulz(G, pasos, coef=(3.4445, -4.7750, 2.0315)):
a, b, c = coef
alta = G.shape[0] > G.shape[1]
X = G.T if alta else G # orientación ancha: X X' es la matriz pequeña
X = X / (np.linalg.norm(X) + 1e-7) # Frobenius >= espectral: todos los sigma en (0, 1]
for _ in range(pasos):
A = X @ X.T
B = b * A + c * A @ A
X = a * X + B @ X
return X.T if alta else X
rng = np.random.default_rng(0)
m, n = 64, 256
# un "gradiente" con estructura: rango bajo dominante más ruido
G = 5 * rng.standard_normal((m, 4)) @ rng.standard_normal((4, n)) + rng.standard_normal((m, n))
s = np.linalg.svd(G, compute_uv=False)
print(f"valores singulares de G: de {s[0]:.1f} a {s[-1]:.2f}; tras normalizar, de {s[0]/np.linalg.norm(s):.3f} a {s[-1]/np.linalg.norm(s):.4f}")
nuclear = s.sum() # norma dual de la espectral
print("polinomio pasos sigma min sigma max <G, X> / (||X||_2 ||G||_*)")
for nombre, coef in [("cúbico", (1.5, -0.5, 0.0)), ("Muon", (3.4445, -4.7750, 2.0315))]:
for pasos in [3, 5, 10, 20]:
X = newton_schulz(G, pasos, coef)
sx = np.linalg.svd(X, compute_uv=False)
print(f"{nombre:10s} {pasos:4d} {sx.min():.3f} {sx.max():.3f} {np.sum(G * X) / (sx[0] * nuclear):.4f}")
flops = 5 * (4 * m * m * n + 2 * m**3)
print(f"\n5 pasos sobre una matriz de {m}x{n}: {flops / 1e6:.1f} millones de operaciones, todas productos densos")The last column is the fraction of optimal linear decrease achieved by each approximation once scaled to spectral norm 1. The cubic needs 20 steps to reach exact (fraction 1). At 5 steps both approximations achieve 76 %, because the four large singular values dominate that measure; they differ on small ones: cubic leaves them at and quintic raises them to . This is exactly what Muon seeks, moving weak directions too, and its polynomial pays by never converging to exact (fraction plateaus around 0.8).
Muon from scratch on a linear layer
To finish from scratch, compare Muon, momentum SGD and Adam on the spectrum interactive’s problem: a teacher–student linear layer with highly anisotropic input covariance . Each method uses its best of five rates. Repeat with inputs rotated by a random orthogonal matrix and teacher rotated accordingly: the same problem in another basis.
d_out, d_in, B, T = 24, 48, 16, 150
lam = np.arange(1, d_in + 1) ** -1.5 # covarianza de las entradas: diag(j^-1.5)
W_ref = np.random.default_rng(1).standard_normal((d_out, d_in)) * 3 / np.sqrt(d_in)
Q = np.linalg.qr(np.random.default_rng(3).standard_normal((d_in, d_in)))[0] # un giro de las entradas
def entrenar(metodo, lr, girar=False, seed=0):
"""Capa y = W x con x = Q z (si se gira) o x = z, z ~ N(0, diag(lam)); maestro W* = W_ref Q'."""
R = Q if girar else np.eye(d_in)
W_star = W_ref @ R.T # el mismo problema, escrito en otra base
rng = np.random.default_rng(seed)
W, m, v = np.zeros((d_out, d_in)), np.zeros((d_out, d_in)), np.zeros((d_out, d_in))
for t in range(1, T + 1):
X = (rng.standard_normal((B, d_in)) * np.sqrt(lam)) @ R.T
E = X @ (W - W_star).T + 0.1 * rng.standard_normal((B, d_out))
G = E.T @ X / B # gradiente de minilote
eta = lr * min(1.0, 2 * (1 - t / T)) # constante y decaimiento lineal en la segunda mitad
if metodo == "SGD": # con momentum de Nesterov
m = 0.95 * m + G
W = W - eta * (G + 0.95 * m)
elif metodo == "Adam":
m = 0.9 * m + 0.1 * G
v = 0.95 * v + 0.05 * G**2
W = W - eta * (m / (1 - 0.9**t)) / (np.sqrt(v / (1 - 0.95**t)) + 1e-8)
else: # Muon
m = 0.95 * m + G
W = W - eta * np.sqrt(max(1, d_out / d_in)) * newton_schulz(G + 0.95 * m, 5)
if not np.all(np.abs(W) < 1e6):
return np.inf
return 0.5 * np.sum(((W - W_star) @ R) ** 2 * lam) # error poblacional
tasas = np.logspace(-2.5, -0.5, 5)
print("pérdida inicial:", round(0.5 * np.sum(W_ref**2 * lam), 3))
print(f"método ejes originales entradas giradas (mejor de {len(tasas)} tasas)")
for metodo in ["SGD", "Adam", "Muon"]:
a = min(entrenar(metodo, lr) for lr in tasas)
b = min(entrenar(metodo, lr, girar=True) for lr in tasas)
print(f"{metodo:6s} {a:.5f} {b:.5f}")Two lessons, neither “Muon wins.” First invariance: SGD and Muon give exactly the same loss with and without rotation because ; Adam does not, because its diagonal preconditioner exploits axis-aligned covariance and loses that advantage under rotation. Second experimental honesty: in this linear convex problem, with each rate well tuned, Muon trails momentum SGD (0.026 versus 0.013), and Adam is best in original axes. Published advantages appear in deep networks with many layers and nonlinearities, where directional allocation matters for reasons this toy does not capture.
The professional version: PyTorch
The next cell implements Muon as an torch.optim.Optimizer subclass and trains a four-layer MLP on synthetic classification with new data each batch, as in single-epoch pretraining. Two hidden matrices use Muon; first and output layers and all biases use AdamW. Both receive the same tuning budget: four rates each. It runs on CPU in under half a minute; on GPU change DEVICE and Newton–Schulz automatically uses bfloat16.
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.set_num_threads(2)
DEVICE = "cpu" # el experimento es pequeño; con una GPU, pon "cuda"
@torch.no_grad()
def newton_schulz5(G, pasos=5, eps=1e-7):
"""Factor polar aproximado de G: valores singulares llevados a la banda [0.68, 1.21]."""
a, b, c = 3.4445, -4.7750, 2.0315
X = G.to(torch.bfloat16 if G.is_cuda else torch.float32) # bfloat16 en GPU; en CPU sería muy lento
alta = X.size(0) > X.size(1)
if alta:
X = X.mT
X = X / (X.norm() + eps)
for _ in range(pasos):
A = X @ X.mT
B = b * A + c * (A @ A)
X = a * X + B @ X
if alta:
X = X.mT
return X.to(G.dtype)
class Muon(torch.optim.Optimizer):
"""Muon para parámetros 2D: momentum de Nesterov, ortogonalización y escalado por forma."""
def __init__(self, params, lr=0.02, momentum=0.95, nesterov=True, ns_pasos=5, weight_decay=0.0):
super().__init__(params, dict(lr=lr, momentum=momentum, nesterov=nesterov, ns_pasos=ns_pasos, weight_decay=weight_decay))
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for grupo in self.param_groups:
for p in grupo["params"]:
if p.grad is None:
continue
assert p.ndim == 2, "Muon solo para matrices: usa AdamW para sesgos, ganancias y embeddings"
estado = self.state[p]
if "buf" not in estado:
estado["buf"] = torch.zeros_like(p)
buf = estado["buf"]
buf.mul_(grupo["momentum"]).add_(p.grad)
u = p.grad.add(buf, alpha=grupo["momentum"]) if grupo["nesterov"] else buf
o = newton_schulz5(u, grupo["ns_pasos"])
escala = max(1.0, p.size(0) / p.size(1)) ** 0.5 # escalado por forma de la versión original
p.mul_(1 - grupo["lr"] * grupo["weight_decay"])
p.add_(o, alpha=-grupo["lr"] * escala)
return loss
# datos sintéticos sin fin: cada lote es nuevo, etiquetado por un MLP maestro aleatorio con 10 clases
g = torch.Generator().manual_seed(0)
d_in = 32
maestro = [torch.randn(d_in, 64, generator=g) / d_in**0.25, torch.randn(64, 10, generator=g) / 2]
def lote_nuevo(n, gen):
x = torch.randn(n, d_in, generator=gen)
return x, (torch.tanh(x @ maestro[0]) @ maestro[1]).argmax(1)
x_te, y_te = lote_nuevo(8192, torch.Generator().manual_seed(123))
def modelo():
torch.manual_seed(1)
return nn.Sequential(nn.Linear(d_in, 128), nn.GELU(), nn.Linear(128, 128), nn.GELU(),
nn.Linear(128, 128), nn.GELU(), nn.Linear(128, 10)).to(DEVICE)
def entrenar(opt_fn, pasos=600, lote=128):
gen = torch.Generator().manual_seed(2) # los mismos lotes para todos los optimizadores
red = modelo()
opts = opt_fn(red)
for t in range(pasos):
x, y = lote_nuevo(lote, gen)
perdida = F.cross_entropy(red(x.to(DEVICE)), y.to(DEVICE))
for o in opts:
o.zero_grad(set_to_none=True)
perdida.backward()
factor = min(1.0, 2 * (1 - t / pasos)) # constante y luego decaimiento lineal
for o in opts:
for grupo in o.param_groups:
grupo["lr"] = grupo["lr_base"] * factor
o.step()
with torch.no_grad():
salida = red(x_te.to(DEVICE))
return F.cross_entropy(salida, y_te.to(DEVICE)).item(), (salida.argmax(1) == y_te.to(DEVICE)).float().mean().item()
def con_base(opt):
for grupo in opt.param_groups:
grupo["lr_base"] = grupo["lr"]
return opt
def solo_adamw(lr):
return lambda red: [con_base(torch.optim.AdamW(red.parameters(), lr=lr, weight_decay=0.01))]
def muon_y_adamw(lr_muon, lr_adam=3e-3):
def f(red):
capas = [m for m in red if isinstance(m, nn.Linear)]
ocultas = [c.weight for c in capas[1:-1]] # matrices ocultas: Muon
resto = [p for p in red.parameters() if all(p is not q for q in ocultas)] # entrada, salida y sesgos
return [con_base(Muon(ocultas, lr=lr_muon)), con_base(torch.optim.AdamW(resto, lr=lr_adam, weight_decay=0.01))]
return f
t0 = time.time()
print("AdamW en todo:")
for lr in [1e-3, 3e-3, 1e-2, 3e-2]:
ent, ex = entrenar(solo_adamw(lr))
print(f" lr = {lr:.0e} pérdida de prueba {ent:.3f} exactitud de prueba {ex:.3f}")
print("Muon en las ocultas + AdamW (lr 3e-3) en el resto:")
for lr in [0.01, 0.03, 0.1, 0.3]:
ent, ex = entrenar(muon_y_adamw(lr))
print(f" lr = {lr:.2f} pérdida de prueba {ent:.3f} exactitud de prueba {ex:.3f}")
print(f"tiempo total: {time.time() - t0:.1f} s")npm run lab and open the connection link.In this small MLP the two are close: best Muon test loss is 0.864 and best AdamW 0.877. This is comparable to seed variation; the right reading is “tie under this budget,” not “Muon wins.” Also notice we did not search more Muon rates than AdamW. (If anything Muon has an informational advantage: its remaining parameters’ AdamW rate is the best from the AdamW sweep.) Unequal tuning is the optimizer literature’s commonest trap.
Recent PyTorch versions include torch.optim.Muon (the lab uses 2.11), with the same rule, default coefficients and both scaling conventions. Momentum is written as moving average and Newton–Schulz input as ; both are times those above, and normalization before iteration makes the step identical. Since torch.optim.Muon’s rate is multiplied by the chosen shape factor, with "match_rms_adamw" use the same rate as AdamW and with "original" one around 0.02:
import torch
matrices = [p for n, p in model.named_parameters() if p.ndim == 2 and "embed" not in n and "lm_head" not in n]
otros = [p for n, p in model.named_parameters() if not (p.ndim == 2 and "embed" not in n and "lm_head" not in n)]
opt_muon = torch.optim.Muon(matrices, lr=3e-4, weight_decay=0.1, momentum=0.95, ns_steps=5,
adjust_lr_fn="match_rms_adamw") # factor 0.2 sqrt(max(A, B)): misma tasa que AdamW
# alternativa: adjust_lr_fn="original" (factor sqrt(max(1, A/B))) con lr del orden de 2e-2
opt_adamw = torch.optim.AdamW(otros, lr=3e-4, betas=(0.9, 0.95), weight_decay=0.1)
# en cada paso: loss.backward(); opt_muon.step(); opt_adamw.step(); y zero_grad en los dos
With adjust_lr_fn="match_rms_adamw" the factor is Moonshot’s , and documentation says AdamW’s rate and weight decay can then be reused. Names embed and lm_head depend on your model: inspect named_parameters().
Evidence at scale and open questions
What is known today, separating results from expectations:
- Speed records. Muon began in public training-speed races: Jordan et al. used it to break NanoGPT (a small GPT-2) and CIFAR-10 training-time records in 2024. These are small, highly optimized tasks with all other details carefully tuned.
- LLM scale. Liu et al. (2025, Moonshot AI) found two changes needed to scale: add weight decay and adjust shape scaling to match AdamW RMS. Their scaling-law experiments indicate compute efficiency around versus AdamW, and they trained Moonlight, a 16 000-million-parameter mixture of experts (3 000 million active), on 5.7 trillion tokens. Kimi K2 from the same group (2025) used MuonClip, rescaling attention query and key weights when logits exceed a threshold because Muon tended to make them grow uncontrollably.
- Careful comparisons. Wen et al. (2025), “Fantastic Pretraining Optimizers and Where to Find Them,” tuned about ten optimizers equally carefully. Many published advantages came from poorly tuned baselines; matrix optimizers such as Muon and SOAP retained an advantage that shrinks with scale: from about at 100 million parameters to at 1 200 million (at that size, hyperparameters extrapolated by scaling law rather than a full sweep).
What remains open:
- Why it works. Spectral-norm reasoning says which step is optimal for a linear model in that norm, not why that norm describes network loss well. Hypotheses (low stable-rank gradients, learning rare directions, links to maximal update parameterization and Bernstein’s modular norms) remain unsettled.
- Distributed cost. Newton–Schulz needs the whole matrix. With parameters sharded across devices (ZeRO, FSDP), each matrix must be gathered before orthogonalization, adding communication elementwise AdamW does not need.
- Interactions. With weight decay, rate schedules, attention stability (hence MuonClip), and fine-tuning models pretrained with another optimizer.
The next lesson follows this thread: curvature-accumulating preconditioners (K-FAC, Shampoo, SOAP) and how to evaluate optimizers without fooling oneself.
Common mistakes
Exercises
Step 1 of 4. What lower bound holds for each term ?
Step 1 of 4. How do you write ?
newton_schulz_orthogonalize(G, steps, coef=(1.5, -0.5, 0.0)), returning the approximation to after steps iterations of with . First normalize by Frobenius norm (plus 1e-12), use wide orientation (transpose if and undo at the end), and return a matrix shaped like G. Also implement desviacion(X), the maximum over singular values of X.import numpy as np
def newton_schulz_orthogonalize(G, steps, coef=(1.5, -0.5, 0.0)):
a, b, c = coef
X = np.array(G, dtype=float)
# tu código: normalizar, orientación ancha y las iteraciones
for _ in range(steps):
A = X @ X.T
X = a * X + (b * A + c * A @ A) @ X
return X
def desviacion(X):
# tu código: max |sigma_i - 1|
return 0.0Summary
- The normalized step measures in the chosen norm and decreases the linear model by ; the descent-lemma guarantee depends on the pair (norm, constant in that norm), and good geometry makes small.
- Sign is robust (clips outliers, invariant to coordinate scaling) but basis-dependent. Lion takes the sign of an interpolation of two moving averages and needs lower rates and higher weight decay than AdamW.
- Natural gradient is steepest descent for local KL, invariant under reparameterization (exact in flow, per step). Empirical Fisher with real labels is not Fisher.
- For a matrix, spectral steepest descent is , the sign of singular values; it distributes the step equally across gradient directions and is rotation-equivariant.
- Newton–Schulz approximates with odd polynomials and matrix products alone; normalize first. Muon’s quintic trades accuracy for speed and takes values to in five steps.
- Muon = Nesterov momentum, Newton–Schulz and shape scaling, only on hidden matrices; embeddings, output, biases and gains use AdamW. Evidence at scale is real but decreases with well-tuned AdamW and larger models.