Rank and the four fundamental subspaces
The complete map of a matrix: what it reaches (column space), what it destroys (null space), and how the four subspaces pair up with their dimensions. Prove row rank equals column rank and the rank–nullity theorem, and introduce CR factorization as a sum of rank-one matrices, leading to SVD and rank bottlenecks in deep learning.
After this lesson you can
- Calculate bases of C(A), N(A), C(Aᵀ) and N(Aᵀ) and verify dimensions r, n - r, r and m - r.
- Prove rank–nullity and equality of row and column rank.
- Describe the solution set of Ax = b as a particular solution plus the null space and explain its affine geometry.
- Factor A = CR and express a rank-r matrix as a sum of r outer products.
- Bound ranks of products and sums and apply them to bottleneck layers and low-rank updates.
Before you start
Motivation: what a matrix reaches and what it destroys
In the linear transformations lesson, matrix stopped being a table and became a function from to . For any function two things matter: which values it can produce and which distinct inputs it confuses. For arbitrary functions the answers can be shapeless sets. For a linear map they are subspaces, computed using elimination from the previous lesson, and their dimensions obey an exact conservation law. This lesson builds the complete map.
The map appears as soon as you build something real:
- A bottleneck layer. A linear autoencoder computes with and . However it is trained, reconstructions lie in a subspace of dimension at most , and a subspace of input directions of dimension at least is invisible to the network. Which subspace it learns connects to PCA in the linear autoencoder.
- An attention head. In the original Transformer (Vaswani et al., 2017), with and heads, each query uses a matrix . By the end of the lesson you can prove in one line that a subspace of input directions of dimension at least is completely ignored by that query.
- Regression with redundant variables. If a categorical variable is encoded with one indicator column per category plus an intercept, the ones column is the sum of indicators. There is then a vector with , and weights and give exactly the same predictions for every : coefficients are not identified. This is perfect collinearity, the dummy-variable trap.
- A redundant robot arm. A seven-joint arm controlling gripper position and orientation (six numbers) has Jacobian matrix . Joint velocities with move the elbow without moving the gripper, and always exist. This redundancy is used to avoid obstacles.
- Cheap fine-tuning. LoRA restricts each weight-matrix update to a product with small inner dimension . All possible updates have rank at most ; understanding that means understanding what a LoRA adapter can and cannot learn.
All five ask the same question: given a matrix, which output subspace can it reach (its column space), which input subspace does it destroy (its null space), and how are dimensions divided between them? The complete answer comprises four subspaces with dimensions , , and , where , the rank, summarizes almost everything needed about a matrix.
First look: flatten the cube
Before the definitions, see what happens when a column stops adding a new direction. Matrix sends the unit cube to the solid generated by its columns : point of the cube goes to .
What you should have seen:
- While all three columns are independent, the solid has volume. Moving toward the plane of and , volume, which is as the determinant shows, falls to . The solid does not disappear: it flattens onto the plane spanned by the columns.
- One direction is completely flattened. When , vector satisfies . A linear relation among columns is exactly a vector the matrix sends to zero.
- Each segment parallel to that direction maps to one point. If , then for every : from the output you cannot tell which point on the segment it came from. That information is lost.
- What is lost and what survives add to 3. With one column relation the image is a plane (dimension 2) and a line is lost (dimension 1). With two relations the image is a line and an entire plane is lost. This accounting is the rank–nullity theorem, the lesson’s central result.
Column space and null space
What the matrix reaches
The descriptions coincide by the column reading of the matrix–vector product: , so possible outputs of are exactly linear combinations of its columns. Thus is the image (range) of linear map , and a subspace of because it is a span. The consequence for linear systems is immediate and worth stating explicitly: has a solution if and only if .
Use one example throughout the lesson:
Its columns have two visible relations: and . All four span the same space as and , which are not parallel, so is a plane in . Which? Both columns have third coordinate equal to the sum of the other two, hence
System has a solution because ; system does not, and there is no need to try solving it to know.
What the matrix destroys
It is a subspace: it contains , and if , then . Read by columns, says : each null-space vector is a linear relation among columns, and the null space is the set of all such relations. In the example, relations and give two null-space vectors,
with sign chosen so that the fourth coordinate of equals . You will soon see they form a basis of .
The null space measures exactly how much the matrix confuses inputs: if and only if , meaning and differ by a null-space vector. This yields an often-used equivalence: map is injective if and only if , exactly when columns of are linearly independent. The second equivalence is the definition of linear independence: the only relation among columns is trivial.
The general solution: particular plus null space
The null space says more than whether the solution of is unique. It says exactly how many there are and what shape they have.
Proof
If , then , so every is a solution. Conversely, if , then , so lies in the null space and .
∎Three consequences. First, the number of solutions is , or infinite, with nothing in between, because a subspace other than contains a whole line. Second, a solution, if it exists, is unique exactly when . Third, and easiest to forget: with the solution set is not a subspace, because it does not contain . It is an affine subspace, a set of form with a subspace: a copy of translated by , which is a subspace if and only if . These are the sets the lesson 3 affine maps send into one another.
In the example, elimination from the previous lesson takes augmented matrix with to
The last row says : condition already known, now derived by elimination. For , pivot variables are and , and free variables and . Solving,
Solutions form a plane in that does not pass through the origin, parallel to the null space. With of we cannot draw it, but with a matrix we can.
Three things worth observing:
- The line’s direction does not depend on . It is always ; only determines the copy’s location. For the rank-1 matrix, the null space is a plane and solutions form planes parallel to it.
- Among all solutions one is privileged. Blue arrow is the shortest solution and forms a right angle with the null space. This is no coincidence: it lies in the row space, the third of the four subspaces, proved in a few sections.
- If leaves , the line disappears. The separation of from the plane points in a specific direction perpendicular to , and readout , with perpendicular to the plane, ceases to be . That lives in the fourth subspace. What to do without a solution (find the closest ) is the least-squares problem.
Rank
By definition the example’s rank is 2. To calculate it generally without guessing relations, use Gaussian elimination, thanks to a property used without stating it in the previous lesson.
Proof
implies , and multiplying by reverses the implication. A column relation is a null-space vector, and column of is .
∎Elimination is exactly this: reduced row echelon form is , with an invertible product of elementary matrices. Column relations are easy to read in , and the lemma transfers them to .
Proof
Let be pivot columns of . Column of is standard vector , so pivot columns of are independent. Any other column of has zeros in rows , which are zero rows, so it is : a combination of pivot columns. By the lemma, the same columns of are independent and each nonpivot column of is the same combination of pivot columns of . They therefore span and form a basis.
∎The factorization
The theorem fits into one matrix equality. Call the matrix of pivot columns of , and the nonzero rows of . Then
Column of is , and the proof says this is precisely the combination yielding . In the example, with and ,
is the recipe: column says how much of each pivot column enters . Column 2 of is because ; column 4 is because ; and on pivot columns contains identity. Also, and occupy numbers versus for : with and , fifty times fewer.
Row rank equals column rank
Rows of are vectors in and span another subspace: the row space, the column space of the transpose, , also written . In the example the third row is the sum of the first two, so row space also has dimension 2. That the number of independent rows always equals the number of independent columns is not obvious: for matrix it says that among a thousand columns in , exactly as many are independent as there are independent rows among three vectors in .
Proof
Let and let be a matrix whose columns form a basis of . Each column lies in , so it is a combination of columns of : for some . Combining the equalities gives with .
Now read the same product by rows: row of is times row of . Every row of is a combination of the rows of , so lies in a space generated by vectors and .
The argument holds for every matrix, in particular : . The two inequalities give equality.
∎The proof does not use elimination: only that every subspace has a basis, with factorization doing the rest. Elimination gives a second proof and a row-space basis: row operations are invertible, so and have the same row space, and the nonzero rows of are independent because each has in a pivot column where the others have . Thus rows of form a basis of , just as columns of do for .
The theorem yields everyday bounds and names. Since and , . If , the matrix has full column rank: independent columns, . If , it has full row rank: and every system is solvable. Shape and rank determine, without further calculation, how many solutions has:
| Case | Shape | Solutions of | ||
|---|---|---|---|---|
| square | exactly 1 | |||
| tall | proper | 0 or 1 | ||
| wide | infinitely many | |||
| any | proper | 0 or infinitely many |
“Proper” means a subspace other than ; “tall” means more equations than unknowns; “wide,” the reverse. The tall row is regression’s regime, with many more data than parameters, leading to least squares. The wide row describes overparameterized models with infinitely many exact solutions to choose among, studied with the pseudoinverse.
Which row is typical? If entries are randomly chosen from a continuous distribution, rank is with probability 1. For a square matrix, deficient rank is equivalent to , and determinant is a polynomial in entries that is not identically zero; the zero set of such a polynomial has Lebesgue measure zero. For with , rank below requires every minor to vanish, in particular that of the first columns, and the same argument applies. Two practical consequences follow. Meaningful low ranks come from structure rather than chance: redundant variables, bottlenecks, latent factors. Noisy data have full rank even if the signal does not, a problem revisited at the end.
The rank–nullity theorem
The two halves of what a matrix does are tied together by an equality.
The rank–nullity theorem reads as a conservation law: each of the input dimensions either survives, contributing to the image, or is destroyed, contributing to the null space. is called nullity. Notice that does not appear: the domain dimension is what counts.
Proof
Since by the lemma, study . It has pivot variables and free variables. For each free variable , obtain special solution by setting , the other free variables to , and solving each pivot variable: the equation in row gives . Show that the special solutions form a null-space basis.
They are independent. At coordinate , equals and the other special solutions equal . If , looking at coordinate gives .
They span the null space. Let and . This is another null-space vector whose free variables all equal . Equations of give each pivot variable as a combination of free variables, so they are also : and .
Therefore .
∎In the example, free variables are and , with special solutions and from before: columns. The proof uses coordinates; the theorem applies to linear maps between abstract spaces, and the coordinate-free proof is even cleaner. Try it.
Step 1 of 4. How do you construct a basis of using the kernel basis?
Consequences are immediate and useful:
- More unknowns than equations forces a nontrivial null space. If , then and : the homogeneous system has nonzero solutions. This is the motivating attention head: has rank at most , so , and input components in that subspace do not affect the query. It is also the seven-joint arm: .
- For a square matrix, injective equals surjective. With , if and only if , that is, if and only if . Both are equivalent to being invertible: the rank entry in lesson 3’s equivalence list now follows from dimension counting.
- The solution set has dimension . If is consistent, its solutions form an affine subspace of dimension : the number of free variables, now with geometric meaning.
The four fundamental subspaces
Three subspaces have appeared: column space, null space and row space. The fourth is the transpose’s null space, completing a symmetry.
The fourth is named because, after transposing, is equivalent to : multiplies on the left. If is row of , the row reading gives , so the left null space is the set of linear relations among rows, just as the null space contains relations among columns. Two lie in , the input space, and two in , the output space.
Proof
The first is the definition of rank; the second, rank–nullity; the third, row rank equals column rank. For the fourth, apply rank–nullity to , with columns and rank : .
∎One elimination gives bases for all four. If with invertible:
| Subspace | Dimension | Basis |
|---|---|---|
| pivot columns of | ||
| nonzero rows of | ||
| special solutions | ||
| last rows of |
The last follows because rows of are independent as is invertible; the last satisfy because they produce zero rows of ; and their count equals the dimension of . In the example, eliminating on gives
so : the relation “row 3 minus row 1 minus row 2 is zero.” This is the same condition deciding whether has a solution, and not by chance. The counts agree: , , and .
Orthogonality: the null space is perpendicular to the row space
So far everything requires only addition and scaling. The dot product brings geometry.
Proof
Read by rows, says for every row : is perpendicular to each row. Any row-space vector is , and in one line, . The same argument with instead of gives the second claim: .
∎Check the example: , , and also annihilates both; in , is perpendicular to and . The proof gives more than its statement: for every defines , so contains all vectors perpendicular to row space, not just some. If denotes vectors perpendicular to all , its orthogonal complement, formalized in lesson 7, we have just shown . The other half, that row space is everything perpendicular to the null space, requires dimension counting. It is the next exercise.
Step 1 of 4. (a) If , is in the null space?
Symbol denotes a direct sum: every vector is uniquely a sum of one from each subspace. The version in finally answers the opening question, when a system has a solution, with a criterion requiring no solution.
Proof
Both cannot occur: if and , then . One must occur because (the previous exercise applied to ): if is not in , it is not perpendicular to some .
∎Vector is an inconsistency certificate: it specifies which combination of equations yields . In the example, subtracts the first two equations from the third, leaving . Checking a certificate costs a dot product, although finding one costs elimination. The same idea for inequalities is Farkas’ lemma, the basis of optimization duality in theorems of alternatives.
With the decomposition, the matrix’s action is fully understood.
Proof
. Every is for some , and by the above : the restriction is surjective. If with both in row space, their difference lies in row space and null space, hence is : it is injective.
∎This is Strang’s (1993) big picture: splits into two perpendicular pieces, the matrix collapses one to the origin and maps the other without loss onto its column space; in , the left null space is what cannot be reached. With arbitrary dimensions it can be drawn as a flow.
The geometric version, with editable matrix , also shows right angles.
The bijection between row and column spaces has an immediate consequence: if , there is exactly one solution of in row space, and it is the shortest of all. Others are with , and by orthogonality,
This was the blue arrow in the solutions interactive. That minimum-norm solution is returned by the pseudoinverse and found by gradient descent on an overparameterized linear problem starting at , because each step is a combination of rows and never leaves row space.
Rank-one matrices
The simplest nonzero matrices have rank one, and every matrix is built from them.
Equivalence is checked in two lines. If , its column is : all are multiples of and at least one is nonzero, so rank is one. If rank is one, for some , each column is for some number , and that is . The four subspaces of follow from : column space is the line of , row space that of , null space hyperplane of dimension , and left null space the hyperplane perpendicular to of dimension . A rank-one matrix stores numbers instead of .
Factorization , read as a sum of outer products (column of times row of ), says every rank- matrix is a sum of rank-one matrices:
In the example,
Fewer than terms are impossible because a sum of rank-one matrices has rank at most (as shown next). Rank thus has a third characterization: the minimum number of outer products summing to the matrix. The decomposition is not unique: if is invertible, is another. SVD chooses the best, with terms ordered by importance.
What the mosaic shows:
- The cross has rank 2: its rows have only two types (all ones, or ones in the two center columns). Two layers suffice; the second is not the whole vertical bar but the vertical bar without the intersection already painted by the first.
- The checkerboard has rank 1, though it looks most complicated: , the outer product of two alternating vectors. With ones and zeros, however, the checkerboard is , with alternating : rank 2. Adding a constant to every entry adds rank-one matrix , changing rank by at most one. This is why centering data matters.
- Ratings nearly fit in two layers. Rounding makes their rank 7, but two well-chosen layers leave error around 4%. This is the latent-factor assumption: few hidden tastes explain most preferences. Distinguishing exact from effective rank is the subject of low-rank approximation.
- The triangle has no shortcuts: rank 8, so no sum of fewer than 8 layers reproduces it.
“Fit” solves the best-layer problem by alternating least squares: with fixed, the best is , and vice versa. Applied layer by layer to the residual (“Fit all”), it constructs the truncated SVD exactly; the Eckart–Young theorem will show no sum of layers does better.
Rank of products and sums: bottlenecks
In lesson 1 the column reading showed that columns of lie in . This lesson’s tools give the complete picture, with upper and lower bounds.
Proof
(1) Each column of is , so and . For the other bound transpose: , using row rank equals column rank twice. And because has columns.
(2) This is the interactive derivation below.
(3) . If , certainly . If , multiply by : , hence . The matrices have columns and the same null space; rank–nullity gives the same rank.
(4) because . Combining a basis of with one of gives vectors spanning that sum, so its dimension is no larger.
∎The lower bound is most interesting because it says how much rank must survive. Try predicting each step:
The second step also says when the upper bound is not attained: rank is lost exactly when intersects the null space of , meaning produces vectors that destroys. With and both rank 1, : everything produced by lies in the null space of . If has full column rank, and exactly ; if has full row rank, .
Four places where these bounds matter:
- Bottlenecks. A network without nonlinearities, , computes a single matrix whose rank cannot exceed the smallest intermediate dimension. A linear autoencoder with hidden units is at most a rank- matrix. Nonlinearities break the bound and prevent the linear collapse of depth.
- LoRA. With , and , point (1) gives , and parameters are trained instead of . With and , these are versus : 256 times fewer. Point (4) bounds how much weight rank can change, .
- The softmax bottleneck. A language model calculates logits for contexts over a vocabulary of tokens as , with and , of rank at most . Log probabilities subtract each row’s normalizer, changing rank by at most one. Yang et al. (2018) showed that if the true log-probability matrix has rank greater than , no parameter values reproduce it. This is the softmax bottleneck.
- Normal equations. By (3), is invertible if and only if has full column rank. This is the condition for least-squares normal equations to have a unique solution; the motivating perfect collinearity violates it.
Implementation from scratch: four subspaces with your own RREF
Everything above translates to about forty lines. Start with the previous lesson’s reduced row echelon form in compact form, with partial pivoting and tolerance relative to matrix scale to decide what counts as zero.
import numpy as np
def rref(A, tol=1e-10):
"""RREF de A y columnas pivote (índices desde 0).
Pivoteo parcial; una entrada es cero si |a| <= tol * max|A|.
"""
R = np.array(A, dtype=float)
m, n = R.shape
eps = tol * np.abs(R).max() if R.size else 0.0
pivots, row = [], 0
for j in range(n):
if row == m:
break
i = row + np.argmax(np.abs(R[row:, j])) # pivoteo parcial
if abs(R[i, j]) <= eps:
R[row:, j] = 0.0 # columna libre: borra el ruido
continue
R[[row, i]] = R[[i, row]] # intercambio de filas
R[row] /= R[row, j] # pivote igual a 1
otras = np.arange(m) != row
R[otras] -= np.outer(R[otras, j], R[row]) # ceros en la columna
pivots.append(j)
row += 1
return R, pivots
A = np.array([[1, 2, 0, 1],
[2, 4, 1, 4],
[3, 6, 1, 5]], dtype=float)
R0, piv = rref(A)
print(R0)
print("columnas pivote:", piv, "-> rango", len(piv))Code indices start at 0: pivot columns [0, 2] are the first and third. With RREF all four bases follow from the preceding table. For left null space use special solutions of , giving the same subspace as rows of with less bookkeeping.
def null_basis(A, tol=1e-10):
"""Base de null(A): una solución especial por variable libre."""
R, piv = rref(A, tol)
n = R.shape[1]
libres = [j for j in range(n) if j not in piv]
N = np.zeros((n, len(libres)))
for k, f in enumerate(libres):
N[f, k] = 1.0 # esta libre vale 1; las demás, 0
for i, p in enumerate(piv):
N[p, k] = -R[i, f] # cada variable pivote la compensa
return N + 0.0 # + 0.0 evita imprimir -0.0
def four_subspaces(A, tol=1e-10):
"""Bases (por columnas) de col(A), null(A), col(A^T), null(A^T)."""
A = np.asarray(A, dtype=float)
R, piv = rref(A, tol)
r = len(piv)
col = A[:, piv] # columnas pivote de A (¡no de R!)
row = R[:r].T # filas no nulas de la RREF
null = null_basis(A, tol)
left_null = null_basis(A.T, tol)
return col, null, row, left_null
col, null, row, left_null = four_subspaces(A)
for nombre, B in [("col(A)", col), ("null(A)", null),
("col(A^T)", row), ("null(A^T)", left_null)]:
print(f"{nombre}: dimensión {B.shape[1]}")
print(B, "\n")The result is exactly the hand-computed bases: and as columns of null, and in left_null. Validate such an implementation against theory, not one example: random matrices of known rank must satisfy all four dimensions and relations , , row space null space, and column space left null space. To create rank , multiply by with Gaussian entries: the product has exactly rank with probability 1.
def comprueba(A, tol=1e-10):
"""Rango y peor violación de las relaciones (relativa a max|A|)."""
m, n = A.shape
col, null, row, left_null = four_subspaces(A, tol)
r = col.shape[1]
assert row.shape[1] == r, "dim col(A^T) != r"
assert null.shape[1] == n - r, "dim null(A) != n - r"
assert left_null.shape[1] == m - r, "dim null(A^T) != m - r"
peor = lambda M: np.abs(M).max(initial=0)
err = max(peor(A @ null), # A x = 0
peor(A.T @ left_null), # A^T y = 0
peor(row.T @ null), # fila ⟂ núcleo
peor(col.T @ left_null)) # columna ⟂ núcleo izquierdo
return r, err / max(np.abs(A).max(), 1.0)
rng = np.random.default_rng(0)
peor_err = 0.0
for _ in range(300):
m, n = rng.integers(1, 9, size=2)
r = rng.integers(0, min(m, n) + 1)
# producto (m x r)(r x n): rango r con probabilidad 1
M = rng.normal(size=(m, r)) @ rng.normal(size=(r, n))
r_hat, err = comprueba(M)
assert r_hat == r, (m, n, r, r_hat)
peor_err = max(peor_err, err)
print("300 matrices: dimensiones r, n - r, r, m - r correctas")
print(f"peor error relativo: {peor_err:.1e}")Worst relative error is on the order of : relations hold up to rounding. It works with too, as it should: the zero matrix breaks many implementations.
The professional version
SciPy computes these subspaces using SVD rather than elimination: scipy.linalg.null_space(A) returns an orthonormal null-space basis and scipy.linalg.orth(A) a column-space basis. These differ from ours and cannot be compared entrywise. Compare subspaces instead: if and only if both matrices and their concatenation have the same rank.
import scipy.linalg as sla
def mismo_subespacio(B1, B2, tol=1e-9):
"""¿Generan B1 y B2 (por columnas) el mismo subespacio?"""
r1 = np.linalg.matrix_rank(B1, tol=tol)
r2 = np.linalg.matrix_rank(B2, tol=tol)
r12 = np.linalg.matrix_rank(np.hstack([B1, B2]), tol=tol)
return r1 == r2 == r12
print("null(A): ", mismo_subespacio(null, sla.null_space(A)))
print("col(A): ", mismo_subespacio(col, sla.orth(A)))
print("col(A^T): ", mismo_subespacio(row, sla.orth(A.T)))
print("null(A^T):", mismo_subespacio(left_null, sla.null_space(A.T)))
N = sla.null_space(A)
print("\nbase ortonormal de null(A) según SciPy:\n", N.round(4))
print("N^T N =\n", (N.T @ N).round(12))
# solución general de A x = b
b = np.array([1.0, 3.0, 4.0])
x_p = np.linalg.lstsq(A, b, rcond=None)[0] # la de mínima norma
x = x_p + null @ rng.normal(size=null.shape[1]) # otra cualquiera
print("\nx_p =", x_p.round(4))
print("max|A x_p - b| =", np.abs(A @ x_p - b).max())
print("max|A x - b| =", np.abs(A @ x - b).max())
print("null^T x_p =", (null.T @ x_p).round(12) + 0.0,
"-> x_p está en el espacio fila")The particular solution returned by lstsq, , is not the from elimination: it is the minimum-norm solution, the only one in row space, hence perpendicular to columns of null. Any other is obtained by adding a null-space vector.
First encounter with numerical rank
In exact arithmetic rank is a well-defined integer. In floating point it is not: a rounding-sized perturbation can turn a rank-2 matrix full rank. Repeat the lesson 2 experiment, now with RREF.
rng = np.random.default_rng(1)
E = 1e-12 * rng.normal(size=A.shape) # ruido de medida diminuto
for tol in [1e-10, 1e-15]:
r_elim = len(rref(A + E, tol)[1])
print(f"tol = {tol:g}: rango por eliminación = {r_elim}")
s = np.linalg.svd(A + E, compute_uv=False)
print("valores singulares de A + E:", s)
print("matrix_rank(A + E): ", np.linalg.matrix_rank(A + E))
print("matrix_rank(A + E, tol=1e-9):",
np.linalg.matrix_rank(A + E, tol=1e-9))The third singular value, on the order of , is the trace of noise. With a tolerance matching that noise rank is 2; with a finer one, 3. np.linalg.matrix_rank also says 3 because its default threshold, with , assumes the matrix exact except for SVD rounding. For measured data, error determines tolerance, not the machine. This is numerical rank; the low-rank approximation lesson teaches how to choose it.
Lab: rank bottlenecks
The second lab checks product bounds and looks inside a LoRA-like update.
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
rank = np.linalg.matrix_rank
m, n = 60, 40
print("dimensión interior k -> rank(AB) (cota min(k, m, n))")
for k in [1, 3, 10, 25, 40, 55]:
A_ = rng.normal(size=(m, k))
B_ = rng.normal(size=(k, n))
print(f"k = {k:2d} -> {rank(A_ @ B_):2d} ({min(k, m, n)})")
# una actualización de tipo LoRA: dW = B A, dimensión interior r
d_out, d_in, r = 256, 192, 8
W0 = rng.normal(size=(d_out, d_in)) / np.sqrt(d_in) # congelados
B_lo = 0.1 * rng.normal(size=(d_out, r))
A_lo = 0.1 * rng.normal(size=(r, d_in))
dW = B_lo @ A_lo
print("\nrank(dW) =", rank(dW))
print("parámetros entrenables:", B_lo.size + A_lo.size,
"frente a", W0.size)
# cota superior no alcanzada: B produce vectores que A destruye
n6 = 6
A6 = rng.normal(size=(n6, 4)) @ rng.normal(size=(4, n6)) # rango 4
N6 = sla.null_space(A6) # 2 columnas
B6 = np.column_stack([N6, rng.normal(size=n6)]) # rango 3
rA, rB, rAB = rank(A6), rank(B6), rank(A6 @ B6)
print(f"\nrank A = {rA}, rank B = {rB}, rank AB = {rAB}")
print(f"cota superior {min(rA, rB)}, cota de Sylvester {rA + rB - n6}")
s = np.linalg.svd(dW, compute_uv=False)
plt.semilogy(np.arange(1, len(s) + 1), s, "o", ms=3)
plt.axvline(r + 0.5, ls="--", color="gray")
plt.xlabel("índice i")
plt.ylabel(r"$\sigma_i(\Delta W)$")
plt.title(f"ΔW = BA con r = {r}: solo {r} valores singulares no nulos")
plt.show()Three readings. Generic products always attain bound : structure, not chance, is needed to lose rank. The LoRA update has exactly rank 8 with 3584 parameters instead of 49,152, visible in the graph: eight singular values on the order of 1, followed by a fifteen-order-of-magnitude jump to the rounding floor. When two columns of fall in the null space of , product rank collapses to 1, exactly Sylvester’s bound : the lower bound is attained too.
Common mistakes
Exercises
More than one answer may be correct.
np.linalg.matrix_rank(X) returns 50. What do you conclude?cr_factorization(A, tol=1e-10), returning (C, R) with C the pivot columns of A and R the nonzero rows of its reduced row echelon form, so A = C @ R. Decide what is zero using relative tolerance tol * max|A|. For a zero matrix of shape (m, n), C must have shape (m, 0) and R shape (0, n). Write it from scratch without SymPy's rref.import numpy as np
def cr_factorization(A, tol=1e-10):
"""(C, R): C = columnas pivote de A; R = filas no nulas de la RREF."""
A = np.asarray(A, dtype=float)
# 1. Reduce una copia de A a su RREF anotando las columnas pivote.
# 2. C = esas columnas de la A original.
# 3. R = las primeras r filas de la RREF.
raise NotImplementedErrorSummary
- Column space and null space. is what the matrix reaches: is solvable if and only if . is what it destroys, the set of column relations, and solutions form affine subspace .
- Rank. is the pivot count, equals row rank, and is the minimum number of outer products summing to . Factorization (pivot columns times nonzero RREF rows) contains it all.
- Rank–nullity. : each input dimension survives or is destroyed. More unknowns than equations forces a nontrivial null space.
- Orthogonality. and , with dimensions and . Only the row-space part of reaches output, and the row-space solution has minimum norm.
- Products and sums. , and . These are the calculations behind bottlenecks, LoRA and normal equations.
- In floating point, rank depends on a tolerance set by data noise, not the machine.