
Form Follows Function(al): Improving a Matrix Algorithm
On this page
TL;DR - I noticed a really cool connection between a pure math class and a CS class I was taking, and I wanted to write about it.
TL;DR - I noticed a really cool connection between a pure math class and a CS class I was taking, and I wanted to write about it.
For the sake of brevity, I do assume a fair working background in linear algebra and probability. Some introductory analysis would be helpful too.
Introduction
The problem in which we are interested is computing the top- singular values and vectors of a matrix. Modern quantitative data very often comes in the form of matrices—rows and rows of data and a column for each measurable quantity. Linear algebra tells us that we can study a lot of the underlying structure of matrices through their eigenvector-eigenvalue pairs, but eigenvectors only exist for square matrices, and even then there’s no guarantee they will exist over the reals. Singular values (SVs) are the fix. Every matrix, square or not, admits a singular value decomposition , where the columns of (right singular vectors) form an orthonormal basis, and maps that basis to an orthogonal set of directions (left singular vectors), stretched by the nonnegative singular values sitting along the diagonal of .
Because we can represent any (correctly-sized) vector as a linear combination of this basis, and sitting right there in the matrix are the scaling factors we apply to each component, we realize that the dominant structural directions in our data are the singular vectors with largest singular value. More precisely, if we choose some cutoff rank , then we are interested in the top singular values and vectors: . This is the fundamental mechanism underpinning many modern data science techniques, like PCA, LoRA, KV-cache, etc.
Now, we could always compute the whole singular value decomposition (SVD), and then pick the top . The textbook way to do this is to make the matrix square by computing its Gram matrix and then computing its eigendecomposition, which turns out to be enough to pick off the singular values8. But for problems with massive datasets9, this would be extraordinarily wasteful. Specifically, for rows and columns, this takes time. The first method to avoid the full SVD is an algorithm called the Power Method, which computes only the top singular value10.
Problem Statememt
For a matrix , without loss of generality assume , and let the SVD of be
For the matrix multiplication version (center),
For the outer product version (right), for 11.
We assume the usual properties of the SVD: the matrices and have orthonormal columns, and is diagonal.
Problem: compute the top right-singular vector and value of strictly faster than the SVD algorithm. That is, compute and in time .
The Power Method
This outline is largely adapted from the fantastic notes from Prof. Teal Witter’s Randomized Algorithms class; all credit belongs to him.12Algorithm
The first step is still to compute the Gram matrix. which takes time .
Because is symmetric, it has real, non-negative eigenvalues and orthonormal eigenvectors . Notice that the eigenvectors of are exactly the right singular vectors of , and its eigenvalues are the squared singular values ().
- Choose randomly. E.g. .13
- For
- Return
In short, we repeat a two-step process times: multiply our vector by , and then normalize it. Our final product is a unit vector equal to , where is just a scaling factor .14
The important parameter
Now that we have it in this form with ‘s, we must acknolwedge that our final analysis will be a guarantee based on the spectral gap parameter , which captures how dominant the top SV was in the dataset to begin with.
Specfically, we define
or more intuitively, “by what percentage must we reduce the most dominant SV, to get to the second-largest SV”.
(Intuitively, if is close to , the top SV is already dominant and it will be easy to isolate it. If is tiny, then there’s a close battle for the top SV, so it’s tough to isolate the correct one)
Analysis of the Power Method
I highly recommend reading through the full analysis to understand the machinery. However, if you choose not to, the important outcomes are the following:
- We can set our error tolerance as needed, and then choose our number of iterations . Our answer is guaranteed to be -close to the top right-singular vector
- Specifically, the minimum iterations needed is
- Notice that the dependence of our required iterations is only logarithmic in . This is very weak! We can dramatically tighten our error tolerance, and require only a modest number of extra iterations
I highly recommend reading through the full analysis to understand the machinery. However, if you choose not to, the important outcomes are the following:
- We can set our error tolerance as needed, and then choose our number of iterations . Our answer is guaranteed to be -close to the top right-singular vector
- Specifically, the minimum iterations needed is
- Notice that the dependence of our required iterations is only logarithmic in . This is very weak! We can dramatically tighten our error tolerance, and require only a modest number of extra iterations
As we saw above, the big influence is . We would be remarkably lucky if the data’s structure were represented by just one dominant vector direction, but often even highly structured data has a handful of important directions. Then, the gap from the first to second could be tiny, and would shoot up dramatically and ruin our runtime. The Lanczos method, which we will now see, brings this dependence down dramatically to .
The Lanczos Method
The first important observation of this method requires us to scrutinize what we actually computed during the Power Method. In particular, the most efficient way for us to get to our final product was to do matrix-vector computations, computing each for
In doing so, we actually computed all the pieces of what we call a Krylov Subspace, which by definition is any subspace generated by starting with a single vector and repeatedly multiplying by a fixed matrix .
The Power Method clearly just returned a scaling of the last column. The whole idea behind Lanczos is to avoid “throwing away” information from earlier columns like the power method, but instead to take advantage of the whole space which we had to generate anyway.
Specifically, to define the Lanczos method, we will let be a matrix with orthonormal columns that spans our Krylov subspace. In practice, we do not compute the Krylov matrix directly and then orthonormalize it, as this is numerically unstable. Instead, because our target matrix is symmetric, we can build the columns of iteratively using a highly efficient “three-term recurrence.”
Algorithm
- Initialize a random starting vector .
- Compute an orthonormal basis for the degree Krylov subspace spanned by .
- Form the matrix . (Because is symmetric, will be a tridiagonal matrix, making it very cheap to store and manipulate).
- Let be the top eigenvector of .
- Return .
Analysis of the Lanczos Method
The heart of the analysis here is 2 claims:
- The Lanczos Method returns a vector that is arbitrarily close to the best approximate eigenvector in the Krylov subspace.
- There always exists some vector in the Krylov subspace that is significantly better than what the Power Method returns
If we can prove these two things, it will immediately follow that the Lanczos Method does significantly better than the Power Method.
Claim 1 (Lanczos almost-optimality). Let be the vector returned by the Lanczos method, and let be any unit vector in the span of the Krylov subspace. If either or , then either or .
In other words, while the Lanczos output does not exactly minimize the mean-squared error to over the Krylov subspace, it comes within a factor of the minimum. As we will see below, with the correct setup, this is all we need.
Claim 2 (Existence of better vector). If we run the Lanczos method for iterations, there is some vector of the form such that
We delay the proof-work of this claim21, and first show that proving this claim suffices to beat the power method.
First, again without loss of generality, given , we assume . Recalling that and are unit vectors, we know and so,
Suppose we invoke Claim 2 with the smaller accuracy parameter . Then the subspace contains a vector with error at most , and Claim 1, applied with , guarantees the Lanczos output satisfies:
exactly matching the guarantee we proved for the Power Method. The cost of shrinking the accuracy parameter is only logarithmic (negligible), and the iteration count becomes
compared to for the Power Method. So, we get quadratic improvement: versus the original .22
An Approximation Theory Question
What remains for us to now do is prove Claim 2, and here enters approximation theory (an area built on functional analysis).
Notice that any vector in the Krylov subspace
is just a linear combination of the basis vectors with some coefficients, as follows:
Equivalently, this is just a degree- polynomial in . So, our problem reduces to finding the best polynomial such that is a good approximation to .23
The next crucial thing to notice is that the polynomial function moves cleanly into our eigendecomposition. In particular, we saw above that for a degree- monomial, , so if we factor sums of monomials, we get
The Power Method chose a very basic polynomial: . This does scale the largest eigenvalue more than the others, but we claim that if we use the lower degree terms, we can do much better.
As an aside, this is where the Randomized Algorithm class jumped to the final result. My goal is to progress to a solution constructively, based on intuitive ideas.
To start building intuition for which degree- polynomial we want to use, it’s strangely helpful to relax the polynomial condition, or relax the degree- condition.
- If we were allowed to pick any arbitrary function , the answer would be trivial: have and for all . Then, .
- If we were allowed to pick a polynomial with degree at least , then again we could have roots, and send the non-dominant ‘s to . But usually we compute a subspace of size .
Unfortunately, we are restricted to degree- polynomials. If we try to approximate Graph 2, we might have uncovered roots where we’re far from 0, as seen in the local extrema of the graph. Instead, the safer bet seems to be finding the best degree- polynomial approximation of Graph 1, where we try to minimise our maximum distance from on .
Now we’re in a good place, with a well-defined problem. Find the best degree- polynomial such that and is minimized on
To begin with, a good intuition for how to use our degrees is as follows. Suppose we want to minimise the maximum absolute value the function achieves on the interval to some upper bound . Then, we should let our polynomial curve in that direction till it hits , and use our next degree to bend it back in the opposite direction trying to keep it in the ribbon.
It turns out this intuition is almost perfect. Approximation theory formalizes this idea with the Equioscillation Theorem.
First, define
Theorem 3 (Equioscillation Theorem). A polynomial of degree minimizes constrained to for if and only if there exist points at which attains its maximum absolute value with alternating signs, i.e.
where or determines the sign of the first extremum.
We have proved the Equioscillation Theorem for and a fixed point . It is clear to see that the polynomial can be affinely transformed to any interval, and any fixed point and still hold the same guarantees. We can use an affine change of variables to make the same claim for on constrained to .
So, we know we need a polynomial that equioscillates times. The natural next question is how do we define this function.
If I have seen further, it is by standing on the shoulders of giants,
— Isaac Newton
We turn to the best, most classic equioscillator we know: the cosine function. In fact, the cosine function was screaming the answer at us all along. If we go back to the Taylor series definition of cosine we get
It literally uses each successive degree of its polynomial with alternate sign to stay perfectly inside , and converges to the cosine at . We, however, are restricted to finite degrees. So what cosine-like polynomial do we choose?
Well, we haven’t extracted all our mileage out of the Equioscillation Theorem yet. It gave us two pieces of information.
- Value information: At the alternation points ,
- Derivative information: at the alternation points, is achieving its maximum or minimum, so, if it’s interior in then . Crucially, we know how many such points there are but not where they are. Any successful argument must somehow not need their locations.
Observe that has degree , but there are extremal points which were candidates to form the roots of . So two of the extremal points were not interior, forcing them to be on the boundaries and ; we can multiply those in ourselves. And, squaring the part, we get with roots exactly at the equioscillation points.
Now consider . This will have roots exactly where and because has at exactly distinct points where it hits , will have roots. The interior points will have multiplicity 2 and the boundaries will have multiplicity 1. So will have roots exactly at the equioscillation points.
Lastly, it is well-established that polynomials are uniquely determined by their roots, upto a constant multiplier. We have shown that both these polynomials have equal degree and have roots exactly at the equioscillation points. So they must be equal up to a constant , giving us the ODE:
Finally, solving this differential equation using standard techniques (out of scope here) reveals that the solution must be:
It can be easily verified by using the useful substitution of on or outside that this exactly matches the Chebyshev polynomials of the first kind26
Notably, on the range we get
exactly as we were trying to do before! And this confirms that our equioscillation is from
So, we have finally proved constructively that the Chebyshev polynomials are the optimal choice for this setting. Specifcally, arbitrarily letting equal they are defined by the recurrence
and it achieves equioscillation at magnitude .
As a last step, in our original formulation, we wanted to construct using the inverse question: “If I have spectral gap , what degree do I need to suppress down to ?”
Let be the affine transform and take the scaled Chebyshev filter
note that the denominator is a constant.
By construction and since and we know on . So,
Everything now hinges on how large is. By rearranging the definition, observe that , using our spectral gap parameter .
We know for that
and we know by definitions of cosh and arccosh that
For , we get . And using the Taylor series of , we get that . Or equivalently, . Putting this together we get,
So, to achieve , we need
Lastly, notice that we have more ‘s, and in the worst case, they might all be aribtrarily close to . Therefore, if we wanted to suppress the sum of all of them to be less than , we would need a new on the order . Plugging this in, we finally match our bound from Claim 2
and we are done.
Recap
To sum up, the steps we took to improve the Lanczos Method’s improvement over the Power Method were:
- We proved that the Lanczos Method’s response gets arbitrarily close to whatever optimal response there may have been in the Krylov Subspace
- We claimed that there existed at least some vector in the Krylov Subspace that was much better than the Power Method’s response (and thus the Lanczos method gets arbitrarily close to that improvement).
- We showed that all vectors in the Krylov subspace were generated by a polynomial function.
- We set up a relevant minimax problem over the space of constrained polynomials where we wanted to be fixed to and then the remaining ‘s shurnk as small as possible.
- We proved that regardless of which specific polynomial was best, it must equioscillate
- Finally, we proved that if it equioscillated, then it must be the Chebyshev polynomial (affinely transformed)
Footnotes
-
Of course, applied maths, as the name suggests, does not fall under this category of criticism. But then again, if your maths isn’t primarily proof-based… is it really maths? ↩
-
(1) Educator in the subject. (2) Academic who writes for other academics in the subject ↩
-
In fact I had to word my previous comment kind of carefully, because it seems maths majors are increasingly hired for this kind of thinking and exposure to rigor. ↩
-
This statement should actually be quite funny after you read the whole article. ↩
-
For any CS or maths major who has the chance to study at the Claremont Colleges, these were MATH126 and MATH138 respectively. 10/10, would recommend. ↩
-
To paraphrase Dr. Doofenshmirtz, “If I had a nickel for every time the exact same concept came up in two different college classes on the same day, I’d have three nickels—which isn’t a lot, but it’s weird that it happened thrice, right?”.
For reference, the other two (and a half?) times are: (1) Markov’s inequality in MATH157 Probability and MATH137 Measure Theory; (2) Bellman-Ford in CS140 Algorithms and MATH187 Operations Research as LP-duality; (2.5?) Lagrange Multipliers again in MATH187, and in Multivariable Calc which I was TAing. ↩ -
Or here, functional analysis. I fear I may have ruined the joke by explaining it. ↩
-
For a matrix , the Gram matrix is . It turns out that this matrix is guaranteed to be square and symmetric, which is sufficient for it to have a complete orthonormal eigendecomposition (a thing we love!) ↩
-
which is practically all problems today ↩
-
It also turns out that computing just the top singular value is enough, because we can “slice” (or more accurately “project”) off that top singular value, and then repeat the method to get the new top (formerly second-largest) singular value, and continue times. ↩
-
here is notation for the integer indexing set . ↩
-
I try to gloss over some of the intricacies here, so I recommend reading the notes for a more thorough treatment. ↩
-
Interestingly, this initial vector is the only place where randomness enters our algorithm. The Gaussian choice is convenient for analysis, but really any random choice works because it makes adversarial worst cases extremely unlikely. ↩
-
While yes, the value of does depend on the matrix and the initial vector, the important thing is it does not change the direction of vectors at any stage, so we preserve the thing we actually care about—the direction pf the largest right-singular vector. ↩
-
That is, changing to a different orthonormal basis, like we did here , does nothing to the distribution of the coordinates. ↩
-
with high probability. This convention in randomized algorithms says that a condition becomes vanishingly improbable. Here, for even a modest size of like , we get a guarantee. ↩
-
the choice of here may seem arbitrary, but the “convenience” here is slotting it nicely into our analysis later ↩
-
Intuitively, we can choose a threshold to be as small as we need, and be guaranteed that either is -close to , or it’s -close to . Notice that they’re both good enough because we can take our singular value to be . ↩
-
The intuitive way to see this is to imagine you have a budget of 1 because we’re restricted to unit vectors, and you have to distribute that budget over the eigenvectors to maximize the total size. You know by definition that eigenvector gets the biggest multiplier , so the maximizing choice to put all your budget on and none anywhere else. ↩
-
The proof follows almost identically for ↩
-
Because that’s the real fun part of this blog post! ↩
-
For reference, with , the power method needs on the order of passes over the data per factor of , while Lanczos needs on the order of . ↩
-
If you’ve taken a course in Real Analysis, this may have pricked up your ears, because the Stone-Weierstrass Theorem tells us we can approximate any function arbitrarily well with polynomials. So, this may seem like a very natural/intuitive position to be in. ↩
-
Technically, we’ve defined as taking only Borel sets, but distinction is not relevant; those cover all non-pathological sets we might actually need to use. ↩
-
Technically, this comes from Hölder’s inequality and relies on the spectral measure being no more than on the space, but that is a given from our normalization of ↩
- Chebyshev Polynomials ↩
