A matrix is a map: it rotates, stretches along a few orthogonal directions (squashing some to zero), and rotates again. That is the SVD, and its stretches, the singular values, answer almost every linear-algebra question in ML: which directions survive (rank), how big the map is (norms), how badly it amplifies errors (conditioning), and how much is lost by keeping only the biggest stretches (low-rank approximation).
Fig. 1: the running matrix A = [[3, 0], [4, 5]] is a rotation, a stretch by 6.708 and 2.236, and another rotation
Section 10 steps through the SVD against the eigendecomposition; the Matrix playground does it for any 2x2 or 3x3 matrix.
You need: the running example of Topic: math (its running example): a tiny three-word model with input and weight rows cat , dog , sat , so is . Worked numbers use it and one running 2x2 matrix ; real numbers come from GPT-2 small's released weights and two public LoRA adapters; all of them are recomputed by the script in this page's source folder. Matrix calculus (Jacobians, layouts, gradients of matrix expressions, FLOP counts) is on Matrix calculus and backprop; floating point on Numerical computing for ML.
| Idea | In one line | One number to remember | Where ML uses it |
|---|---|---|---|
| Dot product, cosine | multiply pairwise and add; equals lengths times cosine of the angle | : orthogonal, score 0 | logits, attention scores, retrieval |
| Matrix as map | columns are where the axis arrows land | : area scales by 15 | every layer |
| Four multiplications | dot products, column combinations, sum of outer products, composition | attention, LoRA's , gradients | |
| Shapes, broadcasting, einsum | inner sizes vanish, outer survive; size-1 axes stretch; letters missing from the output are summed | MSE 1.333 for perfect predictions | every shape bug, reading model code |
| Rank, four subspaces | independent directions used; what a map can output, ignore, read, never reach | always | LoRA, collapse, softmax bottleneck |
| Norms | L1 diamond, L2 circle; spectral = largest stretch | , | weight decay, clipping, Lipschitz |
| Projection, least squares, QR | closest point leaves an orthogonal remainder; , better solved by QR | ; | linear probes, ridge, PCA, RoPE |
| Eigenvalues | directions only scaled; powers become | : 3 and 5 | curvature, stability, power iteration |
| Symmetric, PD | real eigenvalues, orthogonal eigenvectors; | : 6 and 1, an eigenvector | covariances, Hessians, Cholesky |
| SVD | rotate, stretch, rotate; truncate for the best rank- fit | : 6.708 and 2.236; error of rank 1 is 2.236 | compression, PCA, Muon |
| Conditioning | : error amplification | float32 normal equations: 77% error, QR 0.0018% | solvers, precision, preconditioning |
| Low rank in ML | updates and gradients are low rank; pretrained weights are not | GPT-2 : 298 of 768 directions for 90% | LoRA, MLA, GaLore |
| Attention | dot products, softmax rows, weighted average of values | one head's : rank 64 of 768 | every transformer |
| Einsum | letters missing from the output are summed | bhqd,bhkd->bhqk | reading model code |
A vector is a list of numbers and, equally, an arrow from the origin. A GPT-2 small token is a list of 768 numbers; nobody can draw 768 axes, but every rule on this page works the same in 768 dimensions as in 2, which is why the 2-D pictures are worth learning. The dot product multiplies two vectors entry by entry and adds, , and that is how the tiny model scores each word: , , .
The same number has a geometric reading, , with the length ( for ). Divide out the lengths and only the direction is left, the cosine similarity : 1 for the same direction, 0 at right angles (orthogonal), opposite. For the tiny model sat is exactly orthogonal to the input, which is why its score is 0 however long the arrows are.
On real embeddings. GPT-2 small stores one 768-number vector per token in its embedding table. The cosine similarities between a few of them (computed from the released weights, script in this page's source folder):
The projection of onto the direction of is the shadow casts on the line through , , and what is left over is orthogonal to . Projection is the idea behind least squares (section 7), PCA (section 10) and attention reading values (section 13).
Two pictures of the same thing. As a list, is two numbers in a fixed order, and : how code stores it (a tensor of shape (2,)). How many numbers it holds is its dimension, written ("x is a member of the set of all lists of 2 real numbers"). As an arrow from the origin it is two steps right, one step up: how you reason about it. Adding vectors is placing arrows head to tail, ; multiplying by a number (a scalar) stretches the arrow, .
Length. The L2 norm follows from Pythagoras: ; the subscript 2 says "squares, then square root" (other norms are in section 6). A unit vector has length 1; dividing any nonzero vector by its length gives the unit vector pointing the same way, . The notation reads the first vector as a row and the second as a column; it is the same number (the transpose is in section 3).
Why the two definitions agree. Draw , and the third side of their triangle, . The law of cosines (Pythagoras for a triangle without a right angle) says . Expanding with entries, . The two expressions are equal; cancel and divide by : . Check on and : , so , an angle of 26.6 degrees, which is the angle of the arrow above the horizontal.
The numbers. , , . Projecting onto : , , so the projection is and the leftover has .
From the old page, checked: , give , , ; and , orthogonal.
The tiny model's input and its three word rows: cat , dog , sat . The dashed line is the projection of onto the cat arrow. Every number comes from the root's model.
An matrix times a vector with entries gives one with entries, so a matrix is a map from to , and a linear one: and . Straight lines stay straight, the origin stays put, and evenly spaced grid lines stay evenly spaced. Writing with the axis arrows , (the standard basis), linearity gives , and is just the first column of .
The running matrix (from the old page, every number checked) is : lands on , on , the unit square becomes the parallelogram with those sides and the unit circle becomes an ellipse. Switch the preset to see a rotation, shear, projection and reflection do the same.
The determinant, , is the signed factor by which the map scales area: for , . A negative determinant means the map also flips orientation (a mirror image, like the reflection preset). A determinant of 0 means the plane is squashed onto a line or a point (the projection preset): many inputs land on the same output, so the map cannot be undone. In dimensions the determinant scales volume the same way.
Non-square matrices change the dimension. The tiny model's is : it takes the 2-number input to 3 scores, so it maps the plane into a flat plane sitting inside 3-D space, with and landing on its columns and . A matrix goes the other way and must squash a whole direction of 3-D space to zero (section 5 says exactly which one).
Notation: is the entry in row , column (row first, always); an matrix has rows and columns.
Predict before it plays: which reading builds the answer one whole matrix at a time? The same product in every mode, drawn to the same layout; the step list on the left follows the mode.
An matrix times an matrix is the matrix : the inner sizes must match and vanish, the outer sizes survive. There are four ways to read the same product, and each is the natural reading in some part of ML. Take
The animation, step by step (pick a reading on the card)
Transpose. swaps rows and columns, . So (a row times a column) is a dot product and (a column times a row) an outer product. Transposing a product reverses the order, (entry of is row of dotted with column of ). That reversal is what makes backpropagation multiply by on the way back.
Why stacked linear layers collapse. Two linear layers in a row, , are one linear layer : however many you stack, without a non-linear function between them the network can only ever compute one matrix. The activation function (ReLU, GELU) between layers is what stops the collapse.
What a product costs. An times product does multiplications and about as many additions, usually counted as floating-point operations (FLOPs). For one GPT-2 small layer of 768 by 768 applied to 1,024 tokens that is billion FLOPs. Counting FLOPs for whole networks and for the backward pass belongs to Matrix calculus and backprop.
Write the shape beside every symbol: is , has 2 entries, so has 3. A real model holds activations as a tensor of shape : sequences in the batch, tokens each, numbers per token; a layer acts on the last axis only, with the same matrix for every token.
Three layouts for the same layer. Papers treat one input as a column and write with of shape (outputs by inputs). Code stacks inputs as rows and computes : PyTorch's nn.Linear stores weight with shape (out_features, in_features) and computes (PyTorch nn.Linear docs). GPT-2's original code uses a third: its Conv1D stores the weight as (in, out) and computes ; Hugging Face's own docstring says it "works like a linear layer but the weights are transposed" (transformers pytorch_utils.py). Section 12's GPT-2 measurements use this layout. The transpose between conventions is the same map; mixing them inside one derivation is the bug. Reading a model's code against its paper is mostly translating shapes and layouts: which axis is the batch, which is heads, whether the weight is stored (out, in) or (in, out).
Broadcasting. Adding a bias of shape to activations of shape works because libraries broadcast: they line up shapes from the right, and an axis of size 1 (or a missing axis) is stretched to match. NumPy's rule, word for word: "two dimensions are compatible when they are equal, or one of them is 1" (NumPy broadcasting). So gives , and gives . The same rule produces the commonest silent bug:
Predictions of shape (3, 1), as a column, minus targets of shape (3,), also . Instead of three differences of 0 you get every prediction minus every target, ; its mean square is , though the predictions are perfect and the true mean squared error is 0. No error is raised. Fix: make the shapes equal (pred.squeeze(-1)) and assert shapes before every loss.
Einstein summation labels every axis with a letter. The rule: a letter that appears in the inputs but not in the output is summed over; every other letter is kept, in the order the output names them. torch.einsum, numpy.einsum and jax.numpy.einsum all read the same strings, and writing one is the cure when a shape bug survives ten minutes of staring.
| String | Reads as | Math |
|---|---|---|
i,i-> | dot product: multiply along i, sum it away | |
i,j->ij | outer product: nothing summed | |
ij,j->i | matrix times vector | |
ij,jk->ik | matrix product: j shared and summed | |
ij->ji | transpose: relabel only | |
ii-> | trace: the diagonal, summed | |
btd,od->bto | a linear layer on every token (PyTorch's (out, in) weight) | |
bhqd,bhkd->bhqk | attention scores: per batch b and head h, every query q against every key k, summed over d | |
bhqk,bhkd->bhqd | attention output: weights times values, summed over keys k |
Reading the shape off the string. In bhqd,bhkd->bhqk with , , , (the old page's example), is summed away and the output is . Counting the multiply-adds from the same string (one per combination of all distinct letters, here ) and seeing why attention is quadratic in length is done on Matrix calculus and backprop. "Splitting heads" in code is a reshape from to and a transpose of two axes, no arithmetic; the einops library writes it as a named reshape that documents intent, rearrange(x, 'b t (h d) -> b h t d', h=12).
A weight matrix has 589,824 numbers; the question is how many genuinely different directions it uses. The rank of a matrix is the number of independent columns, which always equals the number of independent rows, and is the dimension of the set of outputs the map can produce. An matrix has rank at most ; a square matrix of full rank is invertible (its map can be undone, , with the identity matrix). The null space is the set of inputs the map sends to zero.
For (old page, checked) the second column is twice the first, so the rank is 1 and the map flattens the plane onto the line through ; its determinant is , the same fact seen as area; and the input is sent to , as is every multiple of it.
The input dimensions are shared out exactly between those that reach the output and those squashed to zero, the rank-nullity theorem:
( the number of columns; for the rank-1 matrix, ). The tiny model's has independent columns and , so its rank is 2 and its null space is just : no input direction is lost. The gradient the root computes for it, with , is an outer product, so it has rank 1: one training step on one example changes along a single direction. That small fact is where LoRA starts (section 12).
Rank in floating point. In exact arithmetic rank is an integer you can read off. In floating point, rounding makes almost every matrix full rank, so the useful question is how many singular values (section 10) are large: the effective rank. Section 12 measures it on real GPT-2 weights.
. Left, the input plane: the null-space line along and, at right angles to it, the row-space line along . Every input on a dashed line parallel to the null space lands on the same output. Right, the output plane: every output lies on the column-space line through ; and both land on .
Which outputs can a layer never produce, whatever its input? Which inputs does it ignore? Every matrix of rank comes with four subspaces (lines, planes and their higher-dimensional versions through the origin) that answer these, and Gilbert Strang organises all of linear algebra around them:
| Subspace | What it holds | Lives in | Dimension |
|---|---|---|---|
| Column space | every output the map can produce | ||
| Null space | inputs sent to zero | ||
| Row space | the span of the rows: the input directions the map "reads" | ||
| Left null space | output directions the map can never reach |
The row space and the null space are orthogonal and together fill ; the column space and the left null space are orthogonal and together fill . The reason is one line: is in the null space when , which says that has dot product 0 with every row (Strang, The Fundamental Theorem of Linear Algebra, 1993; MIT 18.06 lectures 9 and 10).
Fig. 4, step by step: the tiny model's , from into
Here the left null space is the line along , so every score vector this model can ever produce satisfies (for , ), whatever the input.
The softmax bottleneck: the same fact at scale. A language model computes its logits as , with the final hidden state ( numbers) and the output matrix (, one row per token), so the logits live in the column space of , of dimension at most . GPT-2 small has and and its output layer has no bias (it reuses the embedding table), so all its logit vectors lie in a 768-dimensional subspace of a 50,257-dimensional space. Yang, Dai, Salakhutdinov and Cohen called this the softmax bottleneck: stack the logits for many contexts into one matrix and its rank is at most ; the log-probabilities differ from the logits by one constant per context, which changes the rank by at most 1; so if the true matrix of log-probabilities of language has rank above , no setting of the weights can reproduce it (their Corollary 1, Yang et al., ICLR 2018, arXiv 1711.03953). Their fix, a mixture of softmaxes, breaks the linearity.
A linear combination of vectors is a sum of scaled copies, ; the span of a set is everything you can reach that way. The span of and is the whole plane; the span of alone is a line through the origin; the span of and is still that same line, because adds nothing new. Vectors are linearly independent when none of them is a combination of the others; equivalently, the only way to combine them into the zero vector is with all coefficients 0. and are dependent: .
A basis of a space is a set of independent vectors that spans it; every basis of the same space has the same number of vectors, the dimension. Once a basis is fixed, every vector has unique coordinates in it. , is a basis of the plane, and in it the tiny model's input is (check: ). Same arrow, different numbers: "the coordinates of a vector" always means "in some basis", and the eigenvector and SVD sections choose bases that make a matrix simple.
Finding the rank by elimination. Subtract multiples of rows from other rows (this does not change the rank) until no more zeros can be made; the rank is the number of nonzero rows left. For : row 2 minus twice row 1 is all zeros; row 3 minus row 1 is , not a multiple of row 1. Two nonzero rows remain, so the rank is 2. The input satisfies and , so sends it to zero, and rank-nullity reads .
The tiny model's subspaces, checked. , , : the null space has dimension , the left null space , spanned by : and . Training changes and therefore the plane, but with 2 numbers per input the scores always live on some plane inside the 3-D space of scores.
Why rank-nullity holds. 1. Pick a basis of the null space ( is the nullity). 2. Extend it with to a basis of all of . 3. Every output is a combination of , because writing in the basis, the parts are sent to zero. 4. Those outputs are independent: if then is in the null space, so it is a combination of the 's, and since the whole basis is independent all . So the output space has dimension exactly , which is the rank.
Weight decay, gradient clipping, spectral normalisation and "the update was too large" all measure size, in different senses, and the choice decides what a regulariser pushes towards. For vectors three norms are common:
For : , , (old page, checked: gives 7, 5 and 4). Always .
Why L1 gives sparsity. Minimising a loss subject to grows the diamond until it first touches a contour of the loss, usually at a corner, where some coordinates are exactly zero; the round L2 ball shrinks every coordinate a little and zeroes none. That is lasso against ridge regression (Regularisation owns the full story).
Matrix norms are functions of the singular values.
For (singular values 6.708 and 2.236, section 10): Frobenius , spectral 6.708, nuclear 8.944.
For (singular values and , derived in section 10): Frobenius ; spectral 6.708; nuclear .
For the tiny model's (singular values and 1): Frobenius , spectral 2.449, nuclear 3.449. For its rank-1 gradient all three coincide: , because a rank-1 matrix has a single nonzero singular value.
The spectral norm is a Lipschitz constant. : no two inputs can end up further apart than times their distance. Spectral normalisation divides a layer's weights by to make that factor 1 (Miyato et al. 2018), which is why a layer's largest singular value controls how much it can amplify a perturbation.
What makes a norm a norm: it is zero only for the zero vector, scales with the vector () and obeys the triangle inequality ().
The unit "circle" of each norm: every point at distance 1 from the origin. L1 is a diamond with corners on the axes, L2 the round circle, L-infinity a square. The dot is where a growing ball first touches a straight line of equal loss (the dashed line): for L1 at a corner, where one coordinate is exactly 0.
Vectors are orthonormal when each has length 1 and every pair is orthogonal. A square matrix with orthonormal columns is an orthogonal matrix, and that fits in one equation, , so its inverse is its transpose, free to compute. Orthogonal matrices are rotations and reflections: they keep every length and angle, , so multiplying by them never amplifies rounding errors, which is why stable algorithms are built from them. The rotation by is ; RoPE, the position encoding of most current LLMs, rotates pairs of query and key coordinates by such matrices.
Fit to the points (the old page's example, checked). Three equations for two unknowns have no exact solution. Stack them, a column of ones for the intercept and a column of values:
The three points, the fitted line and the residuals . Fig. 8 draws the same fit in , one axis per data point, where it becomes a projection.
Fig. 8, step by step: the fit as a projection in
The predictions range over the column space of , a plane in , and is not on it. The closest point leaves a leftover orthogonal to every column, , which gives the normal equations:
No calculus is needed: the derivation is orthogonality. (The same equations come from setting the gradient to zero; deriving such gradients is on Matrix calculus and backprop.) is the projection matrix: projecting twice changes nothing () and is symmetric.
Here and give ; the residuals sum to 0 (orthogonal to the column of ones) and have zero dot product with , exactly as demands.
QR: the same answer without forming . Gram-Schmidt makes the columns orthonormal one at a time (subtract from each column its projections onto the ones already done, then scale to length 1); recording the coefficients gives , with orthonormal columns and upper triangular. The normal equations then become , solved from the bottom row up. Why bother: forming squares the condition number (section 11), here against , the square of 2.924. Harmless at this size, ruinous for an ill-conditioned problem in float32, as section 11 shows on a real run. Library routines (LAPACK, behind NumPy and PyTorch) use Householder reflections rather than textbook Gram-Schmidt, because classical Gram-Schmidt loses orthogonality in floating point when columns are nearly parallel (Trefethen and Bau, lectures 8 to 10).
Ridge and the pseudo-inverse. Ridge regression adds , which changes the equations to . Adding adds to every eigenvalue of (7.162 and 0.838 here), so the condition number drops from to at : regularisation is also a numerical fix. The pseudo-inverse (section 10) gives the least-squares solution even when is rank-deficient, choosing the shortest among the many that fit equally well.
torch.svd_lowrank, orthonormalise with QR at every pass).The solve by hand. (3 points, sum of is 3, sum of is 5) and . The 2x2 inverse is with , so .
Predictions ; residuals . They sum to 0 (orthogonal to the column of ones) and (orthogonal to the column), exactly as demands.
Closest point. For any other point of the subspace, , the two pieces are orthogonal, so by Pythagoras
QR by Gram-Schmidt. has columns and . Step 1: , and . Step 2: the coefficient of along is ; subtract it: . Its length is , so , and
Solve. . Back-substitute from the bottom row: gives ; gives .
Most arrows change direction when a matrix acts on them. A few special ones only get longer or shorter (or flip): the eigenvectors, scaled by their eigenvalue, with . Along an eigenvector the matrix is just multiplication by a number. means sends a nonzero to zero, so it squashes area to zero, so the eigenvalues solve the characteristic equation .
For : , so the eigenvalues are 3 and 5 (a triangular matrix always has its diagonal entries as eigenvalues), with eigenvectors and . They add up to the trace (sum of the diagonal), , and multiply to the determinant, . The two eigenvectors are not orthogonal: their dot product is . For a non-symmetric matrix that is normal; section 9 shows symmetric matrices are different.
, so or (a triangular matrix always has its diagonal entries as eigenvalues). For : needs , so ; check . For : ; check . The eigenvalues add up to the trace (sum of the diagonal), , and multiply to the determinant, .
The two eigenvectors and are not orthogonal: their dot product is . For a non-symmetric matrix that is normal; section 9 shows symmetric matrices are different.
Why eigenvalues rule repeated application. If the eigenvectors form a basis, write any input as ; then : each component is multiplied by its own eigenvalue times, the largest wins, and the result grows like above 1 and shrinks to zero when every . For the whole matrix, (eigenvectors as the columns of , eigenvalues on the diagonal of ) and : powers of a matrix are powers of numbers in the eigenvector basis.
Power iteration is how the largest singular value of a layer is estimated cheaply in spectral normalisation (one step per training step).
Exploding and vanishing gradients. A plain recurrent network applies the same matrix at every time step, and the gradient flowing back through steps is multiplied by (the transpose of) that matrix times: above 1 in the largest eigenvalue magnitude it can explode, below 1 in all it vanishes. (Pascanu, Mikolov and Bengio 2013, quoted below).
When eigenvectors fail. A rotation by 30 degrees turns every arrow, so it has no real eigenvector: its characteristic equation has complex roots . Some matrices have too few eigenvectors to form a basis (the shear has only the direction ). Both are reasons the SVD, which always exists, is usually the better tool for "what does this matrix do".
"It is sufficient for , where is the absolute value of the largest eigenvalue of the recurrent weight matrix", for the vanishing gradient problem to occur, with a bound on the activation's derivative; for linear units () that is the eigenvalue-below-1 picture above (Pascanu et al. 2013, section 2.1).
Start from , multiply by and rescale to length 1, repeatedly. The angle to the dominant eigenvector (eigenvalue 5) goes 18.4, 9.0, 4.8, 2.7, 1.6, 0.9, 0.5, 0.3 degrees: it shrinks by about the ratio each step, because the other component is multiplied by 3 while the dominant one is multiplied by 5. Dashed: the two eigenvector directions, not at right angles.
Covariance matrices and Hessians are symmetric, . The tiny model gives one for free: , always symmetric because .
So the eigenvalues are 6 and 1. For 6: gives ; for 1: . Their dot product is : orthogonal, as promised.
A surprise: is the tiny model's input . Check . So , and indeed the scores have . This input happens to sit on the direction stretches least.
A symmetric matrix defines a quadratic form, the number ; here with . The matrix is positive definite (PD) when for every nonzero , and positive semi-definite (PSD) when . Geometrically the surface is a bowl, and its level sets are ellipses along the eigenvectors:
Four equivalent tests for a symmetric matrix being PD:
is PSD but not PD: eigenvalues 2 and 0, and gives .
Cholesky: the square root of a PD matrix. Every PD matrix factors as with lower triangular and positive diagonal, solved entry by entry from the top-left; if the matrix is not PD a step asks for the square root of a negative number and the factorisation fails, which is the cheapest PD test there is. For , .
Sampling a correlated Gaussian. Draw independent standard normals and output : its covariance is . With , whose factor is , and : . It is the full-covariance form of the reparameterisation trick used to train VAEs (Variational inference and generative-model maths).
Take and with . Compute two ways: as , and, because , as . Subtract: , and since the eigenvalues differ, . (That the eigenvalues are real follows from the same trick with complex conjugates; the full theorem with repeated eigenvalues is in Strang's 18.06 lecture 25.)
Cholesky by hand. For (old page, checked): , , , so . For : , , . Check: for .
: semi-axes along and along , the direction of the tiny model's input. Steep curvature (large ) means a narrow ellipse; a zero eigenvalue (PSD, not PD) would open it into two parallel lines.
Drawn to scale: the circle has radius 1, the ellipse's long axis is 6.708. Only the SVD keeps the two marked arrows at 90° through every step; the eigen route skews the grid on the way.
Eigenvectors need a square matrix and may not exist. The singular value decomposition describes what any matrix does, including a weight, and always exists: a rotation, a stretch along the axes, and another rotation. Predict first: does applying 's three SVD factors one at a time end on the same ellipse as applying in one step? Then watch it, and compare with the eigendecomposition on the same circle (the buttons on the figure switch the route and the matrix; the steps below follow).
There are orthonormal input directions that the matrix sends to orthogonal output directions, . The sum form reads the matrix as rank-1 layers, largest first. Every matrix, of any shape, has an SVD.
How to get it. , so the right singular vectors are the eigenvectors of the symmetric PSD matrix , the singular values are the square roots of its eigenvalues, and . For , has eigenvalues 45 and 5, so and (worked in the closed block below).
The SVD answers the earlier sections at once. Rank = number of nonzero ; effective rank = number of above a tolerance. Four subspaces: span the column space, the left null space, the row space, the null space. Norms: spectral , Frobenius , nuclear . Pseudo-inverse: , with inverting the nonzero and leaving zeros; is the least-squares solution of shortest length. Condition number: (section 11).
Keep only the largest layers, . The Eckart-Young(-Mirsky) theorem says no rank- matrix is closer to , in either the spectral or the Frobenius norm, and the errors are exactly
Fig. 11, step by step: a real matrix rebuilt from rank-one layers
The singular values tell you, before you compress anything, exactly what you will lose: a spectrum that falls fast compresses well; a flat one does not. Storing for an matrix costs numbers (fold each into ) instead of : for at , 98,304 instead of 589,824.
For , the best rank-1 approximation misses by exactly in both norms. On a real matrix, the query matrix of GPT-2 small's layer 5 (768 by 768) needs of its 768 singular directions to keep 90% of its squared Frobenius norm; a random matrix of the same shape needs . Real weights are more concentrated than noise, but far from low rank; section 12 shows what truncation does to the model's loss.
Stack examples as the rows of , subtract each column's mean, and the covariance is . Its eigenvectors (equivalently the right singular vectors of ) are the principal directions, and the variance along the -th is . For the centred points : , eigenvalues 3.427 and 0.073, and the first principal direction carries of the variance: these points are almost a line. Centre first: without it the first "principal component" mostly points at the mean.
Signs chosen so both factors are rotations (old page, checked). . Eigenvalues: , so or 5. Eigenvectors: , . Then and ; orthogonal, . So is a rotation by (it takes to the horizontal axis), stretches, and is a rotation by (the angle of ). Both have determinant . Checks: ; .
The error has spectral and Frobenius norm , as the theorem says (the two norms agree because the error has rank 1); .
PCA, four points. Each column already sums to 0. . Trace 3.5, determinant , so and 0.073.
Two linear systems of the same size, solved by the same code: one gives every digit right, the other gives garbage. The difference is one number,
the ratio of the most a matrix stretches any direction to the least: the aspect ratio of the ellipse the unit circle becomes. for an orthogonal matrix (a circle stays a circle); for a singular one (some direction is squashed flat). For the running examples, and . Solving when carries a small error (measurement noise or rounding):
A relative error in the data can come out up to times bigger in the answer. Rule of thumb: you lose about decimal digits. float32 carries about 7 digits, bfloat16 about 3, so a problem with is fine in float64, marginal in float32 and hopeless in bfloat16 (formats themselves are on Numerical computing for ML).
The same thing happens inside a model fit: the peak of double descent is ill-conditioning. On Regularisation (section 8, whose weak-features double-descent figure draws the singular values inline), the smallest singular value of a 40-row training matrix collapses when the number of features reaches 40 (median 0.086, against 3.55 at ), so least squares divides the noise by almost zero and the test error peaks.
, . Each equation is a line; the solution is where they cross. With they cross at ; change to , a relative change of 0.035%, and the crossing jumps to , a relative change of 100%: an amplification of 2,829, within the bound of 4,002. The lines are drawn to scale: they differ in slope by 0.03 degrees, which is why the crossing is so poorly pinned down.
, because the singular values of are the squares of those of (section 7 had 2.92 against 8.55). On a harder problem the squaring is decisive. Fit a degree-6 polynomial to 50 evenly spaced points on (true coefficients , no noise) in float32, computed with NumPy by this page's script:
| Method | Condition number it works with | Relative error in the coefficients |
|---|---|---|
| Normal equations | 0.77 (77%) | |
| QR, then | 0.000018 |
Same data, same precision, same library; only the algorithm differs. exceeds 1 over float32's unit roundoff (), about , so the normal equations lose every digit. A rerun on 2026-11-07 with NumPy 2.5.4 on OpenBLAS 0.3.34 gave 0.87 for the normal equations and the same 0.000018 for QR: which digits are lost in float32 depends on the BLAS build, not whether they are.
Near a minimum a loss looks like a bowl whose curvature matrix is the Hessian (symmetric, PD at a strict minimum: section 9's ellipse). Gradient descent's step must stay below to be stable in the steepest direction, but then it crawls along the flattest, curvature . With the best fixed step, , the error shrinks by per step, . The old page stated this rate without the best-step condition; it holds only at that step size, and is slower at any other. The derivation, with the root's diag(1, 10) bowl, is on Calculus and optimisation for ML; the root's Gradient lab tab animates it.
The computed answer is off by . Two inequalities from the SVD: (the inverse stretches by at most ), and . Divide the first by and the bound follows. It is tight: equality when lies along and along .
The simplest Newton-Schulz iteration is , which maps each singular value to and leaves the singular vectors alone. Start from , whose singular values are 0.949 and 0.316. After each step the smaller one reads 0.459, 0.640, 0.829, 0.958, 0.997, 1.000 while the larger reaches 1.000 after two: six steps give , the rotation by 26.6° that is the "nearest orthogonal matrix" to . Muon's quintic version uses tuned coefficients to push small singular values up faster, in five steps. Try it on any matrix in the Matrix playground.
LoRA, MLA, GaLore and many compression papers all say "low rank". Low rank of what: pretrained weights, the updates fine-tuning makes, the gradients, or the cached keys and values? The answers differ, and real numbers settle them.
The old page said trained weight matrices "are often effectively low rank". Measured on GPT-2 small (the released weights, 2,048 tokens of WikiText-2 test text, script in this page's source folder), that does not hold in the sense that matters for compression:
k90: singular directions needed to keep 90% of the squared Frobenius norm, out of 768; "random" is a Gaussian matrix of the same shape and norm. Output error: relative error of the layer's output on the real inputs that reach it, . Loss: GPT-2's next-token loss on the same text with only that one matrix replaced by its rank-64 truncation (unchanged model: nats).
Three readings. First, every real spectrum is more concentrated than random (k90 near 300 against 391 for the attention matrices), so there is structure. Second, it is nowhere near rank 64: keeping 64 of 768 directions leaves a relative output error of 42% for the MLP input matrix and 70% to 86% for the other five. Third, how much a matrix matters is not how compressible it is: cutting the MLP input matrix to rank 64 raises the loss by 0.72 nats, cutting the key matrix by 0.20. Truncating every attention and MLP matrix in all 12 layers to 90% of its rank, which saves no parameters at all, already raises the loss from 3.17 to 3.91; at 50% of the rank it is 8.50, close to the 10.8 of a uniform guess over 50,257 tokens (). Real weights carry information in their small singular values too.
Predict first: at , how much of the query matrix's output on real text is lost? Then pick a matrix and move (the Eckart-Young truncation of section 10).
Singular values, largest first, on a log scale. Grey: a Gaussian random matrix of the same shape scaled to the same Frobenius norm. Shaded: the directions truncation drops.
Relative error of the matrix itself (Frobenius, exact from the spectrum) and of its output on 2,048 real token inputs, . The two differ because real inputs do not point equally in every direction.
Each matrix keeps the stated fraction of its full rank (768); the attention input matrix is truncated as its three 768 by 768 blocks, Q, K and V, separately. "Parameters in low-rank form" counts per matrix, capped at : below rank 384 for a square matrix, a truncated SVD is not even smaller than the original. A uniform guess over the 50,257-token vocabulary scores nats.
LoRA (Hu et al. 2021) does not compress the weights; it constrains the change. The layer computes with the pretrained frozen, of shape , of shape and . is a sum of outer products, so its rank is at most . starts at zero, so training starts exactly at the pretrained model, and after training can be merged into for free inference. For , : trainable numbers instead of , 0.39%. The method, its variants (DoRA, rsLoRA, PiSSA) and current practice are on Parameter-Efficient Fine-Tuning (PEFT); the LoRA paper page trains LoRA live on a toy where the true update is known.
Two real adapters, measured. Two public GPT-2 LoRA adapters on Hugging Face target the attention input matrix c_attn () in all 12 layers: monsterapi/gpt2_alpaca-lora (, , trained on Alpaca) and harigovind511/GPT2-Guanaco-LoRA (, , a QLoRA run on a 4-bit base). Rebuilding each and taking its SVD:
The paper's "amplification factor" (section 7.3 and appendix H.4: , with the top- singular directions of ) was " for " on GPT-3's layer 48, and "only around 2" at . On these adapters it is 0.6 to 3.4 (Alpaca) and 0.2 to 0.6 (Guanaco). It does not reproduce at this scale; GPT-2 small, different tasks, ranks and scales ( = 2 and 0.25) are all different from the paper's setting, so this is a measurement, not a refutation. The paper's other finding does hold here: projected on the update's directions is larger than on random directions (median ratio 1.6 and 1.3), so the update is correlated with the pretrained weight.
GaLore keeps full-rank weights but notices that the gradient of a weight matrix is approximately low rank (one example's gradient is exactly rank 1, section 5; a batch sums a few such outer products). Every steps it takes the SVD of the current gradient (, ), keeps the top left singular vectors as a projector (), runs Adam on the small matrix (), and maps the update back with . Adam's two moment matrices shrink from numbers to , plus for ; the paper reports that it "reduces memory usage by up to 65.5% in optimizer states" (GaLore, Zhao et al. 2024, arXiv 2403.03507).
The paper uses and scale for its LLaMA pretraining runs. For one matrix at : 33,554,432 moment numbers become .
Multi-head latent attention (DeepSeek-V2 and V3) caches one compressed vector per token and layer and rebuilds every head's keys and values from it, so the map from hidden state to keys is a product through a 512-wide bottleneck, exactly the shape: cached numbers per token per layer against 32,768 for standard multi-head attention with 128 heads of 128. The mechanism, the absorbed form and the animation are on Attention variants.
Attention itself, , with every shape and why the scores are scaled, is taught on The transformer from zero. Three facts from this page's side, measured on GPT-2 small:
c_attn holds side by side, each twelve blocks, one per head.For a sequence of token vectors stacked as the rows of (), one head computes , , (projections, section 2); is , entry the dot product of query with key (row times column, section 3); dividing by keeps the scores' spread near 1 when the entries of and have variance 1 (the variance of a sum of products is ); softmax along each row turns scores into positive weights summing to 1; multiplying by makes each output row a weighted average of value vectors, a point inside their convex hull: the column picture of section 3, with the weights as coefficients.
Treat the tiny model's input as a query and its three word rows as keys and values (): scores , weights , output
The same example is decoded symbol by symbol on the root's Reading tab ("Reading an equation in a paper").
torch.linalg.solve, cholesky_solve); never form , which is slower and less accurate, and fails badly when is large.lstsq); normal equations only when well conditioned; SVD when rank-deficient.torch.svd_lowrank), not a full SVD.matrix_rank uses ) or look at how fast the spectrum falls.| Decomposition | Form | Exists for | Cost (, leading term) | Use it for |
|---|---|---|---|---|
| LU | (with row swaps) | any square, invertible | general linear systems | |
| Cholesky | symmetric PD | PD systems, Gaussian sampling, PD test | ||
| QR | every matrix | ( for ) | least squares, orthonormal bases | |
| Eigen (symmetric) | symmetric | a small multiple of | covariances, Hessians, PCA | |
| Eigen (general) | diagonalisable square | larger multiple of | repeated application, stability | |
| SVD | every matrix | the largest multiple of of these | rank, norms, conditioning, compression, pseudo-inverse |
Leading-term operation counts from Trefethen and Bau, Numerical Linear Algebra (1997): Householder QR lecture 10, LU lecture 20, Cholesky lecture 23. Eigen and SVD solvers are iterative; their constants depend on the algorithm and whether vectors are wanted.
Treating eigenvalues as stretches. For a non-symmetric matrix they differ from the singular values (3 and 5 against 6.708 and 2.236 for ), and the eigenvectors need not be orthogonal (section 10).
Forgetting to centre before PCA. is the covariance only if every column of has mean zero. GPT-2's embeddings, with a mean cosine near 0.27 between random tokens, are a real case (section 13).
Mixing layouts and conventions. with as (out, in), in PyTorch, with GPT-2's Conv1D (in, out). Each is right; mixing two in one derivation puts transposes in the wrong places. Write the shape beside every symbol. (Derivative layouts are a separate convention, owned by Matrix calculus and backprop.)
Reading "low rank" as "small", or "small" as "unimportant". A rank-1 matrix can have a huge norm and a full-rank matrix can be tiny: rank counts directions, norms measure size. And small singular values of a pretrained weight still matter: dropping the bottom 10% of every GPT-2 matrix raises the loss from 3.17 to 3.91 (section 12).
Inverting a matrix to solve a system, or forming . 77% coefficient error against 0.0018% for QR in the float32 run of section 11.
Silent broadcasting. gives an table, not differences (section 4). Assert shapes before every reduction.
Assuming . Order matters ( in section 3), and , : both reverse the order.
| Question | Short answer | Section |
|---|---|---|
| What is the rank of an outer product ? | 1 (if ): every row is a multiple of | 3, 5 |
| Why is PSD? When is it PD? | ; PD when has full column rank | 9 |
| Eigen decomposition against SVD? | eigen: square, directions not turned, may be complex or missing; SVD: every matrix, orthonormal in and out directions, nonnegative stretches | 8, 10 |
| How do you get the best rank- approximation, and its error? | truncated SVD; spectral error , Frobenius (Eckart-Young) | 10 |
| Why does LoRA save memory, and what does it cost? | trains instead of numbers and their optimiser state; caps the update's rank at | 12 |
| What does the condition number tell you? | error amplification in solves (lose about digits); gradient descent's zig-zag on a quadratic | 11 |
| Why scale attention scores by ? | a dot product of unit-variance terms has variance ; dividing keeps softmax out of saturation | 13 |
| Derive the least-squares solution. | residual orthogonal to the columns: | 7 |
| Why are eigenvectors of a symmetric matrix orthogonal? | 9 | |
| What does the determinant mean? | signed area (volume) scale factor; product of eigenvalues; zero iff singular | 2, 8 |
Type any 2x2 or 3x3 matrix, or pick a preset from the page, and read off everything the Reading tab defines: what it does to the plane, its eigenvalues and eigenvectors, its SVD, rank, determinant, norms and condition number. The 2x2 picture can be played through the SVD's three steps, and the orthogonalise button runs the Newton-Schulz iteration of Reading section 11 one step at a time.
Computed in the page with closed forms for 2x2 and Jacobi rotations on for 3x3, in double precision. Because singular values come from the eigenvalues of , any below about of the largest are reported as 0, so a matrix with condition number above about reads as rank-deficient here (a library SVD, which works on directly, resolves down to about ).
Reading times for knowledge base pages are each page's own stated time where it gives one, otherwise estimated from the length of its Reading tab (about 230 words a minute). Times for outside resources are for the part recommended, checked on 5 October 2026. Every link opens in a new tab.
Any 2x2 or 3x3 matrix: its action on the plane played through the SVD, eigenvalues and eigenvectors, singular values and vectors, rank, determinant, norms, condition number, PD test, and step-by-step orthogonalisation.
Which maths each part of ML uses, and one training step of a tiny language model with every number; this page's running example (, ) comes from it. Tabs: Notation decoder (symbols, shapes, the two derivative layouts), Gradient lab (the tiny model live, curvature bowl with gradient descent, momentum, Adam and Newton). 13 min, plus 4 in closed details.
Jacobians, numerator and denominator layouts, gradients of matrix expressions (including least squares and log det), vector-Jacobian products, autodiff, and FLOP counting from einsum strings. The old version of this page's matrix-calculus section moved there. About 45 min.
Random variables and distributions to losses, MLE, MAP and Bayes; covariance matrices (symmetric PSD, section 9 here) and Gaussians. 32 min, plus 16 in closed details.
Estimation, bias and variance, the bootstrap and hypothesis tests. 33 min, plus 6 in closed details.
Derivatives to convexity, Hessians, Newton and Lagrange; the derivation of gradient descent's rate quoted in section 11. 32 min, plus 11 in closed details.
Entropy, cross-entropy, KL and mutual information; dot products reappear as the logits inside InfoNCE. 38 min, plus 8 in closed details.
Condition numbers of computations, floating point and stable algorithms; precision formats and the stable softmax. 40 min, plus 9 in closed details.
ELBO, VAEs and diffusion, where the Cholesky sampling of section 9 becomes the reparameterisation trick. 23 min, plus 18 in closed details.
The paper's argument, every number checked, and LoRA trained live on a toy whose true update is known (spectra, subspace similarity, Table 7 on the toy). About 21 min.
LoRA, QLoRA, DoRA, PiSSA and the rest in practice: which matrices, which rank, what it costs. 26 min, plus 2 in closed details.
Multi-head latent attention animated against standard attention, to scale (576 against 32,768 cached numbers), and the other ways of shrinking the KV cache. 37 min, plus 28 in closed details.
Attention and the decoder block with every shape, which section 13 here reads as linear algebra. 40 min, plus 22 in closed details.
Adam, Muon and Lion in practice: preconditioning and orthogonalised updates as optimisers. 34 min, plus 14 in closed details.
How normalisation and initialisation keep activations and curvature well conditioned. 23 min, plus 14 in closed details.
L1 against L2 penalties and weight decay, the norms of section 6 used as regularisers. 32 min, plus 8 in closed details.
Linear and ridge regression, PCA and other uses of the decompositions here. 29 min, plus 8 in closed details.
Cosine similarity at work in contrastive losses and embedding spaces. About 31 min.
The Transformer built and trained live; attention's and on real weights. 20 min, plus 2 in closed details.
Rotary position embeddings: queries and keys rotated by orthogonal 2x2 blocks. About 22 min.
Number formats and what compression does to real weights, the other way to shrink a matrix. 34 min, plus 11 in closed details.
16 animated videos: vectors, matrices as maps, determinants, change of basis, eigenvectors. The source of this page's "columns are where the axes land". When: first. About 3 h.
Cambridge University Press 2018, free PDF. Chapters 1 to 5 (vectors, norms, independence), 6 to 10 (matrices, products), 12 to 13 (least squares). Gentle and applied. When: to rebuild technique. About 10 to 12 h for those chapters.
34 recorded lectures. For ML: 1 to 3, 9 to 11 (independence, the four subspaces), 14 to 17 (orthogonality, projections, least squares, Gram-Schmidt), 21 to 22 and 25 to 27 (eigenvalues, symmetric and PD matrices), 29 to 30 (SVD). When: alongside sections 5 to 10. About 12 h for the subset (25 h for all).
Cambridge University Press 2020, free PDF. Chapter 2 (linear algebra), 3 (analytic geometry: norms, inner products, projections), 4 (matrix decompositions: determinant, eigen, Cholesky, SVD, matrix approximation), 10 (PCA). When: for derivations in ML notation. About 12 to 15 h for chapters 2 to 4 and 10.
Spring 2018, with the book Linear Algebra and Learning from Data (2019). Lectures 1 to 9 (factorisations, SVD, PCA, norms) and 21 to 27 (optimisation, backprop). When: after step 3, to connect to ML. About 12 h.
SIAM 1997 (not free). Lectures 4 and 5 (SVD), 7 to 11 (QR, Gram-Schmidt, Householder, least squares), 12 to 15 (conditioning and stability), 20 to 23 (LU, Cholesky). The best short account of why algorithms lose digits; the operation counts in section 14 are from here. When: for section 11 in depth. About 10 h for those lectures.
4th edition, Springer 2024, open access. Proofs without determinants: chapters 2 and 3 (bases, rank-nullity), 5 (eigenvalues), 7 (spectral theorem, SVD). When: for research, when you need the proofs. About 20 h for those chapters.
Version of 15 November 2012, 72 pages of identities. Do not read; look things up. Reference.
Sections 4 (the method), 7 (the rank of the update; Table 7's amplification factor) and appendix H. About 1 h.
200 parameters reach 90% on MRPC; why fine-tuning is low dimensional. About 45 min.
Algorithm 1 and section 4 (memory). About 45 min.
Section 2.1, multi-head latent attention. About 30 min for that section.
Section 2: language modelling as matrix factorisation and the rank bound. About 40 min.
The orthogonalised update and its Newton-Schulz iteration. About 25 min.
Attention heads as low-rank QK and OV matrices on the residual stream. About 1 h 30 min.
LoRA initialised from the top singular directions of the weight. About 40 min.
Dividing by , estimated by one power-iteration step per update. About 40 min.
Section 2: exploding and vanishing gradients as an eigenvalue condition. About 45 min.
The approximation of one matrix by another of lower rank, Psychometrika 1(3). About 20 min.