View the code on GitHub · Read the full honors report (PDF)

A full SVD gives the best rank-$k$ approximation of a matrix, but it is slow, and even a Lanczos solver that computes only the top 200 singular values of a dense 13,514 by 13,514 matrix took 53 seconds on my laptop. Randomized algorithms get close to the same answer in one to three seconds. In this project I wrote four of them in Python (Gaussian rSVD, SRHT-rSVD, a sparse sign sketch and randQB_EI), tested them, and compared accuracy, runtime and memory on synthetic matrices and on kernel matrices from a boundary integral equation, with sizes up to 20,000 by 20,000.

The short version: the three fixed-rank sketches reach the same accuracy, and one power iteration brings them to within 1% of the exact SVD’s error at rank 50. In theory SRHT should be faster, because it does far fewer operations. Whether it actually is depends on how the transform is written. My first compiled version was 6.6 times slower than the Gaussian sketch, and after I rewrote it to work on one row at a time inside the cache, the same sketch became 1.9 times faster. Even then, the full SRHT algorithm only beats Gaussian near rank 200. A good part of this page is about why.

Background

The truncated SVD $A_k = U_k \Sigma_k V_k^T$ is the best rank-$k$ approximation of $A$ in the spectral and the Frobenius norm (Eckart-Young), and its Frobenius error is

$$\lVert A - A_k \rVert_F^2 = \sum_{i > k} \sigma_i^2$$

I use this as the baseline. Every error on this page is relative, $\lVert A - \hat A \rVert_F / \lVert A \rVert_F$, and I compare it with what the exact SVD gives at the same rank.

The randomized idea is to avoid decomposing $A$ directly. Multiply $A$ by a random matrix $\Omega$ with $l = k + p$ columns, where $p$ is a small oversampling margin (I use $p = 10$), and orthonormalize the result:

$$Y = A\Omega, \qquad Q = \mathrm{qr}(Y)$$

Now $Q$ spans roughly the same space as the top singular vectors of $A$, so $A \approx QQ^TA$. The SVD of the small matrix $Q^TA$ is cheap, and multiplying its left factor by $Q$ gives an approximate SVD of $A$. All four methods below follow this pattern. They differ in how they pick $\Omega$ and in when they stop.

The four algorithms

Gaussian rSVD. The entries of $\Omega$ are independent standard normal numbers. This is the method of Halko, Martinsson and Tropp. The dense product $A\Omega$ costs $O(mnl)$. If the singular values decay slowly, the basis can be improved with power iteration: use $(AA^T)^q A\Omega$ instead of $A\Omega$, so directions with large singular values are amplified. I run a QR factorization after every multiplication. Without it, all columns drift toward the top singular vector and the smaller directions are lost in rounding error.

SRHT-rSVD. Here $\Omega^T$ is a subsampled randomized Hadamard transform, $\Omega^T = \sqrt{N/l} \cdot R \cdot H \cdot D$. The matrix $D$ flips the sign of each coordinate at random, $H$ is the normalized Walsh-Hadamard matrix, and $R$ keeps $l$ randomly chosen rows. The transform needs a power-of-two size $N$, so the input is zero-padded from $n$ up to the next power of two. With the fast Walsh-Hadamard transform the sketch costs $O(mN \log N)$ instead of $O(mnl)$. The original method has no power iteration, so I added the same QR-based iteration as in the Gaussian version. This is the standard subspace iteration from Halko, Martinsson and Tropp, and I do not claim it is new.

Sparse sign rSVD. I added this one later as a reference point for the SRHT. Each row of $\Omega$ has only $\zeta = 8$ nonzero entries, $\pm 1/\sqrt{\zeta}$ in random columns, so $A\Omega$ costs $2mn\zeta$ operations with no padding and no transform (Martinsson and Tropp, Section 9.2). Everything after the sketch is the same as in the Gaussian version.

randQB_EI. This method, by Yu, Gu and Li, does not take a rank. It takes a tolerance $\varepsilon$ and grows $Q$ and $B = Q^TA$ in blocks of $b = 10$ columns until $\lVert A - QB \rVert_F \le \varepsilon \lVert A \rVert_F$. The stopping test is cheap. Since $Q$ has orthonormal columns, $\lVert A - QQ^TA \rVert_F^2 = \lVert A \rVert_F^2 - \lVert B \rVert_F^2$, so the code only subtracts the squared norm of each new block from a running total.

Because randQB_EI has no rank input, I run it at several tolerances, record the rank where it stopped, and compare with the others at that rank. Further down I also compare it at the same number of random columns, which turned out to explain its whole gap.

All four accept dense NumPy arrays and SciPy sparse matrices.

Test matrices

The synthetic matrices are 2,000 by 2,000. Each is built as $U \Sigma V^T$ with random orthogonal $U$ and $V$ and chosen singular values: $\sigma_j = e^{-0.1 j}$ (exponential decay), $\sigma_j = 1/j$ (polynomial decay), and values near 1 with 5% noise (flat). The flat one is a control. Nothing should compress it, so a method that does well on it has a bug.

The main matrix is a discretized Laplace kernel,

$$K_{ij} = \frac{1}{4\pi \lVert x_i - y_j \rVert}$$

where the points $x_i$ lie on one unit sphere and the points $y_j$ on another unit sphere, with the two centers 2.1 apart. This is the potential of a point charge, the kind of block that appears when a boundary integral equation is discretized. The spheres never touch, so the kernel is smooth over the whole matrix and a short expansion approximates it well. This is the same reason fast multipole and hierarchical matrix methods work. I chose the separation of 2.1 so the singular values fall fast but not trivially: at $n = 13{,}514$ the exact SVD already reaches 1.4% error at rank 20.

I picked $n = 13{,}514$ on purpose. It is the size of the SuiteSparse matrix poisson3Da, which I had looked at first (more on that below). I ran the full comparison at $n = 13{,}514$ and $n = 20{,}000$, and computed the spectrum alone at six sizes from 900 to 20,000 and at three wider separations.

A full SVD is too slow to repeat at these sizes, so the reference for the kernel matrix comes from the top 250 singular values computed with scipy.sparse.linalg.svds, together with $\lVert A \rVert_F$ computed directly from the entries. The optimal error at rank $k$ needs only the top $k$ singular values and $\lVert A \rVert_F$, so this gives exact optimal errors for every rank up to 200.

How I measured

Each run records wall time, peak memory, and the relative Frobenius and spectral errors. Memory comes from tracemalloc, so it counts Python-level allocations including NumPy buffers, not the whole process. The errors are computed from the factors, without ever forming $A - U \Sigma V^T$. The Frobenius error uses $\lVert A \rVert_F^2 - 2\langle A, U \Sigma V^T \rangle + \lVert \Sigma \rVert_F^2$, and the spectral error takes the top singular value of the residual through an implicit operator. This matters for large or sparse matrices, where the dense residual would not fit in memory. Most settings were run with 12 random seeds, and the numbers below are means over those runs. The ranks are 5, 10, 20, 50, 100 and 200, with $p = 10$.

Every timing on this page comes from one run of one script on my laptop, an Intel i7-8665U with 4 cores, with OpenBLAS and Numba both pinned to 4 threads. That way the BLAS calls and my compiled kernels get the same hardware, and numbers from different sections can be compared.

Accuracy

The plot at the top of this page shows the relative Frobenius error against rank for the $n = 13{,}514$ matrix. Gaussian, SRHT and sparse sign are almost one curve. At $k = 50$ the mean errors are 3.49e-3, 3.42e-3 and 3.49e-3, and the exact SVD gives 1.98e-3. At $k = 200$ they are 3.67e-5, 3.68e-5 and 3.66e-5 against 1.36e-5. Without power iteration, all three stay within a factor of about 3 of the best possible error, and the factor grows slowly with rank: 1.05 at $k = 5$, 1.8 at $k = 50$, 2.7 at $k = 200$. The spectral error is the harder measure and shows the same pattern with a wider gap, about 4 times the optimum at $k = 200$. All three sketches use the same number of columns, which is why they agree so closely.

randQB_EI met its tolerance every time. I ran it with $\varepsilon$ from 0.05 down to 0.0001, 12 seeds each, and all 72 runs converged with a final error below $\varepsilon$.

tolerance $\varepsilon$rank reachedrelative errorruntime (s)peak memory (MB)
0.05200.02880.9810
0.01400.008351.6717
0.003700.002102.7429
0.001960.0008363.6940
0.00031300.0002885.0054
0.00011710.00009486.5771

At the same rank, randQB_EI’s error is 1.3 to 1.6 times the Gaussian one, for instance 0.0288 against 0.0183 at $k = 20$. I first guessed this was because it has no spare columns, and then I tested it. For each of the 72 runs I ran Gaussian rSVD with the same seed at the rank randQB_EI reached, once with $p = 0$, the same number of random columns, and once with the usual $p = 10$.

tolerance $\varepsilon$rankrandQB_EIGaussian, $p = 0$Gaussian, $p = 10$
0.05200.02880.02940.0183
0.003700.002100.002150.00153
0.00011710.00009480.00009490.0000749

With the same number of columns the two agree within 2.5% at every tolerance, so the block-by-block structure costs nothing, and the whole gap is the 10 extra columns. randQB_EI is also the slowest of the four, about four times Gaussian at a similar rank, because every block of 10 columns is two more passes over $A$.

Power iteration

Effect of power iteration on the error at k = 50

For the kernel matrix, one step is almost enough. At $k = 50$ the Gaussian error goes from 3.49e-3 at $q = 0$ to 2.00e-3 at $q = 1$, which is 0.8% above the exact SVD’s 1.98e-3. Steps 2 and 3 give 1.983e-3 and 1.982e-3, so they add nothing that I can see. They do cost time: 0.74, 1.16, 1.70 and 2.32 seconds for $q = 0$ to 3, about 0.6 seconds per extra step.

This is a fast-decaying spectrum, and it is the reason a single step is enough. On the slowly decaying polynomial matrix ($n = 2{,}000$, $k = 50$) the picture is different. The errors are 0.157, 0.1108, 0.1089 and 0.1085 for $q = 0$ to 3, against an optimum of 0.1083. One step leaves the error 2.3% above the optimum and three steps get within 0.2%.

SRHT and sparse sign with power iteration both give 1.982e-3 at $q = 3$ on the kernel matrix, the same as Gaussian to four digits. Since I added the SRHT part myself, I checked it in two ways: this agreement, and a test that compares it with gaussian_rsvd at $q = 3$.

Cost, and when SRHT wins

Runtime and peak memory against rank for the four methods

With the current code, all three fixed-rank methods use between 6 and 130 MB at $n = 13{,}514$, and their runtimes are close. Gaussian takes 0.44 seconds at $k = 5$ and 1.67 seconds at $k = 200$. SRHT takes 0.59 and 1.42 seconds, so it is 1.3 to 1.4 times slower up to $k = 50$ and 15% faster at $k = 200$. Sparse sign follows almost the same curve as SRHT.

The crossover comes from what each sketch costs. Gaussian’s sketch grows with $l = k + p$. The SRHT transforms each whole row whatever $k$ is and then keeps $l$ entries, so its sketch costs the same at every rank, and the two meet between $k = 100$ and $k = 200$. I also noticed that SRHT replaces only the first of the two large products in the algorithm. The second one, $Q^TA$, is dense in both methods, so even a perfect transform would save at most about half of the work.

At $n = 20{,}000$ the SRHT only breaks even at $k = 200$. The reason is padding: 13,514 pads up to 16,384, 21% more, while 20,000 has to pad up to 32,768, 64% more. Sparse sign has no padding, and it stays 11% faster than Gaussian there.

randQB_EI used to peak at 1,393 MB at every tolerance, exactly one dense copy of $A$. It came from np.sum(A * A), which builds a temporary array of the same size as $A$ when it computes $\lVert A \rVert_F^2$. Summing the squares in blocks of rows gives the same number, and now its peak is 10 to 71 MB.

The transform, three times

The SRHT numbers above come from my third version of the Walsh-Hadamard transform. The first two gave a very different answer, and this is the part of the project I learned the most from.

My first version rebuilt the whole array with np.concatenate at each of the 14 butterfly levels, and it transposed a C-contiguous array before reshaping, which silently forces a full copy every call. The second version does the butterfly in place on one padded array and compiles it with Numba. It was correct and much faster, and I stopped there at first. But it still sweeps the whole padded array, 1.8 GB at $n = 13{,}514$, through main memory at each of the 14 levels, on one thread. The third version transforms one row at a time in a 128 KB buffer that stays in the 256 KB L2 cache for all 14 levels, does two levels per pass, and runs the rows in parallel. All three give bit-identical output, which the tests check.

versiontime, n = 2,000time, n = 6,000peak memory, n = 6,000
first (NumPy, concatenate)0.250 s8.32 s1,966 MB
second (in place, whole array)0.050 s0.601 s413 MB
third (one row at a time)0.010 s0.086 s10 MB

These are times for one sketch with $l = 210$. From the first version to the third the sketch became 97 times faster at $n = 6{,}000$.

The sketch step alone at n = 13,514: time against threads, arithmetic, and peak memory

At $n = 13{,}514$ I timed the sketch step alone against the Gaussian product, at $l = 210$:

sketcharithmetic1 thread4 threadsGFLOP/s at 4 threadspeak memory
Gaussian (BLAS)76.7 GFLOP1.75 s0.65 s11723 MB
SRHT, second version3.1 GFLOP5.15 s4.35 s0.71,817 MB
SRHT, third version3.1 GFLOP1.10 s0.35 s9.023 MB
sparse sign2.9 GFLOP1.28 s0.44 s6.723 MB

With the second version I had concluded that SRHT is slower because BLAS is so much better tuned, and that this was a hardware effect rather than a problem in my code. That conclusion was wrong. The same arithmetic in the third version runs 12.6 times faster, and the sketch beats BLAS by 1.9 times. Its throughput is still 13 times lower than BLAS, because a butterfly does one addition or subtraction for every number it loads, while a blocked matrix multiply reuses each number many times. But the SRHT does 25 times less arithmetic, so it wins. I also had the operation count wrong by a factor of 2 before. The transform needs $mN\log_2 N$ additions and subtractions, 3.1 GFLOP here, not 6.2.

Does the size matter?

My first answer was no. The error curves at $n = 13{,}514$ and $n = 20{,}000$ lie on top of each other, and Gaussian’s error at $n = 20{,}000$ is 0.98 to 1.05 times its error at $n = 13{,}514$ at every rank. That is true between those two sizes, but it does not hold below them, so I built the same geometry at six sizes and computed the best rank-$k$ error directly.

Best rank-k error at six sizes, and the same error divided by its value at n = 20,000

$n$best error, $k = 50$best error, $k = 200$decay constant $c$
9006.47e-44.05e-90.655
2,0001.42e-37.20e-70.447
5,0001.81e-36.98e-60.359
10,0001.94e-31.20e-50.341
13,5141.98e-31.36e-50.337
20,0001.97e-31.44e-50.335

A small matrix looks easier than it is. At $n = 900$ the best error at rank 50 is three times smaller than at $n = 20{,}000$, and at rank 200 it is more than 3,000 times smaller. The values settle from about $n = 10{,}000$. The reason is the gap between the spheres, which is 0.1 of the radius. With 900 random points the closest pair across the gap is 0.114 apart, so the matrix hardly sees the region where the kernel is least smooth. With 20,000 points the closest pair is 0.100 apart, which is the gap itself.

The shape of the decay is not geometric either. The singular values fall like $10^{-c\sqrt{j}}$, which is what a multipole expansion predicts in three dimensions, because degree $p$ of the expansion has $(p+1)^2$ terms. At $n = 5{,}000$ this is visible directly: the singular values come in steps that end at $j = 1, 4, 9, 16, \dots$, one step per degree.

Singular values against j and against the square root of j, at four separations

The separation matters far more than the size. Moving the centers from 2.1 to 3 apart lowers the best error at rank 50 from 1.8e-3 to 3.1e-7, while the whole size sweep changed it by a factor of 3. One power iteration is enough at both large sizes.

Compared with Lanczos

A full SVD is not the fair baseline when only the top few hundred singular values are needed. The usual tool for that is a Lanczos solver, SciPy’s svds, which I also used for the reference spectrum.

method, n = 13,514$k = 5$$k = 50$$k = 200$
Lanczos (svds)6.94 s15.7 s53.3 s
Gaussian, $q = 0$0.45 s0.58 s1.68 s
Gaussian, $q = 1$0.88 s1.16 s3.39 s

With one power iteration, Gaussian rSVD is within 3% of the optimal error at every rank and 8 to 16 times faster than Lanczos. Without it, it is 15 to 32 times faster but up to 2.7 times above the optimum. Lanczos reads the whole 1.46 GB matrix once for every matrix-vector product, while the sketch reads it once for a whole block of columns.

A matrix that does not compress

Before the kernel matrix I tried real matrices from SuiteSparse. The first was pde900, a 900 by 900 sparse finite-difference matrix from a convection-diffusion problem. It barely compresses. Even the exact SVD at rank 400 leaves 46% error, and at rank 800 out of 900 there is still 7%. Gaussian rSVD at rank 200 leaves 81% error against 70% for the optimum. randQB_EI shows the same thing: a tolerance of 0.2 needed rank 790.

Error against rank for the pde900 matrix and a kernel matrix of the same size

The kernel matrix of the same size behaves completely differently. Its exact error is 1.0% at rank 20 and about $10^{-5}$ at rank 100, and randQB_EI reaches a tolerance of 0.001 at rank 62. SuiteSparse also publishes the singular values of poisson3Da (13,514 by 13,514), and they decay slowly as well. This is why I moved to kernel matrices. A sparse matrix that comes from discretizing a differential operator couples only nearby points, and its singular values do not fall away quickly. An integral operator with a smooth kernel gives a dense matrix with fast decay. I kept the pde900 result in the repository as a negative result.

The synthetic matrices act as controls in the same way. On the exponential matrix, Gaussian gets 0.0105 at $k = 50$ against an optimum of 0.0067. On the flat matrix it gets 0.987 against 0.984, which means nothing was compressed, and randQB_EI never converged within its rank limit of 300. This is the correct behavior.

Limits

  • I tested one kernel, the Laplace kernel between two well-separated spheres. Other kernels, or points that are close together, are known to be harder, and this is why hierarchical matrix methods exist.
  • The matrices are constructed from a physical kernel. They are not measured data.
  • Each size uses one random set of points, so differences under 1% between the largest sizes could change with a different draw.
  • The SRHT result belongs to my implementation and my 4-core laptop. On a machine with many more cores, or on a GPU, the ranking could change, and a pruned transform that computes only the $l$ kept entries could be faster still.
  • Lanczos is one solver with its default settings. A block Krylov method would be a stronger baseline.
  • Peak memory is the tracemalloc peak, which does not include memory allocated outside Python’s tracking, such as the small buffers inside the Numba kernels.

Code and tests

The code is in the GitHub repository. The algorithms are in src/algorithms/, the experiment scripts in src/experiments/, and the CSV file behind every number on this page is committed next to its script. The figures here are drawn from those files. There are 67 tests. They check that sparse and dense input give the same factors, that the fast transform matches the explicit Hadamard matrix, that all three SRHT versions give bit-identical sketches, and that the low-rank error functions agree with the dense formulas. One trap I hit: for a SciPy sparse matrix, A * A is a matrix product, not an elementwise square, so the Frobenius norm needs .multiply(). A test covers it. The package versions are pinned in requirements.txt.

References

  • N. Halko, P.-G. Martinsson and J. A. Tropp, Finding structure with randomness: probabilistic algorithms for constructing approximate matrix decompositions, SIAM Review 53(2), 2011.
  • P.-G. Martinsson and J. A. Tropp, Randomized numerical linear algebra: foundations and algorithms, Acta Numerica 29, 2020.
  • C. Boutsidis and A. Gittens, Improved matrix algorithms via the subsampled randomized Hadamard transform, SIAM Journal on Matrix Analysis and Applications 34(3), 2013.
  • J. A. Tropp, Improved analysis of the subsampled randomized Hadamard transform, Advances in Adaptive Data Analysis 3(1-2), 2011.
  • W. Yu, Y. Gu and Y. Li, Efficient randomized algorithms for the fixed-precision low-rank matrix approximation, SIAM Journal on Matrix Analysis and Applications 39(3), 2018.
  • R. B. Lehoucq, D. C. Sorensen and C. Yang, ARPACK Users’ Guide, SIAM, 1998.
  • L. Greengard and V. Rokhlin, A fast algorithm for particle simulations, Journal of Computational Physics 73(2), 1987.
  • W. Hackbusch, A sparse matrix arithmetic based on H-matrices, Part I: Introduction to H-matrices, Computing 62, 1999.