Module contents
Lesson 26 of 26Research 120 min

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

Motivation: four problems that do not fit one factorization

The entire module has relied on factorizations: LU, Cholesky, QR, SVD. They cost O(n3)\bigO(n^3) or O(mn2)\bigO(mn^2), 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 m=106m = 10^6 observations and n=500n = 500 variables costs 2mn2=5×10112mn^2 = 5\times 10^{11} flops with QR. Almost all that work is spent on redundant information: the problem has only nn degrees of freedom.
  • Matrices with expensive entries. A kernel matrix of N=105N = 10^5 points has 101010^{10} entries (80 GB in float64) and each requires evaluating k(xi,xj)k(\vb{x}_i, \vb{x}_j). 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 10810^8 parameters, even its diagonal cannot be explicitly stored, but products Hv\mat{H}\vb{v} can be computed for a few gradients (Hessian-vector products, calculated with automatic differentiation mode composition). What is tr⁡(H)\tr(\mat{H})?
  • 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 4096×40964096\times 4096 6 to 9 times faster than torch.linalg.solve in FP64, with lower error.

Modern answers share two ideas. The first is random projection: a well-chosen random matrix compresses Rm\R^m to Rd\R^d, with dd of the order of problem dimension rather than mm, preserving lengths of an entire subspace. This is randomized numerical linear algebra (RandNLA). The second is compute cheaply and correct expensively: do O(n3)\bigO(n^3) work at low precision and recover full accuracy with O(n2)\bigO(n^2) 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 A∈Rm×n\mat{A} \in \R^{m\times n} at rank kk, multiply by Gaussian Ω∈Rn×(k+p)\mat{\Omega} \in \R^{n\times(k + p)}, orthonormalize Y=AΩ\mat{Y} = \mat{A}\mat{\Omega} and work with small matrix Q⊤A\mat{Q}\T\mat{A}. Their expected bound (paper theorem 10.5), for k≥2k \ge 2 and oversampling p≥2p \ge 2, is

E∥(I−QQ⊤)A∥F≤(1+kp−1)1/2(∑j>kσj2)1/2.\E\norm{(\mat{I} - \mat{Q}\mat{Q}\T)\mat{A}}_F \le \Big(1 + \frac{k}{p - 1}\Big)^{1/2}\Big(\sum_{j > k}\sigma_j^2\Big)^{1/2}.

Three features of this bound recur throughout the lesson:

  1. A random matrix “sees” a whole subspace. AΩ\mat{A}\mat{\Omega} is a random mixture of columns of A\mat{A} and, with a few extra columns (pp), captures its dominant range with high probability.
  2. Error is compared with optimum. The right-hand factor is exactly the best rank-kk approximation error (Eckart–Young theorem). RandNLA guarantees have the form “(1+ε)(1 + \eps) times the best possible,” not “small error.”
  3. 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 NN points in Rm\R^m can be projected to Rd\R^d, with d=O(ε−2log⁡N)d = \bigO(\eps^{-2}\log N), preserving all distances by factor 1±ε1 \pm \eps. Linear algebra needs something stronger: preserve norms of all vectors in a subspace, infinitely many.

If U∈Rm×n\mat{U} \in \R^{m\times n} has orthonormal columns spanning VV, every v∈V\vb{v} \in V is Uc\mat{U}\vb{c} with ∥v∥=∥c∥\norm{\vb{v}} = \norm{\vb{c}}, and the condition is equivalent to all singular values of SU\mat{S}\mat{U} lying in [1−ε,1+ε][1 - \eps, 1 + \eps]. This is how distortion is measured in practice: ε=max⁡{σmax⁡(SU)−1, 1−σmin⁡(SU)}\eps = \max\{\sigma_{\max}(\mat{S}\mat{U}) - 1,\ 1 - \sigma_{\min}(\mat{S}\mat{U})\}.

The Gaussian sketch

Proof

Let U\mat{U} be an orthonormal basis of VV. Rows of G\mat{G} are standard Gaussians in Rm\R^m, rotation invariant, so each row of GU\mat{G}\mat{U} is U⊤\mat{U}\T applied to a standard Gaussian: a vector N(0,U⊤U)=N(0,In)\Normal(\vb{0}, \mat{U}\T\mat{U}) = \Normal(\vb{0}, \mat{I}_n). Therefore GU\mat{G}\mat{U} is a matrix d×nd\times n of independent standard Gaussians, regardless of VV. For such a matrix, Gordon’s inequality gives d−n≤Eσmin⁡≤Eσmax⁡≤d+n\sqrt{d} - \sqrt{n} \le \E\sigma_{\min} \le \E\sigma_{\max} \le \sqrt{d} + \sqrt{n}, and since σmax⁡\sigma_{\max} and σmin⁡\sigma_{\min} are 1-Lipschitz functions of entries (in Frobenius norm), Gaussian Lipschitz concentration gives deviations above tt with probability at most e−t2/2e^{-t^2/2} in each tail (Davidson–Szarek corollary; Vershynin, High-Dimensional Probability, theorem 7.3.3). Dividing by d\sqrt{d}, singular values of SU\mat{S}\mat{U} lie in [1−n/d−t/d, 1+n/d+t/d][1 - \sqrt{n/d} - t/\sqrt{d},\ 1 + \sqrt{n/d} + t/\sqrt{d}].

∎

What does not appear is important: mm. A sketch with d=4nd = 4n rows has distortion around 1/21/2 for any subspace of dimension nn, whether it lives in R103\R^{10^3} or R109\R^{10^9}. The issue is cost: forming SA\mat{S}\mat{A} costs 2dmn2dmn flops, and with d=4nd = 4n that is 8mn28mn^2, four times the QR we wanted to avoid. Faster sketches are needed.

SRHT: mix before sampling

The cheapest idea would be to keep dd randomly selected rows of A\mat{A} (rescaled by m/d\sqrt{m/d}). It works when information is spread across rows, and fails when a few rows concentrate it. The concentration measure is the leverage scores ℓi=∥Ui,:∥22\ell_i = \norm{\mat{U}_{i,:}}_2^2, with ∑iℓi=n\sum_i \ell_i = n: if a row has ℓi≈1\ell_i \approx 1, it alone contains one range direction and uniform sampling misses it with probability (1−1/m)d≈1(1 - 1/m)^d \approx 1. A matrix with very unequal leverage is called coherent.

The subsampled randomized Hadamard transform (SRHT) fixes this by mixing first:

S=md P Hm D,\mat{S} = \sqrt{\frac{m}{d}}\,\mat{P}\,\frac{\mat{H}}{\sqrt{m}}\,\mat{D},

where D\mat{D} is diagonal with random signs ±1\pm 1, H\mat{H} is the order-mm Walsh–Hadamard matrix (a power of 2), with entries ±1\pm 1 and H⊤H=mI\mat{H}\T\mat{H} = m\mat{I}, and P\mat{P} selects dd random rows. HD/m\mat{H}\mat{D}/\sqrt{m} is orthogonal, so it changes no norm, but spreads each range direction across rows: with high probability, after mixing all leverage scores are near n/mn/m (up to logarithmic factors), and uniform sampling works. Applying H\mat{H} costs mlog⁡2mm\log_2 m additions per column, like an FFT. In exchange for speed, theory requires dd of order nlog⁡nn\log n rows rather than nn (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 ±1\pm 1 per column in a random row: each row of A\mat{A} is added with random sign to one of dd rows of SA\mat{S}\mat{A}. This is CountSketch (Clarkson and Woodruff, 2013, brought it to regression), costing one data pass, O(nnz⁡(A))\bigO(\operatorname{nnz}(\mat{A})): unbeatable for sparse matrices. The price is size: embedding needs dd of order n2n^2, not nn. The reason is the birthday paradox. If A\mat{A} has nn rows of leverage 1, each with one range direction, and two land in the same sketch row, they add into one vector and SA\mat{S}\mat{A} loses a dimension. With nn rows and dd bins, collision probability is 1−∏i<n(1−i/d)≈1−e−n2/(2d)1 - \prod_{i < n}(1 - i/d) \approx 1 - e^{-n^2/(2d)}, small only if d≫n2d \gg n^2.

SketchCost of forming SA\mat{S}\mat{A}Rows dd for constant distortionCoherence
Gaussian2dmn2dmnO(n)\bigO(n)indifferent
SRHTmnlog⁡2mmn\log_2 mO(nlog⁡n)\bigO(n\log n)indifferent (mixing)
CountSketchnnz⁡(A)\operatorname{nnz}(\mat{A})O(n2)\bigO(n^2)indifferent on average, collisions
Uniform row samplingdndnO(n)\bigO(n) only if incoherentfails

The lab builds all four from scratch and measures distortion on orthonormal basis U\mat{U} of 2048×202048\times 20, first incoherent (orthonormalized Gaussian columns) and then coherent (20 rows with leverage near 1).

[ ]Four sketches and their distortionBrowser
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 n/d\sqrt{n/d}: 0.65 to 0.68 with d=2nd = 2n (prediction 0.71), 0.46 to 0.50 with d=4nd = 4n and 0.22 to 0.27 with d=16nd = 16n. With the coherent basis everything changes. Gaussian does not notice, as the proof says: GU\mat{G}\mat{U} has the same distribution regardless of U\mat{U}. SRHT needs somewhat more margin (0.970.97 with d=2nd = 2n), but from d=8nd = 8n matches Gaussian. Uniform sampling fails for every dd: it misses leverage-1 rows (distortion 0.980.98) or, if it catches them, rescaling m/d\sqrt{m/d} 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 0.020.02 with d=16n=320d = 16n = 320. With d=320d = 320 collision probability is still 45%, so other seeds would fail; that is why theory asks for d≫n2=400d \gg n^2 = 400.

Least squares: solve the sketch or precondition with it

Let A∈Rm×n\mat{A} \in \R^{m\times n} have rank nn with m≫nm \gg n and x∗=arg min⁡x∥Ax−b∥2\vb{x}^* = \argmin_{\vb{x}}\norm{\mat{A}\vb{x} - \vb{b}}_2, with optimal residual r∗=b−Ax∗\vb{r}^* = \vb{b} - \mat{A}\vb{x}^*. The classical solution is Householder QR, backward stable at cost 2mn2−23n32mn^2 - \tfrac{2}{3}n^3 flops (studied in least-squares numerics). There are two ways to use a sketch.

Sketch-and-solve

The most direct: solve small problem x^=arg min⁡x∥S(Ax−b)∥2\hat{\vb{x}} = \argmin_{\vb{x}}\norm{\mat{S}(\mat{A}\vb{x} - \vb{b})}_2, of d×nd\times n.

Proof

Vectors Ax−b\mat{A}\vb{x} - \vb{b} lie in col⁡([A  b])\col([\mat{A}\;\vb{b}]) for every x\vb{x}. Using the embedding lower bound, optimality of x^\hat{\vb{x}} for the sketched problem and the upper bound,

(1−ε)∥Ax^−b∥≤∥S(Ax^−b)∥≤∥S(Ax∗−b)∥≤(1+ε)∥Ax∗−b∥.(1 - \eps)\norm{\mat{A}\hat{\vb{x}} - \vb{b}} \le \norm{\mat{S}(\mat{A}\hat{\vb{x}} - \vb{b})} \le \norm{\mat{S}(\mat{A}\vb{x}^* - \vb{b})} \le (1 + \eps)\norm{\mat{A}\vb{x}^* - \vb{b}}.

For the second, r∗\vb{r}^* is orthogonal to col⁡(A)\col(\mat{A}) (normal equations), so by Pythagoras ∥Ax^−b∥2=∥A(x^−x∗)∥2+∥r∗∥2\norm{\mat{A}\hat{\vb{x}} - \vb{b}}^2 = \norm{\mat{A}(\hat{\vb{x}} - \vb{x}^*)}^2 + \norm{\vb{r}^*}^2, and rearrange using the first bound.

∎

The bound is relative to residual, making it useless for high precision. With ε=1/2\eps = 1/2 it guarantees only residual at most three times optimal and ∥A(x^−x∗)∥\norm{\mat{A}(\hat{\vb{x}} - \vb{x}^*)} error up to 2.8∥r∗∥2.8\norm{\vb{r}^*}. To make that error 10−8∥r∗∥10^{-8}\norm{\vb{r}^*} would require ε≈10−16\eps \approx 10^{-16}, and with ε∼n/d\eps \sim \sqrt{n/d} that is d∼1032nd \sim 10^{32}n. 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 r∗≠0\vb{r}^* \neq \vb{0}.

Sketch-and-precondition

The second way uses the sketch only to build a preconditioner and solves the original problem iteratively.

Proof

For every y\vb{y}, vector AR−1y\mat{A}\mat{R}^{-1}\vb{y} lies in col⁡(A)\col(\mat{A}), and SAR−1=Q\mat{S}\mat{A}\mat{R}^{-1} = \mat{Q} has orthonormal columns, so ∥SAR−1y∥=∥y∥\norm{\mat{S}\mat{A}\mat{R}^{-1}\vb{y}} = \norm{\vb{y}}. By the embedding, (1−ε)∥AR−1y∥≤∥y∥≤(1+ε)∥AR−1y∥(1 - \eps)\norm{\mat{A}\mat{R}^{-1}\vb{y}} \le \norm{\vb{y}} \le (1 + \eps)\norm{\mat{A}\mat{R}^{-1}\vb{y}}. Rearranging, ∥AR−1y∥/∥y∥∈[1/(1+ε),1/(1−ε)]\norm{\mat{A}\mat{R}^{-1}\vb{y}}/\norm{\vb{y}} \in [1/(1 + \eps), 1/(1 - \eps)] for every y≠0\vb{y} \neq \vb{0}.

∎

LSQR (Paige and Saunders, 1982) is mathematically equivalent to conjugate gradients on normal equations, implemented with Golub–Kahan bidiagonalization to avoid forming A⊤A\mat{A}\T\mat{A}. By conjugate gradient’s Chebyshev bound, with κ=κ(AR−1)\kappa = \kappa(\mat{A}\mat{R}^{-1}),

∥A(xk−x∗)∥2≤2(κ−1κ+1)k∥A(x0−x∗)∥2.\norm{\mat{A}(\vb{x}_k - \vb{x}^*)}_2 \le 2\Big(\frac{\kappa - 1}{\kappa + 1}\Big)^k\norm{\mat{A}(\vb{x}_0 - \vb{x}^*)}_2.

With ε=1/2\eps = 1/2, κ≤3\kappa \le 3 and the ratio is 1/21/2 per iteration: about 50 iterations suffice to go from 11 to 10−1510^{-15} for any full-rank A\mat{A}. Sketch distortion no longer limits accuracy, only speed: this is the essential difference from sketch-and-solve.

Cost is the sketch, plus 2dn22dn^2 for small QR, plus about 4mn4mn flops per iteration (products with A\mat{A} and A⊤\mat{A}\T). Compared with QR’s 2mn22mn^2, the ratio is about 2k/n2k/n for kk iterations (plus sketch), so savings arrive when nn is considerably larger than twice the iteration count: with n=64n = 64, as in the interactive, QR still wins in flops; with nn 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 ⌈γn⌉\lceil\gamma n\rceil rows (moderate γ\gamma, e.g. 2) and LSQR or Chebyshev semi-iteration, and parallelizes easily because Gaussian generation and application require no communication.

InteractiveLeast squares with sketching
Explicit 2048×642048\times 64 problem with prescribed κ(A)\kappa(\mat{A}), known solution x∗\vb{x}^* and optimal residual 10−3∥Ax∗∥10^{-3}\norm{\mat{A}\vb{x}^*}. Orange line is sketch-and-solve error, independent of iterations; red is full QR error. Curves are unpreconditioned LSQR (gray) and LSQR on AR−1\mat{A}\mat{R}^{-1} from zero (blue) and from the sketch-and-solve solution (aqua). Reduce dd to 1.25n1.25n: the preconditioner worsens and LSQR slows but keeps decreasing. Enable the coherent matrix and try uniform sampling and CountSketch. Switch to κ=106\kappa = 10^6: unpreconditioned LSQR makes no progress and the preconditioned method stalls above QR, more from zero than from sketch-and-solve.

Initially (SRHT with d=4n=256d = 4n = 256, κ=102\kappa = 10^2), κ(AR−1)=2.79\kappa(\mat{A}\mat{R}^{-1}) = 2.79, the bound predicts ratio 0.470.47 per iteration and preconditioned LSQR reaches QR level (9.6×10−159.6\times 10^{-15}) in 36 iterations. Unpreconditioned LSQR remains at 6.6×10−26.6\times 10^{-2} after 60, and sketch-and-solve at 9.0×10−39.0\times 10^{-3}: relative residual (10−310^{-3}) amplified by distortion and conditioning. With n=64n = 64 and 60 iterations, finite Krylov termination (in exact arithmetic LSQR ends in nn steps) cannot hide the difference: what is seen is the speed given by κ(AR−1)\kappa(\mat{A}\mat{R}^{-1}). Extremes teach most. With d=1.25n=80d = 1.25n = 80, κ(AR−1)≈12\kappa(\mat{A}\mat{R}^{-1}) \approx 12 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 SA\mat{S}\mat{A} rank-deficient (with initial seed even at d=16nd = 16n), so there is no preconditioner; CountSketch succeeds for other seeds when the 32 rows do not collide. Flop accounting gives 1.371.37: with n=64n = 64 and 36 iterations the randomized method still costs more than QR.

LSQR from scratch

LSQR maintains Golub–Kahan bidiagonalization, β1u1=b\beta_1\vb{u}_1 = \vb{b}, α1v1=A⊤u1\alpha_1\vb{v}_1 = \mat{A}\T\vb{u}_1, and at each step βk+1uk+1=Avk−αkuk\beta_{k+1}\vb{u}_{k+1} = \mat{A}\vb{v}_k - \alpha_k\vb{u}_k, αk+1vk+1=A⊤uk+1−βk+1vk\alpha_{k+1}\vb{v}_{k+1} = \mat{A}\T\vb{u}_{k+1} - \beta_{k+1}\vb{v}_k, 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: κ(A)∈{102,106}\kappa(\mat{A}) \in \{10^2, 10^6\} and large (10−210^{-2}) or small (10−610^{-6}) optimal residual relative to ∥Ax∗∥\norm{\mat{A}\vb{x}^*}. The sketch is SRHT with d=4nd = 4n.

[ ]LSQR, sketch-and-solve and sketch-and-preconditionBrowser
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 κ=102\kappa = 10^2 it moves from 10−110^{-1} to 10−510^{-5} when residual drops from 10−210^{-2} to 10−610^{-6}, and with κ=106\kappa = 10^6 relative error in x\vb{x} reaches hundreds. Sketch-and-precondition with κ=102\kappa = 10^2 matches or beats QR in both cases (errors 10−1510^{-15} to 10−1610^{-16} versus QR’s 1.6×10−141.6\times 10^{-14}): sketch distortion (κ(AR−1)=2.80\kappa(\mat{A}\mat{R}^{-1}) = 2.80) only determines iteration count.

With κ=106\kappa = 10^6 something appears that exact-arithmetic theory does not predict. QR gives 4.3×10−94.3\times 10^{-9} with large residual, allowed by least-squares conditioning (order κu+κ2u∥r∗∥/(∥A∥∥x∗∥)\kappa u + \kappa^2 u\norm{\vb{r}^*}/(\norm{\mat{A}}\norm{\vb{x}^*})), and 9.2×10−129.2\times 10^{-12} with small residual. Preconditioned LSQR from zero stays at 6.1×10−86.1\times 10^{-8} and 1.8×10−81.8\times 10^{-8}: 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 (3.1×10−123.1\times 10^{-12}) and improves little in the other (1.7×10−81.7\times 10^{-8}). 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 R\mat{R}.

[ ]Sketch-and-precondition with scipy.sparse.linalg.lsqrBrowser
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 A∈RN×N\mat{A} \in \R^{N\times N} be positive semidefinite, for example kernel matrix aij=k(xi,xj)a_{ij} = k(\vb{x}_i, \vb{x}_j) with Gaussian kernel k(x,y)=e−∥x−y∥2/(2h2)k(\vb{x}, \vb{y}) = e^{-\norm{\vb{x} - \vb{y}}^2/(2h^2)}. The Nyström approximation using column set S\mathcal{S} is

A^=A(:,S) A(S,S)+ A(S,:),\hat{\mat{A}} = \mat{A}(:, \mathcal{S})\,\mat{A}(\mathcal{S}, \mathcal{S})\pinv\,\mat{A}(\mathcal{S}, :),

and only needs columns of S\mathcal{S}: ∣S∣N\abs{\mathcal{S}}N entries. Which columns should be chosen? The tool is partial pivoted Cholesky: at step ii choose pivot sis_i, evaluate column g=A(:,si)\vb{g} = \mat{A}(:, s_i), subtract contributions of previous steps and normalize,

g←g−F:,1:i−1Fsi,1:i−1⊤,F:,i=g/gsi.\vb{g} \leftarrow \vb{g} - \mat{F}_{:, 1:i-1}\mat{F}_{s_i, 1:i-1}\T, \qquad \mat{F}_{:, i} = \vb{g}/\sqrt{g_{s_i}}.

After kk steps, A^=FF⊤\hat{\mat{A}} = \mat{F}\mat{F}\T is exactly the Nyström approximation with columns S={s1,…,sk}\mathcal{S} = \{s_1, \dots, s_k\} (each step is a Schur complement, as in Gaussian elimination in the Cholesky lesson), and residual A−A^\mat{A} - \hat{\mat{A}} is positive semidefinite. Two facts make the algorithm cheap:

  • The residual diagonal updates itself: d←d−F:,i⊙2\vb{d} \leftarrow \vb{d} - \mat{F}_{:, i}^{\odot 2}. No new entry is needed.
  • Trace-norm error can be read from it: since residual is positive semidefinite, ∥A−A^∥∗=tr⁡(A−A^)=∑jdj\norm{\mat{A} - \hat{\mat{A}}}_* = \tr(\mat{A} - \hat{\mat{A}}) = \sum_j d_j.

In total, diagonal (NN entries) plus kk columns: (k+1)N(k + 1)N kernel evaluations and O(k2N)\bigO(k^2N) flops. One decision remains: pivot rule.

Three pivot rules

  • Greedy. Largest residual diagonal element, si=arg max⁡jdjs_i = \argmax_j d_j. 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 sis_i 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 sis_i is chosen with probability proportional to djβd_j^{\beta}, β→∞\beta \to \infty is greedy (“zero temperature”), β=0\beta = 0 uniform (“infinite temperature”) and RPCholesky is β=1\beta = 1, “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.

InteractiveGreedy, uniform and random pivots
Cloud of 392 points: one large cluster, one medium, one small compact cluster (bottom right), and 10 distant outliers, with Gaussian kernel of width 0.8. Each point is colored by residual diagonal (bright: unexplained variance); large points are pivots. Right: median of 15 seeds of relative trace error versus kk, calculated in your browser. With k=20k = 20, greedy has already spent 9 pivots on outliers; switch to uniform and press ‘Another seed’ several times: it often leaves the entire small cluster unexplained. Increase kk to 60: greedy recovers when it runs out of outliers and uniform stalls.

The figure shows the “best rule” depends on budget. With k=20k = 20 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 k=60k = 60 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 r/εr/\eps columns in the worst case, so the bound is optimal up to the logarithmic term (in their 20 real datasets log⁡(1/η)\log(1/\eta) 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 N=104N = 10^4, 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 10410^4 points in R2\R^2. Smile: a face of radius 10 with two eyes of ⌈N⌉\lceil\sqrt{N}\rceil points, mouth of ⌈N/10⌉\lceil N/10\rceil and the rest on the outline, with h=2h = 2; eyes are easy to miss. Spiral: (e0.2tcos⁡t, e0.2tsin⁡t)(e^{0.2t}\cos t,\ e^{0.2t}\sin t) with t=(2τ)6t = (2\tau)^6 and τ\tau equally spaced in [0,1][0, 1], with h=1000h = 1000; the outside is so spread out it behaves like outliers. The following cells reproduce both with N=2000N = 2000 (the browser cannot handle 10410^4), following the authors’ public code, and give the median of 10 seeds.

[ ]Pivoted Cholesky: greedy, uniform and RPCholeskyBrowser
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)
[ ]The spiral: outliers attract greedy pivotsBrowser
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 k=100k = 100 it leaves error 6×10−36\times 10^{-3} versus 2×10−72\times 10^{-7} 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 k=100k = 100 leaves 5.1%; RPCholesky spreads choices and leaves 2.5%, half. With N=2000N = 2000 there are far fewer exterior points than in the paper, making this reduced reproduction: run in native NumPy with N=104N = 10^4 and kk 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: log⁡det⁡A=tr⁡(log⁡A)\log\det\mat{A} = \tr(\log\mat{A}) in Gaussian processes, effective parameter count tr⁡(X(X⊤X+λI)−1X⊤)\tr(\mat{X}(\mat{X}\T\mat{X} + \lambda\mat{I})^{-1}\mat{X}\T) of ridge regression, Hessian trace as loss curvature measure, or divergence tr⁡(∂f/∂z)\tr(\partial\vb{f}/\partial\vb{z}) of a vector field, needed by continuous normalizing flows. In each case a product Az\mat{A}\vb{z} is affordable (a system solve, gradient, Jacobian-vector product), while forming A\mat{A} is not.

It is unbiased because E[z⊤Az]=∑i,jaijE[zizj]=∑iaii\E[\vb{z}\T\mat{A}\vb{z}] = \sum_{i,j}a_{ij}\E[z_iz_j] = \sum_i a_{ii}. For symmetric A\mat{A}, the variance of one term with Rademacher vectors is

Var⁡(z⊤Az)=2(∥A∥F2−∑iaii2),\Var(\vb{z}\T\mat{A}\vb{z}) = 2\Big(\norm{\mat{A}}_F^2 - \sum_i a_{ii}^2\Big),

and with Gaussians, 2∥A∥F22\norm{\mat{A}}_F^2. You will prove the first in exercises. Generally, if components have fourth moment μ4\mu_4, variance is 2∑i≠jaij2+(μ4−1)∑iaii22\sum_{i\neq j}a_{ij}^2 + (\mu_4 - 1)\sum_i a_{ii}^2, and since μ4≥(Ez2)2=1\mu_4 \ge (\E z^2)^2 = 1 with equality only if z2=1z^2 = 1, Rademacher has minimum variance: with a diagonal matrix it is exact with one vector.

Hutchinson is a Monte Carlo estimator: its error is σ/m\sigma/\sqrt{m}. For a positive semidefinite matrix, ∥A∥F≤tr⁡(A)\norm{\mat{A}}_F \le \tr(\mat{A}), so relative standard deviation is at most 2/m\sqrt{2/m}, and relative error ε\eps needs order 1/ε21/\eps^2 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 ∥A∥F≈tr⁡(A)\norm{\mat{A}}_F \approx \tr(\mat{A}) 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:

tr⁡(A)=tr⁡(Q⊤AQ)+tr⁡((I−QQ⊤)A(I−QQ⊤)),\tr(\mat{A}) = \tr(\mat{Q}\T\mat{A}\mat{Q}) + \tr\big((\mat{I} - \mat{Q}\mat{Q}\T)\mat{A}(\mat{I} - \mat{Q}\mat{Q}\T)\big),

where Q\mat{Q} is an orthonormal basis of AS\mat{A}\mat{S} with S\mat{S} of m/3m/3 Rademacher columns (the randomized-SVD range finder, m/3m/3 products). The first term is computed exactly with another m/3m/3 products (AQ\mat{A}\mat{Q}). The second is estimated by Hutchinson using the remaining m/3m/3 products, applied to projected vectors (I−QQ⊤)g(\mat{I} - \mat{Q}\mat{Q}\T)\vb{g}.

Why does it win? For positive semidefinite A\mat{A} with eigenvalues λ1≥λ2≥⋯\lambda_1 \ge \lambda_2 \ge \cdots, and Ak\mat{A}_k its best rank-kk approximation,

∥A−Ak∥F2=∑i>kλi2≤λk+1∑i>kλi≤tr⁡(A)k tr⁡(A),\norm{\mat{A} - \mat{A}_k}_F^2 = \sum_{i > k}\lambda_i^2 \le \lambda_{k+1}\sum_{i > k}\lambda_i \le \frac{\tr(\mat{A})}{k}\,\tr(\mat{A}),

because λk+1≤tr⁡(A)/k\lambda_{k+1} \le \tr(\mat{A})/k (the first kk eigenvalues, all at least as large, sum to at most the trace). If Q\mat{Q} captures the dominant range nearly as well as Ak\mat{A}_k (as the Halko–Martinsson–Tropp bound guarantees with high probability), the part left for Hutchinson has Frobenius norm of order tr⁡(A)/m\tr(\mat{A})/\sqrt{m}, and its error with m/3m/3 vectors is order tr⁡(A)/m⋅1/m=tr⁡(A)/m\tr(\mat{A})/\sqrt{m}\cdot 1/\sqrt{m} = \tr(\mat{A})/m. The paper’s theorem follows: for positive semidefinite A\mat{A}, Hutch++ gives approximation (1±ε)(1 \pm \eps) with O(1/ε)\bigO(1/\eps) products rather than O(1/ε2)\bigO(1/\eps^2), and no algorithm using only matrix-vector products, even adaptively selected, can do better up to a logarithmic factor.

InteractiveThe Hutchinson estimator live
Symmetric 100×100100\times 100 matrix with a spectrum you choose. Left: cumulative Hutchinson estimate divided by trace, with band ±2σ/m\pm 2\sigma/\sqrt{m} from its exact variance, and Hutch++ recalculated for each budget mm. Right: median relative error over 20 seeds, on log–log scales. With spectrum i−2i^{-2}, Hutchinson falls with slope −1/2-1/2 (and much noise) and Hutch++ with an even steeper slope than −1-1: with m=192m = 192 it reaches 1.1×10−41.1\times 10^{-4} versus 4.1×10−24.1\times 10^{-2}, over two orders lower. With flat spectrum Hutch++ loses: there is no low rank to capture and it spends two-thirds of budget on it. Switch to Gaussian vectors with the flat spectrum: the band widens.

Laboratory: variance and both estimators

First, check the variance formula without sampling: with n=2n = 2 there are only four Rademacher vectors, and variance is exact. Then a random 6×66\times 6 matrix with 2×1052\times 10^5 samples of each kind.

[ ]Hutchinson is unbiased and its variance follows the formulaBrowser
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 200×200200\times 200 matrix, using median relative error over 30 seeds. The first two lines of hutchpp contain the randomized-SVD range finder.

[ ]Hutchinson and Hutch++ with equal product budgetsBrowser
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 ∥A∥F/tr⁡(A)\norm{\mat{A}}_F/\tr(\mat{A}) in the second column predicts Hutchinson error. With flat spectrum it is 0.07 and Hutchinson excels (1.5×10−31.5\times 10^{-3} with m=192m = 192); Hutch++ is somewhat worse (4.3×10−34.3\times 10^{-3}), because only one-third of products goes to the important part. With decaying spectra, Hutchinson falls slowly at rate 1/m1/\sqrt{m} and with much noise, while Hutch++ wins with m=192m = 192 by factor 4 with i−1i^{-1}, about 270 times with i−2i^{-2} (3.0×10−23.0\times 10^{-2} versus 1.1×10−41.1\times 10^{-4}), and over four orders with i−3i^{-3}: the faster the spectrum decays, the more trace the exact part captures. Guarantee O(1/m)\bigO(1/m) is worst-case, and for a specific spectrum Hutch++ can fall faster: with λi=i−2\lambda_i = i^{-2}, the tail after capturing k=m/3k = m/3 eigenvalues has ∥A−Ak∥F≈(∑i>ki−4)1/2≈k−3/2/3\norm{\mat{A} - \mat{A}_k}_F \approx (\sum_{i > k}i^{-4})^{1/2} \approx k^{-3/2}/\sqrt{3}, and divided by m/3\sqrt{m/3} gives error of order m−2m^{-2}. In the table, from m=48m = 48 to m=192m = 192 Hutch++ error with i−2i^{-2} falls by factor 22, near 42=164^2 = 16 from that calculation. This matches randomized SVD: dominant-range methods excel when spectra decay.

Trace of a network Hessian

The intended application: estimate tr⁡(H)\tr(\mat{H}) 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).

[ ]tr(H) of a network with Hessian-vector productsLocal GPU
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})")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 ∥H∥F/tr⁡(H)=0.23\norm{\mat{H}}_F/\tr(\mat{H}) = 0.23. With 300 HVPs, Hutchinson median error is 1.2% and Hutch++ 0.1%. The Hessian is not positive semidefinite (its smallest eigenvalue is −0.02-0.02): 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 10810^8 parameters the cell would be the same except the line forming H\mat{H}, which must be removed.

Mixed precision: compute cheaply and correct

Formats

This section’s calculations depend on two numbers per IEEE format: unit roundoff uu, setting precision, and range. The table gives standard format parameters, as summarized by Higham and Mary (2022), with u=2−tu = 2^{-t} for tt significand bits:

FormatSignificand bitsuuSmallest normalLargest finite
BF1683.91×10−33.91\times 10^{-3}1.18×10−381.18\times 10^{-38}3.39×10383.39\times 10^{38}
FP16114.88×10−44.88\times 10^{-4}6.10×10−56.10\times 10^{-5}6.55×1046.55\times 10^{4}
FP32245.96×10−85.96\times 10^{-8}1.18×10−381.18\times 10^{-38}3.40×10383.40\times 10^{38}
FP64531.11×10−161.11\times 10^{-16}2.22×10−3082.22\times 10^{-308}1.80×103081.80\times 10^{308}

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 nu16nu_{16} to u16+nu32u_{16} + nu_{32}).

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 uu (storing x\vb{x} and data), factorization precision ufu_f and residual precision uru_r, with ur≤u≤ufu_r \le u \le u_f.

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 ξ\xi, forward error decreases per step by a factor of order ξ\xi. With LU-IR, ξ≈3n uf∥∣A−1∣∣L^∣∣U^∣∥\xi \approx 3n\,u_f\norm{\abs{\mat{A}^{-1}}\abs{\hat{\mat{L}}}\abs{\hat{\mat{U}}}}, and with stable LU the condition reduces to κ(A) uf≪1\kappa(\mat{A})\,u_f \ll 1. Since 1/uf1/u_f equals 20482048 in FP16 and 256256 in BF16, LU-IR convergence with half-precision factorization is guaranteed only for very well-conditioned matrices with κ(A)\kappa(\mat{A}) clearly below those values (and further below as nn grows).
  • How far? Limiting error is order u+4p urcond⁡(A,x)u + 4p\,u_r\operatorname{cond}(\mat{A}, \vb{x}), with pp the maximum nonzeros per row. It does not depend on ufu_f: factorization precision determines only convergence and speed. With u=uru = u_r = FP64 the limit is that of FP64 elimination, order κu64\kappa u_{64}; with ur=u2u_r = u^2 (quadruple-precision residual) it reaches uu even if A\mat{A} is ill-conditioned.

GMRES-IR

What if κ(A)uf≥1\kappa(\mat{A})u_f \ge 1? Low-precision factors still contain much information about A\mat{A} even if insufficient for fixed-point iteration. Carson and Higham (2017, 2018) use them to precondition GMRES: preconditioned matrix A~=U^−1L^−1A\tilde{\mat{A}} = \hat{\mat{U}}^{-1}\hat{\mat{L}}^{-1}\mat{A} satisfies, in their worst-case analysis,

κ∞(A~)≲(1+γnfκ∞(A))2,γnf=nuf1−nuf,\kappa_\infty(\tilde{\mat{A}}) \lesssim \big(1 + \gamma_n^f\kappa_\infty(\mat{A})\big)^2, \qquad \gamma_n^f = \frac{nu_f}{1 - nu_f},

and its eigenvalues are often clustered near 1, so GMRES converges in few iterations even when κ(A)uf\kappa(\mat{A})u_f greatly exceeds 1. If products with A~\tilde{\mat{A}} use precision u2u^2, the analysis guarantees convergence while κ∞(A)\kappa_\infty(\mat{A}) is below u−1/2uf−1u^{-1/2}u_f^{-1}, up to constants. With FP16 factorization that is 212⋅211≈8×1062^{12}\cdot 2^{11} \approx 8\times 10^6 when working in FP32 and 226.5⋅211≈2×10112^{26.5}\cdot 2^{11} \approx 2\times 10^{11} 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 nn iterations, each correction costs O(n3)\bigO(n^3) and all savings vanish. GMRES-IR expands applicability while GMRES iterations are few; the interactive shows them at each step.

InteractiveThe precision ladder
System of 60×6060\times 60 with prescribed κ(A)\kappa(\mat{A}). LU is computed with each operation rounded to FP16, BF16 or FP32 (exact format simulation, including subnormals and overflow); residual and sum use FP64. Left: LU-IR error (substitutions in low format) and GMRES-IR error (FP64 GMRES preconditioned with low factors) at each step; dashed line is κu64\kappa u_{64}, the FP64 limit. Right: LU-IR error after 10 steps versus κ\kappa for the three formats; the marker is your κ\kappa. Raise κ\kappa in FP16: at 10410^4 LU-IR crawls (0.5 contraction per step) and at 10510^5 diverges, while GMRES-IR arrives with 16 and 28 GMRES iterations per step. Then multiply A\mat{A} by 10610^6 (overflow) or 10−710^{-7} (underflow) and enable scaling.

The right-hand map makes the theory prediction an experiment. Each format has its threshold where κuf\kappa u_f ceases to be small: after 10 steps, LU-IR reaches FP64 precision up to κ=103\kappa = 10^3 in FP16 (κuf≈0.5\kappa u_f \approx 0.5) and 10810^8 in FP32 (κuf≈6\kappa u_f \approx 6); in BF16, with κ=102\kappa = 10^2 (κuf≈0.4\kappa u_f \approx 0.4), it is at 3×10−103\times 10^{-10} and still decreasing. For another order of magnitude it crawls (FP16 with κ=104\kappa = 10^4 ends at 10−310^{-3}; BF16 with 10310^3 stalls at 0.20.2), then diverges: from 104.510^{4.5} in FP16, 103.510^{3.5} in BF16 and 10910^{9} in FP32. Convergence with κuf\kappa u_f somewhat above 1 does not contradict theory: κuf<1\kappa u_f < 1 is sufficient, with normwise κ\kappa and worst-case rounding, and in this small matrix LU errors are much smaller than that bound. With large nn constant 3n3n and factor growth matter more, lowering the threshold; the lab measures it with n=1024n = 1024.

Scale before rounding

FP16 cannot represent numbers above 6550465504 or, as normals, below 6.1×10−56.1\times 10^{-5}. A matrix with entries of order 10510^5 overflows on conversion and factors fill with infinities; one with entries of order 10−810^{-8} becomes zeros. Higham, Pranesh and Zounon (2019) propose equilibrating rows and columns in working precision, multiplying by μ=θxmax⁡/max⁡ij∣aij∣\mu = \theta x_{\max}/\max_{ij}\abs{a_{ij}} with θ∈(0,1]\theta \in (0, 1] and only then rounding to FP16; the correction is unscaled in high precision. With θ=0.1\theta = 0.1 there is room for elimination growth, although Higham and Mary warn that with large growth factors (matrices with a very small singular value) θ=0.1\theta = 0.1 may not suffice. The interactive uses only scalar factor μ\mu because its matrix is already equilibrated, and with n=60n = 60 needs only θ=0.1\theta = 0.1; the lab shows that with n=1024n = 1024 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 n=4096n = 4096 and increasing κ\kappa. 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 n=1024n = 1024 and randsvd matrices of prescribed κ\kappa (singular values logarithmically spaced from 1 to 1/κ1/\kappa), 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.

[ ]Mixed precision on the RTX 4060Local GPU
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()
This cell needs the local lab (PyTorch with your GPU). Start it with 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 κ\kappa from 10210^2 to 10610^6, FP32 LU plus 5 to 11 refinement steps takes 6 to 9 times less than torch.linalg.solve in FP64, with lower error: 3.9×10−153.9\times 10^{-15} versus 6.0×10−136.0\times 10^{-13} with κ=102\kappa = 10^2, 1.2×10−111.2\times 10^{-11} versus 6.3×10−106.3\times 10^{-10} with κ=106\kappa = 10^6. Direct solve leaves between 6 and 54 times κu64\kappa u_{64}, the price of factor nn and elimination growth of 4096×40964096\times 4096; refined stays below κu64\kappa u_{64} because iteration with residual in working precision becomes componentwise backward stable (Skeel, 1980), and error is then set by componentwise conditioning cond⁡(A,x)≤κ∞(A)\operatorname{cond}(\mat{A}, \vb{x}) \le \kappa_\infty(\mat{A}), potentially much smaller, without elimination growth. With κ=108\kappa = 10^8, κu32≈6\kappa u_{32} \approx 6 and refinement diverges. The same FP32 converged with κ=108\kappa = 10^8 on the interactive’s 60×6060\times 60 matrix: threshold falls with nn.

Simulated FP16 and BF16 with n=1024n = 1024. The threshold falls much more than κuf<1\kappa u_f < 1 suggests. In FP16, LU-IR reaches FP64 accuracy with κ=10\kappa = 10, crawls with κ=102\kappa = 10^2 (4.7×10−104.7\times 10^{-10} after 10 steps) and diverges with κ=103\kappa = 10^3 when κuf\kappa u_f is only 0.490.49. In BF16 it already crawls with κ=10\kappa = 10 and diverges with 10210^2. This is constant 3n3n in the convergence condition: with n=1024n = 1024 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 κ=104\kappa = 10^4 and BF16 up to 10210^2. But note iteration counts: 44 and 46 per correction with κ=103\kappa = 10^3, and 252 and 279 with κ=104\kappa = 10^4, one quarter of nn. Each GMRES iteration costs about 4n24n^2 flops plus orthogonalization, so 250 iterations already cost more than LU itself (23n3\tfrac{2}{3}n^3): Carson and Higham’s warning in numbers. With κ=105\kappa = 10^5 GMRES exhausts 300 iterations without convergence.

Scaling. Base matrix entries are at most 0.0480.048. Multiplied by 10610^6, the matrix fits FP16 (4.8×104<655044.8\times 10^4 < 65504), but elimination makes it grow and factors fill with infinities. Multiplied by 10−710^{-7}, its 1 048 5761\,048\,576 entries round to zero. Scaling with θ=0.1\theta = 0.1 is insufficient: growth max⁡∣uij∣/max⁡∣μaij∣\max\abs{u_{ij}}/\max\abs{\mu a_{ij}} is nearly 10, and 6550×106550\times 10 is already near the maximum, so an intermediate entry overflows. With θ=0.01\theta = 0.01 factors are finite and LU-IR converges again (1.1×10−91.1\times 10^{-9} after 10 steps, same rate as unscaled with κ=102\kappa = 10^2). This is precisely Higham and Mary’s warning: θ\theta must allow growth, which increases with nn.

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 I=∫01f(t) ⁣dtI = \int_0^1 f(t)\dd t, assume ff a Gaussian process with kernel kk. Since II is linear in ff, conditional on f(t1),…,f(tn)f(t_1), \dots, f(t_n) it is Gaussian with mean z⊤K−1f\vb{z}\T\mat{K}^{-1}\vb{f} and variance ∬k−z⊤K−1z\iint k - \vb{z}\T\mat{K}^{-1}\vb{z}, where Kij=k(ti,tj)\mat{K}_{ij} = k(t_i, t_j) and zi=∫01k(t,ti) ⁣dtz_i = \int_0^1 k(t, t_i)\dd t. The mean is a quadrature rule with weights K−1z\mat{K}^{-1}\vb{z}. 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.

[ ]Bayesian quadrature: trapezoid rule as posterior meanBrowser
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 ff, increasingly so: posterior deviation falls as hh (halves when nn doubles) and true error as h2h^2 (quarters), so their ratio rises from 2 with n=5n = 5 to 35 with n=65n = 65 and keeps doubling. The Brownian prior assumes functions as irregular as a random path, while ff 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:

  1. What precision is achieved and how measured? A “ten times faster” randomized solver with error 10−410^{-4} does not compete with LAPACK, which gives 10−1510^{-15} (sketch-and-solve versus QR). Look for forward and backward error, not only relative residual.
  2. What conditioning? The least-squares section showed sketch-and-precondition matches QR with κ=102\kappa = 10^2 and loses one to three orders with κ=106\kappa = 10^6. An experiment only on Gaussian matrices (which have κ≈1\kappa \approx 1) does not establish stability.
  3. What matrix shape? Randomized least-squares methods win when m≫nm \gg n and nn is hundreds or thousands; with n=64n = 64, as in the interactive, QR wins in flops. Coherent matrices break uniform sampling and CountSketch with few rows.
  4. 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.
  5. 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.
  6. 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 2162^{16} 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, 4n4n rows and LSQR). It runs on your CPU using all threads.

[ ]What is the baseline? Four least-squares solversLocal GPU
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")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With the same sketch-and-precondition implementation (47 and 50 iterations, solution differing from QR by 10−1310^{-13}), “speedup” ranges from 0.60.6 to 1.51.5 depending on the comparison. With n=128n = 128 it is slower than gelsd (0.6×0.6\times) and ties SciPy QR (between 0.9×0.9\times and 1.0×1.0\times depending on run). With n=512n = 512 it ties gelsd (1.0×1.0\times) and beats QR by 1.5×1.5\times. That SVD-based gelsd beats QR is no paradox: when m≫nm \gg n, LAPACK first reduces A\mat{A} to triangular using QR that never forms Q\mat{Q}, then computes SVD of an n×nn\times n, while scipy.linalg.qr(mode="economic") explicitly forms an Q\mat{Q} of 216×n2^{16}\times n, nearly doubling work. A paper comparing only that QR would announce a speedup that disappears against gelsd. The factor grows with nn, as flop ratio 2k/n2k/n predicts: with 50 iterations, the randomized method clearly wins only when nn is in hundreds or thousands. Times vary across runs on a shared machine; ratios are what persist.

Common mistakes

Exercises

ProofHutchinson: unbiasedness and variance
Prove: Let A∈Rn×n\mat{A} \in \R^{n\times n} be symmetric and z\vb{z} have independent Rademacher components. Then E[z⊤Az]=tr⁡(A)\E[\vb{z}\T\mat{A}\vb{z}] = \tr(\mat{A}) and Var⁡(z⊤Az)=2(∥A∥F2−∑iaii2)\Var(\vb{z}\T\mat{A}\vb{z}) = 2\big(\norm{\mat{A}}_F^2 - \sum_i a_{ii}^2\big).
0
Write q=z⊤Az=∑i,jaijzizjq = \vb{z}\T\mat{A}\vb{z} = \sum_{i,j}a_{ij}z_iz_j and use zi2=1z_i^2 = 1.

Step 1 of 4. How do you obtain the mean?

NumericVariance with one vector
For A=[2113]\mat{A} = \begin{bmatrix} 2 & 1 \\ 1 & 3 \end{bmatrix}, what is Hutchinson estimator variance with one Rademacher vector?
NumericPreconditioned LSQR iterations
A regression with A\mat{A} of 106×5010^6\times 50 is solved by sketch-and-precondition, and the preconditioner leaves κ(AR−1)≈2\kappa(\mat{A}\mat{R}^{-1}) \approx 2. According to bound ((κ−1)/(κ+1))k\big((\kappa - 1)/(\kappa + 1)\big)^k (without factor 2), what is the minimum LSQR iteration count reducing error by factor 10−1010^{-10}?
NumericWhat sketch-and-solve guarantees
A sketch has distortion ε=0.2\eps = 0.2 on col⁡([A  b])\col([\mat{A}\;\vb{b}]). What is the largest ratio ∥Ax^−b∥/∥Ax∗−b∥\norm{\mat{A}\hat{\vb{x}} - \vb{b}}/\norm{\mat{A}\vb{x}^* - \vb{b}} allowed by the sketch-and-solve bound?
NumericCountSketch's birthday
A matrix has 20 leverage-1 rows (each alone contains one range direction). You apply a CountSketch of d=160d = 160 rows, sending each row randomly to one of 160. What is the probability at least two of the 20 land in the same sketch row (and the sketch loses a dimension)?
CodeRPCholesky in eight lines
Implement rp_cholesky(diag, col, k, rng), performing kk 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 NN evaluations) can be requested. Return (F, S): F of N×kN\times k with A≈FF⊤\mat{A} \approx \mat{F}\mat{F}\T and pivot list S in order. Request only pivot columns, and do not fail if residual trace vanishes before kk 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, S
Shift+Enter to run
QuizWhen FP16 refinement fails
You factor A\mat{A} (moderate nn) using FP16 LU (uf≈4.9×10−4u_f \approx 4.9\times 10^{-4}) and refine with FP64 residual and sum. Which statement is correct?
QuizA ten-times-faster solver
A paper presents a randomized least-squares solver ‘ten times faster than LAPACK.’ Which questions are essential before believing it?

More than one answer may be correct.

QuizHutchinson or Hutch++?
You have 150 matrix-vector products to estimate the trace of a positive semidefinite matrix 1000×10001000\times 1000. When will Hutch++ give, with high probability, a clearly worse estimate than Hutchinson at the same budget?

Summary

Key idea
Two ideas solve problems classical factorizations cannot address: random projection compresses a problem to its information dimension while preserving subspace lengths, and computing cheaply then correcting does cubic work in low precision and recovers full accuracy with quadratic work. In both cases randomness or low precision determines speed, and a well-designed iteration determines accuracy.
  • A sketch S∈Rd×m\mat{S} \in \R^{d\times m} embeds a subspace of dimension nn if it preserves norms within 1±ε1 \pm \eps. Gaussian does so with d≈n/ε2d \approx n/\eps^2 without seeing data; SRHT mixes before sampling and costs mnlog⁡mmn\log m; CountSketch costs one data pass but needs d∼n2d \sim n^2 because of the birthday paradox.
  • Sketch-and-solve gives residual at most (1+ε)/(1−ε)(1 + \eps)/(1 - \eps) times optimum: useful for few digits, never machine precision. Sketch-and-precondition uses R\mat{R} from QR of SA\mat{S}\mat{A}: κ(AR−1)≤(1+ε)/(1−ε)\kappa(\mat{A}\mat{R}^{-1}) \le (1 + \eps)/(1 - \eps) and LSQR reaches QR accuracy in iterations independent of κ(A)\kappa(\mat{A}); ill-conditioned problems need stability care (sketch-and-solve start, SPIR, FOSSILS).
  • RPCholesky chooses pivots proportional to residual diagonal: (k+1)N(k + 1)N entries, O(k2N)\bigO(k^2N) flops and nearly trace-optimal approximation with k≈r/ε+rlog⁡(1/(εη))k \approx r/\eps + r\log(1/(\eps\eta)) columns, without greedy (outliers) or uniform (small clusters) failures.
  • Hutchinson estimates tr⁡(A)\tr(\mat{A}) with mm products and variance 2(∥A∥F2−∑aii2)/m2(\norm{\mat{A}}_F^2 - \sum a_{ii}^2)/m with Rademacher vectors; Hutch++ exactly computes the low-rank part using randomized SVD and lowers cost from O(1/ε2)\bigO(1/\eps^2) to O(1/ε)\bigO(1/\eps) products for positive semidefinite matrices.
  • Three-precision iterative refinement converges if the correction solver is a contraction (κuf≪1\kappa u_f \ll 1 for LU-IR), and limiting error is set by uu and uru_r, not ufu_f. GMRES-IR uses low-precision factors as preconditioner and widens κ\kappa 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.