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.
Consider these four problems, which arise repeatedly when building real systems:
Condition a Gaussian. A vector (x1,x2) is jointly Gaussian and you observe x1. What is the distribution of x2 now? This question arises in any probabilistic model reasoning from partial data.
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) per point. Can it be done in O(d2)?
The Kalman filter. Each new measurement corrects the estimated state of a robot or aircraft, and that correction is a covariance update formula.
Gaussian processes. The prediction variance at a new point is k∗∗−k∗⊤(K+σ2I)−1k∗: 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 if the column partition of M matches the row partition of N. The blocks then multiply like numbers, with one caution: factor order.
Proof
Entry (i,j) of MN is ∑l=1nmilnlj, the sum over all columns l of M. Group indices l by the common partition: the sum splits into groups L, and the part for group L is the corresponding entry of MILNLJ (row i of MIL times column j of NLJ). Summing over L gives the entry of ∑LMILNLJ.
∎
You already know special cases. The four ways of viewing matrix multiplication from lesson 1 are different partitions: partitioning B into columns gives AB=[Ab1⋯Abn]; partitioning A into columns and B into rows gives the sum of outer products AB=∑lalb~l⊤, each a rank-one matrix. The block transpose moves blocks and also transposes each one:
[ACBD]⊤=[A⊤B⊤C⊤D⊤].
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 entry by entry, with cij=∑lailblj, performs two operations (multiply and add) for every two numbers read: intensity 1. If instead you partition all three matrices into tiles of b×b and compute CIJ=∑LAILBLJ with all three tiles in fast memory (registers, cache, or shared memory, 3b2 numbers), each number of AIL is used b times, once for each column of BLJ. Total traffic falls from about 2n3 numbers to 2n3/b, and intensity rises to b.
InteractiveTiled multiplication and distribution across GPUs
1 / 27
A
tile row I
⋅
B
tile column J
=
C
accumulated fraction
Step 1 of 27: C11+=A11B11. The C tile has accumulated 4 of the 12 terms of each dot product. While it accumulates, C11 stays in fast memory, and each number in the A and B tiles is used 4 times.
tile of A in use
tile of B in use
C accumulated
View
Tile size b
Tile products (n/b)327
Fast memory needed 3b248 numbers
Slow memory reads1008 (without tiling: 3600)
Operations per number read3.43 ≈ b
Press ▶: tile CIJ accumulates as a sum of products AILBLJ, and its color indicates what fraction of each inner product has been accumulated. Change b and watch the final readout: operations per number read grow as b. 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:
By columns: W=[W1W2] gives Y=[XW1XW2]. Each GPU computes its output columns without talking to the other.
By rows: X=[X1X2] and W=[W1W2] give Y=X1W1+X2W2, 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×2 of numbers [acbd] with a=0. One step of Gaussian elimination subtracts c/a times the first row from the second, leaving
[a0bd−acb],
so the determinant is a(d−cb/a)=ad−bc. The number d−cb/a is what remains of d after subtracting what the first row already explains.
Now replace each number by a block. Let
M=[ACBD],A∈Rp×p,B∈Rp×q,C∈Rq×p,D∈Rq×q,
with A invertible. Left multiplication by a block triangular matrix subtracts CA−1 times the upper block row from the lower one:
[Ip−CA−10Iq][ACBD]=[A0BD−CA−1B].
Block multiplication rules do the calculation: block (2,1) is −CA−1A+C=0 and (2,2) is −CA−1B+D. Note the order: CA−1B, never CBA−1, which in general does not even make sense.
Performing the same elimination on the right (subtracting A−1B times the left block column from the right) also eliminates B, yielding the factorization that contains everything else:
Check the first by multiplying right to left, which predicts each step:
[A00S][I0A−1BI]=[A0BS]
Block (1, 2) is A times A⁻¹B, which is B.
1/3
InteractiveEliminating a whole block
Partition
We partition M into blocks with A of size 3×3 and D of size 3×3. We eliminate the whole block C at once, just as Gaussian elimination removes a number, using A as the pivot.
Advance step by step. With A as pivot, block C disappears and S=D−CA−1B remains in the lower corner (magenta); then B disappears, leaving block diagonal form with detM=detA⋅detS in the readouts. Move p: it changes which submatrix is inverted and how cost is distributed, but the four stages always sum to 32n3. 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×n matrices they are triangular with ones on the diagonal, so their determinant is 1 and their inverse is obtained by changing the sign of the off-diagonal block. Hence, without further calculation:
Proof
(1) By the product rule, detM=1⋅det[A00S]⋅1=detAdetS. (2) The outer factors are invertible, so M has the rank of the central factor, rankA+rankS=p+rankS, and is invertible if and only if that rank is p+q. (3) Invert the three factors in reverse order:
M−1=[I0−A−1BI][A−100S−1][I−CA−10I],
and multiply by blocks. The second factorization of the previous theorem gives the statement about (M−1)11. (4) This is elimination applied to the right-hand side: the second equation minus CA−1 times the first gives Sy=g−CA−1f.
∎
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 costs 32p3, solving AX=B for the q columns of B costs 2p2q, product CX costs 2pq2, and factoring S costs 32q3. The sum is
32p3+2p2q+2pq2+32q3=32(p+q)3=32n3,
exactly the cost of the LU factorization of M. This is no coincidence: with p=1, one Gaussian elimination step leaves the Schur complement of pivot a11 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 is positive definite. Write M=[AB⊤BD] symmetric with A≻0 and S=D−B⊤A−1B. The block factorization becomes a congruence because the left factor is the transpose of the right:
M=E⊤[A00S]E,E=[I0A−1BI].Proof
If M≻0, so is its block A (take vectors (x,0)), so in both parts we may assume A≻0. For every z∈Rp+q we have z⊤Mz=w⊤diag(A,S)w with w=Ez, and since E is invertible, w ranges over all Rp+q as z does, and w=0 only if z=0. Therefore M is positive (semi)definite if and only if diag(A,S) is, and with A≻0 this is equivalent to S being so.
∎
There is a second, deeper interpretation of the same complement. Consider the quadratic formf(x,y)=x⊤Ax+2x⊤By+y⊤Dy and minimize it only over x, keeping y fixed. The gradient 2Ax+2By vanishes at x∗=−A−1By, and substituting gives:
xminf(x,y)=y⊤(D−B⊤A−1B)y=y⊤Sy.
Two consequences you will use often:
Cholesky is Schur recursion. If M≻0, write M=[αbb⊤M′]. Then α>0, the first column of the Cholesky factor is (α,b/α), and the rest of the algorithm applies Cholesky to complement M′−bb⊤/α, 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, condition t≥x⊤P−1x is nonlinear in (t,x,P), but equivalent to [Px⊤xt]⪰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) be Gaussian with mean (μ1,μ2) and covariance
Σ=[Σ11Σ21Σ12Σ22],Σ21=Σ12⊤,Σ11≻0.
Apply the same block elimination matrix to x: define z=x2−Σ21Σ11−1x1. It is a linear transformation of a Gaussian vector, so (x1,z) is jointly Gaussian, and
Cov(z,x1)=Σ21−Σ21Σ11−1Σ11=0.
For jointly Gaussian vectors, zero correlation implies independence. Thus x2=Σ21Σ11−1x1+z with z independent of x1, and fixing x1=a does not change the distribution of z. Its mean is μ2−Σ21Σ11−1μ1 and its covariance, expanding Cov(z,z), is Σ22−Σ21Σ11−1Σ12. Therefore:
This is the conditioning formula studied in depth in module 4. Notice three things. The conditional mean is linear in a: it is the regression line (or hyperplane). The conditional covariance does not depend on 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: Σ/Σ11=(Λ22)−1. Marginalization is read from Σ (take a block); conditioning is read from Λ (take a block and invert it).
InteractiveConditioning is taking a Schur complement
line x1=a
p(x2∣x1=a) and ± one standard deviation
p(x2) marginal
regression E[x2∣x1]
Σ22−Σ11Σ212=1.44−1.961.342=0.518
Σ=[1.961.341.341.44]
Marginal variance Σ221.440
Explained: Σ21Σ11−1Σ120.922
Conditional (Schur)0.518
1/(Σ−1)220.518
Mean E[x2∣x1=a]1.029
Conditional standard deviation0.720
Measured in the band
Drag the blue point to set x1=a. The magenta curve is the conditional density of x2: a slice of the joint Gaussian along the blue line. Its center follows the orange regression line, but its width does not change with a: it is the square root of the Schur complement. Compare it with the marginal (gray, left) and increase ∣ρ∣ to see it narrow. Samples in the narrow strip around a have exactly that spread.
In one dimension, with Σ11=σ12, Σ22=σ22 and Σ12=ρσ1σ2, the complement is σ22−ρ2σ22=σ22(1−ρ2): observing x1 removes fraction ρ2 of the variance of x2, the coefficient of determination for regression of x2 on x1.
Rank-one updates: Sherman–Morrison
We move to the second family of problems: you have A−1 (or a factorization of A) and A changes slightly in one direction. The simplest case is A=I:
M=I+uv⊤,Mx=x+(v⊤x)u.
Geometrically, each point slides in direction u by the amount measured by v⊤x. Vectors with v⊤x=0, a hyperplane, stay fixed: they are eigenvectors with eigenvalue 1, of multiplicity n−1. u itself maps to (1+v⊤u)u: it is an eigenvector with eigenvalue 1+v⊤u (if v⊤u=0, u lies in the hyperplane, M is a shear, and all its eigenvalues equal 1). 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
Mu=(1+v⊤u)u
displacement (v⊤x)u
transformed unit square: area ∣detM∣
M=I+uv⊤ and Mx=x+(v⊤x)u.
v⊤x: how far x slides0.98
v⊤u0.920
Eigenvalues of M1 and 1.920
1+v⊤u1.920
detM (calculated)1.920
M−1=[0.69−0.10−0.500.83]
Sherman-Morrison: I−uv⊤/(1+v⊤u)
Drag u, v, and point x. The dashed magenta segment from x to Mx is always parallel to u and measures v⊤x∥u∥. The dashed gray line does not move, and the transformed unit square has area 1+v⊤u. Press the button to bring v⊤u to −1: the plane collapses and the inverse ceases to exist.
To invert I+uv⊤, try an inverse of the same form, I+βuv⊤:
(I+uv⊤)(I+βuv⊤)=I+(1+β+βv⊤u)uv⊤,
because uv⊤uv⊤=(v⊤u)uv⊤. It suffices to take β=−1/(1+v⊤u). For any invertible A, write A+uv⊤=A(I+A−1uv⊤) and apply the above with A−1u instead of u:
The second claim is visible in the widget and checked in one line: (A+uv⊤)A−1u=u(1+v⊤A−1u)=0 with A−1u=0. As for cost: with A−1 stored, computing A−1u, v⊤A−1, and the outer product costs O(n2), versus O(n3) to invert again.
The Woodbury identity
If the perturbation has rank k, write UCV with U∈Rn×k, C∈Rk×k and V∈Rk×n, and the formula generalizes by replacing the number 1+v⊤A−1u with a matrix k×k.
This is the Woodbury matrix identity, also called Sherman–Morrison–Woodbury; with k=1 and 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=[AVU−C−1].
Its two Schur complements are
N/A=−C−1−VA−1U,N/(−C−1)=A−U(−C−1)−1V=A+UCV.
The first is invertible by hypothesis, so N is invertible (point 2 of the consequences theorem) and, since detN=det(−C−1)det(N/(−C−1)), so is A+UCV. Now compute block (N−1)11 in two ways. Eliminating with the lower-right block gives (N−1)11=(N/(−C−1))−1=(A+UCV)−1. Eliminating with A, the block inverse formula gives
Woodbury exchanges an inverse of n×n for one of k×k, plus solves with A. It pays off when two conditions hold:
Solving with A is cheap: A is diagonal, banded, or already factored. The typical case is “diagonal plus low rank”: σ2I+UU⊤ in factor analysis, or a Nyström kernel approximation, σ2I+KnmKmm−1Kmn, in Gaussian processes with m inducing points. There Woodbury solves in O(nk2) what costs O(n3) directly, and with n=105 this is the difference between possible and impossible.
k≪n: the dominant cost is solving AZ=U, about 2n2k operations with A already factored, plus nk2 to form the capacitance matrix.
The figure compares three strategies for a common specific case: A symmetric positive definite with its Cholesky factor already computed, an update A+UU⊤, and m systems to solve with the new matrix. Refactorization forms A+UU⊤ (n2k) and factors it (n3/3). Woodbury solves AZ=U (2n2k), forms and factors capacitance I+U⊤Z (nk2+k3/3), and pays an extra 4nk+2k2 for each system. Updating Cholesky applies k rank-one updates to the factor, about 3n2 operations each, leaving a new factor with which each system costs the same as before.
InteractiveWhen does Woodbury pay off?
Operations to solve m systems with A+UU⊤, with the Cholesky factor of A already computed. Logarithmic axes.
Refactor
Woodbury
Update Cholesky
Error measured in your browser now (n=80, k=4): ∥x^−x∥/∥x∥ against κ(A).
Refactor
Woodbury
Update Cholesky
u·κ(A)
A has 4 eigenvalues equal to 1/κ and U points in those directions: κ(A+UU⊤)≈2 for every κ. The problem is easy, but Woodbury passes through A−1 and loses the digits corresponding to κ(A).
Woodbury2.20×10⁹ flops
Update Cholesky3.20×10⁹ flops
Refactor3.35×10¹¹ flops
Woodbury / refactor0.0066
k/n0.0010
Each point on the map is a pair (n,k) and its color shows which strategy uses the fewest operations; the readouts give exact counts. With m=1, Woodbury wins while k≲0.26n and the boundary is nearly the line k=0.26n. Increase m: Woodbury's extra cost per system brings the Cholesky update into play. Below, error measured right now in your browser: when U corrects exactly the weak directions of A, Woodbury loses the digits of κ(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κ, with u≈10−16 and κ the condition numberof the problem being solved. Refactorization and Cholesky updates work with A+UU⊤ and have error of order uκ(A+UU⊤). Woodbury instead solves systems with A and subtracts two large nearly equal quantities: it inherits κ(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 and A+UCV are not.
The matrix determinant lemma
The determinant can also be updated cheaply.
Proof
Compute the determinant of [InV−UIk] in two ways. Eliminating with block In gives detIn⋅det(Ik+VU). Eliminating with block Ik gives det(In+UV)⋅detIk. This proves Sylvester. For the general case, A+UV=A(In+A−1UV), and Sylvester applied to A−1U and V gives det(In+A−1UV)=det(Ik+VA−1U).
∎
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⊤ is the product of its eigenvalues, 1n−1(1+v⊤u). With a factor C in the middle, the same calculation on N gives det(A+UCV)=det(C−1+VA−1U)detCdetA.
Two uses you will encounter:
Gaussian model likelihood. The log likelihood of N(0,Σ) contains logdetΣ. With Σ=D+UU⊤ and D diagonal, logdetΣ=∑ilogdi+logdet(Ik+U⊤D−1U), in O(nk2) instead of O(n3). 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+uh(w⊤z+b), whose Jacobian is I+h′(w⊤z+b)uw⊤, a rank-one update of the identity. Its determinant is 1+h′(w⊤z+b)w⊤u: O(d) instead of O(d3). With h=tanh we have h′∈(0,1], so w⊤u>−1 guarantees that determinant is always positive; the paper imposes w⊤u≥−1, sufficient for f to be invertible (in the limiting case the determinant vanishes on hyperplane w⊤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) with xt∈Rd, and at each instant you want the weighted least-squares solution
θ^t=θargmini=1∑tλt−i(yi−xi⊤θ)2+λtδ∥θ∥2,
where λ∈(0,1] is the forgetting factor (data from s steps ago have weight λs) and δ>0 is a small prior term making the problem solvable from the first point. The normal equations are Gtθ^t=ht with
Each new point is a rank-one update of G. Write Pt=Gt−1 and apply Sherman–Morrison to λGt−1+xtxt⊤, whose invertible part has inverse Pt−1/λ:
Pt=λ1(Pt−1−λ+xtTPt−1xtPt−1xtxtTPt−1)
Sherman–Morrison with A = λG, A⁻¹ = P/λ; multiply numerator and denominator by λ.
1/5
That is recursive least squares (RLS): O(d2) operations per point instead of O(d3), without storing the data. In exact arithmetic, θ^t matches the batch solution at each step. The effective forgetting memory is ∑sλs=1/(1−λ) points: λ=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/δ with δ=0.01; the batch solution minimizes the same weighted sum, ∑iλt−i(yi−xi⊤θ)2+λtδ∥θ∥2, solving the 2×2 system from scratch at each step.
Point t1 of 140
Estimated liney = 0.37 + 0.01 x
∥θ^RLS−θ^batch∥1×10⁻¹⁶
Innovation yt−y^t0.38
Gain ∥gt∥0.990
trPt100.990
Effective memory 1/(1−λ)∞
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 λ near 1 their difference remains at rounding level. The true relationship changes at t=70. With λ=1 all points weigh equally and the line takes a long time to turn; decrease λ and old points fade. With λ 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 and λ>0 has solution w^=(X⊤X+λId)−1X⊤y. The push-through identity
(X⊤X+λId)−1X⊤=X⊤(XX⊤+λIn)−1
is proved in one line: X⊤(XX⊤+λIn)=(X⊤X+λId)X⊤, and it suffices to multiply on the left by (X⊤X+λId)−1 and on the right by (XX⊤+λIn)−1, both invertible because λ>0. In general, A(I+BA)−1=(I+AB)−1A whenever the inverses exist: factor A “pushes” through the parentheses. (It also follows from Woodbury applied to λId+X⊤X.)
Thus the same w^ can be computed in two ways:
Form
System
Dominant cost
Useful when
primal
(X⊤X+λId)w^=X⊤y
nd2+d3/3
n≫d: many examples, few features
dual
(XX⊤+λIn)α=y, w^=X⊤α
n2d+n3/3
d≫n: few examples, many features
The dual form says more: w^=X⊤α is a combination of examples, and prediction at a new point, x⊤w^=∑iαix⊤xi, 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 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 into the factor diagonal, in O(n2) 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 with k tiny eigenvalues and an update correcting them. The updated problem has κ≈2 for any κ(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 δ.
[ ]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 is not recomputed. After 105 updates, without forgetting and with highly correlated features (κ(G)≈4×104), we measure how far 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 shrinks like 1/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 is simply divided by λ at each step, so any error in that direction is multiplied by 1/λ per step. The skew-symmetric part of the error, which the formula does not correct, grows geometrically until P ceases to be positive definite and θ^ departs from the exact solution far beyond rounding. We see this with λ=0.999 (effective memory of 1,000 points) and 3×104 steps, with and without resymmetrization every 100 steps.
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 with rotations (such as chol_update) instead of 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^ both ways, timed for n≪d and n≫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” is always a call to an A solver, and the capacitance matrix is factored, not inverted.
Update factorizations. SciPy offers scipy.linalg.qr_update (rank-k 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, C and K=C−1+VA−1U are invertible, then (A+UCV)−1=A−1−A−1UK−1VA−1.
0
Write W=A−1−A−1UK−1VA−1, with A of size n×n, U of n×k, C of k×k and V of k×n.
Step 1 of 4. What suffices to check?
ProofBlock determinant
Prove: If A is invertible, det[ACBD]=detAdet(D−CA−1B).
0
Let M be the block matrix, with A of size p×p and D of size q×q, and S=D−CA−1B.
Step 1 of 3. Which factorization of M do we use?
Numeric
Compute det(I+uv⊤) with u=(1,2,3) and v=(1,1,1).
Numeric
The vector (x1,x2,x3) is Gaussian with covariance Σ=421231112. What is Var(x3∣x1,x2)?
Numeric
What is the smallest t for which M=21112111t is positive semidefinite?
Numeric
In recursive least squares with λ=1, Pt−1=I2 and a new xt=(1,1) arrives. What is trPt?
Quiz
For M=[ACBD] with A, D, M and both complements invertible, which expressions equal the upper-left block (M−1)11?
More than one answer may be correct.
Quiz
You have the Cholesky factor of a symmetric positive definite A with n=104 and want to solve a system with A+UU⊤, where U is n×k. Counting operations as in the cost figure, at what order of magnitude of k does Woodbury stop paying off versus refactorization?
Quiz
You fit ridge to n=500 documents described by d=200000 features (n-gram counts). Which system do you solve?
Quiz
You use RLS with λ=0.99 and one feature is exactly 0 in all data after some time. In exact arithmetic, what happens to Pt in that direction?
Code
Implement sherman_morrison_update(A_inv, u, v), which returns (A+uv⊤)−1 from A−1 in O(n2), and woodbury_solve(A_solve, U, C, V, b), which solves (A+UCV)x=b using A only through A_solve(R), which returns A−1R for a vector or matrix R. Do not form any n×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 b 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 in the corner. Block factorization yields detM=detAdet(M/A), the block inverse with (M−1)22=(M/A)−1, 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-k change by solving an k×k system; the determinant lemma does the same for determinants. They pay off with k≪n and a cheap A solver, and inherit the conditioning of 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.