Frontier: randomized numerical linear algebra and mixed precision
Study randomized sketches for least squares, kernel approximations and trace estimation, alongside mixed-precision iterative refinement and probabilistic numerics.
After this lesson you can
- Build Gaussian, SRHT and CountSketch sketches and measure subspace distortion.
- Solve least squares by sketch-and-solve and sketch-and-precondition and explain their accuracy.
- Approximate kernel matrices with RPCholesky and compare greedy and uniform pivoting.
- Estimate traces of implicit matrices using Hutchinson and Hutch++ matrix-vector products or HVPs.
- Implement mixed-precision iterative refinement on GPU and predict convergence.
- Critically read a recent RandNLA or mixed-precision paper and reproduce an experiment.
Before you start
- 09Computing the SVDHouseholder QR in practiceNumerical least squaresCholesky in finite precision: stability and jitterIterative refinementKrylov subspaces, Arnoldi and LanczosGeneralized minimal residual methodPreconditioningConjugate gradientPower iterationMonte Carlo error and confidence intervalsTensor CoresIEEE 754 and deep learning formatsBackward stabilityMode composition and higher-order derivatives
- 04Concentration of the normGaussian concentration for Lipschitz functionsHoeffding's inequality
- 02Low-rank approximationEckart-Young-Mirsky theoremRandomized SVD
Motivation: four problems that do not fit one factorization
The entire module has relied on factorizations: LU, Cholesky, QR, SVD. They cost or , read the entire matrix repeatedly and work in one precision. Four situations, common in machine learning and scientific computing, make that recipe unsuitable:
- Matrices that are too tall. Regression with observations and variables costs flops with QR. Almost all that work is spent on redundant information: the problem has only degrees of freedom.
- Matrices with expensive entries. A kernel matrix of points has entries (80 GB in
float64) and each requires evaluating . A rank-100 approximation fits in 80 MB, but which entries should be examined to find it? - Matrices you do not have. For a network Hessian with parameters, even its diagonal cannot be explicitly stored, but products can be computed for a few gradients (Hessian-vector products, calculated with automatic differentiation mode composition). What is ?
- Hardware favoring low precision. GPU tensor units multiply in FP16 or BF16 much faster than FP64, and consumer GPUs such as RTX 4060 have barely any FP64 units. In this lesson’s lab, an FP32 LU plus a few FP64 refinement steps solves a system of 6 to 9 times faster than
torch.linalg.solvein FP64, with lower error.
Modern answers share two ideas. The first is random projection: a well-chosen random matrix compresses to , with of the order of problem dimension rather than , preserving lengths of an entire subspace. This is randomized numerical linear algebra (RandNLA). The second is compute cheaply and correct expensively: do work at low precision and recover full accuracy with work at high precision. This is mixed precision. Both are active research areas with results from the past five years already in LAPACK, cuSOLVER and PyTorch, and both demand careful reading: a probabilistic guarantee or speedup factor says little without knowing the comparison.
The lesson covers five tools, each with theorem, interactive and experiment: sketches and subspace embeddings; sketch-and-precondition least squares; RPCholesky for kernel matrices; Hutchinson and Hutch++ trace estimators; and three-precision iterative refinement with GMRES-IR. It ends with probabilistic numerics, reinterpreting numerical methods as inference, and a guide to reading and reproducing papers.
Starting point: randomized SVD
The modern field begins largely with Halko, Martinsson and Tropp (2011), studied in randomized SVD. To approximate at rank , multiply by Gaussian , orthonormalize and work with small matrix . Their expected bound (paper theorem 10.5), for and oversampling , is
Three features of this bound recur throughout the lesson:
- A random matrix “sees” a whole subspace. is a random mixture of columns of and, with a few extra columns (), captures its dominant range with high probability.
- Error is compared with optimum. The right-hand factor is exactly the best rank- approximation error (Eckart–Young theorem). RandNLA guarantees have the form “ times the best possible,” not “small error.”
- The guarantee is in expectation or probability. One seed reveals nothing about spread; all experiments here therefore give medians or ranges over several seeds.
Randomized SVD is also a building block. Hutch++ uses it to separate a matrix’s low-rank part, and multiplication by a random matrix to compress without losing information is the sketch idea coming next.
Sketching: compress without losing a subspace
From Johnson–Lindenstrauss to subspaces
The Johnson–Lindenstrauss lemma says points in can be projected to , with , preserving all distances by factor . Linear algebra needs something stronger: preserve norms of all vectors in a subspace, infinitely many.
If has orthonormal columns spanning , every is with , and the condition is equivalent to all singular values of lying in . This is how distortion is measured in practice: .
The Gaussian sketch
Proof
Let be an orthonormal basis of . Rows of are standard Gaussians in , rotation invariant, so each row of is applied to a standard Gaussian: a vector . Therefore is a matrix of independent standard Gaussians, regardless of . For such a matrix, Gordon’s inequality gives , and since and are 1-Lipschitz functions of entries (in Frobenius norm), Gaussian Lipschitz concentration gives deviations above with probability at most in each tail (Davidson–Szarek corollary; Vershynin, High-Dimensional Probability, theorem 7.3.3). Dividing by , singular values of lie in .
∎What does not appear is important: . A sketch with rows has distortion around for any subspace of dimension , whether it lives in or . The issue is cost: forming costs flops, and with that is , four times the QR we wanted to avoid. Faster sketches are needed.
SRHT: mix before sampling
The cheapest idea would be to keep randomly selected rows of (rescaled by ). It works when information is spread across rows, and fails when a few rows concentrate it. The concentration measure is the leverage scores , with : if a row has , it alone contains one range direction and uniform sampling misses it with probability . A matrix with very unequal leverage is called coherent.
The subsampled randomized Hadamard transform (SRHT) fixes this by mixing first:
where is diagonal with random signs , is the order- Walsh–Hadamard matrix (a power of 2), with entries and , and selects random rows. is orthogonal, so it changes no norm, but spreads each range direction across rows: with high probability, after mixing all leverage scores are near (up to logarithmic factors), and uniform sampling works. Applying costs additions per column, like an FFT. In exchange for speed, theory requires of order rows rather than (Martinsson and Tropp, 2020, section 9). Blendenpik uses the same idea with other fast transforms (including cosine).
CountSketch: one entry per column
The cheapest sketch has a single per column in a random row: each row of is added with random sign to one of rows of . This is CountSketch (Clarkson and Woodruff, 2013, brought it to regression), costing one data pass, : unbeatable for sparse matrices. The price is size: embedding needs of order , not . The reason is the birthday paradox. If has rows of leverage 1, each with one range direction, and two land in the same sketch row, they add into one vector and loses a dimension. With rows and bins, collision probability is , small only if .
| Sketch | Cost of forming | Rows for constant distortion | Coherence |
|---|---|---|---|
| Gaussian | indifferent | ||
| SRHT | indifferent (mixing) | ||
| CountSketch | indifferent on average, collisions | ||
| Uniform row sampling | only if incoherent | fails |
The lab builds all four from scratch and measures distortion on orthonormal basis of , first incoherent (orthonormalized Gaussian columns) and then coherent (20 rows with leverage near 1).
import numpy as np
import scipy.sparse as sp
def fwht(X):
"""Walsh-Hadamard sin normalizar por columnas (m potencia de 2): log2(m) pasadas de mariposas."""
X = np.array(X, dtype=float)
m = X.shape[0]
h = 1
while h < m:
X = X.reshape(m // (2 * h), 2, h, -1)
X = np.concatenate([X[:, :1] + X[:, 1:], X[:, :1] - X[:, 1:]], axis=1)
h *= 2
return X.reshape(m, -1)
def gaussiano(m, d, rng):
S = rng.standard_normal((d, m)) / np.sqrt(d)
return lambda A: S @ A
def srht(m, d, rng):
signos = rng.choice([-1.0, 1.0], size=m)
filas = rng.choice(m, size=d, replace=False)
return lambda A: fwht(signos[:, None] * A.reshape(m, -1))[filas] / np.sqrt(d)
def countsketch(m, d, rng):
S = sp.csr_matrix((rng.choice([-1.0, 1.0], size=m), (rng.integers(0, d, size=m), np.arange(m))), shape=(d, m))
return lambda A: S @ A
def uniforme(m, d, rng):
filas = rng.integers(0, m, size=d)
return lambda A: A[filas] * np.sqrt(m / d)
SKETCHES = {"gaussiano": gaussiano, "SRHT": srht, "CountSketch": countsketch, "uniforme": uniforme}
def distorsion(S, U):
s = np.linalg.svd(S(U), compute_uv=False)
return max(s[0] - 1, 1 - s[-1])
rng = np.random.default_rng(0)
m, n = 2048, 20
U_inc, _ = np.linalg.qr(rng.standard_normal((m, n)))
Ac = rng.standard_normal((m, n))
Ac[:n] += 1e3 * np.eye(n) # 20 filas que concentran el rango
U_coh, _ = np.linalg.qr(Ac)
print(f"influencia máxima: incoherente {(U_inc**2).sum(1).max():.3f}, coherente {(U_coh**2).sum(1).max():.3f}")
ds = [2 * n, 4 * n, 8 * n, 16 * n]
print("distorsión, mediana de 5 semillas; d =", ds)
for nombre_U, U in [("incoherente", U_inc), ("coherente", U_coh)]:
for nombre, fab in SKETCHES.items():
fila = [np.median([distorsion(fab(m, d, np.random.default_rng(s)), U) for s in range(5)]) for d in ds]
print(f" {nombre_U:11s} {nombre:12s}", " ".join(f"{e:5.2f}" for e in fila))
print(" predicción gaussiana sqrt(n/d): ", " ".join(f"{np.sqrt(n / d):5.2f}" for d in ds))With the incoherent basis all four sketches behave alike and closely follow theorem prediction : 0.65 to 0.68 with (prediction 0.71), 0.46 to 0.50 with and 0.22 to 0.27 with . With the coherent basis everything changes. Gaussian does not notice, as the proof says: has the same distribution regardless of . SRHT needs somewhat more margin ( with ), but from matches Gaussian. Uniform sampling fails for every : it misses leverage-1 rows (distortion ) or, if it catches them, rescaling inflates them (distortions 1.5 to 2.6, above 1). CountSketch illustrates the birthday paradox: distortion is nearly 1 while the 20 important rows collide, and jumps to with . With collision probability is still 45%, so other seeds would fail; that is why theory asks for .
Least squares: solve the sketch or precondition with it
Let have rank with and , with optimal residual . The classical solution is Householder QR, backward stable at cost flops (studied in least-squares numerics). There are two ways to use a sketch.
Sketch-and-solve
The most direct: solve small problem , of .
Proof
Vectors lie in for every . Using the embedding lower bound, optimality of for the sketched problem and the upper bound,
For the second, is orthogonal to (normal equations), so by Pythagoras , and rearrange using the first bound.
∎The bound is relative to residual, making it useless for high precision. With it guarantees only residual at most three times optimal and error up to . To make that error would require , and with that is . Sketch-and-solve works when a couple of digits suffice (an initial estimate, a model with much greater statistical noise anyway) and never reaches machine precision while .
Sketch-and-precondition
The second way uses the sketch only to build a preconditioner and solves the original problem iteratively.
Proof
For every , vector lies in , and has orthonormal columns, so . By the embedding, . Rearranging, for every .
∎LSQR (Paige and Saunders, 1982) is mathematically equivalent to conjugate gradients on normal equations, implemented with Golub–Kahan bidiagonalization to avoid forming . By conjugate gradient’s Chebyshev bound, with ,
With , and the ratio is per iteration: about 50 iterations suffice to go from to for any full-rank . Sketch distortion no longer limits accuracy, only speed: this is the essential difference from sketch-and-solve.
Cost is the sketch, plus for small QR, plus about flops per iteration (products with and ). Compared with QR’s , the ratio is about for iterations (plus sketch), so savings arrive when is considerably larger than twice the iteration count: with , as in the interactive, QR still wins in flops; with in the hundreds, as in Blendenpik, the randomized method wins. Blendenpik (Avron, Maymounkov and Toledo, 2010) combined fast mixing, row sampling and LSQR and, according to its abstract, outperforms LAPACK “by large factors” on very tall dense problems, with QR-like residuals. LSRN (Meng, Saunders and Mahoney, 2014) uses a Gaussian projection with rows (moderate , e.g. 2) and LSQR or Chebyshev semi-iteration, and parallelizes easily because Gaussian generation and application require no communication.
Initially (SRHT with , ), , the bound predicts ratio per iteration and preconditioned LSQR reaches QR level () in 36 iterations. Unpreconditioned LSQR remains at after 60, and sketch-and-solve at : relative residual () amplified by distortion and conditioning. With and 60 iterations, finite Krylov termination (in exact arithmetic LSQR ends in steps) cannot hide the difference: what is seen is the speed given by . Extremes teach most. With , and LSQR does not arrive in 60 iterations although it keeps decreasing. With the coherent matrix (32 leverage-1 rows), uniform sampling and CountSketch leave rank-deficient (with initial seed even at ), so there is no preconditioner; CountSketch succeeds for other seeds when the 32 rows do not collide. Flop accounting gives : with and 36 iterations the randomized method still costs more than QR.
LSQR from scratch
LSQR maintains Golub–Kahan bidiagonalization, , , and at each step , , updating the solution with one Givens rotation per step. The following code is the minimal Paige–Saunders version, without stopping criterion, and compares it with QR and sketch-and-solve on four problems: and large () or small () optimal residual relative to . The sketch is SRHT with .
import numpy as np
def lsqr(matvec, rmatvec, b, n, iters):
"""LSQR de Paige y Saunders (1982) desde x0 = 0, con un número fijo de iteraciones."""
x = np.zeros(n)
beta = np.linalg.norm(b); u = b / beta
v = rmatvec(u); alfa = np.linalg.norm(v); v = v / alfa
w = v.copy(); phibar, rhobar = beta, alfa
for _ in range(iters):
u = matvec(v) - alfa * u; beta = np.linalg.norm(u); u = u / beta
v = rmatvec(u) - beta * v; alfa = np.linalg.norm(v); v = v / alfa
rho = np.hypot(rhobar, beta); c, s = rhobar / rho, beta / rho # rotación de Givens
theta = s * alfa; rhobar = -c * alfa
phi = c * phibar; phibar = s * phibar
x = x + (phi / rho) * w
w = v - (theta / rho) * w
return x
def problema(m, n, kappa, residuo, rng):
"""A = U diag(s) V^T y b = A x* + r con r ortogonal al rango: x* es la solución exacta."""
U, _ = np.linalg.qr(rng.standard_normal((m, n)))
V, _ = np.linalg.qr(rng.standard_normal((n, n)))
A = (U * np.logspace(0, -np.log10(kappa), n)) @ V.T
x = rng.standard_normal(n)
z = rng.standard_normal(m)
r = z - U @ (U.T @ z)
r *= residuo * np.linalg.norm(A @ x) / np.linalg.norm(r)
return A, A @ x + r, x
m, n = 4096, 20
print("error relativo ||x - x*|| / ||x*||")
for kappa in [1e2, 1e6]:
for residuo in [1e-2, 1e-6]:
A, b, x = problema(m, n, kappa, residuo, np.random.default_rng(1))
err = lambda y: np.linalg.norm(y - x) / np.linalg.norm(x)
Qa, Ra = np.linalg.qr(A)
x_qr = np.linalg.solve(Ra, Qa.T @ b)
S = srht(m, 4 * n, np.random.default_rng(7)) # de la celda anterior
SA, Sb = S(A), S(b[:, None])[:, 0]
Q, R = np.linalg.qr(SA)
x_ss = np.linalg.solve(R, Q.T @ Sb) # sketch-and-solve
mv = lambda v: A @ np.linalg.solve(R, v) # A R^{-1}
rmv = lambda u: np.linalg.solve(R.T, A.T @ u) # R^{-T} A^T
x_sp = np.linalg.solve(R, lsqr(mv, rmv, b, n, 60)) # sketch-and-precondition desde 0
d_w = np.linalg.solve(R, lsqr(mv, rmv, b - A @ x_ss, n, 60))
x_w = x_ss + d_w # desde la solución sketch-and-solve
sv = np.linalg.svd(mv(np.eye(n)), compute_uv=False)
print(f"kappa {kappa:.0e}, residuo {residuo:.0e}: QR {err(x_qr):.1e} | sketch-and-solve {err(x_ss):.1e} | "
f"s&p desde 0 {err(x_sp):.1e} | s&p desde x_ss {err(x_w):.1e} | kappa(AR^-1) = {sv[0] / sv[-1]:.2f}")Read columns in pairs. Sketch-and-solve always has error proportional to residual and conditioning: with it moves from to when residual drops from to , and with relative error in reaches hundreds. Sketch-and-precondition with matches or beats QR in both cases (errors to versus QR’s ): sketch distortion () only determines iteration count.
With something appears that exact-arithmetic theory does not predict. QR gives with large residual, allowed by least-squares conditioning (order ), and with small residual. Preconditioned LSQR from zero stays at and : one order worse than QR in the first case and over three in the second. Starting from sketch-and-solve reaches QR accuracy for small residual () and improves little in the other (). This is not an implementation error. Meier, Nakatsukasa, Townsend and Webb (2023) proved sketch-and-precondition as used by Blendenpik and LSRN is not stable on ill-conditioned problems, and starting from sketch-and-solve, as Rokhlin and Tygert (2008) already proposed, often greatly improves accuracy, though not always backward stability. Epperly (2024) proved properly implemented iterative sketching is forward stable, and Epperly, Meier and Nakatsukasa (2024) proposed SPIR and FOSSILS, combining sketch-and-precondition with iterative refinement and backward stability at the same convergence rate. This is frontier work: a 2010 technique whose numerical stability was understood in 2023 and 2024.
The library version
SciPy has LSQR with stopping criteria and accepts a LinearOperator, so the preconditioner takes three lines. scipy.linalg.solve_triangular exploits the shape of .
import numpy as np
import scipy.linalg as sla
from scipy.sparse.linalg import LinearOperator, lsqr as lsqr_scipy
A, b, x = problema(4096, 20, 1e2, 1e-2, np.random.default_rng(1))
S = srht(4096, 80, np.random.default_rng(7))
R = np.linalg.qr(S(A), mode="r")
op = LinearOperator(A.shape, matvec=lambda v: A @ sla.solve_triangular(R, v),
rmatvec=lambda u: sla.solve_triangular(R, A.T @ u, trans="T"), dtype=float)
y, istop, itn = lsqr_scipy(op, b, atol=1e-14, btol=1e-14, iter_lim=200)[:3]
x_sp = sla.solve_triangular(R, y)
print(f"scipy lsqr: {itn} iteraciones, motivo de parada {istop}, error {np.linalg.norm(x_sp - x) / np.linalg.norm(x):.1e}")
y0, _, itn0 = lsqr_scipy(A, b, atol=1e-14, btol=1e-14, iter_lim=200)[:3]
print(f"sin precondicionar: {itn0} iteraciones, error {np.linalg.norm(y0 - x) / np.linalg.norm(x):.1e}")Kernel matrices: Cholesky with random pivots
Nyström and partial Cholesky are the same
Let be positive semidefinite, for example kernel matrix with Gaussian kernel . The Nyström approximation using column set is
and only needs columns of : entries. Which columns should be chosen? The tool is partial pivoted Cholesky: at step choose pivot , evaluate column , subtract contributions of previous steps and normalize,
After steps, is exactly the Nyström approximation with columns (each step is a Schur complement, as in Gaussian elimination in the Cholesky lesson), and residual is positive semidefinite. Two facts make the algorithm cheap:
- The residual diagonal updates itself: . No new entry is needed.
- Trace-norm error can be read from it: since residual is positive semidefinite, .
In total, diagonal ( entries) plus columns: kernel evaluations and flops. One decision remains: pivot rule.
Three pivot rules
- Greedy. Largest residual diagonal element, . This is LAPACK full-pivoted Cholesky (
pstrf). It looks optimal, removing the column with most variance each step. But an outlier column, from an isolated point, has residual diagonal 1 until selected and, once selected, explains only that point. - Uniform. Random among columns, classical Nyström of Williams and Seeger (2001). It explores without looking at the diagonal, so a small cluster (eyes of a face, a rare data regime) has low chance of any pivot.
- Random proportional to residual diagonal. This section’s algorithm.
Chen, Epperly, Tropp and Webber (2025) offer a unifying interpretation: if is chosen with probability proportional to , is greedy (“zero temperature”), uniform (“infinite temperature”) and RPCholesky is , “neither too hot nor too cold.” Residual diagonal is the variance left to explain at each point: RPCholesky pursues it without obsessing over the maximum.
The figure shows the “best rule” depends on budget. With greedy leaves 49% trace error, uniform (median of 15 seeds) 14% and RPCholesky 10%: greedy spent 9 of 20 pivots on outliers explaining only themselves, and uniform missed the small cluster in 9 of 15 seeds. With greedy has exhausted 10 outliers and ties RPCholesky (0.20% versus 0.22%), while uniform remains at 2.9%: an order worse because in 4 of 15 seeds it still misses the small cluster. RPCholesky is best or tied throughout the range, as its theorem says; greedy catches it only when budget suffices for all outliers.
The paper also proves no column Nyström method can beat about columns in the worst case, so the bound is optimal up to the logarithmic term (in their 20 real datasets ranges from 2.4 to 26). Greedy and uniform have no such guarantee: matrices exist where they fail, and the two in their figure 1, reproduced below, are designed to show this. In their benchmark of 20 LIBSVM, OpenML and UCI kernel matrices with , RPCholesky achieves lowest trace error on all.
Reproducing figure 1 of Chen and coauthors
The paper’s figure 1 compares rules on two Gaussian kernel matrices of points in . Smile: a face of radius 10 with two eyes of points, mouth of and the rest on the outline, with ; eyes are easy to miss. Spiral: with and equally spaced in , with ; the outside is so spread out it behaves like outliers. The following cells reproduce both with (the browser cannot handle ), following the authors’ public code, and give the median of 10 seeds.
import numpy as np
def sonrisa(N):
ojos, boca = int(np.ceil(np.sqrt(N))), int(np.ceil(N / 10))
rng = np.random.default_rng(0)
P = []
for dx in (-4.0, 4.0): # dos ojos: discos de radio 1
r, t = np.sqrt(rng.random(ojos)), 2 * np.pi * rng.random(ojos)
P.append(np.c_[dx + r * np.cos(t), 4 + r * np.sin(t)])
xb = np.linspace(-5, 5, boca)
P.append(np.c_[xb, xb**2 / 16 - 5]) # boca
t = np.linspace(0, 2 * np.pi, N - 2 * ojos - boca)
P.append(np.c_[10 * np.cos(t), 10 * np.sin(t)]) # contorno
return np.vstack(P), 2.0
def espiral(N):
t = np.linspace(0, 2, N) ** 6
return np.c_[np.exp(0.2 * t) * np.cos(t), np.exp(0.2 * t) * np.sin(t)], 1000.0
def cholesky_pivotado(X, h, k, regla, rng):
"""k pasos de Cholesky pivotado parcial sobre el núcleo gaussiano. Devuelve la traza residual relativa tras cada paso."""
N = len(X)
F, d, elegidos = np.zeros((N, k)), np.ones(N), []
traza = [1.0]
for i in range(k):
if regla == "voraz":
s = int(np.argmax(d))
elif regla == "rp":
s = int(rng.choice(N, p=d / d.sum()))
else:
s = int(rng.choice(np.setdiff1d(np.arange(N), elegidos)))
g = np.exp(-0.5 * ((X - X[s]) ** 2).sum(1) / h**2) - F[:, :i] @ F[s, :i] # una columna nueva
F[:, i] = g / np.sqrt(g[s]) if g[s] > 1e-12 else 0.0
d = np.maximum(d - F[:, i] ** 2, 0.0)
elegidos.append(s)
traza.append(d.sum() / N)
return np.array(traza)
def compara(X, h, kmax=100, semillas=10, ks=(10, 20, 40, 60, 100)):
for regla in ["voraz", "uniforme", "rp"]:
T = 1 if regla == "voraz" else semillas
curvas = [cholesky_pivotado(X, h, kmax, regla, np.random.default_rng(s)) for s in range(T)]
med = np.median(curvas, axis=0)
print(f" {regla:9s}", " ".join(f"{med[k]:.1e}" for k in ks))
X, h = sonrisa(2000)
print("Sonrisa, N = 2000: tr(A - Â)/tr(A) con k =", (10, 20, 40, 60, 100))
compara(X, h)X, h = espiral(2000)
print("Espiral, N = 2000: tr(A - Â)/tr(A) con k =", (10, 20, 40, 60, 100))
compara(X, h)Both figure-1 failures appear as described. On the smile, uniform stalls: with it leaves error versus for RPCholesky, over four orders of magnitude, because eyes (4.5% of points) often receive no pivot. Greedy matches RPCholesky, as in the paper. On the spiral roles reverse: uniform barely improves (8.8% to 7.6%) because almost all points are central and it chooses there; greedy takes exterior points one by one and with leaves 5.1%; RPCholesky spreads choices and leaves 2.5%, half. With there are far fewer exterior points than in the paper, making this reduced reproduction: run in native NumPy with and up to 200 (a few seconds) to see the greedy/RPCholesky gap persist for more steps.
Estimating trace with matrix-vector products
Why traces
Many important quantities are traces of matrices accessible only via products: in Gaussian processes, effective parameter count of ridge regression, Hessian trace as loss curvature measure, or divergence of a vector field, needed by continuous normalizing flows. In each case a product is affordable (a system solve, gradient, Jacobian-vector product), while forming is not.
It is unbiased because . For symmetric , the variance of one term with Rademacher vectors is
and with Gaussians, . You will prove the first in exercises. Generally, if components have fourth moment , variance is , and since with equality only if , Rademacher has minimum variance: with a diagonal matrix it is exact with one vector.
Hutchinson is a Monte Carlo estimator: its error is . For a positive semidefinite matrix, , so relative standard deviation is at most , and relative error needs order products. One percent costs about 20,000.
Hutch++: remove the large part first
Hutchinson’s worst case is a matrix with few large eigenvalues: then and relative variance is maximal. But that is exactly the part randomized SVD captures well. Meyer, Musco, Musco and Woodruff (2021) split the trace in two:
where is an orthonormal basis of with of Rademacher columns (the randomized-SVD range finder, products). The first term is computed exactly with another products (). The second is estimated by Hutchinson using the remaining products, applied to projected vectors .
Why does it win? For positive semidefinite with eigenvalues , and its best rank- approximation,
because (the first eigenvalues, all at least as large, sum to at most the trace). If captures the dominant range nearly as well as (as the Halko–Martinsson–Tropp bound guarantees with high probability), the part left for Hutchinson has Frobenius norm of order , and its error with vectors is order . The paper’s theorem follows: for positive semidefinite , Hutch++ gives approximation with products rather than , and no algorithm using only matrix-vector products, even adaptively selected, can do better up to a logarithmic factor.
Laboratory: variance and both estimators
First, check the variance formula without sampling: with there are only four Rademacher vectors, and variance is exact. Then a random matrix with samples of each kind.
import numpy as np
from itertools import product
def var_rademacher(A):
return 2 * (np.sum(A * A) - np.sum(np.diag(A) ** 2))
A = np.array([[1.0, 3.0], [3.0, 2.0]])
valores = [np.array(z) @ A @ np.array(z) for z in product([-1.0, 1.0], repeat=2)]
print("z^T A z para los 4 vectores de Rademacher:", valores)
print(f"media {np.mean(valores)} (traza {np.trace(A)}), varianza {np.var(valores)} (fórmula {var_rademacher(A)})")
rng = np.random.default_rng(0)
B = rng.standard_normal((6, 6)); B = B + B.T
Z = rng.choice([-1.0, 1.0], size=(200_000, 6))
q = np.einsum("ij,jk,ik->i", Z, B, Z)
G = rng.standard_normal((200_000, 6))
qg = np.einsum("ij,jk,ik->i", G, B, G)
print(f"\nB 6x6: traza {np.trace(B):.3f}; Rademacher media {q.mean():.3f}, varianza {q.var():.2f} (fórmula {var_rademacher(B):.2f})")
print(f" gaussianos media {qg.mean():.3f}, varianza {qg.var():.2f} (fórmula 2||B||_F^2 = {2 * np.sum(B * B):.2f})")Now Hutchinson versus Hutch++ at equal budget, on four spectra of an matrix, using median relative error over 30 seeds. The first two lines of hutchpp contain the randomized-SVD range finder.
import numpy as np
def hutchinson(matvec, n, m, rng):
Z = rng.choice([-1.0, 1.0], size=(n, m))
return np.sum(Z * matvec(Z)) / m
def hutchpp(matvec, n, m, rng):
k = m // 3
Q, _ = np.linalg.qr(matvec(rng.choice([-1.0, 1.0], size=(n, k)))) # buscador de rango: k productos
G = rng.choice([-1.0, 1.0], size=(n, m - 2 * k))
G = G - Q @ (Q.T @ G) # proyecta fuera del rango de Q
return np.trace(Q.T @ matvec(Q)) + np.sum(G * matvec(G)) / G.shape[1]
n = 200
rng = np.random.default_rng(0)
Q0, _ = np.linalg.qr(rng.standard_normal((n, n)))
i = np.arange(1, n + 1)
espectros = {"plano": 0.5 + rng.random(n), "i^-1": 1 / i, "i^-2": 1 / i**2, "i^-3": 1 / i**3}
print("mediana del error relativo (30 semillas)")
for nombre, lam in espectros.items():
A = (Q0 * lam) @ Q0.T
tr, mv = lam.sum(), (lambda X, A=A: A @ X)
fila = []
for m in [12, 48, 192]:
eh = np.median([abs(hutchinson(mv, n, m, np.random.default_rng(s)) - tr) / tr for s in range(30)])
ep = np.median([abs(hutchpp(mv, n, m, np.random.default_rng(s)) - tr) / tr for s in range(30)])
fila.append(f"m={m:3d}: {eh:.1e} / {ep:.1e}")
print(f" {nombre:5s} ||A||_F/tr = {np.linalg.norm(lam) / tr:.2f} | Hutchinson / Hutch++ ", " | ".join(fila))Ratio in the second column predicts Hutchinson error. With flat spectrum it is 0.07 and Hutchinson excels ( with ); Hutch++ is somewhat worse (), because only one-third of products goes to the important part. With decaying spectra, Hutchinson falls slowly at rate and with much noise, while Hutch++ wins with by factor 4 with , about 270 times with ( versus ), and over four orders with : the faster the spectrum decays, the more trace the exact part captures. Guarantee is worst-case, and for a specific spectrum Hutch++ can fall faster: with , the tail after capturing eigenvalues has , and divided by gives error of order . In the table, from to Hutch++ error with falls by factor 22, near from that calculation. This matches randomized SVD: dominant-range methods excel when spectra decay.
Trace of a network Hessian
The intended application: estimate of a small network’s loss Hessian using only Hessian-vector products. The product is a JVP of the gradient (forward over reverse), torch.func.vmap vectorizes over a block of vectors and, since the network has 1377 parameters, the exact Hessian can be formed for checking. This cell runs on your machine (CPU, seconds).
import numpy as np
import torch
from torch.func import functional_call, grad, jvp, vmap
torch.manual_seed(0)
X = torch.randn(512, 8, dtype=torch.float64)
y = torch.sin(X @ torch.randn(8, 1, dtype=torch.float64)) + 0.1 * torch.randn(512, 1, dtype=torch.float64)
red = torch.nn.Sequential(torch.nn.Linear(8, 32), torch.nn.Tanh(), torch.nn.Linear(32, 32), torch.nn.Tanh(),
torch.nn.Linear(32, 1)).double()
opt = torch.optim.Adam(red.parameters(), lr=1e-2)
for _ in range(300):
opt.zero_grad(); perdida_entreno = ((red(X) - y) ** 2).mean(); perdida_entreno.backward(); opt.step()
nombres = [k for k, _ in red.named_parameters()]
formas = [p.shape for p in red.parameters()]
tam = [p.numel() for p in red.parameters()]
theta = torch.cat([p.detach().reshape(-1) for p in red.parameters()])
p = theta.numel()
def perdida(t):
ps, i = {}, 0
for nm, sh, k in zip(nombres, formas, tam):
ps[nm] = t[i:i + k].reshape(sh); i += k
return ((functional_call(red, ps, (X,)) - y) ** 2).mean()
g = grad(perdida)
hvp = lambda v: jvp(g, (theta,), (v,))[1] # H v: forward sobre reverse
HVP = vmap(hvp) # un bloque de vectores (por filas) de una vez
H = torch.func.hessian(perdida)(theta) # solo para comprobar: p x p
traza = torch.trace(H).item()
ev = torch.linalg.eigvalsh(H)
print(f"p = {p} parámetros, pérdida {perdida(theta).item():.4f}, tr(H) = {traza:.4f}")
print(f"autovalores: mayor {ev[-1].item():.2f}, 10.º {ev[-10].item():.2f}, 50.º {ev[-50].item():.3f}, menor {ev[0].item():.1e}")
print(f"||H||_F / tr(H) = {torch.linalg.norm(H).item() / traza:.2f}")
def rademacher(k, gen):
return torch.randint(0, 2, (k, p), generator=gen, dtype=torch.float64) * 2 - 1
def hutchinson(m, gen):
Z = rademacher(m, gen)
return (Z * HVP(Z)).sum().item() / m
def hutchpp(m, gen):
k = m // 3
Q, _ = torch.linalg.qr(HVP(rademacher(k, gen)).T)
G = rademacher(m - 2 * k, gen)
G = G - (G @ Q) @ Q.T
return (Q.T * HVP(Q.T)).sum().item() + (G * HVP(G)).sum().item() / (m - 2 * k)
for m in [30, 90, 300]:
eh = [abs(hutchinson(m, torch.Generator().manual_seed(s)) - traza) / abs(traza) for s in range(10)]
ep = [abs(hutchpp(m, torch.Generator().manual_seed(100 + s)) - traza) / abs(traza) for s in range(10)]
print(f"m = {m:3d} HVPs: Hutchinson mediana {np.median(eh):.1e} (máx {max(eh):.1e}) | "
f"Hutch++ mediana {np.median(ep):.1e} (máx {max(ep):.1e})")npm run lab and open the connection link.The trained network Hessian has the shape favoring Hutch++: one eigenvalue 24, the tenth already 1.6 and a long small-eigenvalue tail, with . With 300 HVPs, Hutchinson median error is 1.2% and Hutch++ 0.1%. The Hessian is not positive semidefinite (its smallest eigenvalue is ): Hutch++’s guarantee is for positive semidefinite matrices, but the paper gives general bounds and it still works here because the negative part is tiny. With a network of parameters the cell would be the same except the line forming , which must be removed.
Mixed precision: compute cheaply and correct
Formats
This section’s calculations depend on two numbers per IEEE format: unit roundoff , setting precision, and range. The table gives standard format parameters, as summarized by Higham and Mary (2022), with for significand bits:
| Format | Significand bits | Smallest normal | Largest finite | |
|---|---|---|---|---|
| BF16 | 8 | |||
| FP16 | 11 | |||
| FP32 | 24 | |||
| FP64 | 53 |
BF16 retains FP32 range and sacrifices precision; FP16 has more precision and tiny range. Tensor units multiply blocks with FP16 or BF16 inputs and accumulate in FP32, improving factorization accuracy (Blanchard and coauthors reduce the backward-error bound of pure FP16 LU from order to ).
Iterative refinement in three precisions
The LU lesson’s iterative refinement already used two precisions: FP32 factorization and FP64 residual. Carson and Higham (2018) generalized it to three: working precision (storing and data), factorization precision and residual precision , with .
Carson and Higham’s (2018) analysis, reformulated by Higham and Mary (2022) for any correction solver, separates two questions that should not be confused:
- Does it converge? If the correction solver has relative error , forward error decreases per step by a factor of order . With LU-IR, , and with stable LU the condition reduces to . Since equals in FP16 and in BF16, LU-IR convergence with half-precision factorization is guaranteed only for very well-conditioned matrices with clearly below those values (and further below as grows).
- How far? Limiting error is order , with the maximum nonzeros per row. It does not depend on : factorization precision determines only convergence and speed. With = FP64 the limit is that of FP64 elimination, order ; with (quadruple-precision residual) it reaches even if is ill-conditioned.
GMRES-IR
What if ? Low-precision factors still contain much information about even if insufficient for fixed-point iteration. Carson and Higham (2017, 2018) use them to precondition GMRES: preconditioned matrix satisfies, in their worst-case analysis,
and its eigenvalues are often clustered near 1, so GMRES converges in few iterations even when greatly exceeds 1. If products with use precision , the analysis guarantees convergence while is below , up to constants. With FP16 factorization that is when working in FP32 and in FP64, versus LU-IR’s few thousand. Amestoy and coauthors (2021) extended the analysis to five precisions and Haidar and coauthors use only two in practice (FP16 factorization, all else FP64), the interactive and lab variant.
The authors stress one warning: if GMRES needs order iterations, each correction costs and all savings vanish. GMRES-IR expands applicability while GMRES iterations are few; the interactive shows them at each step.
The right-hand map makes the theory prediction an experiment. Each format has its threshold where ceases to be small: after 10 steps, LU-IR reaches FP64 precision up to in FP16 () and in FP32 (); in BF16, with (), it is at and still decreasing. For another order of magnitude it crawls (FP16 with ends at ; BF16 with stalls at ), then diverges: from in FP16, in BF16 and in FP32. Convergence with somewhat above 1 does not contradict theory: is sufficient, with normwise and worst-case rounding, and in this small matrix LU errors are much smaller than that bound. With large constant and factor growth matter more, lowering the threshold; the lab measures it with .
Scale before rounding
FP16 cannot represent numbers above or, as normals, below . A matrix with entries of order overflows on conversion and factors fill with infinities; one with entries of order becomes zeros. Higham, Pranesh and Zounon (2019) propose equilibrating rows and columns in working precision, multiplying by with and only then rounding to FP16; the correction is unscaled in high precision. With there is room for elimination growth, although Higham and Mary warn that with large growth factors (matrices with a very small singular value) may not suffice. The interactive uses only scalar factor because its matrix is already equilibrated, and with needs only ; the lab shows that with it is insufficient.
RTX 4060 laboratory
The next cell performs three GPU experiments. First, real FP32 LU (torch.linalg.lu_factor, calling cuSOLVER) with FP64 refinement versus torch.linalg.solve in FP64, for and increasing . Second, simulated FP16 and BF16 LU: a rank-1 update loop where every PyTorch operation on half or bfloat16 tensors rounds its result to that format, with LU-IR and GMRES-IR for and randsvd matrices of prescribed (singular values logarithmically spaced from 1 to ), the same test type used by Carson and Higham (2018) and Higham and Mary (2022). Third, scaling. It runs locally and takes about a minute.
import time
import torch
dev = "cuda"
torch.backends.cuda.matmul.allow_tf32 = False # FP32 de verdad, sin TF32
print(torch.cuda.get_device_name(0))
def randsvd(n, kappa, seed):
"""U diag(s) V^T con valores singulares logarítmicos de 1 a 1/kappa (FP64, en la GPU)."""
g = torch.Generator(device=dev).manual_seed(seed)
U, _ = torch.linalg.qr(torch.randn(n, n, dtype=torch.float64, device=dev, generator=g))
V, _ = torch.linalg.qr(torch.randn(n, n, dtype=torch.float64, device=dev, generator=g))
s = kappa ** (-torch.arange(n, dtype=torch.float64, device=dev) / (n - 1))
return (U * s) @ V.T
def cronometra(f, rep=3):
best, out = float("inf"), None
for _ in range(rep):
torch.cuda.synchronize(); t0 = time.perf_counter()
out = f()
torch.cuda.synchronize(); best = min(best, time.perf_counter() - t0)
return best, out
def error(y, x):
return (torch.linalg.norm(y - x) / torch.linalg.norm(x)).item()
# ---------- 1. LU en FP32 en la GPU y refinamiento en FP64
def lu_ir_fp32(A, b, max_pasos=30):
LU, piv = torch.linalg.lu_factor(A.float()) # O(n^3) en FP32
x = torch.linalg.lu_solve(LU, piv, b.float()).double()
previo = float("inf")
for paso in range(1, max_pasos + 1):
r = b - A @ x # residuo en FP64
d = torch.linalg.lu_solve(LU, piv, r.float()).double() # corrección con los factores FP32
x = x + d # suma en FP64
dn = (torch.linalg.norm(d) / torch.linalg.norm(x)).item() # tamaño relativo de la corrección
if not torch.isfinite(x).all() or (dn > previo and dn > 1e-10):
return x, paso, "diverge" # las correcciones crecen
if dn < 1e-15 or (paso > 3 and dn > 0.5 * previo):
return x, paso, "converge" if dn < 1e-10 else "se estanca" # ya no mejora
previo = dn
return x, max_pasos, "límite"
n = 4096
print(f"\n1) n = {n}: solve en FP64 frente a LU en FP32 + refinamiento en FP64")
for kappa in [1e2, 1e4, 1e6, 1e8]:
A = randsvd(n, kappa, 1)
x = torch.randn(n, 1, dtype=torch.float64, device=dev, generator=torch.Generator(device=dev).manual_seed(2))
b = A @ x
t64, x64 = cronometra(lambda: torch.linalg.solve(A, b))
tmix, (xm, pasos, estado) = cronometra(lambda: lu_ir_fp32(A, b))
print(f" kappa = {kappa:.0e}: FP64 {t64 * 1e3:6.0f} ms, error {error(x64, x):.1e} | mixto {tmix * 1e3:5.0f} ms, "
f"{pasos:2d} pasos ({estado}), error {error(xm, x):.1e} | cociente de tiempos {t64 / tmix:.1f}")
del A, x, b
torch.cuda.empty_cache()
# ---------- 2. LU simulada en FP16 y BF16: cada operación redondeada al formato
def lu_baja(A, dtype):
n = A.shape[0]
M = A.to(dtype).clone()
piv = torch.arange(n, device=dev)
for k in range(n - 1):
p = k + int(torch.argmax(M[k:, k].abs()))
if p != k:
M[[k, p]] = M[[p, k]]
piv[[k, p]] = piv[[p, k]]
M[k + 1:, k] = M[k + 1:, k] / M[k, k] # división redondeada
M[k + 1:, k + 1:] = M[k + 1:, k + 1:] - torch.outer(M[k + 1:, k], M[k, k + 1:]) # producto y resta redondeados
return M.double(), piv
def aplica_lu(M, piv, r):
"""(LU)^{-1} P r en FP64 con los factores de precisión baja."""
y = torch.linalg.solve_triangular(M, r[piv], upper=False, unitriangular=True)
return torch.linalg.solve_triangular(M, y, upper=True)
def gmres(matvec, rhs, tol=1e-12, maxit=300):
"""GMRES en FP64 con Gram-Schmidt repetido; devuelve solución e iteraciones."""
beta = torch.linalg.norm(rhs)
V = torch.zeros(rhs.shape[0], maxit + 1, dtype=torch.float64, device=dev)
H = torch.zeros(maxit + 1, maxit, dtype=torch.float64, device=dev)
V[:, 0] = rhs[:, 0] / beta
for j in range(maxit):
w = matvec(V[:, j:j + 1])[:, 0]
for _ in range(2):
h = V[:, :j + 1].T @ w
w = w - V[:, :j + 1] @ h
H[:j + 1, j] += h
H[j + 1, j] = torch.linalg.norm(w)
e1 = torch.zeros(j + 2, 1, dtype=torch.float64, device=dev); e1[0] = beta
y = torch.linalg.lstsq(H[:j + 2, :j + 1].cpu(), e1.cpu()).solution.to(dev)
if torch.linalg.norm(H[:j + 2, :j + 1] @ y - e1) < tol * beta:
return V[:, :j + 1] @ y, j + 1
V[:, j + 1] = w / H[j + 1, j]
return V[:, :maxit] @ y, maxit
n = 1024
print(f"\n2) n = {n}: LU simulada en precisión baja; LU-IR (10 pasos) y GMRES-IR")
for nombre, dt in [("FP16", torch.float16), ("BF16", torch.bfloat16)]:
u = 2.0 ** -11 if dt == torch.float16 else 2.0 ** -8
for kappa in [1e1, 1e2, 1e3, 1e4, 1e5]:
A = randsvd(n, kappa, 3)
x = torch.randn(n, 1, dtype=torch.float64, device=dev, generator=torch.Generator(device=dev).manual_seed(4))
b = A @ x
M, piv = lu_baja(A, dt)
xl = aplica_lu(M, piv, b)
for _ in range(10):
xl = xl + aplica_lu(M, piv, b - A @ xl)
xg, its = aplica_lu(M, piv, b), []
for _ in range(4):
d, k = gmres(lambda v: aplica_lu(M, piv, A @ v), aplica_lu(M, piv, b - A @ xg))
xg, its = xg + d, its + [k]
if error(xg, x) < 1e-12:
break
print(f" {nombre} kappa = {kappa:.0e} (kappa u_f = {kappa * u:7.2g}): LU-IR {error(xl, x):.1e} | "
f"GMRES-IR {error(xg, x):.1e} con {its} iteraciones de GMRES")
del A, M
torch.cuda.empty_cache()
# ---------- 3. Escalar antes de redondear a FP16
print("\n3) Escalado (Higham, Pranesh y Zounon): A multiplicada por un factor y factorizada en FP16")
A0 = randsvd(n, 1e2, 5)
x = torch.randn(n, 1, dtype=torch.float64, device=dev, generator=torch.Generator(device=dev).manual_seed(6))
print(f" max |a_ij| de la matriz base: {A0.abs().max().item():.3f}")
for factor in [1e6, 1e-7]:
A = factor * A0
b = A @ x
for theta in [None, 0.1, 0.01]: # None: sin escalar; si no, mu = theta * 65504 / max|a_ij|
mu = theta * 65504 / A.abs().max().item() if theta else 1.0
M, piv = lu_baja(mu * A, torch.float16)
ceros = int(((mu * A).half() == 0).sum())
U = torch.triu(M)
crec = (U[torch.isfinite(U)].abs().max() / (mu * A).abs().max()).item() # crecimiento de la eliminación
xl = mu * aplica_lu(M, piv, b)
for _ in range(10):
xl = xl + mu * aplica_lu(M, piv, b - A @ xl)
nombre = "sin escalado" if theta is None else f"theta = {theta}"
print(f" factor {factor:.0e}, {nombre:12s}: factores finitos {bool(torch.isfinite(M).all())}, "
f"entradas a 0 al redondear {ceros}, max|U|/max|mu A| = {crec:.1f}, error {error(xl, x):.1e}")
del A0, A, M
torch.cuda.empty_cache()npm run lab and open the connection link.The three experiments say different things and should be read individually.
FP32 on GPU plus refinement. For from to , FP32 LU plus 5 to 11 refinement steps takes 6 to 9 times less than torch.linalg.solve in FP64, with lower error: versus with , versus with . Direct solve leaves between 6 and 54 times , the price of factor and elimination growth of ; refined stays below because iteration with residual in working precision becomes componentwise backward stable (Skeel, 1980), and error is then set by componentwise conditioning , potentially much smaller, without elimination growth. With , and refinement diverges. The same FP32 converged with on the interactive’s matrix: threshold falls with .
Simulated FP16 and BF16 with . The threshold falls much more than suggests. In FP16, LU-IR reaches FP64 accuracy with , crawls with ( after 10 steps) and diverges with when is only . In BF16 it already crawls with and diverges with . This is constant in the convergence condition: with and every operation rounded to 11 or 8 bits (without real tensor units’ FP32 accumulation, the more pessimistic case), LU errors accumulate across a thousand elimination steps. GMRES-IR widens the range: FP16 converges up to and BF16 up to . But note iteration counts: 44 and 46 per correction with , and 252 and 279 with , one quarter of . Each GMRES iteration costs about flops plus orthogonalization, so 250 iterations already cost more than LU itself (): Carson and Higham’s warning in numbers. With GMRES exhausts 300 iterations without convergence.
Scaling. Base matrix entries are at most . Multiplied by , the matrix fits FP16 (), but elimination makes it grow and factors fill with infinities. Multiplied by , its entries round to zero. Scaling with is insufficient: growth is nearly 10, and is already near the maximum, so an intermediate entry overflows. With factors are finite and LU-IR converges again ( after 10 steps, same rate as unscaled with ). This is precisely Higham and Mary’s warning: must allow growth, which increases with .
Probabilistic numerics: computation as inference
Every method in this lesson returns an answer and at most a worst-case or expected error bound. Probabilistic numerics proposes something else: treat a computation result as an unknown quantity reasoned about probabilistically. Place a prior distribution on the unknown object (function to integrate, solution of a system), condition on evaluations made by the method and return a posterior: an estimate and uncertainty about computational error. Hennig, Osborne and Kersting (2022) develop the full program.
The canonical example is Bayesian quadrature. To estimate , assume a Gaussian process with kernel . Since is linear in , conditional on it is Gaussian with mean and variance , where and . The mean is a quadrature rule with weights . Diaconis (1988) observed that with Brownian motion as prior, that rule is the trapezoid rule: classical methods reappear as posterior means. Similarly, Hennig (2015) showed conjugate gradient arises as the posterior mean of Gaussian inference on a linear-system solution, and Cockayne, Oates, Ipsen and Girolami (2019) built Bayesian conjugate gradient that also returns covariance.
import numpy as np
# a priori: f(t) = c + B(t), con c ~ N(0, 1) y B un movimiento browniano: k(s, t) = 1 + min(s, t)
k = lambda s, t: 1 + np.minimum(s, t)
z = lambda t: 1 + t - t**2 / 2 # ∫_0^1 k(s, t) ds
kk = 1 + 1 / 3 # ∫∫ k(s, t) ds dt
def cuadratura_bayesiana(f, n):
t = np.linspace(0, 1, n)
K = k(t[:, None], t[None, :])
w = np.linalg.solve(K, z(t)) # pesos de la regla
media = w @ f(t)
var = kk - z(t) @ w
return media, np.sqrt(max(var, 0)), w
f = lambda t: np.exp(np.sin(3 * t))
t_ref = np.linspace(0, 1, 200_001) # referencia: trapecio con 200 000 intervalos (error ~1e-11)
I = np.trapezoid(f(t_ref), t_ref) if hasattr(np, "trapezoid") else np.trapz(f(t_ref), t_ref)
for n in [5, 9, 17, 33, 65]:
media, sd, w = cuadratura_bayesiana(f, n)
h = 1 / (n - 1)
w_trap = np.full(n, h); w_trap[[0, -1]] = h / 2
print(f"n = {n:2d}: |pesos - trapecio| = {np.abs(w - w_trap).max():.1e} | error real {abs(media - I):.1e} | "
f"desviación a posteriori {sd:.1e} | cociente {sd / abs(media - I):6.0f}")Weights exactly match the trapezoid rule: Bayesian quadrature with this prior is trapezoidal quadrature. But returned uncertainty is miscalibrated for this , increasingly so: posterior deviation falls as (halves when doubles) and true error as (quarters), so their ratio rises from 2 with to 35 with and keeps doubling. The Brownian prior assumes functions as irregular as a random path, while is analytic. This is the general lesson of probabilistic numerics: uncertainty is only as good as its prior, and choosing one matching actual problem regularity (smoother Matérn kernels, for example) is difficult. This lesson’s randomized estimators are the opposite: their uncertainty (Hutchinson variance, median across seeds) is frequentist and comes from randomness introduced by the algorithm, not a prior over the problem.
How to read a paper in this area
A RandNLA or mixed-precision paper often offers a probabilistic theorem and a timing table. Neither suffices alone. Questions to ask, using the research module’s critical reading checklist as a general framework:
- What precision is achieved and how measured? A “ten times faster” randomized solver with error does not compete with LAPACK, which gives (sketch-and-solve versus QR). Look for forward and backward error, not only relative residual.
- What conditioning? The least-squares section showed sketch-and-precondition matches QR with and loses one to three orders with . An experiment only on Gaussian matrices (which have ) does not establish stability.
- What matrix shape? Randomized least-squares methods win when and is hundreds or thousands; with , as in the interactive, QR wins in flops. Coherent matrices break uniform sampling and CountSketch with few rows.
- What baseline? The most important question, made concrete in the next cell. A strong baseline is the best classical method, well configured on the same hardware and thread count.
- How many seeds and what spread? A mean without dispersion hides tails. Chen and coauthors give medians with 20th and 80th quantiles over 100 runs; that is the standard to emulate.
- Is the guarantee worst-case, in expectation or probabilistic? For which matrix class (positive semidefinite, full rank)? Are theorem constants realistic or is it an order bound?
The following cell solves two least-squares problems of rows with four methods: np.linalg.lstsq (LAPACK gelsd, SVD-based, NumPy’s default), scipy.linalg.lstsq with gelsy (pivoted QR), Householder QR using scipy.linalg.qr, and Blendenpik-style sketch-and-precondition (random signs, cosine transform, rows and LSQR). It runs on your CPU using all threads.
import time
import numpy as np
import scipy.linalg as sla
import scipy.fft as sfft
from scipy.sparse.linalg import LinearOperator, lsqr
def mejor(f, rep=3):
t, out = float("inf"), None
for _ in range(rep):
t0 = time.perf_counter(); out = f(); t = min(t, time.perf_counter() - t0)
return t, out
rng = np.random.default_rng(0)
for m, n in [(2**16, 128), (2**16, 512)]: # la de n = 512 ocupa 256 MB
A = rng.standard_normal((m, n)) * np.logspace(0, -4, n) # kappa del orden de 10^4
x = rng.standard_normal(n)
b = A @ x + 1e-3 * np.linalg.norm(A @ x) / np.sqrt(m) * rng.standard_normal(m)
def qr_householder():
Q, R = sla.qr(A, mode="economic", check_finite=False)
return sla.solve_triangular(R, Q.T @ b, check_finite=False)
def sketch_precondition():
signos = rng.choice([-1.0, 1.0], size=m)
M = sfft.dct(signos[:, None] * A, type=2, norm="ortho", axis=0, workers=-1) # mezcla rápida
R = np.linalg.qr(M[rng.choice(m, size=4 * n, replace=False)], mode="r")
Ri = lambda v: sla.solve_triangular(R, v, check_finite=False)
RiT = lambda v: sla.solve_triangular(R, v, trans="T", check_finite=False)
op = LinearOperator((m, n), matvec=lambda v: A @ Ri(v), rmatvec=lambda u: RiT(A.T @ u), dtype=float)
y, istop, its = lsqr(op, b, atol=1e-14, btol=1e-14, iter_lim=200)[:3]
return Ri(y), its
t_svd, x_svd = mejor(lambda: np.linalg.lstsq(A, b, rcond=None)[0])
t_gelsy, x_gelsy = mejor(lambda: sla.lstsq(A, b, lapack_driver="gelsy", check_finite=False)[0])
t_qr, x_qr = mejor(qr_householder)
t_sp, (x_sp, its) = mejor(sketch_precondition)
dif = lambda y: np.linalg.norm(y - x_qr) / np.linalg.norm(x_qr)
print(f"m = {m}, n = {n}: gelsd {t_svd:.2f} s | gelsy {t_gelsy:.2f} s | QR {t_qr:.2f} s | "
f"sketch-and-precondition {t_sp:.2f} s ({its} iteraciones, diferencia con QR {dif(x_sp):.0e})")
print(f" aceleración de sketch-and-precondition: {t_svd / t_sp:.1f}x frente a gelsd, {t_qr / t_sp:.1f}x frente a QR")npm run lab and open the connection link.With the same sketch-and-precondition implementation (47 and 50 iterations, solution differing from QR by ), “speedup” ranges from to depending on the comparison. With it is slower than gelsd () and ties SciPy QR (between and depending on run). With it ties gelsd () and beats QR by . That SVD-based gelsd beats QR is no paradox: when , LAPACK first reduces to triangular using QR that never forms , then computes SVD of an , while scipy.linalg.qr(mode="economic") explicitly forms an of , nearly doubling work. A paper comparing only that QR would announce a speedup that disappears against gelsd. The factor grows with , as flop ratio predicts: with 50 iterations, the randomized method clearly wins only when is in hundreds or thousands. Times vary across runs on a shared machine; ratios are what persist.
Common mistakes
Exercises
Step 1 of 4. How do you obtain the mean?
rp_cholesky(diag, col, k, rng), performing partial pivoted Cholesky steps with random pivots proportional to residual diagonal on a positive semidefinite matrix where only the diagonal (diag, an array) and columns (col(j), each call costs evaluations) can be requested. Return (F, S): F of with and pivot list S in order. Request only pivot columns, and do not fail if residual trace vanishes before steps (leave remaining columns zero).import numpy as np
def rp_cholesky(diag, col, k, rng):
"""Devuelve (F, S): F de N x k con A ≈ F Fᵀ y la lista de pivotes S.
diag: array con la diagonal de A. col(j): columna j de A (cada llamada cuenta como N entradas).
rng: np.random.Generator para elegir los pivotes."""
diag = np.asarray(diag, dtype=float)
N = diag.shape[0]
F = np.zeros((N, k))
S = []
# tu código: k pasos de Cholesky pivotado con pivotes aleatorios proporcionales a la diagonal residual
return F, SMore than one answer may be correct.
Summary
- A sketch embeds a subspace of dimension if it preserves norms within . Gaussian does so with without seeing data; SRHT mixes before sampling and costs ; CountSketch costs one data pass but needs because of the birthday paradox.
- Sketch-and-solve gives residual at most times optimum: useful for few digits, never machine precision. Sketch-and-precondition uses from QR of : and LSQR reaches QR accuracy in iterations independent of ; ill-conditioned problems need stability care (sketch-and-solve start, SPIR, FOSSILS).
- RPCholesky chooses pivots proportional to residual diagonal: entries, flops and nearly trace-optimal approximation with columns, without greedy (outliers) or uniform (small clusters) failures.
- Hutchinson estimates with products and variance with Rademacher vectors; Hutch++ exactly computes the low-rank part using randomized SVD and lowers cost from to products for positive semidefinite matrices.
- Three-precision iterative refinement converges if the correction solver is a contraction ( for LU-IR), and limiting error is set by and , not . GMRES-IR uses low-precision factors as preconditioner and widens range while GMRES needs few iterations. FP16 needs scaling before rounding.
- Probabilistic numerics reinterprets methods as inference (trapezoid and conjugate gradient are posterior means), and its uncertainty is only as good as the prior. When reading a paper, ask about accuracy, conditioning, matrix shape, baseline and seed dispersion.