Skip to content
Mathematical foundations Foundation 24 min read

Matrices as linear maps

A matrix is not a table of numbers; it is a function that moves every point of space in a straight-lines-stay-straight way, and its columns tell you exactly where the axes land. Almost every parameter in a neural network lives in such a matrix, and almost every FLOP a GPU spends is a matrix multiply.

10,000 ft

A neural network is mostly matrices with simple non-linear functions in between. Each linear layer, each attention projection (\(W_Q, W_K, W_V, W_O\)), each MLP in a transformer and each embedding table is a matrix, and in a large language model these matrices hold over 99% of the parameters. Training and inference cost is dominated by multiplying them (compute maths), which is why GPUs are built around matrix-multiply units (how a GPU works). Understanding a matrix as a linear map, a geometric transformation of space, is what lets you reason about what a layer can and cannot do, why depth needs non-linearity, how gradients flow backward (through transposes), and what low-rank tricks such as LoRA really change.

2,000 ft

A function \(f\) is linear if it preserves addition and scaling. Any linear map from \(\mathbb{R}^n\) to \(\mathbb{R}^m\) is completely determined by where it sends the \(n\) basis vectors, and writing those \(n\) images as columns gives an \(m\times n\) matrix \(A\). Applying the map is the matrix–vector product \(A\mathbf{x}\); doing one map after another is the matrix product, which is why matrix multiplication is defined the odd way it is and why order matters. The determinant measures how the map scales volume; the rank counts how many dimensions survive; the transpose is the map that carries gradients backward.

One matrix, four readings
One matrix, four readings. matrix A (m × n), columns = images of the axes, rows = n-dim detectors (dot products), product AB = do B, then A, det = volume scale · rank = surviving dims, where e_i goes, what each output measures, composition, geometryOne matrix, four readings. matrix A (m × n), columns = images of the axes, rows = n-dim detectors (dot products), product AB = do B, then A, det = volume scale · rank = surviving dims, where e_i goes, what each output measures, composition, geometry

Ground level

What "linear" means

A function \(f:\mathbb{R}^n\to\mathbb{R}^m\) is linear when, for all vectors \(\mathbf{x},\mathbf{y}\) and scalars \(\alpha,\beta\),

\[ f(\alpha\mathbf{x} + \beta\mathbf{y}) = \alpha f(\mathbf{x}) + \beta f(\mathbf{y}). \]

Geometrically: grid lines stay straight, parallel lines stay parallel and evenly spaced, and the origin stays put. Rotations, reflections, stretches, shears and projections are linear. Translations (shifting everything by \(\mathbf{b}\)) are not, because they move the origin; \(\mathbf{x}\mapsto W\mathbf{x}+\mathbf{b}\) is called affine. A neural network's "linear layer" is affine, but the bias is easy to absorb (append a constant 1 to \(\mathbf{x}\)), so everything on this page applies.

The payoff of linearity is enormous: to know \(f\) everywhere, you only need to know it on a basis. Every \(\mathbf{x}\) is \(x_1\mathbf{e}_1 + \dots + x_n\mathbf{e}_n\), so

\[ f(\mathbf{x}) = x_1 f(\mathbf{e}_1) + \dots + x_n f(\mathbf{e}_n). \]

Write the \(n\) vectors \(f(\mathbf{e}_j)\) as the columns of a matrix \(A\) and this sum is the matrix–vector product \(A\mathbf{x}\). That is the whole definition of a matrix: the columns are where the basis vectors land.

A worked example: read a matrix by its columns

\[ A = \begin{pmatrix} 2 & 1 \\ 0 & 1 \end{pmatrix}. \]

Column 1 says \(\mathbf{e}_1 = (1,0)\) goes to \((2,0)\): the x-axis is stretched by 2. Column 2 says \(\mathbf{e}_2 = (0,1)\) goes to \((1,1)\): the y-axis tips over to the right, a shear. The unit square, with corners \((0,0),(1,0),(1,1),(0,1)\), lands on the parallelogram \((0,0),(2,0),(3,1),(1,1)\), which has area 2. And \(\det A = 2\cdot 1 - 1\cdot 0 = 2\): the determinant is that area scale factor (all checked in Build it).

e₁e₂area 1Ae₁ = (2, 0)Ae₂ = (1, 1)area 2 = det AA
A = [[2, 1], [0, 1]] sends e₁ to its first column and e₂ to its second. Everything else follows by linearity: the unit square becomes a parallelogram of area |det A| = 2.

Now play. The widget applies any 2×2 matrix to the grid and the unit circle. Try a rotation, a reflection (\(\det<0\): the grid flips), a projection (\(\det = 0\): the plane collapses onto a line), and look for the directions that only stretch, never turn. Those are the eigenvectors of the next page but one.

The matrix–vector product, two ways

For \(A\in\mathbb{R}^{m\times n}\) and \(\mathbf{x}\in\mathbb{R}^n\), \(A\mathbf{x}\in\mathbb{R}^m\) has entries \((A\mathbf{x})_i = \sum_j A_{ij}x_j\). Read it two ways:

  • Row view, "detectors": entry \(i\) of the output is the dot product of row \(i\) with \(\mathbf{x}\). Each row is a pattern; the output says how strongly \(\mathbf{x}\) matches each pattern. This is the neuron view: a layer with \(m\) neurons is \(m\) dot products (vectors).
  • Column view, "mixing": the output is \(x_1(\text{col}_1) + \dots + x_n(\text{col}_n)\), a weighted mix of the columns. This is the where can the output go view: only into the span of the columns.

Both are always true at once. An embedding lookup is the column view with a one-hot \(\mathbf{x}\): multiplying the embedding matrix by the one-hot vector for token 42 just selects column 42, which is why frameworks implement it as indexing rather than multiplication.

Matrix multiplication is composition

If \(B\) maps \(\mathbb{R}^p\to\mathbb{R}^n\) and \(A\) maps \(\mathbb{R}^n\to\mathbb{R}^m\), doing \(B\) then \(A\) is again linear, so it has a matrix, and that matrix is defined to be \(AB\). Its \(j\)-th column must be where \(\mathbf{e}_j\) ends up: \(A(B\mathbf{e}_j) = A(\text{col}_j B)\). Expanding gives the familiar formula

\[ (AB)_{ij} = \sum_{k=1}^{n} A_{ik}B_{kj}, \qquad (m\times n)(n\times p) \to (m\times p). \]

The "row times column" rule is not a convention someone chose; it is forced by wanting the product to mean "do one map, then the other". Read right to left: \(AB\mathbf{x}\) applies \(B\) first.

Four equivalent ways to see \(C = AB\), each useful somewhere:

View Statement Where it helps
Entries \(C_{ij} = (\text{row}_i A)\cdot(\text{col}_j B)\) attention scores \(QK^\top\): every query dotted with every key
Columns \(\text{col}_j C = A\,(\text{col}_j B)\) applying one layer to a batch of inputs stored as columns
Rows \(\text{row}_i C = (\text{row}_i A)\,B\) the PyTorch convention: a batch of row vectors times a weight matrix
Outer products \(C = \sum_k (\text{col}_k A)(\text{row}_k B)\) low-rank structure: a rank-\(r\) matrix is a sum of \(r\) outer products (LoRA, SVD)

Order matters. Let \(R\) rotate by 90° and \(S\) shear: \(R=\begin{pmatrix}0&-1\\1&0\end{pmatrix}\), \(S=\begin{pmatrix}1&1\\0&1\end{pmatrix}\). Then

\[ SR = \begin{pmatrix}1&-1\\1&0\end{pmatrix} \neq RS = \begin{pmatrix}0&-1\\1&1\end{pmatrix}. \]

Rotating then shearing is not shearing then rotating. Matrix multiplication is associative, \((AB)C = A(BC)\), but not commutative.

Associativity is a performance tool. Multiplying an \(m\times n\) by an \(n\times p\) matrix takes \(mnp\) multiply–adds, conventionally counted as \(2mnp\) FLOPs. For a vector \(\mathbf{x}\) and square \(A,B\) of size \(d\): \((AB)\mathbf{x}\) costs about \(2d^3 + 2d^2\) FLOPs, while \(A(B\mathbf{x})\) costs \(4d^2\). At \(d=4096\) that is 137 GFLOP versus 67 MFLOP, a factor of about 2,000 for the same answer. Reverse-mode autodiff is, at heart, choosing the cheap bracketing of a long product of Jacobians (chain rule and Jacobians).

Why depth needs non-linearity

Stack three linear layers: \(W_3(W_2(W_1\mathbf{x})) = (W_3W_2W_1)\mathbf{x}\). That is one matrix. A hundred linear layers can represent nothing a single one cannot (Build it confirms it to every digit). Insert a non-linear function between them, such as \(\operatorname{ReLU}(z)=\max(0,z)\), and the composition stops collapsing: the network becomes piecewise linear with a number of pieces that can grow exponentially with depth. That is why every architecture alternates matrices with non-linearities (activations).

Linear layers collapse; non-linearities keep depth meaningful
Linear layers collapse; non-linearities keep depth meaningful. x, W₁, W₂, W₃, y = (W₃W₂W₁)x, W₁ then ReLU, W₂ then ReLU, piecewise-linear, many piecesLinear layers collapse; non-linearities keep depth meaningful. x, W₁, W₂, W₃, y = (W₃W₂W₁)x, W₁ then ReLU, W₂ then ReLU, piecewise-linear, many pieces

Deep linear networks are still studied, because although their function is linear, their training dynamics are not: Saxe, McClelland and Ganguli (2013) solved them exactly and found the plateaus and sudden drops seen in real networks.

Determinant: how volume scales

The determinant \(\det A\) of a square matrix is the factor by which \(A\) scales areas (2-D) or volumes (\(n\)-D), with a sign that says whether orientation is flipped. For \(2\times 2\),

\[ \det\begin{pmatrix}a&b\\c&d\end{pmatrix} = ad - bc . \]

Three facts carry most of the weight:

  • \(\det A = 0\) exactly when \(A\) squashes space into a lower dimension, so some non-zero vector maps to \(\mathbf{0}\) and the map cannot be undone.
  • \(\det(AB) = \det A\,\det B\): scale factors multiply under composition.
  • \(\det A^{-1} = 1/\det A\).

In AI the determinant matters most in generative modelling: normalising flows transform a simple density through invertible maps, and the change-of-variables formula needs \(\log\lvert\det J\rvert\) of each map's Jacobian, so flow layers are designed to make that determinant cheap (triangular Jacobians) (generative modelling). Multivariate Gaussian densities contain \(\det\Sigma\) for the same reason: it normalises volume (distributions).

Rank, column space and null space

The column space (range) of \(A\) is the span of its columns: every output the map can produce. Its dimension is the rank. The null space is every \(\mathbf{x}\) with \(A\mathbf{x}=\mathbf{0}\): the directions the map destroys. They are tied by the rank–nullity theorem:

\[ \operatorname{rank}(A) + \dim\operatorname{null}(A) = n \quad(\text{number of columns}). \]

Every input dimension either survives into the output or is annihilated. Example: \(L=\mathbf{u}\mathbf{v}^\top\) with \(\mathbf{u}=(1,2)\), \(\mathbf{v}=(3,1)\) gives \(L=\begin{pmatrix}3&1\\6&2\end{pmatrix}\). Every output is a multiple of \((1,2)\), so the rank is 1; the null space is the line through \((1,-3)\) (check: \(L(1,-3)^\top = (0,0)\)); \(1 + 1 = 2\) columns.

Why rank is central in modern AI. A \(d\times d\) matrix of rank \(r\) factors as \(BA\) with \(B\in\mathbb{R}^{d\times r}\), \(A\in\mathbb{R}^{r\times d}\), so it needs \(2dr\) numbers instead of \(d^2\). LoRA (Hu et al., 2021) fine-tunes a model by learning only such a low-rank update \(\Delta W = BA\); at \(d=4096\), \(r=8\) that is 65,536 parameters instead of about 16.8 million per matrix, 256× fewer. That this works at all is evidence that fine-tuning changes live in a low-dimensional subspace (Aghajanyan et al., 2020). Multi-head attention's per-head projections, bottleneck layers and the key–value compression in some efficient attention variants are all rank constraints.

Inverses and solving linear systems

A square \(A\) is invertible if some \(A^{-1}\) satisfies \(A^{-1}A = AA^{-1} = I\). All of these are equivalent: \(\det A\neq 0\); rank \(n\); null space \(\{\mathbf{0}\}\); columns form a basis; \(A\mathbf{x}=\mathbf{b}\) has exactly one solution for every \(\mathbf{b}\). For \(2\times 2\),

\[ \begin{pmatrix}a&b\\c&d\end{pmatrix}^{-1} = \frac{1}{ad-bc}\begin{pmatrix}d&-b\\-c&a\end{pmatrix}. \]

Worked: \(B = \begin{pmatrix}4&1\\2&3\end{pmatrix}\), \(\det B = 10\), \(B^{-1}=\begin{pmatrix}0.3&-0.1\\-0.2&0.4\end{pmatrix}\), so \(B\mathbf{x} = (1,2)\) has solution \(\mathbf{x} = (0.1, 0.6)\).

Solve, don't invert

In code, compute np.linalg.solve(A, b) rather than np.linalg.inv(A) @ b. Solving (LU factorisation plus two triangular solves) is cheaper and more accurate. And when \(A\) is nearly singular (a large condition number, the ratio of largest to smallest singular value), small errors in \(\mathbf{b}\) become large errors in \(\mathbf{x}\) whichever method you use. See numerical computing.

The transpose is the backward map

The transpose \(A^\top\) swaps rows and columns, \((A^\top)_{ij} = A_{ji}\), and \((AB)^\top = B^\top A^\top\). Its geometric meaning is less obvious and more important: \(A^\top\) is the unique map with

\[ (A\mathbf{x})\cdot\mathbf{y} = \mathbf{x}\cdot(A^\top\mathbf{y}) \quad\text{for all }\mathbf{x},\mathbf{y}. \]

\(A\) carries vectors forward from input space to output space; \(A^\top\) carries "measurements" (things you dot against) backward from output space to input space. That is exactly what backpropagation needs. If \(\mathbf{y}=W\mathbf{x}\) and a loss \(L\) has gradient \(\mathbf{g}=\partial L/\partial\mathbf{y}\), then

\[ \frac{\partial L}{\partial\mathbf{x}} = W^\top\mathbf{g}, \qquad \frac{\partial L}{\partial W} = \mathbf{g}\,\mathbf{x}^\top . \]

Every backward pass is a sequence of multiplications by transposed weight matrices (derivatives and gradients, backpropagation). In practice the backward pass costs about twice the forward pass in FLOPs because it computes both of these products, which is where the "6 FLOPs per parameter per token" rule of thumb for training comes from (2 forward + 4 backward; Kaplan et al., 2020, Section 2.1).

A zoo of special matrices

Matrix Definition Geometry Where in AI
Identity \(I\) ones on the diagonal does nothing residual connections compute \(\mathbf{x} + F(\mathbf{x})\), i.e. \((I + F)\) for a linear \(F\) (residual networks)
Diagonal zeros off the diagonal stretch each axis the per-feature gains in LayerNorm/RMSNorm; Adam's per-parameter step sizes
Orthogonal \(Q\) \(Q^\top Q = I\) rotation or reflection; preserves lengths and angles orthogonal initialisation; RoPE rotates query/key pairs (positional encoding)
Symmetric \(A = A^\top\) stretches along perpendicular axes (spectral theorem) covariance matrices, Hessians, kernel matrices
Positive definite \(\mathbf{x}^\top A\mathbf{x} > 0\) for \(\mathbf{x}\neq\mathbf{0}\) a "bowl"; defines an inner product covariances; the Hessian at a strict minimum
Lower triangular zeros above the diagonal each output depends only on earlier inputs the causal mask in a decoder: token \(i\) attends to tokens \(\le i\)
Permutation one 1 per row and column reorders coordinates shuffling, routing tokens to experts
Low rank \(\operatorname{rank} r \ll n\) collapses onto an \(r\)-dim subspace LoRA, matrix factorisation, compression

Counting a transformer's matrices

Matrices are where the parameters are, and counting them is a skill worth having. In a standard transformer layer of width \(d\) with the usual 4× MLP: attention has four \(d\times d\) matrices (\(W_Q, W_K, W_V, W_O\)), \(4d^2\) parameters; the MLP has a \(d\times 4d\) and a \(4d\times d\) matrix, \(8d^2\). So each layer holds about \(12d^2\) parameters, and the whole stack \(N \approx 12\,n_\text{layer}\,d^2\), the approximation used by Kaplan et al. (2020). For GPT-3's largest model, \(n_\text{layer}=96\) and \(d = 12{,}288\) (Brown et al., 2020):

\[ 12 \times 96 \times 12{,}288^2 = 173{,}946{,}175{,}488 \approx 174\text{ billion}, \]

plus a \(50{,}257 \times 12{,}288\) token-embedding matrix (about 0.62 billion). That matches the advertised 175B. Biases and normalisation gains are a rounding error. Every one of those parameters is an entry of some matrix acting as a linear map.

History

From elimination to tensor cores

Solving simultaneous linear equations by elimination appears in the Chinese Nine Chapters on the Mathematical Art (compiled by around the 1st century CE) and was systematised by Gauss in the early 1800s. Determinants came before matrices (Leibniz, Cramer, Cauchy). James Joseph Sylvester coined the word matrix in 1850, and Arthur Cayley's A Memoir on the Theory of Matrices (1858) defined matrix multiplication as composition and treated matrices as algebraic objects. The abstract notion of a linear map on a vector space was set out by Giuseppe Peano in 1888. In 1969 Volker Strassen showed that two \(2\times 2\) matrices can be multiplied with 7 multiplications instead of 8 (Gaussian elimination is not optimal), so \(n\times n\) products need fewer than \(n^3\) operations. In 2022 DeepMind's AlphaTensor used reinforcement learning to search for such algorithms and, for \(4\times 4\) matrices in arithmetic modulo 2, found one with 47 multiplications, improving on Strassen's 49 (Fawzi et al., 2022). In practice GPUs still use the ordinary \(O(n^3)\) algorithm, made fast by tensor cores that multiply small matrix tiles in hardware.

First principles

Why matrices at all? Start from the single demand that a map respects addition and scaling. Then (shown above) it is fixed by its values on a basis, and any choice of those values gives a valid linear map. So linear maps \(\mathbb{R}^n\to\mathbb{R}^m\) and \(m\times n\) arrays of numbers are in exact one-to-one correspondence. The matrix is just the map written down in coordinates.

Why this multiplication rule? Because we want \((AB)\mathbf{x} = A(B\mathbf{x})\) for every \(\mathbf{x}\). Apply both sides to \(\mathbf{e}_j\): column \(j\) of \(AB\) must equal \(A\) times column \(j\) of \(B\). There is no freedom left. Associativity then comes for free, because function composition is associative. Non-commutativity comes for free too, because "put on socks, then shoes" differs from "shoes, then socks".

Why this determinant? Ask for a function of \(n\) column vectors that measures signed volume. Volume should (i) be linear in each column separately (doubling one edge doubles the volume; volumes along an edge add), (ii) vanish when two columns are equal (a flat box), and (iii) give 1 for the unit cube. These three demands determine a unique function, and it is the determinant. From them: swapping two columns flips the sign, adding a multiple of one column to another changes nothing (shearing a box preserves its volume), and \(\det(AB) = \det A\det B\) because scaling volume by \(\det B\) and then by \(\det A\) scales it by the product.

Why are linear maps the building block of learning? Three reasons. They are the simplest functions that can mix all their inputs. Their composition, inversion and gradients have closed forms. And by Taylor's theorem every smooth function looks linear when you zoom in close enough, which is exactly what the derivative is (derivatives and gradients). Networks interleave learnable linear maps, which do the heavy lifting cheaply on GPUs, with fixed non-linearities that make the whole thing expressive.

What breaks if you drop linearity? You lose the basis-determines-everything property, so a map from \(\mathbb{R}^{4096}\) needs far more than \(4096\times m\) numbers to describe. You lose composition as multiplication, and with it the GPU's reason to exist. The art of deep learning is keeping almost everything linear and spending non-linearity only where it buys expressiveness.

The maths

Shapes. \(A\in\mathbb{R}^{m\times n}\) maps \(\mathbb{R}^n\to\mathbb{R}^m\). Product \((m\times n)(n\times p) = m\times p\); the inner dimensions must agree. Cost \(mnp\) multiply–adds (\(2mnp\) FLOPs).

Rules. \((AB)C = A(BC)\); \(A(B+C) = AB+AC\); in general \(AB\ne BA\); \((AB)^\top = B^\top A^\top\); \((AB)^{-1} = B^{-1}A^{-1}\) (undo the last step first); \(\det(AB)=\det A\det B\); \(\det A^\top = \det A\); \(\operatorname{rank}(AB)\le\min(\operatorname{rank}A,\operatorname{rank}B)\).

Derivation: \((AB)^\top = B^\top A^\top\) from the adjoint property

For all \(\mathbf{x},\mathbf{y}\): \((AB\mathbf{x})\cdot\mathbf{y} = (B\mathbf{x})\cdot(A^\top\mathbf{y}) = \mathbf{x}\cdot(B^\top A^\top\mathbf{y})\). The transpose of \(AB\) is the unique matrix with \((AB\mathbf{x})\cdot\mathbf{y} = \mathbf{x}\cdot((AB)^\top\mathbf{y})\) for all \(\mathbf{x},\mathbf{y}\), so \((AB)^\top = B^\top A^\top\). Index form: \(((AB)^\top)_{ij} = (AB)_{ji} = \sum_k A_{jk}B_{ki} = \sum_k (B^\top)_{ik}(A^\top)_{kj}\).

Derivation: the gradients of a linear layer

Let \(\mathbf{y} = W\mathbf{x}\) with \(W\in\mathbb{R}^{m\times n}\) and a scalar loss \(L(\mathbf{y})\) with \(\mathbf{g} = \partial L/\partial\mathbf{y}\in\mathbb{R}^m\). Since \(y_i = \sum_j W_{ij}x_j\):

\[ \frac{\partial L}{\partial x_j} = \sum_i \frac{\partial L}{\partial y_i}\frac{\partial y_i}{\partial x_j} = \sum_i g_i W_{ij} = (W^\top\mathbf{g})_j , \]
\[ \frac{\partial L}{\partial W_{ij}} = \frac{\partial L}{\partial y_i}\frac{\partial y_i}{\partial W_{ij}} = g_i x_j = (\mathbf{g}\mathbf{x}^\top)_{ij}. \]

For a batch stored as rows, \(Y = XW^\top\) with \(X\in\mathbb{R}^{B\times n}\), the same reasoning gives \(\partial L/\partial X = G W\) and \(\partial L/\partial W = G^\top X\) with \(G\in\mathbb{R}^{B\times m}\): the shapes tell you the answer. The forward pass is one matmul (\(2Bmn\) FLOPs) and the backward is two (\(4Bmn\)), the source of the 2 + 4 = 6 FLOPs per parameter per token.

Rank–nullity, sketched

Pick a basis \(\mathbf{n}_1,\dots,\mathbf{n}_k\) of the null space and extend it to a basis of \(\mathbb{R}^n\) by adding \(\mathbf{v}_1,\dots,\mathbf{v}_{n-k}\). Every output \(A\mathbf{x}\) is a combination of \(A\mathbf{v}_1,\dots,A\mathbf{v}_{n-k}\) (the \(A\mathbf{n}_i\) are zero), and these are independent (if \(\sum c_iA\mathbf{v}_i = \mathbf{0}\) then \(\sum c_i\mathbf{v}_i\) is in the null space, which forces all \(c_i=0\)). So the column space has dimension \(n-k\): rank + nullity = \(n\).

Change of basis. If the columns of an invertible \(P\) are a new basis, a vector with new coordinates \(\mathbf{x}'\) has standard coordinates \(P\mathbf{x}'\), and the map \(A\) written in the new basis is \(P^{-1}AP\). Matrices related this way are similar: same map, different coordinates. They share determinant, rank, trace and eigenvalues. Diagonalisation (eigenvectors, SVD and PCA) is the search for a \(P\) that makes \(P^{-1}AP\) diagonal.

Build it

NumPy: columns as images of the axes, determinant as area, non-commutativity, the collapse of stacked linear layers, a rank-1 matrix and its null space, and solving a system.

import numpy as np
np.set_printoptions(precision=3, suppress=True)

# 1. Columns are where the basis vectors land
A = np.array([[2.0, 1.0],
              [0.0, 1.0]])            # a shear-and-stretch
print("A e1 =", A @ [1, 0], " A e2 =", A @ [0, 1])

# 2. The unit square maps to a parallelogram whose area is |det A|
square = np.array([[0, 1, 1, 0],
                   [0, 0, 1, 1]], dtype=float)   # corners as columns
P = A @ square
x, y = P
area = 0.5 * abs(x @ np.roll(y, -1) - y @ np.roll(x, -1))   # shoelace formula
print("image of square:\n", P, "\narea =", area, " det =", np.linalg.det(A))

# 3. Order matters: rotate-then-shear vs shear-then-rotate
t = np.pi / 2
R = np.array([[np.cos(t), -np.sin(t)], [np.sin(t), np.cos(t)]])
S = np.array([[1.0, 1.0], [0.0, 1.0]])
print("S @ R =\n", S @ R, "\nR @ S =\n", R @ S)

# 4. Stacking linear layers without a nonlinearity collapses to one matrix
rng = np.random.default_rng(0)
W1, W2, W3 = (rng.standard_normal((4, 4)) for _ in range(3))
xin = rng.standard_normal(4)
deep = W3 @ (W2 @ (W1 @ xin))
W = W3 @ W2 @ W1
print("3 layers:", deep, "\n1 layer: ", W @ xin)

# 5. A rank-1 matrix squashes the plane onto a line
L = np.outer([1.0, 2.0], [3.0, 1.0])   # u v^T
print("rank:", np.linalg.matrix_rank(L), " det:", round(np.linalg.det(L), 12))
print("null-space direction (L @ [1,-3]):", L @ [1.0, -3.0])

# 6. Solve, don't invert
B = np.array([[4.0, 1.0], [2.0, 3.0]]); b = np.array([1.0, 2.0])
print("solve:", np.linalg.solve(B, b), " check B @ x =", B @ np.linalg.solve(B, b))

Output:

A e1 = [2. 0.]  A e2 = [1. 1.]
image of square:
 [[0. 2. 3. 1.]
 [0. 0. 1. 1.]] 
area = 2.0  det = 2.0
S @ R =
 [[ 1. -1.]
 [ 1.  0.]] 
R @ S =
 [[ 0. -1.]
 [ 1.  1.]]
3 layers: [ 2.996 13.957 16.421 15.195] 
1 layer:  [ 2.996 13.957 16.421 15.195]
rank: 1  det: 0.0
null-space direction (L @ [1,-3]): [0. 0.]
solve: [0.1 0.6]  check B @ x = [1. 2.]

Things to try

  • Insert np.maximum(0, ·) (ReLU) between the three layers in step 4. The two outputs now differ; find an input where the deep network and the single collapsed matrix disagree most.
  • Write the gradient of loss = (W @ x).sum() with respect to x and W by hand using \(W^\top\mathbf{g}\) and \(\mathbf{g}\mathbf{x}^\top\), then check numerically with finite differences.
  • Time (A @ B) @ x against A @ (B @ x) for \(d = 2000\) on your machine. Predict the ratio first from the FLOP counts.
  • Build a \(512\times 512\) matrix as B @ A with B of shape \(512\times 8\) and A of shape \(8\times 512\). Confirm its rank is 8 and count the parameters in both forms.
  • Count the parameters of a transformer with \(n_\text{layer} = 32\) and \(d = 4096\) using \(12\,n_\text{layer}d^2\).

Common misconceptions

  • "A matrix is a grid of numbers." The grid is a coordinate description. The object is the map, and the same map has different grids in different bases.
  • "Linear layers make networks linear." Only if nothing non-linear sits between them. With one non-linearity the composition is non-linear; without any, depth is wasted.
  • "The inverse is how you solve systems." Use a solver; explicit inverses are slower and less accurate.
  • "Transpose is just a reshuffle." It is the adjoint: the map that carries gradients backward. Getting this right is half of deriving backprop.

Check yourself

Write the matrix that rotates the plane by 90° anticlockwise, using only the columns-are-images rule.

\(\mathbf{e}_1=(1,0)\mapsto(0,1)\) and \(\mathbf{e}_2=(0,1)\mapsto(-1,0)\), so \(R = \begin{pmatrix}0&-1\\1&0\end{pmatrix}\). Its determinant is 1: area and orientation are preserved.

What are the shapes and FLOPs of Q Kᵀ for a sequence of 2,048 tokens and head dimension 128?

\(Q, K\in\mathbb{R}^{2048\times 128}\), \(K^\top\in\mathbb{R}^{128\times 2048}\), so \(QK^\top\in\mathbb{R}^{2048\times 2048}\) and costs \(2\times 2048\times 128\times 2048 \approx 1.07\) GFLOP per head. The output grows with the square of the sequence length: the root of attention's quadratic cost (long context).

A matrix maps ℝ⁵ → ℝ³. What is the smallest possible dimension of its null space?

Rank is at most 3 (only 3 output dimensions), so by rank–nullity the null space has dimension at least \(5 - 3 = 2\). Any map from a bigger space to a smaller one destroys some directions.

If det A = 3 and det B = −2 for 4×4 matrices, what are det(AB), det(A⁻¹) and det(2A)?

\(\det(AB) = -6\). \(\det(A^{-1}) = 1/3\). \(\det(2A) = 2^4\cdot 3 = 48\), because scaling every one of 4 edges by 2 scales volume by \(2^4\).

For y = W x with W of shape 3×5, what are the shapes of ∂L/∂x and ∂L/∂W, and how do you compute them from g = ∂L/∂y?

\(\mathbf{g}\in\mathbb{R}^3\). \(\partial L/\partial\mathbf{x} = W^\top\mathbf{g}\in\mathbb{R}^5\) and \(\partial L/\partial W = \mathbf{g}\mathbf{x}^\top\in\mathbb{R}^{3\times 5}\): same shape as \(W\), as every parameter gradient must be.

Why does a LoRA update of rank 8 on a 4096×4096 matrix have 65,536 parameters, and what can it not do?

\(\Delta W = BA\) with \(B\in\mathbb{R}^{4096\times 8}\), \(A\in\mathbb{R}^{8\times 4096}\): \(2\times 4096\times 8 = 65{,}536\). It can only change the layer's outputs within an 8-dimensional subspace (the column space of \(B\)) and only respond to 8 input directions (the row space of \(A\)); a change requiring rank 9 or more is out of reach.

Hard: show that a composition of affine maps is affine, and explain why a bias does not rescue a deep network without non-linearities.

\(W_2(W_1\mathbf{x}+\mathbf{b}_1)+\mathbf{b}_2 = (W_2W_1)\mathbf{x} + (W_2\mathbf{b}_1 + \mathbf{b}_2)\), which has the same form \(W\mathbf{x}+\mathbf{b}\). By induction any depth collapses to a single affine map, whose decision boundaries are single hyperplanes. Biases shift; only non-linearities bend.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Where this leads