9.4 Eigenvalues, power iteration, and the spectral radius
Training a recurrent network, as in Vanilla RNN with manual BPTT and truncation in AI Engineering, multiplies the hidden state by the same weight matrix at every step, and backpropagation multiplies the gradient by the same number of times. Whether that product grows without bound or fades to nothing over 200 steps is decided by one number, the spectral radius : above 1 the gradients explode, below 1 they vanish. The training monitor in Training loop and the autograd bigram prints it for every weight matrix, and the same machinery later finds the largest curvature of a loss, which bounds the learning rate.
Concepts from other sections (12)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Backpropagation: reverse-mode automatic differentiation that computes all parameter gradients in one backward pass. Read more: Chapter 2: Deep Learning in AI Engineering
- Exploding and vanishing gradients: gradient norms that grow or shrink like as they travel back through the recurrence. Read more: 9.1 Vanilla RNN with manual BPTT and truncation in AI Engineering
- Characteristic polynomial: , whose roots are the eigenvalues of . Read more: Chapter 9: Linear Algebra
- Determinant: a single number for a square matrix: the factor by which scales signed volume. It is zero exactly when squashes space flat and so cannot be inverted, and . Read more: Chapter 9: Linear Algebra
- Orthonormal: a set of unit-length vectors that are pairwise orthogonal. Read more: 9.3 Orthogonality, Householder QR, and orthogonal initialization
- Null space / kernel: the vectors a matrix sends to zero, ; a nonzero null space means the map loses information. Read more: Chapter 9: Linear Algebra
- Hessian-vector product: , the derivative of the gradient along , computed without forming . Read more: 14.4 Hessian-vector products and the recompute-versus-memory schedule
- Hessian: the symmetric matrix of second partial derivatives, whose eigenvalues classify a critical point. Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange
- quadratic convergence: , so correct digits double each step. Read more: 7.2 Newton’s Method
- Gradient norm: a measure of update magnitude before optimizer-specific scaling. Read more: 17.5 Training failures, profiling, and recovery in AI Engineering
- Condition number: how much the exact answer of a problem moves relative to a change in its input. Read more: 15.3 Error analysis, condition numbers, and tolerance budgets
- training step: one zero-grad, loss, finiteness check, backward, clip, and optimizer update on one batch. Read more: 6.6 Training loop and the autograd bigram in AI Engineering
numpy.linalg.eigvals would answer, but the method is simple enough to build from scratch: multiply, normalize, repeat. This section builds it, sees where it fails (rotations), and fixes that failure with the QR factorization from Orthogonality, Householder QR, and orthogonal initialization. Along the way it reuses lu and lu_solve from Gaussian elimination and LU with partial pivoting (lu.py) and qr_householder (qr.py).
The solution is eig.py, with contract eig.pyi. It has three functions: power_iteration(matvec, n, iters, rng) for the dominant eigenpair, inverse_iteration(A, shift, iters, rng) for the eigenpair nearest a shift (one LU and many solves), and spectral_radius(W, iters) for by the QR algorithm, complex eigenvalues included.
Learning objectives
- Derive why power iteration converges to the dominant eigenvector at the rate per step, and run it by hand.
- Explain why the Rayleigh quotient, a random start, and per-step normalization are each required.
- Find the eigenvalue nearest a shift by inverse iteration with one LU factorization.
- Explain why power iteration fails on rotations and how the QR algorithm reads complex pairs from blocks.
- Relate the spectral radius to exploding and vanishing gradients.
Notation
Section titled “Notation”| Symbol | Meaning | Type / shape |
|---|---|---|
| a real square matrix | float64[n, n] | |
| eigenvalues and eigenvectors: , | complex scalar, vector | |
| eigenvalues ordered by modulus | ||
| the spectral radius | scalar | |
| the unit vector after steps of an iteration | float64[n] | |
| the Rayleigh quotient of a unit vector | scalar | |
| a shift: a guess near the wanted eigenvalue | scalar | |
| the QR factorization at step of the QR algorithm | ||
| the imaginary unit, |
Eigenvalues and eigenvectors
Section titled “Eigenvalues and eigenvectors”A non-zero vector is an eigenvector of with eigenvalue when : maps onto its own line, only stretching it. The eigenvalues are the roots of the characteristic polynomial , a polynomial of degree , so there are of them counted with multiplicity, possibly complex; a real polynomial’s complex roots come in conjugate pairs . For a matrix the polynomial is : trace and determinant, solved by the quadratic formula. A symmetric matrix has only real eigenvalues and an orthonormal basis of eigenvectors.
Power iteration
Section titled “Power iteration”Computing roots of a degree- polynomial is not how you find eigenvalues in practice. Instead, let the matrix find them for you. Write a start vector in the eigenvector basis, . Then
If and , every other term shrinks like , so the direction of converges to . Three practical rules follow from that formula.
First, normalize every step, . The direction is all that matters, and overflows: is inf in float64, and inf/inf is NaN.
Second, start at random. A start with never finds in exact arithmetic, and is exactly such a start for . Random entries make an event of probability zero. The contract draws from the caller’s generator, for uniforms, so runs are reproducible.
Third, report the Rayleigh quotient . For an exact eigenvector it equals , with its sign; equals and turns into . For a symmetric matrix, the Rayleigh quotient’s error is the square of the direction’s error, so it converges twice as fast.
One corner remains: if some is exactly zero, lies in the null space. The eigenvalue is 0, and dividing would produce NaN, so return 0.
Inverse iteration
Section titled “Inverse iteration”Power iteration finds only the largest eigenvalue. To find others, change the matrix. has the same eigenvectors as , with eigenvalues . The largest of those belongs to the nearest , so power iteration on finds it, at the rate per step: very fast for a good shift.
Each step needs , which is a solve with . Never form the inverse, and never refactor: call lu once ( operations), then lu_solve per step (). The answer reported is , an eigenvalue of itself. If is exactly an eigenvalue, is singular and there is nothing to solve with, so raise.
Complex pairs and the QR algorithm
Section titled “Complex pairs and the QR algorithm”Power iteration has a blind spot. The rotation has trace 0 and determinant 4, so and : equal moduli, no real eigenvector. Power iteration sends to , then , then . The direction turns by every step and never settles, and recurrent weight matrices are full of such rotations.
The QR algorithm handles them. Start from and repeat
Since , you have : a similarity transform, which never changes the eigenvalues. It is power iteration on all directions at once, kept orthonormal by the QR step: the first column follows , the first two span the dominant 2-dimensional invariant subspace, and so on. When the moduli separate, converges to block upper triangular form (the real Schur form). Entry decays like , and what remains on the diagonal are blocks (real eigenvalues) and blocks (complex pairs, whose subdiagonal never vanishes). The spectral radius is the largest modulus over the blocks: for a block, the quadratic formula above for a one. spectral_radius treats a subdiagonal entry below times the largest entry as zero.
Why the spectral radius decides explosion
Section titled “Why the spectral radius decides explosion”You now have a way to compute ; it remains to see why it is the number that matters. For any vector norm, as (Gelfand’s formula), so grows like when and shrinks like when , up to factors polynomial in . Backpropagation through steps of multiplies by , which has the same spectral radius. Note that , with equality for symmetric (and orthogonal) : an orthogonal initialization starts every recurrent weight at exactly .
Working it by hand
Section titled “Working it by hand”Power iteration on , with eigenvalues 3 (eigenvector ) and 1 (eigenvector ). Take the start (the solution draws a random one) and skip the normalization to keep integers:
| Rayleigh quotient | ||
|---|---|---|
| 0 | ||
| 1 | ||
| 2 | ||
| 3 |
The wrong component stays while the right one triples, so the angle error shrinks by per step, and the Rayleigh quotient’s error by : , , . After 60 steps both are exact to rounding: to and .
The spectral radius of a scaled rotation, . Its QR factorization is the rotation itself, , so : the QR algorithm leaves it unchanged, and the block never becomes triangular. That is the expected outcome for a complex pair. The block’s trace is and its determinant , so
Designing the API
Section titled “Designing the API”def power_iteration(matvec, n: int, iters: int, rng) -> tuple[float, NDArray]: """v0 = n draws of 2 * rng.uniform() - 1, normalized; iters steps of v = Av / ||Av||; returns (v . A v, v). (0.0, v) if some Av is exactly 0."""
def inverse_iteration(A, shift: float, iters: int, rng) -> tuple[float, NDArray]: """power_iteration on (A - shift I)^-1 via one lu and a lu_solve per step; returns (v . A v, v). ValueError if A - shift I is singular."""
def spectral_radius(W, iters: int = 100) -> float: """max |lambda| by the unshifted QR algorithm with qr_householder; 0.0 for 0 x 0."""The one design decision worth dwelling on is that power_iteration takes a function, not a matrix. The algorithm only ever needs products , so a callable lets inverse iteration substitute a solve with the LU factors, and lets later optimization code pass a Hessian-vector product without ever forming the Hessian.
Building it step by step
Section titled “Building it step by step”The reasoning chain follows the principles. Power iteration needs only products , so it takes a matvec callable. The start must have almost surely and be reproducible, so it is draws of from the caller’s generator, normalized. Only the direction matters and overflows, so each step divides by ; a zero norm means is in the null space, so return eigenvalue 0 rather than . The estimate must keep its sign, so the return value is the Rayleigh quotient of the final unit vector, which costs one more matvec; in the worked example this is the column that converges to 3 with its error shrinking by per step.
Inverse iteration is power iteration with “solve with ” as the matvec. Factor once, outside the loop, and check the pivots once so a shift equal to an eigenvalue raises. The reported value must belong to , not to the inverse, so it is recomputed as . The spectral radius cannot come from power iteration because a complex pair never converges, so it uses the QR algorithm , which preserves eigenvalues and drives to block triangular form; reading moduli from the and diagonal blocks covers both real and complex cases. “Zero” on the subdiagonal must be relative to the matrix’s scale, so the threshold is .
The start vector:
def _start(n: int, rng: Any) -> NDArray: """A random unit vector: almost surely not orthogonal to any eigenvector.""" v = np.array([2.0 * rng.uniform() - 1.0 for _ in range(n)], dtype=np.float64) norm = math.sqrt(float(v @ v)) if norm == 0.0: v = np.ones(n) # probability zero with 53-bit uniforms; stay defined norm = math.sqrt(n) return v / normPower iteration, with the three rules visible as three lines:
def power_iteration(matvec, n, iters, rng): if n < 1: raise ValueError(f"power_iteration: n must be >= 1, got {n}") if iters < 0: raise ValueError(f"power_iteration: iters must be >= 0, got {iters}") v = _start(n, rng) # rule 2: random start for _ in range(iters): w = np.asarray(matvec(v), dtype=np.float64) norm = math.sqrt(float(w @ w)) if norm == 0.0: return 0.0, v # v is in the null space: eigenvalue 0 v = w / norm # rule 1: renormalize every step, or |lambda|^t overflows # rule 3: the Rayleigh quotient keeps the sign that ||A v|| would lose return float(v @ np.asarray(matvec(v), dtype=np.float64)), vInverse iteration reuses it with a solve as the matvec. The lambda closes over the factors, so lu runs exactly once whatever iters is:
def inverse_iteration(A, shift, iters, rng): A = np.asarray(A, dtype=np.float64) if A.ndim != 2 or A.shape[0] != A.shape[1]: raise ValueError(f"inverse_iteration: A must be square, got shape {A.shape}") n = A.shape[0] P, L, U = lu(A - shift * np.eye(n)) # factor once ... if np.any(np.diag(U) == 0.0): raise ValueError("inverse_iteration: A - shift I is singular (shift is an eigenvalue)") _, v = power_iteration(lambda x: lu_solve(P, L, U, x), n, iters, rng) # ... solve every step # discard the eigenvalue of the inverse; report the one of A return float(v @ (A @ v)), vThe spectral radius runs the unshifted QR algorithm on a copy, then reads the diagonal blocks:
def spectral_radius(W, iters=100): T = np.array(W, dtype=np.float64) # a copy: the monitored weights stay put if T.ndim != 2 or T.shape[0] != T.shape[1]: raise ValueError(f"spectral_radius: W must be square, got shape {T.shape}") if T.shape[0] == 0: return 0.0 for _ in range(iters): Q, R = qr_householder(T) T = R @ Q # = Q^T T Q: same eigenvalues return max(_block_moduli(T))def _block_moduli(T): n = T.shape[0] scale = float(np.abs(T).max()) or 1.0 # the all-zero matrix still has a scale out = [] i = 0 while i < n: if i == n - 1 or abs(T[i + 1, i]) <= 1e-12 * scale: out.append(abs(float(T[i, i]))) # 1x1 block: a real eigenvalue i += 1 continue a, b, c, d = T[i, i], T[i, i + 1], T[i + 1, i], T[i + 1, i + 1] # 2x2 block: roots of t^2 - (a + d) t + (ad - bc), possibly complex tr, det = a + d, a * d - b * c disc = cmath.sqrt(tr * tr / 4.0 - det) out += [abs(tr / 2.0 + disc), abs(tr / 2.0 - disc)] i += 2 return outOn the scaled rotation, stays equal to , the subdiagonal is far above the threshold, and the formula gives twice. The full solution is eig.py.
Why this design
Section titled “Why this design”Power iteration costs iters matvecs plus one; for a dense matrix that is time and memory. Inverse iteration adds one factorization and then per step. The unshifted QR algorithm costs , acceptable for the small weight matrices a monitor inspects.
Each rejected alternative fails for a specific reason. loses the sign and converges at the angle rate, not its square. Power iteration for fails on exactly the matrices recurrent networks produce, rotations, and cannot be patched by more iterations. Production QR (LAPACK) reduces to Hessenberg form and uses Francis double shifts for quadratic convergence; that is faster but adds bookkeeping that hides the idea, while the unshifted version converges linearly, at the ratio of consecutive moduli, which is enough for a diagnostic. The tradeoff accepted is that if two eigenvalue moduli are very close but distinct, 100 iterations may leave a large subdiagonal and the pair is read as a block, which still gives the right moduli.
What can go wrong
Section titled “What can go wrong”A correct solution has to pass a set of targeted checks. The hand example must give and . must give , because a later optimizer tells a maximum from a saddle by the sign. must give 3, not 1, because a fixed start like can be orthogonal to . With 0 steps, must be the normalized draws, so results are reproducible from the seed. A long run with must stay finite over 400 steps. Twenty symmetric matrices with dominant eigenvalue against must match np.linalg.eigh in sign and vector at that slow ratio. The zero map must give 0 without NaN (rank-deficient weights exist), and bad n and iters must raise.
Inverse iteration on the spectrum must find 3 with shift 2.9 and 1 with shift 0, and an exact eigenvalue as the shift must raise; that is how the smallest Hessian eigenvalue is found later. Over 25 steps lu must be called exactly once, which is the point of a factorization. For spectral_radius, the scaled rotation must give , since recurrent weights rotate; five non-symmetric matrices with real, negative, and complex dominant eigenvalues must match np.linalg.eigvals; the edge sizes (, , a nilpotent matrix with all eigenvalues 0, non-square input) must behave; and the caller’s must be unchanged, because the monitor reads live weights.
The mistakes behind those failures:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| returning instead of | reported for eigenvalue | returns v @ matvec(v) |
| a fixed start such as | the wrong eigenvalue whenever is orthogonal to | draws the start from the generator in _start |
| normalizing only at the end | inf, then NaN, after a few hundred steps | v = w / norm inside the loop |
| dividing by | NaN for a vector in the null space | returns (0.0, v) when norm == 0.0 |
| iterating with instead of its inverse | finds the eigenvalue farthest from | passes lu_solve as the matvec |
| refactoring at every step | correct but iters times slower | calls lu before the loop; the lambda only solves |
| spectral radius by power iteration | never converges on rotations; wrong for complex pairs | uses the QR algorithm, not power iteration |
| reading only the diagonal after the QR algorithm | complex pairs reported as their real parts | _block_moduli solves each block in closed form |
| iterating in the caller’s array | the weights being monitored change | iterates on np.array(W), a copy |
Where this leads
Section titled “Where this leads”In AI Engineering, the training monitor of Training loop and the autograd bigram logs of each weight matrix, and Vanilla RNN with manual BPTT and truncation uses it as the exploding-gradient diagnostic: gradient norms grow when . In this book, Convexity, smoothness, gradient descent, and Armijo line search reads the condition number of a quadratic as . Later optimization material finds the top Hessian eigenvalue by power_iteration on Hessian-vector products, which sets the edge of stability , and the smallest one by inverse iteration.
Further reading
Section titled “Further reading”- LAPACK
dhseqr(vianumpy.linalg.eigvals;SRC/dhseqr.f,dlahqr.f): reduction to Hessenberg form first ( per step instead of ), Wilkinson and Francis double shifts for quadratic convergence, deflation, and aggressive early deflation. - Lanczos and Arnoldi (ARPACK,
scipy.sparse.linalg.eigsh;scipy/sparse/linalg/_eigen/arpack/): keep every iterate and extract eigenvalues from the whole Krylov subspace, giving many eigenpairs from far fewer products. - PyHessian (Yao et al., 2020): power iteration and Lanczos on Hessian-vector products of a real network.
- Spectral normalization in GANs (
torch.nn.utils.parametrizations.spectral_norm): one power-iteration step per training step to keep . - Trefethen and Bau, Numerical Linear Algebra, lectures 24 to 28; Strang, Introduction to Linear Algebra, ch. 6; Pascanu, Mikolov, and Bengio, “On the difficulty of training recurrent neural networks” (2013).
Key terms
Section titled “Key terms”- Eigenvector / eigenvalue: a non-zero and scalar with .
- Spectral radius: .
- Power iteration: repeated multiplication and normalization, converging to the dominant eigenvector.
- Rayleigh quotient: for a unit vector ; the signed eigenvalue estimate.
- Inverse iteration: power iteration on , finding the eigenvalue nearest the shift .
- Similarity transform: for orthogonal , which preserves eigenvalues.
- QR algorithm: the iteration , converging to block upper triangular (real Schur) form.
Summary
Section titled “Summary”- An eigenvector is a direction a matrix only stretches, ; repeated multiplication amplifies the eigenvalue of largest modulus fastest, so power iteration converges to it at the rate per step.
- Return the Rayleigh quotient , not , and renormalize every step: the first loses the sign, the second overflows.
- Inverse iteration runs power iteration on , whose dominant eigenvalue belongs to the nearest ; factor once with LU and solve at every step.
- A real matrix’s dominant eigenvalues can be a complex pair (a rotation), where power iteration never converges; the QR algorithm exposes them as blocks, and reads off the blocks.
- means gradients explode through repeated multiplication, means they vanish.
Review questions
Section titled “Review questions”-
Why does
power_iterationtake a function and not a matrix?Answer
The algorithm only ever needs . A callable lets inverse iteration substitute a solve with the LU factors and lets an optimizer substitute a Hessian-vector product, without forming either matrix.
-
What is returned for , and why would be wrong?
Answer
and . for either sign of , so it cannot distinguish from .
-
In
inverse_iteration, why is the resultv @ (A @ v)and not the value returned bypower_iteration?Answer
power_iterationwould return the Rayleigh quotient of , which is . The caller wants , which is the Rayleigh quotient of at the same vector. -
Why does the QR algorithm leave the scaled rotation unchanged, and why is that the right outcome?
Answer
factors as , , so . A complex pair cannot be split into real blocks, so the block is the final form, and
_block_modulireads both moduli from it. -
Why is the subdiagonal threshold
1e-12 * scaleand not a fixed1e-12?Answer
Whether an entry is negligible depends on the size of the matrix entries. For weights of size a fixed threshold would call every entry zero and drop complex pairs; for entries of size it would never declare convergence.