Module contents
Lesson 14 of 25Advanced 85 min

Block matrices, Schur complements and low-rank updates

Block algebra underpins Gaussian conditioning, online regression, Kalman filters and Gaussian processes. Study block elimination, Schur complements, the Woodbury identity and the matrix determinant lemma, including when these save computation and when numerical errors matter.

After this lesson you can

  • Multiply, eliminate and invert block matrices by identifying the Schur complement.
  • Compute block determinants and use Schur complements to test definiteness.
  • Prove and apply the Sherman–Morrison and Woodbury identities and the matrix determinant lemma.
  • Implement recursive least squares with rank-one updates.
  • Choose primal or dual formulations of a regularized problem based on dimensions.

Before you start

Motivation: four problems, one calculation

Consider these four problems, which arise repeatedly when building real systems:

  1. Condition a Gaussian. A vector (x1,x2)(\vb{x}_1, \vb{x}_2) is jointly Gaussian and you observe x1\vb{x}_1. What is the distribution of x2\vb{x}_2 now? This question arises in any probabilistic model reasoning from partial data.
  2. Update an online regression. You have a linear model fitted to a million observations and one more arrives (a market tick or a sensor reading). Resolving the normal equations costs O(d3)\bigO(d^3) per point. Can it be done in O(d2)\bigO(d^2)?
  3. The Kalman filter. Each new measurement corrects the estimated state of a robot or aircraft, and that correction is a covariance update formula.
  4. Gaussian processes. The prediction variance at a new point is k∗∗−k∗⊤(K+σ2I)−1k∗k_{**} - \vb{k}_*\T(\mat{K} + \sigma^2\mat{I})\inv\vb{k}_*: what you knew beforehand minus what the data explain.

All four are solved by the same operation: partition a matrix into blocks and eliminate one whole block, just as Gaussian elimination eliminates a number. What remains in the corner has a name, the Schur complement, and yields block inverse and determinant formulas, the block definiteness criterion, the Woodbury identity, and the matrix determinant lemma. These four tools derive in a few lines results that seem independent in probability, statistics, or control textbooks.

This lesson also covers when not to use them. Woodbury saves orders of magnitude when the update has low rank, saves nothing when rank is comparable to dimension, and can lose digits the problem does not justify. Knowing which case applies is part of the craft.

Thinking in blocks

Partitioned matrices and their product

Two partitions are conformable for product MN\mat{M}\mat{N} if the column partition of M\mat{M} matches the row partition of N\mat{N}. The blocks then multiply like numbers, with one caution: factor order.

Proof

Entry (i,j)(i, j) of MN\mat{M}\mat{N} is ∑l=1nmilnlj\sum_{l=1}^{n} m_{il} n_{lj}, the sum over all columns ll of M\mat{M}. Group indices ll by the common partition: the sum splits into groups LL, and the part for group LL is the corresponding entry of MILNLJ\mat{M}_{IL}\mat{N}_{LJ} (row ii of MIL\mat{M}_{IL} times column jj of NLJ\mat{N}_{LJ}). Summing over LL gives the entry of ∑LMILNLJ\sum_L \mat{M}_{IL}\mat{N}_{LJ}.

∎

You already know special cases. The four ways of viewing matrix multiplication from lesson 1 are different partitions: partitioning B\mat{B} into columns gives AB=[ Ab1⋯Abn ]\mat{A}\mat{B} = [\,\mat{A}\vb{b}_1 \cdots \mat{A}\vb{b}_n\,]; partitioning A\mat{A} into columns and B\mat{B} into rows gives the sum of outer products AB=∑lalb~l⊤\mat{A}\mat{B} = \sum_l \vb{a}_l\tilde{\vb{b}}_l\T, each a rank-one matrix. The block transpose moves blocks and also transposes each one:

[ABCD]⊤=[A⊤C⊤B⊤D⊤].\begin{bmatrix} \mat{A} & \mat{B} \\ \mat{C} & \mat{D} \end{bmatrix}\T = \begin{bmatrix} \mat{A}\T & \mat{C}\T \\ \mat{B}\T & \mat{D}\T \end{bmatrix}.

Why hardware multiplies in tiles

Block multiplication is more than notation: it is how matrices are multiplied on any modern processor. A GPU or CPU performs operations much faster than it can fetch numbers from main memory, so the limiting factor is not operation count but how often each fetched number is reused. This ratio of operations to data moved is arithmetic intensity.

Computing C=AB\mat{C} = \mat{A}\mat{B} entry by entry, with cij=∑lailbljc_{ij} = \sum_l a_{il}b_{lj}, performs two operations (multiply and add) for every two numbers read: intensity 11. If instead you partition all three matrices into tiles of b×bb \times b and compute CIJ=∑LAILBLJ\mat{C}_{IJ} = \sum_L \mat{A}_{IL}\mat{B}_{LJ} with all three tiles in fast memory (registers, cache, or shared memory, 3b23b^2 numbers), each number of AIL\mat{A}_{IL} is used bb times, once for each column of BLJ\mat{B}_{LJ}. Total traffic falls from about 2n32n^3 numbers to 2n3/b2n^3/b, and intensity rises to bb.

InteractiveTiled multiplication and distribution across GPUs
1 / 27
A\mat{A}
tile row II
⋅\cdot
B\mat{B}
tile column JJ
=
C\mat{C}
accumulated fraction
Step 1 of 27: C11+=A11 B11\mat{C}_{11} \mathrel{+}= \mat{A}_{11}\,\mat{B}_{11}. The C\mat{C} tile has accumulated 4 of the 12 terms of each dot product. While it accumulates, C11\mat{C}_{11} stays in fast memory, and each number in the A\mat{A} and B\mat{B} tiles is used 4 times.
  • tile of A\mat{A} in use
  • tile of B\mat{B} in use
  • C\mat{C} accumulated
View
Tile size bb
Tile products (n/b)3(n/b)^327
Fast memory needed 3b23b^248 numbers
Slow memory reads1008 (without tiling: 3600)
Operations per number read3.43 ≈ b
Press ▶: tile CIJ\mat{C}_{IJ} accumulates as a sum of products AILBLJ\mat{A}_{IL}\mat{B}_{LJ}, and its color indicates what fraction of each inner product has been accumulated. Change bb and watch the final readout: operations per number read grow as bb. Then switch views and compare two ways to distribute a linear layer across two GPUs: by columns no communication is needed; by rows the two partial sums must be added.

The two distributions in the figure are exactly those of tensor parallelism used to train models that do not fit on one GPU. For a layer Y=XW\mat{Y} = \mat{X}\mat{W}:

  • By columns: W=[ W1   W2 ]\mat{W} = [\,\mat{W}_1 \;\, \mat{W}_2\,] gives Y=[ XW1   XW2 ]\mat{Y} = [\,\mat{X}\mat{W}_1 \;\, \mat{X}\mat{W}_2\,]. Each GPU computes its output columns without talking to the other.
  • By rows: X=[ X1   X2 ]\mat{X} = [\,\mat{X}_1 \;\, \mat{X}_2\,] and W=[W1W2]\mat{W} = \begin{bmatrix} \mat{W}_1 \\ \mat{W}_2 \end{bmatrix} give Y=X1W1+X2W2\mat{Y} = \mat{X}_1\mat{W}_1 + \mat{X}_2\mat{W}_2, and the two partial sums are combined with an all-reduce.

Megatron-LM (Shoeybi et al., 2019) chains the two in a transformer’s MLP block: it partitions the first matrix by columns so the elementwise nonlinearity applies separately to each half, and the second by rows so the whole block needs only one reduction. It is block algebra. Tiled multiplication kernels are written by hand in module 21 (tiled multiplication in Triton).

Block elimination and the Schur complement

From the scalar case to blocks

Start with the matrix 2×22 \times 2 of numbers [abcd]\begin{bmatrix} a & b \\ c & d \end{bmatrix} with a≠0a \neq 0. One step of Gaussian elimination subtracts c/ac/a times the first row from the second, leaving

[ab0d−c ba],\begin{bmatrix} a & b \\ 0 & d - \dfrac{c\,b}{a} \end{bmatrix},

so the determinant is a (d−cb/a)=ad−bca\,(d - cb/a) = ad - bc. The number d−cb/ad - cb/a is what remains of dd after subtracting what the first row already explains.

Now replace each number by a block. Let

M=[ABCD],A∈Rp×p, B∈Rp×q, C∈Rq×p, D∈Rq×q,\mat{M} = \begin{bmatrix} \mat{A} & \mat{B} \\ \mat{C} & \mat{D} \end{bmatrix}, \qquad \mat{A} \in \R^{p \times p},\ \mat{B} \in \R^{p \times q},\ \mat{C} \in \R^{q \times p},\ \mat{D} \in \R^{q \times q},

with A\mat{A} invertible. Left multiplication by a block triangular matrix subtracts CA−1\mat{C}\mat{A}\inv times the upper block row from the lower one:

[Ip0−CA−1Iq][ABCD]=[AB0D−CA−1B].\begin{bmatrix} \mat{I}_p & \mat{0} \\ -\mat{C}\mat{A}\inv & \mat{I}_q \end{bmatrix} \begin{bmatrix} \mat{A} & \mat{B} \\ \mat{C} & \mat{D} \end{bmatrix} = \begin{bmatrix} \mat{A} & \mat{B} \\ \mat{0} & \mat{D} - \mat{C}\mat{A}\inv\mat{B} \end{bmatrix}.

Block multiplication rules do the calculation: block (2,1)(2, 1) is −CA−1A+C=0-\mat{C}\mat{A}\inv\mat{A} + \mat{C} = \mat{0} and (2,2)(2, 2) is −CA−1B+D-\mat{C}\mat{A}\inv\mat{B} + \mat{D}. Note the order: CA−1B\mat{C}\mat{A}\inv\mat{B}, never CBA−1\mat{C}\mat{B}\mat{A}\inv, which in general does not even make sense.

Performing the same elimination on the right (subtracting A−1B\mat{A}\inv\mat{B} times the left block column from the right) also eliminates B\mat{B}, yielding the factorization that contains everything else:

Check the first by multiplying right to left, which predicts each step:

[A00S][IA−1B0I]=[AB0S]\begin{bmatrix} \mat{A} & \mat{0} \\ \mat{0} & \mat{S} \end{bmatrix}\begin{bmatrix} \mat{I} & \mat{A}^{-1}\mat{B} \\ \mat{0} & \mat{I} \end{bmatrix} = \begin{bmatrix} \mat{A} & \mat{B} \\ \mat{0} & \mat{S} \end{bmatrix}
Block (1, 2) is A times A⁻¹B, which is B.
1/3
InteractiveEliminating a whole block
Partition
We partition M\mat{M} into blocks with A\mat{A} of size 3×33 \times 3 and D\mat{D} of size 3×33 \times 3. We eliminate the whole block C\mat{C} at once, just as Gaussian elimination removes a number, using A\mat{A} as the pivot.
412010151201216120021512102141010215
M=[ABCD]\mat{M} = \begin{bmatrix} \mat{A} & \mat{B} \\ \mat{C} & \mat{D} \end{bmatrix}
factor A: 23p3\tfrac{2}{3}p^3 = 13 %A⁻¹B: 2p2q2p^2q = 38 %C·(A⁻¹B): 2pq22pq^2 = 38 %factor S: 23q3\tfrac{2}{3}q^3 = 13 %
  • A\mat{A}
  • B\mat{B}
  • C\mat{C}
  • D\mat{D}
  • Schur complement
p = 3
Pivot
det⁡A\det \mat{A}94
det⁡S\det \mat{S}, with S=M/A\mat{S} = \mat{M}/\mat{A}49.404
Product of both4644
det⁡M\det \mat{M} (direct)4644
Smallest eigenvalue of the complement2.694 > 0
Advance step by step. With A\mat{A} as pivot, block C\mat{C} disappears and S=D−CA−1B\mat{S} = \mat{D} - \mat{C}\mat{A}^{-1}\mat{B} remains in the lower corner (magenta); then B\mat{B} disappears, leaving block diagonal form with det⁡M=det⁡A⋅det⁡S\det\mat{M} = \det\mat{A}\cdot\det\mat{S} in the readouts. Move pp: it changes which submatrix is inverted and how cost is distributed, but the four stages always sum to 23n3\tfrac{2}{3}n^3. Also try eliminating with D and the matrix with a singular pivot.

Consequences of the factorization

The outer factors are block triangular with identities on the diagonal: as n×nn \times n matrices they are triangular with ones on the diagonal, so their determinant is 11 and their inverse is obtained by changing the sign of the off-diagonal block. Hence, without further calculation:

Proof

(1) By the product rule, det⁡M=1⋅det⁡[A00S]⋅1=det⁡Adet⁡S\det\mat{M} = 1 \cdot \det\begin{bmatrix} \mat{A} & \mat{0} \\ \mat{0} & \mat{S} \end{bmatrix} \cdot 1 = \det\mat{A}\det\mat{S}. (2) The outer factors are invertible, so M\mat{M} has the rank of the central factor, rank⁡A+rank⁡S=p+rank⁡S\rank\mat{A} + \rank\mat{S} = p + \rank\mat{S}, and is invertible if and only if that rank is p+qp + q. (3) Invert the three factors in reverse order:

M−1=[I−A−1B0I][A−100S−1][I0−CA−1I],\mat{M}\inv = \begin{bmatrix} \mat{I} & -\mat{A}\inv\mat{B} \\ \mat{0} & \mat{I} \end{bmatrix}\begin{bmatrix} \mat{A}\inv & \mat{0} \\ \mat{0} & \mat{S}\inv \end{bmatrix}\begin{bmatrix} \mat{I} & \mat{0} \\ -\mat{C}\mat{A}\inv & \mat{I} \end{bmatrix},

and multiply by blocks. The second factorization of the previous theorem gives the statement about (M−1)11(\mat{M}\inv)_{11}. (4) This is elimination applied to the right-hand side: the second equation minus CA−1\mat{C}\mat{A}\inv times the first gives Sy=g−CA−1f\mat{S}\vb{y} = \vb{g} - \mat{C}\mat{A}\inv\vb{f}.

∎

Point (4) is how block-structured systems, such as KKT systems in constrained optimization, are solved in practice. Point (3) has an interpretation we will use repeatedly: a diagonal block of the inverse is the inverse of a Schur complement.

Cost and its relationship to LU

Counting operations using factorizations (without forming inverses): factoring A\mat{A} costs 23p3\tfrac{2}{3}p^3, solving AX=B\mat{A}\mat{X} = \mat{B} for the qq columns of B\mat{B} costs 2p2q2p^2q, product CX\mat{C}\mat{X} costs 2pq22pq^2, and factoring S\mat{S} costs 23q3\tfrac{2}{3}q^3. The sum is

23p3+2p2q+2pq2+23q3=23(p+q)3=23n3,\tfrac{2}{3}p^3 + 2p^2q + 2pq^2 + \tfrac{2}{3}q^3 = \tfrac{2}{3}(p + q)^3 = \tfrac{2}{3}n^3,

exactly the cost of the LU factorization of M\mat{M}. This is no coincidence: with p=1p = 1, one Gaussian elimination step leaves the Schur complement of pivot a11a_{11} in the corner, and complete elimination is a succession of Schur complements. Block elimination is reorganized LU so that nearly all work consists of large matrix products, which hardware does well. LAPACK routines are written this way.

Block definiteness

For symmetric matrices the Schur complement answers another question: whether M\mat{M} is positive definite. Write M=[ABB⊤D]\mat{M} = \begin{bmatrix} \mat{A} & \mat{B} \\ \mat{B}\T & \mat{D} \end{bmatrix} symmetric with A≻0\mat{A} \succ 0 and S=D−B⊤A−1B\mat{S} = \mat{D} - \mat{B}\T\mat{A}\inv\mat{B}. The block factorization becomes a congruence because the left factor is the transpose of the right:

M=E⊤[A00S]E,E=[IA−1B0I].\mat{M} = \mat{E}\T\begin{bmatrix} \mat{A} & \mat{0} \\ \mat{0} & \mat{S} \end{bmatrix}\mat{E}, \qquad \mat{E} = \begin{bmatrix} \mat{I} & \mat{A}\inv\mat{B} \\ \mat{0} & \mat{I} \end{bmatrix}.
Proof

If M≻0\mat{M} \succ 0, so is its block A\mat{A} (take vectors (x,0)(\vb{x}, \vb{0})), so in both parts we may assume A≻0\mat{A} \succ 0. For every z∈Rp+q\vb{z} \in \R^{p+q} we have z⊤Mz=w⊤diag⁡(A,S)w\vb{z}\T\mat{M}\vb{z} = \vb{w}\T\diag(\mat{A}, \mat{S})\vb{w} with w=Ez\vb{w} = \mat{E}\vb{z}, and since E\mat{E} is invertible, w\vb{w} ranges over all Rp+q\R^{p+q} as z\vb{z} does, and w=0\vb{w} = \vb{0} only if z=0\vb{z} = \vb{0}. Therefore M\mat{M} is positive (semi)definite if and only if diag⁡(A,S)\diag(\mat{A}, \mat{S}) is, and with A≻0\mat{A} \succ 0 this is equivalent to S\mat{S} being so.

∎

There is a second, deeper interpretation of the same complement. Consider the quadratic form f(x,y)=x⊤Ax+2x⊤By+y⊤Dyf(\vb{x}, \vb{y}) = \vb{x}\T\mat{A}\vb{x} + 2\vb{x}\T\mat{B}\vb{y} + \vb{y}\T\mat{D}\vb{y} and minimize it only over x\vb{x}, keeping y\vb{y} fixed. The gradient 2Ax+2By2\mat{A}\vb{x} + 2\mat{B}\vb{y} vanishes at x∗=−A−1By\vb{x}^* = -\mat{A}\inv\mat{B}\vb{y}, and substituting gives:

min⁡xf(x,y)=y⊤(D−B⊤A−1B)y=y⊤Sy.\min_{\vb{x}} f(\vb{x}, \vb{y}) = \vb{y}\T(\mat{D} - \mat{B}\T\mat{A}\inv\mat{B})\vb{y} = \vb{y}\T\mat{S}\vb{y}.

Two consequences you will use often:

  • Cholesky is Schur recursion. If M≻0\mat{M} \succ 0, write M=[αb⊤bM′]\mat{M} = \begin{bmatrix} \alpha & \vb{b}\T \\ \vb{b} & \mat{M}' \end{bmatrix}. Then α>0\alpha > 0, the first column of the Cholesky factor is (α,b/α)(\sqrt{\alpha}, \vb{b}/\sqrt{\alpha}), and the rest of the algorithm applies Cholesky to complement M′−bb⊤/α\mat{M}' - \vb{b}\vb{b}\T/\alpha, which is positive definite by the criterion. Thus Cholesky never finds a nonpositive pivot in a positive definite matrix, and it is the cheapest definiteness test: if it fails, the matrix was not definite.
  • Nonlinear constraints become linear. With P≻0\mat{P} \succ 0, condition t≥x⊤P−1xt \ge \vb{x}\T\mat{P}\inv\vb{x} is nonlinear in (t,x,P)(t, \vb{x}, \mat{P}), but equivalent to [Pxx⊤t]⪰0\begin{bmatrix} \mat{P} & \vb{x} \\ \vb{x}\T & t \end{bmatrix} \succeq 0, linear in the unknowns. This trick converts many problems into semidefinite programs (Boyd and Vandenberghe, appendix A.5.5).

Conditioning is taking a Schur complement

Let x=(x1,x2)\vb{x} = (\vb{x}_1, \vb{x}_2) be Gaussian with mean (μ1,μ2)(\boldsymbol{\mu}_1, \boldsymbol{\mu}_2) and covariance

Σ=[Σ11Σ12Σ21Σ22],Σ21=Σ12⊤,Σ11≻0.\boldsymbol{\Sigma} = \begin{bmatrix} \boldsymbol{\Sigma}_{11} & \boldsymbol{\Sigma}_{12} \\ \boldsymbol{\Sigma}_{21} & \boldsymbol{\Sigma}_{22} \end{bmatrix}, \qquad \boldsymbol{\Sigma}_{21} = \boldsymbol{\Sigma}_{12}\T,\quad \boldsymbol{\Sigma}_{11} \succ 0.

Apply the same block elimination matrix to x\vb{x}: define z=x2−Σ21Σ11−1x1\vb{z} = \vb{x}_2 - \boldsymbol{\Sigma}_{21}\boldsymbol{\Sigma}_{11}\inv\vb{x}_1. It is a linear transformation of a Gaussian vector, so (x1,z)(\vb{x}_1, \vb{z}) is jointly Gaussian, and

Cov⁡(z,x1)=Σ21−Σ21Σ11−1Σ11=0.\Cov(\vb{z}, \vb{x}_1) = \boldsymbol{\Sigma}_{21} - \boldsymbol{\Sigma}_{21}\boldsymbol{\Sigma}_{11}\inv\boldsymbol{\Sigma}_{11} = \mat{0}.

For jointly Gaussian vectors, zero correlation implies independence. Thus x2=Σ21Σ11−1x1+z\vb{x}_2 = \boldsymbol{\Sigma}_{21}\boldsymbol{\Sigma}_{11}\inv\vb{x}_1 + \vb{z} with z\vb{z} independent of x1\vb{x}_1, and fixing x1=a\vb{x}_1 = \vb{a} does not change the distribution of z\vb{z}. Its mean is μ2−Σ21Σ11−1μ1\boldsymbol{\mu}_2 - \boldsymbol{\Sigma}_{21}\boldsymbol{\Sigma}_{11}\inv\boldsymbol{\mu}_1 and its covariance, expanding Cov⁡(z,z)\Cov(\vb{z}, \vb{z}), is Σ22−Σ21Σ11−1Σ12\boldsymbol{\Sigma}_{22} - \boldsymbol{\Sigma}_{21}\boldsymbol{\Sigma}_{11}\inv\boldsymbol{\Sigma}_{12}. Therefore:

This is the conditioning formula studied in depth in module 4. Notice three things. The conditional mean is linear in a\vb{a}: it is the regression line (or hyperplane). The conditional covariance does not depend on a\vb{a}: it depends on what you observe, not on the observed value. By point (3) of the previous theorem, the conditional covariance is the inverse of the corresponding block of the precision matrix Λ=Σ−1\boldsymbol{\Lambda} = \boldsymbol{\Sigma}\inv: Σ/Σ11=(Λ22)−1\boldsymbol{\Sigma}/\boldsymbol{\Sigma}_{11} = (\boldsymbol{\Lambda}_{22})\inv. Marginalization is read from Σ\boldsymbol{\Sigma} (take a block); conditioning is read from Λ\boldsymbol{\Lambda} (take a block and invert it).

InteractiveConditioning is taking a Schur complement
  • line x1=ax_1 = a
  • p(x2∣x1=a)p(x_2 \mid x_1 = a) and ±\pm one standard deviation
  • p(x2)p(x_2) marginal
  • regression E[x2∣x1]\mathbb{E}[x_2 \mid x_1]
Σ22−Σ212Σ11=1.44−1.3421.96=0.518\Sigma_{22} - \frac{\Sigma_{21}^2}{\Sigma_{11}} = 1.44 - \frac{1.34^2}{1.96} = 0.518
1.50
0.80
1.40
1.20
Σ=[1.961.341.341.44]\boldsymbol{\Sigma} = \begin{bmatrix} 1.96 & 1.34 \\ 1.34 & 1.44 \end{bmatrix}
Marginal variance Σ22\Sigma_{22}1.440
Explained: Σ21Σ11−1Σ12\Sigma_{21}\Sigma_{11}^{-1}\Sigma_{12}0.922
Conditional (Schur)0.518
1/(Σ−1)221/(\boldsymbol{\Sigma}^{-1})_{22}0.518
Mean E[x2∣x1=a]\mathbb{E}[x_2 \mid x_1 = a]1.029
Conditional standard deviation0.720
Measured in the band
Drag the blue point to set x1=ax_1 = a. The magenta curve is the conditional density of x2x_2: a slice of the joint Gaussian along the blue line. Its center follows the orange regression line, but its width does not change with aa: it is the square root of the Schur complement. Compare it with the marginal (gray, left) and increase ∣ρ∣\abs{\rho} to see it narrow. Samples in the narrow strip around aa have exactly that spread.

In one dimension, with Σ11=σ12\Sigma_{11} = \sigma_1^2, Σ22=σ22\Sigma_{22} = \sigma_2^2 and Σ12=ρσ1σ2\Sigma_{12} = \rho\sigma_1\sigma_2, the complement is σ22−ρ2σ22=σ22(1−ρ2)\sigma_2^2 - \rho^2\sigma_2^2 = \sigma_2^2(1 - \rho^2): observing x1x_1 removes fraction ρ2\rho^2 of the variance of x2x_2, the coefficient of determination for regression of x2x_2 on x1x_1.

Rank-one updates: Sherman–Morrison

We move to the second family of problems: you have A−1\mat{A}\inv (or a factorization of A\mat{A}) and A\mat{A} changes slightly in one direction. The simplest case is A=I\mat{A} = \mat{I}:

M=I+uv⊤,Mx=x+(v⊤x) u.\mat{M} = \mat{I} + \vb{u}\vb{v}\T, \qquad \mat{M}\vb{x} = \vb{x} + (\vb{v}\T\vb{x})\,\vb{u}.

Geometrically, each point slides in direction u\vb{u} by the amount measured by v⊤x\vb{v}\T\vb{x}. Vectors with v⊤x=0\vb{v}\T\vb{x} = 0, a hyperplane, stay fixed: they are eigenvectors with eigenvalue 11, of multiplicity n−1n - 1. u\vb{u} itself maps to (1+v⊤u) u(1 + \vb{v}\T\vb{u})\,\vb{u}: it is an eigenvector with eigenvalue 1+v⊤u1 + \vb{v}\T\vb{u} (if v⊤u=0\vb{v}\T\vb{u} = 0, u\vb{u} lies in the hyperplane, M\mat{M} is a shear, and all its eigenvalues equal 11). This gives the determinant, the product of eigenvalues, and tells you how to invert: undo the slide.

InteractiveVisualizing a rank-one update
  • fixed line v⊤x=0\vb{v}\T\vb{x} = 0
  • Mu=(1+v⊤u) u\mat{M}\vb{u} = (1 + \vb{v}\T\vb{u})\,\vb{u}
  • displacement (v⊤x) u(\vb{v}\T\vb{x})\,\vb{u}
  • transformed unit square: area ∣det⁡M∣\abs{\det\mat{M}}
M=I+uv⊤\mat{M} = \mat{I} + \vb{u}\vb{v}\T and Mx=x+(v⊤x) u\mat{M}\vb{x} = \vb{x} + (\vb{v}\T\vb{x})\,\vb{u}.
v⊤x\vb{v}\T\vb{x}: how far x\vb{x} slides0.98
v⊤u\vb{v}\T\vb{u}0.920
Eigenvalues of M\mat{M}1 and 1.920
1+v⊤u1 + \vb{v}\T\vb{u}1.920
det⁡M\det \mat{M} (calculated)1.920
M−1=[0.69−0.50−0.100.83]\mat{M}^{-1} = \begin{bmatrix} 0.69 & -0.50 \\ -0.10 & 0.83 \end{bmatrix}
Sherman-Morrison: I−uv⊤/(1+v⊤u)\mat{I} - \vb{u}\vb{v}\T/(1 + \vb{v}\T\vb{u})
Drag u\vb{u}, v\vb{v}, and point x\vb{x}. The dashed magenta segment from x\vb{x} to Mx\mat{M}\vb{x} is always parallel to u\vb{u} and measures ∣v⊤x∣ ∥u∥\abs{\vb{v}\T\vb{x}}\,\norm{\vb{u}}. The dashed gray line does not move, and the transformed unit square has area ∣1+v⊤u∣\abs{1 + \vb{v}\T\vb{u}}. Press the button to bring v⊤u\vb{v}\T\vb{u} to −1-1: the plane collapses and the inverse ceases to exist.

To invert I+uv⊤\mat{I} + \vb{u}\vb{v}\T, try an inverse of the same form, I+β uv⊤\mat{I} + \beta\,\vb{u}\vb{v}\T:

(I+uv⊤)(I+βuv⊤)=I+(1+β+β v⊤u) uv⊤,(\mat{I} + \vb{u}\vb{v}\T)(\mat{I} + \beta\vb{u}\vb{v}\T) = \mat{I} + (1 + \beta + \beta\,\vb{v}\T\vb{u})\,\vb{u}\vb{v}\T,

because uv⊤uv⊤=(v⊤u) uv⊤\vb{u}\vb{v}\T\vb{u}\vb{v}\T = (\vb{v}\T\vb{u})\,\vb{u}\vb{v}\T. It suffices to take β=−1/(1+v⊤u)\beta = -1/(1 + \vb{v}\T\vb{u}). For any invertible A\mat{A}, write A+uv⊤=A(I+A−1u v⊤)\mat{A} + \vb{u}\vb{v}\T = \mat{A}(\mat{I} + \mat{A}\inv\vb{u}\,\vb{v}\T) and apply the above with A−1u\mat{A}\inv\vb{u} instead of u\vb{u}:

The second claim is visible in the widget and checked in one line: (A+uv⊤)A−1u=u(1+v⊤A−1u)=0(\mat{A} + \vb{u}\vb{v}\T)\mat{A}\inv\vb{u} = \vb{u}(1 + \vb{v}\T\mat{A}\inv\vb{u}) = \vb{0} with A−1u≠0\mat{A}\inv\vb{u} \neq \vb{0}. As for cost: with A−1\mat{A}\inv stored, computing A−1u\mat{A}\inv\vb{u}, v⊤A−1\vb{v}\T\mat{A}\inv, and the outer product costs O(n2)\bigO(n^2), versus O(n3)\bigO(n^3) to invert again.

The Woodbury identity

If the perturbation has rank kk, write UCV\mat{U}\mat{C}\mat{V} with U∈Rn×k\mat{U} \in \R^{n \times k}, C∈Rk×k\mat{C} \in \R^{k \times k} and V∈Rk×n\mat{V} \in \R^{k \times n}, and the formula generalizes by replacing the number 1+v⊤A−1u1 + \vb{v}\T\mat{A}\inv\vb{u} with a matrix k×kk \times k.

This is the Woodbury matrix identity, also called Sherman–Morrison–Woodbury; with k=1k = 1 and C=1\mat{C} = 1 it is Sherman–Morrison. It can be proved by multiplying and checking that the result is the identity (the first exercise). The following proof also explains where it comes from: the same block inverse computed in two ways.

Proof

Consider the matrix (n+k)×(n+k)(n + k) \times (n + k)

N=[AUV−C−1].\mat{N} = \begin{bmatrix} \mat{A} & \mat{U} \\ \mat{V} & -\mat{C}\inv \end{bmatrix}.

Its two Schur complements are

N/A=−C−1−VA−1U,N/(−C−1)=A−U(−C−1)−1V=A+UCV.\mat{N}/\mat{A} = -\mat{C}\inv - \mat{V}\mat{A}\inv\mat{U}, \qquad \mat{N}/(-\mat{C}\inv) = \mat{A} - \mat{U}(-\mat{C}\inv)\inv\mat{V} = \mat{A} + \mat{U}\mat{C}\mat{V}.

The first is invertible by hypothesis, so N\mat{N} is invertible (point 2 of the consequences theorem) and, since det⁡N=det⁡(−C−1)det⁡(N/(−C−1))\det\mat{N} = \det(-\mat{C}\inv)\det(\mat{N}/(-\mat{C}\inv)), so is A+UCV\mat{A} + \mat{U}\mat{C}\mat{V}. Now compute block (N−1)11(\mat{N}\inv)_{11} in two ways. Eliminating with the lower-right block gives (N−1)11=(N/(−C−1))−1=(A+UCV)−1(\mat{N}\inv)_{11} = (\mat{N}/(-\mat{C}\inv))\inv = (\mat{A} + \mat{U}\mat{C}\mat{V})\inv. Eliminating with A\mat{A}, the block inverse formula gives

(N−1)11=A−1+A−1U(N/A)−1VA−1=A−1−A−1U(C−1+VA−1U)−1VA−1.(\mat{N}\inv)_{11} = \mat{A}\inv + \mat{A}\inv\mat{U}(\mat{N}/\mat{A})\inv\mat{V}\mat{A}\inv = \mat{A}\inv - \mat{A}\inv\mat{U}(\mat{C}\inv + \mat{V}\mat{A}\inv\mat{U})\inv\mat{V}\mat{A}\inv.

The two expressions are the same block.

∎

When it pays off

Woodbury exchanges an inverse of n×nn \times n for one of k×kk \times k, plus solves with A\mat{A}. It pays off when two conditions hold:

  1. Solving with A\mat{A} is cheap: A\mat{A} is diagonal, banded, or already factored. The typical case is “diagonal plus low rank”: σ2I+UU⊤\sigma^2\mat{I} + \mat{U}\mat{U}\T in factor analysis, or a Nyström kernel approximation, σ2I+KnmKmm−1Kmn\sigma^2\mat{I} + \mat{K}_{nm}\mat{K}_{mm}\inv\mat{K}_{mn}, in Gaussian processes with mm inducing points. There Woodbury solves in O(nk2)\bigO(nk^2) what costs O(n3)\bigO(n^3) directly, and with n=105n = 10^5 this is the difference between possible and impossible.
  2. k≪nk \ll n: the dominant cost is solving AZ=U\mat{A}\mat{Z} = \mat{U}, about 2n2k2n^2k operations with A\mat{A} already factored, plus nk2nk^2 to form the capacitance matrix.

The figure compares three strategies for a common specific case: A\mat{A} symmetric positive definite with its Cholesky factor already computed, an update A+UU⊤\mat{A} + \mat{U}\mat{U}\T, and mm systems to solve with the new matrix. Refactorization forms A+UU⊤\mat{A} + \mat{U}\mat{U}\T (n2kn^2k) and factors it (n3/3n^3/3). Woodbury solves AZ=U\mat{A}\mat{Z} = \mat{U} (2n2k2n^2k), forms and factors capacitance I+U⊤Z\mat{I} + \mat{U}\T\mat{Z} (nk2+k3/3nk^2 + k^3/3), and pays an extra 4nk+2k24nk + 2k^2 for each system. Updating Cholesky applies kk rank-one updates to the factor, about 3n23n^2 operations each, leaving a new factor with which each system costs the same as before.

InteractiveWhen does Woodbury pay off?
Operations to solve mm systems with A+UU⊤\mat{A} + \mat{U}\mat{U}\T, with the Cholesky factor of A\mat{A} already computed. Logarithmic axes.
  • Refactor
  • Woodbury
  • Update Cholesky
Error measured in your browser now (n=80n = 80, k=4k = 4): ∥x^−x∥/∥x∥\lVert \hat{\vb{x}} - \vb{x} \rVert / \lVert \vb{x} \rVert against κ(A)\kappa(\mat{A}).
  • Refactor
  • Woodbury
  • Update Cholesky
  • u·κ(A)
A\mat{A} has 4 eigenvalues equal to 1/κ1/\kappa and U\mat{U} points in those directions: κ(A+UU⊤)≈2\kappa(\mat{A} + \mat{U}\mat{U}\T) \approx 2 for every κ\kappa. The problem is easy, but Woodbury passes through A−1\mat{A}^{-1} and loses the digits corresponding to κ(A)\kappa(\mat{A}).
n = 10 000
k = 10
m = 1
Woodbury2.20×10⁹ flops
Update Cholesky3.20×10⁹ flops
Refactor3.35×10¹¹ flops
Woodbury / refactor0.0066
k/nk/n0.0010
Each point on the map is a pair (n,k)(n, k) and its color shows which strategy uses the fewest operations; the readouts give exact counts. With m=1m = 1, Woodbury wins while k≲0.26 nk \lesssim 0.26\,n and the boundary is nearly the line k=0.26 nk = 0.26\,n. Increase mm: Woodbury's extra cost per system brings the Cholesky update into play. Below, error measured right now in your browser: when U\mat{U} corrects exactly the weak directions of A\mat{A}, Woodbury loses the digits of κ(A)\kappa(\mat{A}) even if the problem is well-conditioned.

Numerical risk

The lower plot contains the most important lesson about Woodbury. The error of a stable system solve is of order u κu\,\kappa, with u≈10−16u \approx 10^{-16} and κ\kappa the condition number of the problem being solved. Refactorization and Cholesky updates work with A+UU⊤\mat{A} + \mat{U}\mat{U}\T and have error of order u κ(A+UU⊤)u\,\kappa(\mat{A} + \mat{U}\mat{U}\T). Woodbury instead solves systems with A\mat{A} and subtracts two large nearly equal quantities: it inherits κ(A)\kappa(\mat{A}). If the update is precisely what makes the problem easy (for example, regularization adding curvature in flat directions), Woodbury can lose ten digits that neither other strategy loses. The capacitance matrix can also be ill-conditioned even if A\mat{A} and A+UCV\mat{A} + \mat{U}\mat{C}\mat{V} are not.

The matrix determinant lemma

The determinant can also be updated cheaply.

Proof

Compute the determinant of [In−UVIk]\begin{bmatrix} \mat{I}_n & -\mat{U} \\ \mat{V} & \mat{I}_k \end{bmatrix} in two ways. Eliminating with block In\mat{I}_n gives det⁡In⋅det⁡(Ik+VU)\det\mat{I}_n \cdot \det(\mat{I}_k + \mat{V}\mat{U}). Eliminating with block Ik\mat{I}_k gives det⁡(In+UV)⋅det⁡Ik\det(\mat{I}_n + \mat{U}\mat{V})\cdot\det\mat{I}_k. This proves Sylvester. For the general case, A+UV=A(In+A−1UV)\mat{A} + \mat{U}\mat{V} = \mat{A}(\mat{I}_n + \mat{A}\inv\mat{U}\mat{V}), and Sylvester applied to A−1U\mat{A}\inv\mat{U} and V\mat{V} gives det⁡(In+A−1UV)=det⁡(Ik+VA−1U)\det(\mat{I}_n + \mat{A}\inv\mat{U}\mat{V}) = \det(\mat{I}_k + \mat{V}\mat{A}\inv\mat{U}).

∎

This is the matrix determinant lemma. The rank-one version is what the rank-one update figure in the Sherman–Morrison section showed: the determinant of I+uv⊤\mat{I} + \vb{u}\vb{v}\T is the product of its eigenvalues, 1n−1(1+v⊤u)1^{n-1}(1 + \vb{v}\T\vb{u}). With a factor C\mat{C} in the middle, the same calculation on N\mat{N} gives det⁡(A+UCV)=det⁡(C−1+VA−1U)det⁡Cdet⁡A\det(\mat{A} + \mat{U}\mat{C}\mat{V}) = \det(\mat{C}\inv + \mat{V}\mat{A}\inv\mat{U})\det\mat{C}\det\mat{A}.

Two uses you will encounter:

  • Gaussian model likelihood. The log likelihood of N(0,Σ)\Normal(\vb{0}, \boldsymbol{\Sigma}) contains log⁡det⁡Σ\log\det\boldsymbol{\Sigma}. With Σ=D+UU⊤\boldsymbol{\Sigma} = \mat{D} + \mat{U}\mat{U}\T and D\mat{D} diagonal, log⁡det⁡Σ=∑ilog⁡di+log⁡det⁡(Ik+U⊤D−1U)\log\det\boldsymbol{\Sigma} = \sum_i \log d_i + \log\det(\mat{I}_k + \mat{U}\T\mat{D}\inv\mat{U}), in O(nk2)\bigO(nk^2) instead of O(n3)\bigO(n^3). Woodbury gives the quadratic term and the lemma gives the determinant.
  • Normalizing flows. A flow transforms a simple density with invertible functions and needs the determinant of each Jacobian. The planar flow of Rezende and Mohamed (2015) uses f(z)=z+u h(w⊤z+b)f(\vb{z}) = \vb{z} + \vb{u}\,h(\vb{w}\T\vb{z} + b), whose Jacobian is I+h′(w⊤z+b) uw⊤\mat{I} + h'(\vb{w}\T\vb{z} + b)\,\vb{u}\vb{w}\T, a rank-one update of the identity. Its determinant is 1+h′(w⊤z+b) w⊤u1 + h'(\vb{w}\T\vb{z} + b)\,\vb{w}\T\vb{u}: O(d)\bigO(d) instead of O(d3)\bigO(d^3). With h=tanh⁡h = \tanh we have h′∈(0,1]h' \in (0, 1], so w⊤u>−1\vb{w}\T\vb{u} > -1 guarantees that determinant is always positive; the paper imposes w⊤u≥−1\vb{w}\T\vb{u} \ge -1, sufficient for ff to be invertible (in the limiting case the determinant vanishes on hyperplane w⊤z+b=0\vb{w}\T\vb{z} + b = 0). You will see this in module 19’s planar and radial flows.

Applications

Recursive least squares

Return to the second motivating problem. Data arrive one at a time, (xt,yt)(\vb{x}_t, y_t) with xt∈Rd\vb{x}_t \in \R^d, and at each instant you want the weighted least-squares solution

θ^t=arg min⁡θ  ∑i=1tλt−i (yi−xi⊤θ)2+λtδ ∥θ∥2,\hat{\theta}_t = \argmin_\theta \; \sum_{i=1}^{t} \lambda^{t-i}\,(y_i - \vb{x}_i\T\theta)^2 + \lambda^t\delta\,\norm{\theta}^2,

where λ∈(0,1]\lambda \in (0, 1] is the forgetting factor (data from ss steps ago have weight λs\lambda^s) and δ>0\delta > 0 is a small prior term making the problem solvable from the first point. The normal equations are Gtθ^t=ht\mat{G}_t\hat{\theta}_t = \vb{h}_t with

Gt=λGt−1+xtxt⊤,ht=λht−1+xtyt,G0=δI, h0=0.\mat{G}_t = \lambda\mat{G}_{t-1} + \vb{x}_t\vb{x}_t\T, \qquad \vb{h}_t = \lambda\vb{h}_{t-1} + \vb{x}_t y_t, \qquad \mat{G}_0 = \delta\mat{I},\ \vb{h}_0 = \vb{0}.

Each new point is a rank-one update of G\mat{G}. Write Pt=Gt−1\mat{P}_t = \mat{G}_t\inv and apply Sherman–Morrison to λGt−1+xtxt⊤\lambda\mat{G}_{t-1} + \vb{x}_t\vb{x}_t\T, whose invertible part has inverse Pt−1/λ\mat{P}_{t-1}/\lambda:

Pt=1λ(Pt−1−Pt−1xtxtTPt−1λ+xtTPt−1xt)\mat{P}_t = \frac{1}{\lambda}\left(\mat{P}_{t-1} - \frac{\mat{P}_{t-1}\vb{x}_t\vb{x}_t^{\mathsf{T}}\mat{P}_{t-1}}{\lambda + \vb{x}_t^{\mathsf{T}}\mat{P}_{t-1}\vb{x}_t}\right)
Sherman–Morrison with A = λG, A⁻¹ = P/λ; multiply numerator and denominator by λ.
1/5

That is recursive least squares (RLS): O(d2)\bigO(d^2) operations per point instead of O(d3)\bigO(d^3), without storing the data. In exact arithmetic, θ^t\hat{\theta}_t matches the batch solution at each step. The effective forgetting memory is ∑sλs=1/(1−λ)\sum_s \lambda^s = 1/(1 - \lambda) points: λ=0.99\lambda = 0.99 remembers about 100.

InteractiveRegression learning point by point
t = 1
  • RLS (Sherman-Morrison)
  • batch, solved from scratch
  • true relationship
  • new point
  • its innovation
  • estimated slope
  • true slope
  • estimated intercept
  • true intercept
Prior P0=I/δ\mat{P}_0 = \mat{I}/\delta with δ=0.01\delta = 0.01; the batch solution minimizes the same weighted sum, ∑iλt−i(yi−xi⊤θ)2+λtδ∥θ∥2\sum_i \lambda^{t-i}(y_i - \vb{x}_i\T\theta)^2 + \lambda^t\delta\lVert\theta\rVert^2, solving the 2×22 \times 2 system from scratch at each step.
1.000
Point tt1 of 140
Estimated liney = 0.37 + 0.01 x
∥θ^RLS−θ^batch∥\lVert \hat{\theta}_{\text{RLS}} - \hat{\theta}_{\text{batch}} \rVert1×10⁻¹⁶
Innovation yt−y^ty_t - \hat{y}_t0.38
Gain ∥gt∥\lVert \vb{g}_t \rVert0.990
tr⁡Pt\tr \mat{P}_t100.990
Effective memory 1/(1−λ)1/(1-\lambda)∞
Points arrive one at a time; each corrects the line (orange) in proportion to its innovation (red segment). The dashed black line is the batch solution computed from scratch at each step: they coincide, and with λ\lambda near 11 their difference remains at rounding level. The true relationship changes at t=70t = 70. With λ=1\lambda = 1 all points weigh equally and the line takes a long time to turn; decrease λ\lambda and old points fade. With λ\lambda too low the line follows noise and its difference from the batch solution starts to grow: forgetting amplifies rounding errors, the effect measured in the implementation section.

The push-through identity and primal and dual forms

Ridge regression with X∈Rn×d\mat{X} \in \R^{n \times d} and λ>0\lambda > 0 has solution w^=(X⊤X+λId)−1X⊤y\hat{\vb{w}} = (\mat{X}\T\mat{X} + \lambda\mat{I}_d)\inv\mat{X}\T\vb{y}. The push-through identity

(X⊤X+λId)−1X⊤=X⊤(XX⊤+λIn)−1(\mat{X}\T\mat{X} + \lambda\mat{I}_d)\inv\mat{X}\T = \mat{X}\T(\mat{X}\mat{X}\T + \lambda\mat{I}_n)\inv

is proved in one line: X⊤(XX⊤+λIn)=(X⊤X+λId)X⊤\mat{X}\T(\mat{X}\mat{X}\T + \lambda\mat{I}_n) = (\mat{X}\T\mat{X} + \lambda\mat{I}_d)\mat{X}\T, and it suffices to multiply on the left by (X⊤X+λId)−1(\mat{X}\T\mat{X} + \lambda\mat{I}_d)\inv and on the right by (XX⊤+λIn)−1(\mat{X}\mat{X}\T + \lambda\mat{I}_n)\inv, both invertible because λ>0\lambda > 0. In general, A(I+BA)−1=(I+AB)−1A\mat{A}(\mat{I} + \mat{B}\mat{A})\inv = (\mat{I} + \mat{A}\mat{B})\inv\mat{A} whenever the inverses exist: factor A\mat{A} “pushes” through the parentheses. (It also follows from Woodbury applied to λId+X⊤X\lambda\mat{I}_d + \mat{X}\T\mat{X}.)

Thus the same w^\hat{\vb{w}} can be computed in two ways:

FormSystemDominant costUseful when
primal(X⊤X+λId) w^=X⊤y(\mat{X}\T\mat{X} + \lambda\mat{I}_d)\,\hat{\vb{w}} = \mat{X}\T\vb{y}nd2+d3/3nd^2 + d^3/3n≫dn \gg d: many examples, few features
dual(XX⊤+λIn) α=y(\mat{X}\mat{X}\T + \lambda\mat{I}_n)\,\boldsymbol{\alpha} = \vb{y}, w^=X⊤α\hat{\vb{w}} = \mat{X}\T\boldsymbol{\alpha}n2d+n3/3n^2d + n^3/3d≫nd \gg n: few examples, many features

The dual form says more: w^=X⊤α\hat{\vb{w}} = \mat{X}\T\boldsymbol{\alpha} is a combination of examples, and prediction at a new point, x⊤w^=∑iαi x⊤xi\vb{x}\T\hat{\vb{w}} = \sum_i \alpha_i\,\vb{x}\T\vb{x}_i, uses only inner products between examples. Replacing them with a kernel function is the kernel trick of module 11. Scikit-learn makes this choice for you: with Ridge(solver="cholesky"), if there are more features than examples it solves the dual form.

Implementation from scratch

Start with the block inverse and determinant, with A−1B\mat{A}\inv\mat{B} computed by solving systems, and check the result against NumPy.

[ ]Block inverse and determinantBrowser
import numpy as np

def schur_inverse(M, p):
    """Inversa de M por bloques con el complemento de Schur de A = M[:p, :p]."""
    A, B = M[:p, :p], M[:p, p:]
    C, D = M[p:, :p], M[p:, p:]
    AiB = np.linalg.solve(A, B)            # A⁻¹B sin formar A⁻¹
    CAi = np.linalg.solve(A.T, C.T).T      # C A⁻¹
    S = D - C @ AiB                        # complemento de Schur M/A
    Si = np.linalg.inv(S)
    Ai = np.linalg.inv(A)
    top = np.hstack([Ai + AiB @ Si @ CAi, -AiB @ Si])
    bottom = np.hstack([-Si @ CAi, Si])
    return np.vstack([top, bottom]), S

rng = np.random.default_rng(0)
n, p = 7, 3
M = rng.normal(size=(n, n)) + n * np.eye(n)
Minv, S = schur_inverse(M, p)
print("‖M⁻¹ por bloques − M⁻¹ de NumPy‖ =", np.linalg.norm(Minv - np.linalg.inv(M)))
print("det M            =", np.linalg.det(M))
print("det A · det(M/A) =", np.linalg.det(M[:p, :p]) * np.linalg.det(S))
print("(M⁻¹)₂₂ = (M/A)⁻¹:", np.allclose(np.linalg.inv(M)[p:, p:], np.linalg.inv(S)))

Cholesky as Schur-complement recursion: at each step take the first column and continue with the pivot’s complement. If a pivot is not positive, the matrix was not positive definite.

[ ]Cholesky as successive Schur complementsBrowser
def cholesky_schur(M):
    S = np.array(M, dtype=float)
    n = S.shape[0]
    L = np.zeros((n, n))
    for k in range(n):
        a = S[0, 0]
        if a <= 0:
            raise np.linalg.LinAlgError(f"pivote {a:.3g} en el paso {k}: no es definida positiva")
        L[k:, k] = S[:, 0] / np.sqrt(a)
        S = S[1:, 1:] - np.outer(S[1:, 0], S[0, 1:]) / a   # complemento de Schur de a
    return L

G = rng.normal(size=(6, 6))
G = G @ G.T + np.eye(6)
print("máx |L − cholesky(G)| =", np.abs(cholesky_schur(G) - np.linalg.cholesky(G)).max())
try:
    cholesky_schur(np.array([[1.0, 2.0], [2.0, 1.0]]))
except np.linalg.LinAlgError as e:
    print("Matriz indefinida:", e)

Now Sherman–Morrison, Woodbury for “diagonal plus low rank,” and the determinant lemma, compared with dense computation.

[ ]Sherman–Morrison, Woodbury, and the determinant lemmaBrowser
import time

def sherman_morrison(A_inv, u, v):
    """(A + u vᵀ)⁻¹ a partir de A⁻¹ en O(n²)."""
    Au = A_inv @ u
    vA = v @ A_inv
    return A_inv - np.outer(Au, vA) / (1.0 + v @ Au)

A = rng.normal(size=(50, 50)) + 10 * np.eye(50)
u, v = rng.normal(size=50), rng.normal(size=50)
err = np.abs(sherman_morrison(np.linalg.inv(A), u, v) - np.linalg.inv(A + np.outer(u, v))).max()
print(f"Sherman-Morrison frente a invertir de nuevo: {err:.1e}")

def woodbury_solve_diag(d, U, b):
    """Resuelve (diag(d) + U Uᵀ) x = b en O(n k²)."""
    Z = U / d[:, None]                   # A⁻¹U
    y = b / d                            # A⁻¹b
    cap = np.eye(U.shape[1]) + U.T @ Z   # capacitancia k × k
    return y - Z @ np.linalg.solve(cap, U.T @ y)

n, k = 1000, 10
d = rng.uniform(1, 2, size=n)
U = rng.normal(size=(n, k))
b = rng.normal(size=n)
t0 = time.perf_counter(); x_w = woodbury_solve_diag(d, U, b); t1 = time.perf_counter()
M = np.diag(d) + U @ U.T
x_d = np.linalg.solve(M, b); t2 = time.perf_counter()
print(f"error relativo {np.linalg.norm(x_w - x_d) / np.linalg.norm(x_d):.1e}; "
      f"Woodbury {1e3 * (t1 - t0):.2f} ms, denso {1e3 * (t2 - t1):.0f} ms")

logdet_lema = np.sum(np.log(d)) + np.linalg.slogdet(np.eye(k) + U.T @ (U / d[:, None]))[1]
print(f"log det por el lema: {logdet_lema:.6f}   denso: {np.linalg.slogdet(M)[1]:.6f}")

The third strategy on the cost map, updating the Cholesky factor, also fits in a few lines. Each step applies a rotation absorbing one component of x\vb{x} into the factor diagonal, in O(n2)\bigO(n^2) total.

[ ]Rank-one update of the Cholesky factorBrowser
def chol_update(L, x):
    """Devuelve L' triangular inferior con L' L'ᵀ = L Lᵀ + x xᵀ."""
    L, x = L.copy(), x.copy()
    n = len(x)
    for k in range(n):
        r = np.hypot(L[k, k], x[k])
        c, s = r / L[k, k], x[k] / L[k, k]
        L[k, k] = r
        L[k+1:, k] = (L[k+1:, k] + s * x[k+1:]) / c
        x[k+1:] = c * x[k+1:] - s * L[k+1:, k]
    return L

A = G.copy()
x = rng.normal(size=6)
L1 = chol_update(np.linalg.cholesky(A), x)
print("máx |L' − cholesky(A + x xᵀ)| =", np.abs(L1 - np.linalg.cholesky(A + np.outer(x, x))).max())

The cost figure’s experiment in Python: A\mat{A} with kk tiny eigenvalues and an update correcting them. The updated problem has κ≈2\kappa \approx 2 for any κ(A)\kappa(\mat{A}), but Woodbury does not know this.

[ ]Woodbury inherits the conditioning of ABrowser
def experimento(kappa, n=120, k=5, seed=0):
    r = np.random.default_rng(seed)
    Q, _ = np.linalg.qr(r.normal(size=(n, n)))
    ev = np.ones(n)
    ev[n - k:] = 1 / kappa                         # k direcciones casi planas
    A = (Q * ev) @ Q.T
    U = Q[:, n - k:] + 0.3 * r.normal(size=(n, k)) / np.sqrt(n)
    M = A + U @ U.T                                # la actualización las corrige
    x = r.normal(size=n)
    b = M @ x
    L = np.linalg.cholesky(A)
    solveA = lambda R: np.linalg.solve(L.T, np.linalg.solve(L, R))
    Z, y = solveA(U), solveA(b)
    x_w = y - Z @ np.linalg.solve(np.eye(k) + U.T @ Z, U.T @ y)
    x_r = np.linalg.solve(M, b)
    e = lambda z: np.linalg.norm(z - x) / np.linalg.norm(x)
    return e(x_r), e(x_w), np.linalg.cond(M)

print(" κ(A)     κ(A+UUᵀ)  refactorizar  Woodbury")
for kappa in [1e2, 1e6, 1e10, 1e14]:
    er, ew, cM = experimento(kappa)
    print(f"{kappa:7.0e}  {cM:8.2f}  {er:12.1e}  {ew:8.1e}")

Recursive least squares

The complete update is four lines. At each of the first 300 steps we compare it with the batch solution of the same problem, solved from scratch, and finally with np.linalg.lstsq, which lacks the prior term δ\delta.

[ ]RLS from scratch versus the batch solutionBrowser
def rls_update(theta, P, x, y, lam=1.0):
    Px = P @ x
    g = Px / (lam + x @ Px)               # ganancia
    theta = theta + g * (y - x @ theta)   # corrección por la innovación
    P = (P - np.outer(g, Px)) / lam       # Sherman-Morrison
    return theta, P

d, delta = 4, 1e-6
theta_real = np.array([1.0, -2.0, 0.5, 3.0])
r = np.random.default_rng(1)
X = r.normal(size=(300, d))
y = X @ theta_real + 0.1 * r.normal(size=300)

theta, P = np.zeros(d), np.eye(d) / delta
peor = 0.0
for t in range(300):
    theta, P = rls_update(theta, P, X[t], y[t])
    Xt, yt = X[:t + 1], y[:t + 1]
    lotes = np.linalg.solve(Xt.T @ Xt + delta * np.eye(d), Xt.T @ yt)
    peor = max(peor, np.linalg.norm(theta - lotes) / np.linalg.norm(lotes))
print(f"máxima diferencia relativa con la solución por lotes en 300 pasos: {peor:.1e}")
print("diferencia final con lstsq:", np.linalg.norm(theta - np.linalg.lstsq(X, y, rcond=None)[0]))

What about after many updates? Each step makes rounding errors that are never corrected because P\mat{P} is not recomputed. After 10510^5 updates, without forgetting and with highly correlated features (κ(G)≈4×104\kappa(\mat{G}) \approx 4 \times 10^4), we measure how far P\mat{P} has moved from the exact inverse and how much symmetry it has lost. The cell takes a few seconds in the browser.

[ ]Drift after 10⁵ updates (λ = 1)Browser
T = 100_000
r = np.random.default_rng(0)
X = r.normal(size=(T, 1)) + 0.01 * r.normal(size=(T, d))   # rasgos casi colineales
y = X @ theta_real + 0.1 * r.normal(size=T)

def rls_corre(lam, sym_cada=0, T=T):
    """La misma actualización que rls_update, escrita en el sitio para que el bucle sea rápido."""
    theta, P = np.zeros(d), np.eye(d) * 1e3
    filas, ys = list(X[:T]), y[:T].tolist()     # indexar listas es más barato que indexar arrays
    asim = []
    for t in range(T):
        x = filas[t]
        Px = P @ x
        g = Px / (lam + x @ Px)
        theta += g * (ys[t] - x @ theta)
        P -= np.outer(g, Px)
        if lam != 1.0:
            P /= lam
        if sym_cada and (t + 1) % sym_cada == 0:
            P = 0.5 * (P + P.T)                # resimetrizar
        if (t + 1) % 1000 == 500:              # medida a mitad de camino entre resimetrizaciones
            asim.append(np.linalg.norm(P - P.T) / np.linalg.norm(P))
    return theta, P, np.array(asim)

theta, P, asim = rls_corre(1.0)
G = X.T @ X + 1e-3 * np.eye(d)
print(f"κ(G) = {np.linalg.cond(G):.1e}")
print(f"‖P − G⁻¹‖/‖G⁻¹‖ = {np.linalg.norm(P - np.linalg.inv(G)) / np.linalg.norm(np.linalg.inv(G)):.1e}")
print(f"asimetría final ‖P − Pᵀ‖/‖P‖ = {asim[-1]:.1e}")
print(f"θ̂ frente a lotes: {np.linalg.norm(theta - np.linalg.solve(G, X.T @ y)) / np.linalg.norm(theta_real):.1e}")

Without forgetting, drift is harmless: P\mat{P} shrinks like 1/t1/t and errors do not grow. With forgetting the story changes. In a direction barely excited by the data, the update supplies no information and P\mat{P} is simply divided by λ\lambda at each step, so any error in that direction is multiplied by 1/λ1/\lambda per step. The skew-symmetric part of the error, which the formula does not correct, grows geometrically until P\mat{P} ceases to be positive definite and θ^\hat{\theta} departs from the exact solution far beyond rounding. We see this with λ=0.999\lambda = 0.999 (effective memory of 1,000 points) and 3×1043 \times 10^4 steps, with and without resymmetrization every 100 steps.

[ ]With forgetting, uncorrected asymmetry explodesBrowser
T2 = 30_000
th_a, P_a, asim_a = rls_corre(0.999, sym_cada=0, T=T2)
th_b, P_b, asim_b = rls_corre(0.999, sym_cada=100, T=T2)
print("  paso    ‖P − Pᵀ‖/‖P‖ sin resimetrizar    resimetrizando cada 100")
for i in range(0, len(asim_a), 3):
    print(f"{1000 * i + 500:6d}    {asim_a[i]:24.1e}    {asim_b[i]:22.1e}")
print("menor autovalor de la parte simétrica de P:")
print(f"  sin resimetrizar: {np.linalg.eigvalsh(0.5 * (P_a + P_a.T)).min():.2e}")
print(f"  resimetrizando:   {np.linalg.eigvalsh(0.5 * (P_b + P_b.T)).min():.2e}")
w = 0.999 ** (T2 - 1 - np.arange(T2))                       # pesos λ^(T−i)
Xw = X[:T2] * w[:, None]
G_w = Xw.T @ X[:T2] + 0.999 ** T2 * 1e-3 * np.eye(d)        # mismo a priori: P₀ = 10³ I
th_lotes = np.linalg.solve(G_w, Xw.T @ y[:T2])
rel = lambda th: np.linalg.norm(th - th_lotes) / np.linalg.norm(th_lotes)
print(f"θ̂ frente a la solución por lotes ponderada: sin resimetrizar {rel(th_a):.1e}, resimetrizando {rel(th_b):.1e}")

Resymmetrizing is the cheapest remedy. Robust alternatives are the Joseph form of the covariance update and, especially, square-root versions, which propagate a Cholesky factor of P\mat{P} with rotations (such as chol_update) instead of P\mat{P}: the matrix is then symmetric and positive semidefinite by construction. This is the same lesson as in the Kalman filter.

Primal versus dual

Finally, the push-through identity in numbers: the same w^\hat{\vb{w}} both ways, timed for n≪dn \ll d and n≫dn \gg d.

[ ]Primal and dual ridge formsBrowser
def ridge_primal(X, y, lam):
    d = X.shape[1]
    return np.linalg.solve(X.T @ X + lam * np.eye(d), X.T @ y)

def ridge_dual(X, y, lam):
    n = X.shape[0]
    return X.T @ np.linalg.solve(X @ X.T + lam * np.eye(n), y)

r = np.random.default_rng(2)
for n, d in [(50, 1000), (1000, 50)]:
    X = r.normal(size=(n, d)); y = r.normal(size=n)
    t0 = time.perf_counter(); w_p = ridge_primal(X, y, 1.0)
    t1 = time.perf_counter(); w_d = ridge_dual(X, y, 1.0)
    t2 = time.perf_counter()
    print(f"n = {n:4d}, d = {d:4d}: primal {1e3 * (t1 - t0):7.1f} ms, dual {1e3 * (t2 - t1):7.1f} ms, "
          f"‖w_primal − w_dual‖ = {np.linalg.norm(w_p - w_d):.1e}")

The form solving the smaller system wins by a wide margin, and the vectors agree up to rounding.

The professional version

The above builds understanding. In real code:

  • Do not form inverses. Factor once and solve: scipy.linalg.cho_factor and cho_solve for symmetric positive definite matrices, lu_factor and lu_solve in general, or scipy.linalg.solve(M, b, assume_a="pos"). In Woodbury, “A−1\mat{A}\inv” is always a call to an A\mat{A} solver, and the capacitance matrix is factored, not inverted.
  • Update factorizations. SciPy offers scipy.linalg.qr_update (rank-kk update of a QR factorization) and qr_insert and qr_delete (add or remove rows and columns), used for stable online least squares. It does not include a Cholesky update: chol_update above, or a compiled version, is typical.
  • Ridge and kernels. sklearn.linear_model.Ridge(solver="cholesky") chooses the dual form when there are more features than examples; KernelRidge always works in the dual.
  • In PyTorch, torch.linalg.cholesky and torch.cholesky_solve do the same on GPU and support matrix batches: this is how Woodbury and the determinant lemma are implemented in trainable Gaussian models and flows.
[ ]The same calculations with SciPyBrowser
import scipy.linalg as sl

# Woodbury con un resolvedor de A como caja negra (aquí, un factor de Cholesky)
n, k = 400, 6
B0 = r.normal(size=(n, n))
A = B0 @ B0.T / n + np.eye(n)
U = r.normal(size=(n, k)); b = r.normal(size=n)
fA = sl.cho_factor(A)
Z = sl.cho_solve(fA, U); y0 = sl.cho_solve(fA, b)
cap = sl.cho_factor(np.eye(k) + U.T @ Z)            # capacitancia, factorizada
x_w = y0 - Z @ sl.cho_solve(cap, U.T @ y0)
x_ref = sl.solve(A + U @ U.T, b, assume_a="pos")
print(f"Woodbury con cho_solve: error relativo {np.linalg.norm(x_w - x_ref) / np.linalg.norm(x_ref):.1e}")

# QR actualizada en O(n²) en lugar de refactorizar
Q, R = sl.qr(A)
u, v = r.normal(size=n), r.normal(size=n)
Q1, R1 = sl.qr_update(Q, R, u, v)
print("‖Q₁R₁ − (A + u vᵀ)‖ =", np.linalg.norm(Q1 @ R1 - (A + np.outer(u, v))))

Common mistakes

Exercises

ProofWoodbury by verification
Prove: If A\mat{A}, C\mat{C} and K=C−1+VA−1U\mat{K} = \mat{C}^{-1} + \mat{V}\mat{A}^{-1}\mat{U} are invertible, then (A+UCV)−1=A−1−A−1UK−1VA−1(\mat{A} + \mat{U}\mat{C}\mat{V})^{-1} = \mat{A}^{-1} - \mat{A}^{-1}\mat{U}\mat{K}^{-1}\mat{V}\mat{A}^{-1}.
0
Write W=A−1−A−1UK−1VA−1\mat{W} = \mat{A}^{-1} - \mat{A}^{-1}\mat{U}\mat{K}^{-1}\mat{V}\mat{A}^{-1}, with A\mat{A} of size n×nn \times n, U\mat{U} of n×kn \times k, C\mat{C} of k×kk \times k and V\mat{V} of k×nk \times n.

Step 1 of 4. What suffices to check?

ProofBlock determinant
Prove: If A\mat{A} is invertible, det⁡[ABCD]=det⁡A det⁡(D−CA−1B)\det\begin{bmatrix} \mat{A} & \mat{B} \\ \mat{C} & \mat{D} \end{bmatrix} = \det\mat{A}\,\det(\mat{D} - \mat{C}\mat{A}^{-1}\mat{B}).
0
Let M\mat{M} be the block matrix, with A\mat{A} of size p×pp \times p and D\mat{D} of size q×qq \times q, and S=D−CA−1B\mat{S} = \mat{D} - \mat{C}\mat{A}^{-1}\mat{B}.

Step 1 of 3. Which factorization of M\mat{M} do we use?

Numeric
Compute det⁡(I+uv⊤)\det(\mat{I} + \vb{u}\vb{v}\T) with u=(1,2,3)\vb{u} = (1, 2, 3) and v=(1,1,1)\vb{v} = (1, 1, 1).
Numeric
The vector (x1,x2,x3)(x_1, x_2, x_3) is Gaussian with covariance Σ=[421231112]\boldsymbol{\Sigma} = \begin{bmatrix} 4 & 2 & 1 \\ 2 & 3 & 1 \\ 1 & 1 & 2 \end{bmatrix}. What is Var⁡(x3∣x1,x2)\Var(x_3 \given x_1, x_2)?
Numeric
What is the smallest tt for which M=[21112111t]\mat{M} = \begin{bmatrix} 2 & 1 & 1 \\ 1 & 2 & 1 \\ 1 & 1 & t \end{bmatrix} is positive semidefinite?
Numeric
In recursive least squares with λ=1\lambda = 1, Pt−1=I2\mat{P}_{t-1} = \mat{I}_2 and a new xt=(1,1)\vb{x}_t = (1, 1) arrives. What is tr⁡Pt\tr\mat{P}_t?
Quiz
For M=[ABCD]\mat{M} = \begin{bmatrix} \mat{A} & \mat{B} \\ \mat{C} & \mat{D} \end{bmatrix} with A\mat{A}, D\mat{D}, M\mat{M} and both complements invertible, which expressions equal the upper-left block (M−1)11(\mat{M}^{-1})_{11}?

More than one answer may be correct.

Quiz
You have the Cholesky factor of a symmetric positive definite A\mat{A} with n=104n = 10^4 and want to solve a system with A+UU⊤\mat{A} + \mat{U}\mat{U}\T, where U\mat{U} is n×kn \times k. Counting operations as in the cost figure, at what order of magnitude of kk does Woodbury stop paying off versus refactorization?
Quiz
You fit ridge to n=500n = 500 documents described by d=200 000d = 200\,000 features (n-gram counts). Which system do you solve?
Quiz
You use RLS with λ=0.99\lambda = 0.99 and one feature is exactly 00 in all data after some time. In exact arithmetic, what happens to Pt\mat{P}_t in that direction?
Code
Implement sherman_morrison_update(A_inv, u, v), which returns (A+uv⊤)−1(\mat{A} + \vb{u}\vb{v}\T)^{-1} from A−1\mat{A}^{-1} in O(n2)\bigO(n^2), and woodbury_solve(A_solve, U, C, V, b), which solves (A+UCV)x=b(\mat{A} + \mat{U}\mat{C}\mat{V})\vb{x} = \vb{b} using A\mat{A} only through A_solve(R), which returns A−1R\mat{A}^{-1}\mat{R} for a vector or matrix R\mat{R}. Do not form any n×nn \times n matrix in woodbury_solve and call A_solve at most twice.
import numpy as np

def sherman_morrison_update(A_inv, u, v):
  """(A + u vᵀ)⁻¹ a partir de A⁻¹."""
  # tu código
  pass

def woodbury_solve(A_solve, U, C, V, b):
  """Resuelve (A + U C V) x = b con A_solve(R) = A⁻¹ R."""
  # tu código
  pass
Shift+Enter to run

Summary

  • Block matrices multiply like matrices of numbers while respecting factor order. Tiled multiplication reuses each datum bb times, which is why hardware uses it; partitioning a layer by columns or rows is tensor parallelism.
  • Eliminating a whole block leaves Schur complement M/A=D−CA−1B\mat{M}/\mat{A} = \mat{D} - \mat{C}\mat{A}\inv\mat{B} in the corner. Block factorization yields det⁡M=det⁡Adet⁡(M/A)\det\mat{M} = \det\mat{A}\det(\mat{M}/\mat{A}), the block inverse with (M−1)22=(M/A)−1(\mat{M}\inv)_{22} = (\mat{M}/\mat{A})\inv, and block system solves. LU and Cholesky are sequences of Schur complements.
  • A symmetric matrix is positive definite if and only if a diagonal block and its complement are. The complement is what remains of the quadratic form after optimizing the other variables; in a Gaussian, the covariance remaining after observing them.
  • Sherman–Morrison and Woodbury update an inverse after a rank-kk change by solving an k×kk \times k system; the determinant lemma does the same for determinants. They pay off with k≪nk \ll n and a cheap A\mat{A} solver, and inherit the conditioning of A\mat{A}, not that of the updated problem.
  • Recursive least squares, Kalman, Gaussian processes, and dual ridge are direct applications: rank-one updates, Schur conditioning, and the push-through identity.
Key idea
Eliminating an entire block, as Gaussian elimination eliminates a number, leaves the Schur complement. Conditioning a Gaussian, checking definiteness, block inversion, and updating an inverse after a low-rank change (Woodbury) are the same calculation interpreted in different ways.