Low rank and orthogonalization in modern deep learning
Connect randomized SVD, singular-mode learning, low-rank optimizers, spectral steepest descent and Newton–Schulz orthogonalization.
After this lesson you can
- Derive randomized range-finder bounds and the effect of power iterations.
- Explain singular-mode dynamics in deep linear networks.
- Compare LoRA and GaLore gradient geometry and optimizer memory.
- Derive spectral-norm steepest descent and Newton–Schulz convergence.
- Distinguish optimizer theorems from empirical and speculative claims.
Before you start
- 02Singular value decompositionPolar decompositionLow-rank approximationEckart-Young-Mirsky theoremSchatten norms and nuclear normOperator normQR decompositionMatrix functionsStable rank and effective rankLinear layer gradientsVector-Jacobian and Jacobian-vector productsOrthogonal matrixMatrix exponential
- 04Multivariate Gaussian distributionRotational invariance of the standard Gaussian
- 06Gradient descentStochastic momentumAdam
- 15Micro framework to PyTorch correspondenceMultilayer perceptron
- 00Canonical training and evaluation loop
Motivation: linear algebra inside the optimizer
A transformer is primarily a collection of matrices . During training each receives at every step a same-shaped gradient and the optimizer turns it into update . Until recently optimizers treated matrices as long vectors: Adam scales each entry separately and does not know has rows and columns. Several influential recent ideas for training large models restore matrix structure to :
- LoRA (Hu et al., 2021) adapts a pretrained model by restricting updates to low rank, with , and . This is low-rank approximation as a design constraint.
- GaLore (Zhao et al., 2024) restricts optimizer state rather than weights: it projects each gradient onto leading singular vectors and stores Adam moments in that small subspace.
- Muon (Jordan, 2024) replaces the update with , the orthogonal factor of the gradient’s polar decomposition, computing it without SVD using only matrix products.
Behind all three is familiar linear algebra: SVD, the Eckart–Young theorem, Schatten norms and matrix functions. This lesson develops five pieces: randomized SVD for enormous matrices, the order in which deep linear networks learn target singular modes, why layer gradients have low-rank structure, which descent direction belongs to each matrix norm, and how a polynomial applied to a matrix sends all its singular values to 1.
A methodological note before starting. This is active research where precise theorems, well-executed large-scale experiments and unreplicated blog claims coexist. We distinguish the three in each section and summarize them in a final table. The lesson follows gradient descent and the multilayer perceptron; if you have not studied them, follow the algebra and return to training later.
Capturing range with randomness: randomized SVD
The full SVD of costs operations and, worse, requires many irregular matrix accesses. For an matrix this is order operations, and usually only the first singular values matter, with between 10 and a few hundred. Halko, Martinsson and Tropp (2011) split the problem in two:
- Find the range. Seek a matrix with orthonormal columns, slightly greater than , such that : a subspace of dimension containing nearly all action of .
- Factorize the small problem. Form , which is small, calculate its exact SVD and return . Since , factorization error is exactly that of step 1.
Step 2 is cheap deterministic algebra. All interest lies in step 1, and the answer is surprising: multiplying by a few Gaussian vectors suffices.
Why randomness works
Write and take . Then
By rotational invariance of the multivariate Gaussian, is again : are independent and typically size 1. Thus is a random combination of weighted by : large-singular-value directions dominate. With vectors, the span of mainly points to leading singular directions. The same invariance has a practical consequence: algorithm behavior depends only on singular values of , not vectors. To study it, diagonal suffices, as in the next figure.
Products by are batched, as by matrix multiplication, the most efficient operation on processors. If is sparse or known only through a function computing (a Hessian, a network operator), the algorithm still works: it never needs entries of .
The figure shows the two ingredients theory will justify. Oversampling is cheap and always helps: with some of the leading directions are only half captured, while with or nearly fully. Power iterations replace with , with the same singular vectors and singular values : the spectral tail sinks and the sketch concentrates on leading directions. Which is preferable for equal products with ? It depends on the spectrum. For matrices, and 60 products (mean of five seeds), in slow spectrum one power iteration without oversampling leaves error and 40 extra columns without powers ; with low rank plus noise floor, versus . For a fast-decaying spectrum the reverse holds: 40 extra columns reach optimum and one power iteration without oversampling remains at .
A deterministic bound
To see these effects, split into its leading singular-value block and remainder , and similarly split into (projection onto the leading right singular vectors) and (onto the rest).
Proof
Since has full row rank, its pseudoinverse satisfies . Define . Its columns combine those of , so and projecting onto the larger space leaves less residual: . Calculate :
Call it . Since , . Write by column blocks, the first and the rest:
is a projector and , are orthogonal, so . For a horizontal block matrix, , hence . With and the bound follows.
∎The two terms have direct interpretations. First, is the Eckart–Young optimum: no -dimensional subspace improves it. Second is the price of randomness. It contains , the whole spectral tail mixed by the Gaussian, large for a heavy tail; and , the reciprocal of the smallest singular value of Gaussian . With that matrix is square and its smallest singular value is order with a tail toward zero; a few units of move it away from zero (by Marchenko–Pastur, for large and fixed it approaches ). Oversampling controls ; power iterations control the tail.
The mean bound and power iteration effect
Taking expectations over the Gaussian, Halko, Martinsson and Tropp obtain explicit bounds (their theorems 10.5 and 10.6). For and :
The Frobenius bound is striking: with mean error is at most times the Eckart–Young optimum in that norm. The spectral bound shows the slow-spectrum problem: the final term contains the tail Frobenius norm, potentially much greater than . With and large , grows as and the bound deteriorates without limit. Power iterations fix this: since has singular values and, for any orthogonal projector , (proposition 8.6 of the same paper), apply the spectral bound with instead of and take the -th root. The effective ratio between tail and is raised to : with a gap between neighboring singular values becomes .
In practice and between 1 and 3 nearly always suffice. scikit-learn defaults to and (or if ), normalizing between iterations with LU when .
Learning by modes: deep linear networks
SVD is not only computational. It also describes how a network learns. The provable case is deep linear networks, : without activations the represented function is linear, but loss is nonconvex in weights and training dynamics are surprisingly rich. Saxe, McClelland and Ganguli (2014) solved it exactly.
Take whitened inputs and input–output correlation with SVD . Expanding the square, population squared loss is
Gradient descent with small step is approximated by gradient flow with time . With linear-layer gradients, for two layers:
The two equations couple all weights. The key is to seek solutions respecting the geometry of .
Proof
Substitute ansatz , into the flow. Since , and . Then
Both derivatives exactly match the ansatz form with , so the ODE solution in generates, via the ansatz, a matrix-flow solution; uniqueness for ODEs with locally Lipschitz field makes it the solution. For : , a logistic equation with the stated solution (check by differentiation). With layers, with , ; the same calculation gives and, with , .
∎The logistic equation says much. If is small, the mode spends a long time near zero (a plateau), then grows abruptly and saturates at . Time to halfway is
inversely proportional to . Strong modes are learned first and weak ones wait. This is singular-mode learning dynamics: a deep linear network with small initialization learns input–output modes one by one, in decreasing singular-value order, and loss decreases in steps with plateaus at . One layer behaves differently: is linear, each mode follows and all advance with the same time constant. Depth changes dynamics even without adding expressive capacity.
Three qualifications separate proof from observation:
- Exact is the theorem with aligned balanced initialization. The figure shows that small random initialization with two layers closely resembles the prediction with order-one time offsets; with three layers plateaus and steps remain but times differ more from the aligned curve, and ordering among modes with similar can change depending on initialization projection onto each. Saxe et al. argue the approximation heuristically. Later rigorous results relax assumptions for two-layer networks with vanishing initialization, such as Gidel, Bach and Lacoste-Julien (2019) for discrete gradient descent, but do not cover arbitrary initialization or depth.
- Large initialization. When is order 1, the initial product is already comparable to target, the network moves little relative to its size and modes advance in parallel. This is a linear relative of lazy training (Chizat, Oyallon and Bach, 2019), where a network behaves almost like its linearization around initialization.
- Nonlinear networks. Stepwise learning and preference for low-effective-rank solutions are often observed with activations, and broad literature studies implicit low-rank bias in deep factorizations (e.g. Arora, Cohen, Hu and Luo, 2019). But extending Saxe’s theorem to a transformer is a hypothesis, not a result.
Another theorem detail matters later: with orthogonal balanced initialization, all product singular values begin equal and each mode’s dynamics depend only on its . Saxe et al. proposed orthogonal initialization from this analysis.
Low-rank gradients: from LoRA to GaLore
What does a layer gradient look like? For in a network and a batch of examples, the chain rule with the vector–Jacobian product gives
The gradient is a sum of outer products, so . In a transformer, counts tokens and usually exceeds , so the gradient is not literally low-rank. Empirically its spectrum decays quickly: a few directions contain most Frobenius norm, and its effective rank is small relative to . Two ways exploit this.
LoRA freezes and trains only , with initially so the starting model is unchanged. For a matrix and , numbers are trained instead of million. Prior empirical motivation is that pretrained-model fine-tuning has low intrinsic dimension: Aghajanyan, Zettlemoyer and Gupta (2020) find, for example, that tuning RoBERTa on MRPC by optimizing only 200 parameters projected to full space by a random linear map reaches 90 % of full-tuning performance. The restriction is strong: total weight change has rank forever.
GaLore does something else. It allows full-rank weight changes but compresses optimizer memory. For with :
- Every steps, calculate the leading left singular vectors of the current gradient, .
- Each step project and update Adam moments on , obtaining direction .
- Return the update to full space: .
Adam moments occupy numbers instead of , a factor less, at the cost of storing ( numbers) and an SVD of every steps (or the preceding randomized SVD). Since changes over time, the sum of many updates can be full rank, unlike LoRA. Zhao et al. (2024) report up to 65.5 % reduction in optimizer-state memory while maintaining loss in pretraining 1B and 7B LLaMA models, and pretraining a 7B model on a 24 GB consumer GPU by combining an 8-bit optimizer. Their theoretical analysis proves gradient low-rankness during training for a restricted network class (reversible, with certain losses), excluding transformers: for those evidence is empirical.
Steepest descent by norm
Gradient descent is usually presented as “move in direction ”. But steepest descent depends on how step size is measured. If the budget is Euclidean length , the best direction is . Another norm changes the answer.
If step size is penalized as well as budgeted, minimizing model yields : write with , maximize first in then minimize in . Bernstein and Newhouse (2024) show that several known optimizers with moving averages disabled are exactly this for different norms: Euclidean gives gradient descent; maximum-entry norm gives sign descent , Adam without moving averages; and spectral norm gives Shampoo without accumulation. Spectral norm is our focus.
This is spectral-norm steepest descent. You will prove it in the first guided exercise using SVD and unit-vector inequality . The point is what it says: preserves singular directions of but sets every singular value to 1. If the gradient has and , Euclidean descent moves direction 50 a thousand times less than the first; spectral descent moves them equally. Whether that helps training is a hypothesis (weak gradient directions are no longer overwhelmed by dominant ones), not a theorem consequence.
The figure shows the general structure. In singular-value space Schatten norms are norms and the problem reduces to vectors: Frobenius () gives ; spectral (), ; nuclear (), . Readouts confirm attained value is the dual norm: Frobenius is self-dual, spectral and nuclear are mutually dual.
Why spectral norm for network layers? It directly controls layer-output change: for every input. If activations have typical size (order-one inputs), the natural norm is the operator norm between RMS norms, , and steepest descent under it is . Original Muon implementation uses that shape factor clipped below, .
Orthogonalizing without SVD: Newton–Schulz iteration
Computing by SVD at every step for every matrix is expensive and on GPU is also sequential, unable to exploit matrix-multiplication units. The alternative is a classical numerical-analysis idea: approximate the polar factor by an iteration using only matrix multiplication.
Proof
because . Similarly . Summing with coefficients gives .
∎This is a matrix function applied to singular values rather than eigenvalues, and works only for odd polynomials (an even term such as would change matrix shape). If an iterated odd polynomial sends every toward 1, iteration converges to without calculating or .
The name combines two ideas. Newton iteration for the polar factor is , requiring inversion; Schulz approximates the inverse with Taylor expansion when . Substitution gives . Björck and Bowie (1971) studied it for the nearest orthogonal matrix, precisely the polar factor.
Three properties of determine everything:
- Quadratic convergence near 1. : error is squared each step because .
- Slow growth near 0. : a small singular value is multiplied only by per step. From , 16 iterations merely exceed and 20 come within of 1.
- A limited basin. and is positive on . If , is negative and iteration can converge to in that direction; if , and it diverges. Frobenius normalization guarantees because .
Muon’s quintic
An optimizer does not need exact ; it needs something close in few iterations and low precision (bf16). Keller Jordan empirically chose quintic polynomial
with slope at the origin so small singular values grow rapidly. The price is that iteration does not converge: its positive fixed points are and , both unstable, and singular values eventually oscillate in a band. Computing with the polynomial, five iterations move any into interval , one more leaves them in , and maps that interval into itself: they do not escape, but do not stay still. The result is with diagonal near identity, empirically just as effective as an update direction. That last claim is empirical, not a theorem. Its basin also ends at , closer to 1 than the cubic’s: prior normalization is even more necessary.
With all this, Muon (MomentUm Orthogonalized by Newton–Schulz) for hidden matrix is:
with Nesterov momentum and five quintic bf16 steps. It applies only to hidden-layer 2D matrices; embeddings, output head and vector parameters (biases, normalization gains) remain on AdamW. Liu et al. (2025) identified two adjustments to scale it to large language models: adding weight decay and scaling the update by to match typical AdamW update magnitude. From scaling-law experiments they report Muon reaches the same loss as AdamW with about half the compute.
Orthogonality at initialization and in parameterization
Saxe’s theorem suggests starting the layer product with equal singular values. With Gaussian matrices of variance each layer preserves vector norm on average, but singular values follow Marchenko–Pastur between and , and dispersion multiplies across a product of layers: the ratio of largest to smallest singular value grows exponentially with (measured below: with layers of it exceeds ). With orthogonal matrices the product is orthogonal and all singular values equal 1 exactly at any depth. Having all input–output Jacobian singular values near 1 is dynamical isometry; Pennington, Schoenholz and Ganguli (2017) studied it in nonlinear networks. In PyTorch it is torch.nn.init.orthogonal_.
Sometimes a matrix must remain orthogonal throughout training, for example in recurrent networks to avoid exploding or vanishing gradients, or normalizing flows to make the determinant . Direct optimization over orthogonal matrices needs manifold methods; an alternative is to parameterize: write with free and mapping to orthogonal matrices. Two classical constructions start with antisymmetric :
- Exponential. with the matrix exponential. Since and commute, and . It covers all rotations.
- Cayley. . Eigenvalues of are purely imaginary, so is invertible; since and commute, . It is cheaper (one linear solve), but cannot reach orthogonal matrices with eigenvalue .
torch.nn.utils.parametrizations.orthogonal implements both (and a third using Householder reflections), letting the optimizer work on .
Implementation from scratch
First randomized SVD. To construct dense matrices with known spectrum without QR of , mix with a few Householder reflections on each side: the result is with orthogonal and , and exact is known. Residual spectral norm is estimated by the power method, much cheaper than SVD of .
import numpy as np
import time
def householder_mix(M, n_refl, rng, lado):
"""Aplica n_refl reflexiones de Householder aleatorias por la izquierda (lado=0) o por la derecha (lado=1)."""
M = M.copy()
for _ in range(n_refl):
v = rng.standard_normal(M.shape[lado])
v /= np.linalg.norm(v)
if lado == 0:
M -= 2.0 * np.outer(v, v @ M)
else:
M -= 2.0 * np.outer(M @ v, v)
return M
def matriz_con_espectro(m, n, s, rng):
"""A = U diag(s) V^T densa, con U y V ortogonales (productos de reflexiones) y valores singulares s."""
A = np.zeros((m, n))
A[np.arange(n), np.arange(n)] = s
return householder_mix(householder_mix(A, 4, rng, 0), 4, rng, 1)
def buscador_de_rango(A, l, q, rng):
"""Base ortonormal Q (m x l) del rango aproximado de A, con q iteraciones de potencia reortogonalizadas."""
Omega = rng.standard_normal((A.shape[1], l))
Q, _ = np.linalg.qr(A @ Omega)
for _ in range(q):
Z, _ = np.linalg.qr(A.T @ Q) # reortogonalizar tras cada producto: sin esto,
Q, _ = np.linalg.qr(A @ Z) # los modos pequeños se pierden en el redondeo
return Q
def svd_aleatorizada(A, k, p=10, q=1, rng=None):
rng = np.random.default_rng() if rng is None else rng
Q = buscador_de_rango(A, k + p, q, rng)
B = Q.T @ A # (k + p) x n: pequeña
Ub, s, Vt = np.linalg.svd(B, full_matrices=False)
return (Q @ Ub)[:, :k], s[:k], Vt[:k]
def norma2(E, iters=60, seed=0):
"""Estimación de ||E||_2 por iteración de la potencia sobre E^T E (cota inferior que converge deprisa)."""
x = np.random.default_rng(seed).standard_normal(E.shape[1])
for _ in range(iters):
x = E.T @ (E @ x)
x /= np.linalg.norm(x)
return np.linalg.norm(E @ x)
m, n, k = 1000, 500, 20
j = np.arange(1, n + 1)
espectros = {"rápido": np.exp(-(j - 1) / 8), "lento": 1 / np.sqrt(j)}
rng = np.random.default_rng(0)
mats = {nombre: matriz_con_espectro(m, n, s, rng) for nombre, s in espectros.items()}
print(f"{'espectro':8s} {'p':>3s} {'q':>2s} ||A - A_k|| / sigma_k+1 err. rel. sigma_1 err. rel. sigma_k")
for nombre, s in espectros.items():
A = mats[nombre]
for p, q in [(0, 0), (10, 0), (10, 1), (10, 2)]:
U, sk, Vt = svd_aleatorizada(A, k, p, q, np.random.default_rng(1))
e = norma2(A - (U * sk) @ Vt)
print(f"{nombre:8s} {p:3d} {q:2d} {e / s[k]:22.3f} {abs(sk[0] - s[0]) / s[0]:17.2e} {abs(sk[-1] - s[k-1]) / s[k-1]:17.2e}")The table reproduces the figure. With fast spectrum, and one power iteration already reach the Eckart–Young optimum to three digits. With slow spectrum, without powers error is over twice optimum even with , and estimated errs by 8 %: the heavy tail contaminates even the first direction. With error falls to . is always least accurately estimated: it competes with the tail.
A = mats["lento"]
t0 = time.perf_counter(); U_, s_, Vt_ = np.linalg.svd(A, full_matrices=False); t_svd = time.perf_counter() - t0
t0 = time.perf_counter(); svd_aleatorizada(A, k, 10, 2, np.random.default_rng(2)); t_rsvd = time.perf_counter() - t0
print(f"SVD completa: {t_svd:.2f} s SVD aleatorizada (k=20, p=10, q=2): {t_rsvd:.3f} s cociente: {t_svd / t_rsvd:.0f}x")
print("¿coinciden los valores singulares exactos con los construidos?", np.allclose(s_, espectros["lento"]))In the browser randomized SVD is about six times faster on this matrix (somewhat more with native NumPy), and the advantage grows with size: full SVD cost scales as and randomized as . On the machine used to write this lesson, with , full SVD took 1.5 s and randomized 0.05 s.
Now Newton–Schulz. Construct an “gradient” with singular values from 1 to on a logarithmic scale, apply both iterations and measure distance of from the polar factor.
import numpy as np
import time
def newton_schulz(G, pasos, coef=(1.5, -0.5, 0.0), normalizar=True):
"""X <- aX + b(XX^T)X + c(XX^T)^2 X. Devuelve la lista de iterados X_0, ..., X_pasos."""
a, b, c = coef
X = G / np.linalg.norm(G) if normalizar else G.copy() # ||G||_F >= ||G||_2: todos los sigma <= 1
traspuesta = X.shape[0] > X.shape[1]
if traspuesta: # trabajar con la cara corta: XX^T es min(m, n) x min(m, n)
X = X.T
iterados = [X]
for _ in range(pasos):
S = X @ X.T
P = b * S + c * (S @ S) if c else b * S
X = a * X + P @ X
iterados.append(X)
return [Y.T for Y in iterados] if traspuesta else iterados
rng = np.random.default_rng(0)
m, n = 64, 128
U, _ = np.linalg.qr(rng.standard_normal((m, m)))
V, _ = np.linalg.qr(rng.standard_normal((n, m)))
s = np.logspace(0, -3, m) # de 1 a 1e-3, como un gradiente con cola larga
G = (U * s) @ V.T
polar = U @ V.T # el objetivo: el factor polar U V^T
MUON = (3.4445, -4.7750, 2.0315)
for nombre, coef in [("cúbica", (1.5, -0.5, 0.0)), ("quíntica de Muon", MUON)]:
its = newton_schulz(G, 12, coef)
print(nombre)
for k in [0, 1, 2, 4, 6, 8, 12]:
sv = np.linalg.svd(its[k], compute_uv=False)
# X_k = U p(Σ) V^T, así que ||X_k - UV^T||_2 = max |σ_i - 1| (lo comprobamos en la celda siguiente)
print(f" k = {k:2d} sigma en [{sv.min():.4f}, {sv.max():.4f}] ||X_k - UV^T||_2 = {np.max(np.abs(sv - 1)):.3f}")Two facts stand out. Frobenius normalization, which guarantees the basin, shrinks the whole spectrum: starts at , not 1, and at . With cubic, after 12 iterations the smallest singular value only reaches . Quintic moves it into band in six iterations and it remains there: polar-factor distance plateaus at , namely , the lower band edge. Neither reaches in few steps with such a broad spectrum; quintic instead gives a matrix with all singular values order 1, what the optimizer needs.
# ¿actúa de verdad sobre cada valor singular por separado? Comparar con el polinomio aplicado a s
p3 = lambda x: 1.5 * x - 0.5 * x**3
s_pred = s / np.linalg.norm(G)
for _ in range(5):
s_pred = p3(s_pred)
s_med = np.linalg.svd(newton_schulz(G, 5)[5], compute_uv=False)
print("máx |sigma medido - p^5(sigma)|:", np.max(np.abs(np.sort(s_med) - np.sort(s_pred))))
print("||X_5 - UV^T||_2 directa:", np.linalg.norm(newton_schulz(G, 5)[5] - polar, 2), " max|sigma - 1|:", np.max(np.abs(s_med - 1)))
# coste: productos de matrices frente a una SVD, en este Python (CPU, sin BLAS en el navegador)
X = rng.standard_normal((256, 512))
t0 = time.perf_counter(); newton_schulz(X, 5, MUON); t_ns = time.perf_counter() - t0
t0 = time.perf_counter(); Ux, sx, Vtx = np.linalg.svd(X, full_matrices=False); t_svd = time.perf_counter() - t0
mm, nn = X.shape
print(f"5 pasos quínticos: {t_ns:.3f} s, unos {5 * (4 * mm * mm * nn + 2 * mm**3) / 1e9:.2f} GFLOP")
print(f"SVD reducida: {t_svd:.3f} s")The first check confirms the theorem up to rounding (). The second teaches honesty: in the browser, without BLAS, SVD wins. Five quintic steps on an matrix cost about GFLOP and take roughly three times as long as reduced SVD, which does a similar operation count; with native CPU NumPy the times are comparable. Newton–Schulz’s advantage is operation type, not count: dense matrix products execute in bf16 near GPU peak and batch together, versus sequential SVD requiring fp32 or fp64. The next section measures this on GPU.
Finally, layer products and orthogonal parameterizations.
import numpy as np
from scipy.linalg import expm
rng = np.random.default_rng(0)
n, L = 64, 40
def espectro_del_producto(fabrica):
P = np.eye(n)
for _ in range(L):
P = fabrica() @ P
s = np.linalg.svd(P, compute_uv=False)
return s.max(), s.min()
gauss = lambda: rng.standard_normal((n, n)) / np.sqrt(n) # varianza 1/n: escala "correcta" en media
orto = lambda: np.linalg.qr(rng.standard_normal((n, n)))[0] # Q de una QR gaussiana
for nombre, f in [("gaussiana 1/sqrt(n)", gauss), ("ortogonal", orto)]:
smax, smin = espectro_del_producto(f)
print(f"{nombre:20s} producto de {L} capas: sigma_max = {smax:.3g}, sigma_min = {smin:.3g}, cociente = {smax / smin:.3g}")
# parametrizaciones ortogonales: Cayley y exponencial de una antisimétrica
M = rng.standard_normal((5, 5))
A = (M - M.T) / 2 # antisimétrica: A^T = -A
I = np.eye(5)
Q_cay = (I - A) @ np.linalg.inv(I + A)
Q_exp = expm(A)
for nombre, Q in [("Cayley", Q_cay), ("exponencial", Q_exp)]:
print(f"{nombre:12s} ||Q^T Q - I|| = {np.linalg.norm(Q.T @ Q - I):.1e} det = {np.linalg.det(Q):+.6f}")The product of 40 Gaussian layers has an extreme singular-value ratio of order : numerically it is rank deficient, as is a gradient passing through. The orthogonal product’s ratio is exactly 1.
The library version
Randomized SVD is in scikit-learn (sklearn.utils.extmath.randomized_svd) and PyTorch (torch.svd_lowrank, also accepting sparse matrices). scikit-learn normalizes power iterations with LU (cheaper than QR and sufficient to avoid overflow); its documentation recommends increasing oversampling before iterations, adding that 0 or 1 iterations suffice if component count reaches effective rank and the spectrum does not decay slowly. This is what you measured: oversampling pays for fast spectra and powers for slow ones.
from sklearn.utils.extmath import randomized_svd
import torch
A = mats["lento"] # la matriz de 1000 x 500 de espectro lento de la primera celda
# scikit-learn: n_oversamples es p y n_iter es q
U, s, Vt = randomized_svd(A, n_components=20, n_oversamples=10, n_iter=2, random_state=0)
# PyTorch: q es el número de columnas del sketch (k + p) y niter las iteraciones de potencia
U, s, V = torch.svd_lowrank(torch.as_tensor(A), q=30, niter=2) # devuelve V, no V^T
On the previous slow-spectrum matrix, scikit-learn randomized_svd gives error with n_iter=0 and with n_iter=2, consistent with our implementation. Importing scikit-learn in the browser takes seconds, so this block does not execute here; try local Python.
For Muon and GaLore the lab runs on GPU. A character MiniGPT (4 blocks, , context 128) trains on source code from Python standard-library modules, present in any installation. This is the usual training loop, with correspondence between hand-written operations and PyTorch.
import math, time, inspect
import json.decoder, json.encoder, collections, argparse, textwrap, statistics, fractions, dataclasses
import torch
import torch.nn as nn
import torch.nn.functional as F
dev = "cuda" if torch.cuda.is_available() else "cpu"
# corpus: código fuente de la biblioteca estándar (está en cualquier instalación de Python)
modulos = [json.decoder, json.encoder, collections, argparse, textwrap, statistics, fractions, dataclasses]
texto = "".join(inspect.getsource(m) for m in modulos)
vocab = sorted(set(texto))
stoi = {c: i for i, c in enumerate(vocab)}
datos = torch.tensor([stoi[c] for c in texto], dtype=torch.long)
corte = int(0.9 * len(datos))
train, val = datos[:corte].to(dev), datos[corte:].to(dev)
print(f"{len(texto)} caracteres, vocabulario {len(vocab)}, dispositivo {dev}")
T, B, D, CAPAS, CABEZAS = 128, 32, 128, 4, 4
class Bloque(nn.Module):
def __init__(self):
super().__init__()
self.ln1, self.ln2 = nn.LayerNorm(D), nn.LayerNorm(D)
self.qkv = nn.Linear(D, 3 * D, bias=False)
self.proj = nn.Linear(D, D, bias=False)
self.fc = nn.Linear(D, 4 * D, bias=False)
self.fc2 = nn.Linear(4 * D, D, bias=False)
def forward(self, x):
q, k, v = self.qkv(self.ln1(x)).split(D, dim=-1)
sep = lambda t: t.view(x.shape[0], x.shape[1], CABEZAS, D // CABEZAS).transpose(1, 2)
a = F.scaled_dot_product_attention(sep(q), sep(k), sep(v), is_causal=True)
x = x + self.proj(a.transpose(1, 2).reshape(x.shape))
return x + self.fc2(F.gelu(self.fc(self.ln2(x))))
class MiniGPT(nn.Module):
def __init__(self):
super().__init__()
self.emb = nn.Embedding(len(vocab), D)
self.pos = nn.Parameter(0.02 * torch.randn(T, D))
self.bloques = nn.ModuleList([Bloque() for _ in range(CAPAS)])
self.ln = nn.LayerNorm(D)
self.cabeza = nn.Linear(D, len(vocab), bias=False)
def forward(self, idx):
x = self.emb(idx) + self.pos[: idx.shape[1]]
for b in self.bloques:
x = b(x)
return self.cabeza(self.ln(x))
def lote(fuente, gen):
i = torch.randint(len(fuente) - T - 1, (B,), generator=gen).to(dev)
off = torch.arange(T, device=dev)
return fuente[i[:, None] + off], fuente[i[:, None] + off + 1]
@torch.no_grad()
def perdida_val(modelo, n=20):
gen = torch.Generator().manual_seed(123)
tot = 0.0
for _ in range(n):
x, y = lote(val, gen)
tot += F.cross_entropy(modelo(x).flatten(0, 1), y.flatten()).item()
return tot / nnpm run lab and open the connection link.All three optimizers share model, seed, data and step count. Muon and GaLore apply only to block matrices; remaining parameters use AdamW. Our GaLore always projects on the left for simplicity (the original chooses the short side) and resets moments on subspace change. Finally torch.optim.Muon, PyTorch’s official implementation, is added with our configuration.
def ns5(G, pasos=5, eps=1e-7):
"""Iteración quíntica de Newton-Schulz de Muon, en bf16 si hay GPU."""
a, b, c = 3.4445, -4.7750, 2.0315
X = G.to(torch.bfloat16 if G.is_cuda else torch.float32)
X = X / (X.norm() + eps)
alta = X.shape[0] > X.shape[1]
if alta:
X = X.T
for _ in range(pasos):
S = X @ X.T
X = a * X + (b * S + c * S @ S) @ X
return (X.T if alta else X).to(G.dtype)
class Muon(torch.optim.Optimizer):
"""Momento de Nesterov y ortogonalización: W <- W - lr * escala * NS5(M)."""
def __init__(self, params, lr=0.02, momento=0.95):
super().__init__(params, dict(lr=lr, momento=momento))
@torch.no_grad()
def step(self):
for g in self.param_groups:
for p in g["params"]:
st = self.state[p]
if "M" not in st:
st["M"] = torch.zeros_like(p)
M = st["M"].mul_(g["momento"]).add_(p.grad)
O = ns5(p.grad + g["momento"] * M) # variante de Nesterov
escala = max(1.0, p.shape[0] / p.shape[1]) ** 0.5 # misma RMS de actualización para toda forma
p.add_(O, alpha=-g["lr"] * escala)
st["ultima"] = O
class GaLoreAdam(torch.optim.Optimizer):
"""Adam sobre R = PᵀG, con P los r primeros vectores singulares izquierdos de G (renovado cada `cada` pasos)."""
def __init__(self, params, lr=1e-2, rango=32, cada=100, alfa=0.25, betas=(0.9, 0.999), eps=1e-8):
super().__init__(params, dict(lr=lr, rango=rango, cada=cada, alfa=alfa, betas=betas, eps=eps))
@torch.no_grad()
def step(self):
for g in self.param_groups:
b1, b2 = g["betas"]
for p in g["params"]:
st = self.state[p]
G = p.grad
if "t" not in st:
st["t"] = 0
if st["t"] % g["cada"] == 0: # nuevo subespacio: SVD del gradiente actual
U, _, _ = torch.linalg.svd(G.float(), full_matrices=False)
st["P"] = U[:, : g["rango"]].to(G.dtype)
st["m"] = torch.zeros(g["rango"], G.shape[1], device=G.device)
st["v"] = torch.zeros_like(st["m"])
st["t"] += 1
R = st["P"].T @ G # r x n: aquí vive el estado del optimizador
st["m"].mul_(b1).add_(R, alpha=1 - b1)
st["v"].mul_(b2).addcmul_(R, R, value=1 - b2)
t = (st["t"] - 1) % g["cada"] + 1 # corrección de sesgo desde el último reinicio
N = (st["m"] / (1 - b1**t)) / ((st["v"] / (1 - b2**t)).sqrt() + g["eps"])
upd = g["alfa"] * (st["P"] @ N) # de vuelta al espacio completo
p.add_(upd, alpha=-g["lr"])
st["ultima"] = upd
def entrenar(metodo, pasos=600, semilla=0):
torch.manual_seed(semilla)
modelo = MiniGPT().to(dev)
es_oculta = lambda n, p: p.ndim == 2 and "bloques" in n
ocultas = [p for n, p in modelo.named_parameters() if es_oculta(n, p)]
resto = [p for n, p in modelo.named_parameters() if not es_oculta(n, p)]
adamw_resto = torch.optim.AdamW(resto, lr=3e-3, weight_decay=0.0)
if metodo == "AdamW":
opts = [torch.optim.AdamW(ocultas, lr=3e-3, weight_decay=0.0), adamw_resto]
elif metodo == "Muon":
opts = [Muon(ocultas, lr=0.02), adamw_resto]
elif metodo == "torch Muon":
opts = [torch.optim.Muon(ocultas, lr=0.02, weight_decay=0.0, momentum=0.95, nesterov=True), adamw_resto]
else:
opts = [GaLoreAdam(ocultas, lr=1e-2, rango=D // 4), adamw_resto]
gen = torch.Generator().manual_seed(semilla)
curva, t0 = [], time.perf_counter()
for paso in range(pasos + 1):
if paso % 100 == 0:
curva.append((paso, perdida_val(modelo)))
if paso == pasos:
break
x, y = lote(train, gen)
loss = F.cross_entropy(modelo(x).flatten(0, 1), y.flatten())
for o in opts:
o.zero_grad(set_to_none=True)
loss.backward()
for o in opts:
o.step()
if dev == "cuda":
torch.cuda.synchronize()
segundos = time.perf_counter() - t0
# números que guarda el optimizador para las matrices ocultas (sin contar la última actualización)
estado = sum(v.numel() for p in ocultas for k, v in opts[0].state[p].items() if torch.is_tensor(v) and v.ndim > 0 and k != "ultima")
W = modelo.bloques[1].fc.weight # una matriz oculta de 512 x 128
st = opts[0].state[W]
if metodo == "AdamW":
upd = (st["exp_avg"] / (1 - 0.9**pasos)) / ((st["exp_avg_sq"] / (1 - 0.999**pasos)).sqrt() + 1e-8)
elif metodo == "torch Muon":
upd = ns5(st["momentum_buffer"])
else:
upd = st["ultima"]
s = torch.linalg.svdvals(upd.float())
rango_estable = ((s**2).sum() / s[0] ** 2).item()
return curva, estado, rango_estable, segundos
n_ocultas = sum(p.numel() for n, p in MiniGPT().named_parameters() if p.ndim == 2 and "bloques" in n)
print(f"parámetros en matrices ocultas: {n_ocultas / 1e3:.0f}k")
res = {}
for metodo in ["AdamW", "Muon", "GaLore", "torch Muon"]:
res[metodo] = curva, estado, re, seg = entrenar(metodo)
print(f"{metodo:10s} val: " + " ".join(f"{p}:{l:.3f}" for p, l in curva)
+ f" | estado {estado / 1e3:.0f}k | rango estable {re:.1f} | {seg:.1f} s")npm run lab and open the connection link.In the run used to write this lesson (laptop RTX 4060), validation loss at 600 steps was 1.56 with AdamW, 1.45 with our Muon (and 1.45 with torch.optim.Muon, implementing the same algorithm and following nearly the same curve), and 2.02 with rank-32 GaLore. Repetition changes the third digit because GPU operations are nondeterministic. Hidden-matrix optimizer state occupied 1573k numbers with AdamW (two moments), 786k with Muon (one) and 377k with GaLore. Stable rank of the last update of layer fc of was about 80 with Muon versus 6 with AdamW and GaLore: Muon distributes the step across many directions, exactly as predicts. Read these as one seed, 600 steps, a tiny model and untuned learning rates. The experiment cannot conclude Muon is better than AdamW or GaLore worse; it shows implementation works and each method’s spectral effect is expected. The next section explains what stronger conclusions require.
Finally, the cost argument on hardware for which Muon was designed:
def cronometrar(f, rep=10):
f()
if dev == "cuda":
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(rep):
f()
if dev == "cuda":
torch.cuda.synchronize()
return (time.perf_counter() - t0) / rep
for m, n in [(1024, 1024), (1024, 4096)]:
G = torch.randn(m, n, device=dev)
t_ns = cronometrar(lambda: ns5(G))
t_svd = cronometrar(lambda: torch.linalg.svd(G, full_matrices=False), rep=3)
O = ns5(G).float()
U, s, Vt = torch.linalg.svd(G, full_matrices=False)
sv = torch.linalg.svdvals(O)
print(f"{m}x{n}: NS5 en bf16 {1e3 * t_ns:7.2f} ms SVD en fp32 {1e3 * t_svd:8.2f} ms "
f"cociente {t_svd / t_ns:5.1f}x sigma(NS5) en [{sv.min():.2f}, {sv.max():.2f}] "
f"||NS5 - UV^T||_F / ||UV^T||_F = {((O - U @ Vt).norm() / (U @ Vt).norm()).item():.2f}")npm run lab and open the connection link.On GPU the order reverses: in our runs NS5 was 20 to 65 times faster than SVD for these shapes (the exact number depends on GPU and load, but the gap exceeds an order of magnitude). Inspect singular values. For rectangular , all lie in as the polynomial predicts; for the square matrix the minimum remains , because a square Gaussian has singular values arbitrarily near 0 (Marchenko–Pastur ratio 1) and five steps cannot lift them. A real network orthogonalizes momentum, not a Gaussian, but the warning is general: NS5 is not .
What is proved and what is not
| Claim | Status | Source |
|---|---|---|
| Randomized SVD with satisfies the mean bounds above; powers reduce the tail to | Theorem | Halko, Martinsson and Tropp (2011) |
| An aligned balanced deep linear network learns modes in singular-value order, with times | Theorem | Saxe, McClelland and Ganguli (2014) |
| With , steepest descent is | Theorem | Spectral–nuclear duality; Bernstein and Newhouse (2024) |
| Newton–Schulz cubic converges quadratically to the polar factor if | Theorem | Björck and Bowie (1971); this lesson’s exercise |
| Fine-tuning has low intrinsic dimension | Empirical, for measured tasks and models | Aghajanyan et al. (2020) |
| LoRA matches full GPT-3 fine-tuning with 10 000 times fewer trainable parameters | Empirical, in their experiments | Hu et al. (2021) |
| GaLore maintains full-pretraining loss on LLaMA 1B and 7B | Empirical; theory only for reversible networks | Zhao et al. (2024) |
| Muon needs half AdamW compute for the same loss | Empirical, with scaling laws and specific settings | Liu et al. (2025) |
| Replacing with quintic output does not worsen training | Empirical, no systematic study published in original source | Jordan (2024), blog post |
| Muon works because networks learn singular modes like linear ones | Speculative | No proof |
To replicate a claim like those in the lower table, a reasonable minimum is: state it precisely (metric and compute or token budget); tune learning rates of all methods equally, because a badly tuned baseline manufactures advantages; repeat over multiple seeds and report spread; check the conclusion under changed model size; and if possible isolate the mechanism (e.g. Muon with exact versus quintic). The preceding lab does almost none of this and therefore concludes nothing about which optimizer is better.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. How do you write using the SVD of ?
Step 1 of 4. Why does retain the same singular vectors?
randomized_svd(A, k, p, q, rng), returning (U, s, Vt) with U of with orthonormal columns, s of length in decreasing order and Vt of , such that approximates at rank . Use a Gaussian of generated with rng, q power iterations reorthogonalizing with QR after each product by or , and the SVD of small matrix . Do not compute the SVD of A. Tests check, among other things, that with and spectral error is within 10 % of the Eckart–Young optimum.import numpy as np
def randomized_svd(A, k, p, q, rng):
"""Devuelve (U, s, Vt) con U de m x k, s de longitud k y Vt de k x n."""
m, n = A.shape
l = min(k + p, m, n)
# 1. sketch: Y = A Omega con Omega gaussiana n x l, y Q = base ortonormal de Y
# 2. q iteraciones de potencia, reortogonalizando tras cada producto por A o por A^T
# 3. B = Q^T A, SVD pequeña de B y vuelta: U = Q U_B
return np.zeros((m, k)), np.zeros(k), np.zeros((k, n))Summary
- Randomized SVD multiplies by Gaussians, orthonormalizes and factorizes a small matrix. Its error is near the Eckart–Young optimum for fast spectral decay; for slow decay power iterations raise singular values to and separate the tail. Oversampling controls ; powers control the tail.
- In an aligned balanced deep linear network, each singular mode follows a logistic curve with time : small initialization gives plateaus and learning in singular-value order. One layer or large initialization has no steps.
- A layer gradient is a sum of outer products with rapidly decaying spectrum. LoRA restricts updates to rank ; GaLore stores Adam moments in a refreshed rank- subspace and saves factor in state memory.
- Steepest-descent direction depends on norm: , or . Spectral and nuclear norms are dual: .
- Newton–Schulz applies to each singular value using matrix products. The cubic converges quadratically to on but raises small values slowly; Muon’s quintic raises them fast but remains in a band around 1. Always normalize first.
- Separate theorems, empirical evidence and speculation, and replicate before adopting: this lesson’s lab illustrates what one seed on a tiny model can and cannot establish.