1.3Matrices as transformations
A matrix is a machine that moves every point in space at once, rotating, stretching, shearing or flattening it. Every neural-network layer is one, plus a shift.
From one dot product to many
In the previous lesson a single neuron took one dot product: its weight vector against the input. A real layer has many neurons, each with its own weight vector, all looking at the same input. Stack those weight vectors as the rows of a grid and you have a matrixMatrixA rectangular grid of numbers. Multiplying a vector by a matrix applies a linear transformation such as a rotation, scaling or projection. . Multiplying the input vector by it computes all the dot products at once:
That is the “list of dot products” view, and it is exactly how a GPU computes it. But there is a second view that gives far better intuition: a matrix is a function that moves points. Feed in a vector, get out a new vector. Apply it to every point of the plane, and the plane itself bends, stretches and turns.
Print a square grid on a rubber sheet and pin the center to the table. Now grab the sheet and stretch it, twist it, or slide the top edge sideways. The grid lines stay straight and evenly spaced, the center never moves, but squares become rectangles, diamonds or slanted parallelograms.
Each way of deforming the sheet is a matrix. The pinned center is the origin, which a matrix never moves. Where the two grid arrows along the bottom-left square end up are the columns of the matrix. And how much the area of each little square grows or shrinks is the determinant.
What a matrix does to space
A 2×2 matrix has four numbers:
Here is the key trick for reading one. The two basic arrows (“one step right”) and (“one step up”) get sent to
The columns of the matrix are where the basis arrows land. And since any vector is a combination of these two, , its image is the same combination of the new arrows: . Knowing where two arrows go tells you where everything goes. That is why grid lines stay straight and evenly spaced. Functions with this property are called linear transformationsLinear transformationA function on vectors that keeps grid lines straight, parallel and evenly spaced and keeps the origin fixed. Every one can be written as multiplication by a matrix., and every one of them is a matrix.
Slides each row sideways in proportion to its height. Squares become parallelograms with the same area.
Things to try:
- Rotate 30°. The grid turns rigidly. The area of the square stays exactly 1: rotations preserve area, so .
- Shear. Only one number changed from the identity (), and the grid leans over. Squares become slanted parallelograms with the same area.
- Reflect. The area is still 1, but the parallelogram turns red: . Orientation flipped, like looking in a mirror. Notice that î and ĵ have swapped their clockwise order.
- Project to x-axis. The entire plane collapses onto a line, the area goes to 0, and . Many different inputs now land on the same output, so there is no way to undo it.
- Move slider slowly through 0 starting from the shear. Watch the determinant pass through zero exactly when the parallelogram flattens.
- Turn on the bias. The whole grid shifts. The origin moves now, so strictly speaking this is no longer linear. It is an affine map, and it is exactly what a neural-network layer computes.
The determinant: how much area changes
The determinantDeterminantA single number computed from a square matrix: the factor by which the transformation scales areas (or volumes). Negative means orientation flips; zero means space is flattened. of a 2×2 matrix is
Geometrically it is the area of the parallelogram that the unit square becomes, with a sign. Every region of the plane gets scaled by the same factor: if , every shape triples in area. A negative determinant means the transformation also flips orientation. A determinant of zero means the matrix squashes space into a lower dimension (a line or a point), and information is destroyed.
In higher dimensions the same idea holds with volumes. You won’t compute determinants much when working with neural networks, but the picture of “does this squash space or not?” comes up often. For example, a layer that maps 4,096 numbers down to 1,024 must lose information, and understanding what it keeps is part of interpretability research.
Layers are matrices (plus a shift)
A fully connected neural-network layer computes
where is a weight matrix and is a bias vector. In the demo’s language: warp the space with , then slide it by . The weights and biases are the parameters that training adjusts.
Real layers are not 2×2. Matrices can be rectangular: a matrix with rows and columns maps -dimensional vectors to -dimensional ones. In a mid-sized LLM, the hidden vectors have a few thousand entries. One 4,096×4,096 matrix already holds about 16.8 million numbers, and the feed-forward block of Llama 3 8B maps 4,096 dimensions up to 14,336 and back. Most of an LLM’s parameters live in matrices like these, and most of its running time is spent multiplying by them.
What does training actually do to these matrices? It adjusts every entry, a little at a time, so that each layer warps the space in a way that makes the next layer’s job easier. A helpful picture for classifiers: the raw inputs of two classes may be tangled together, like two interleaved spirals. Layer by layer (with nonlinearities in between), the network stretches and folds the space until the two classes sit in separate regions, and the final layer only has to draw a flat boundary between them. The 2D demo shows a single, fixed step of that process. A trained network chains dozens of them, each one learned.
Changing dimensions
Square matrices warp a space into itself, like the demo. Rectangular ones move vectors between spaces of different sizes, and LLMs use both kinds constantly:
- Going up. A 3×2 matrix takes 2D vectors to 3D. The output can only fill a flat 2D sheet inside 3D space, since the matrix has only two columns to combine, but that sheet can be tilted in any way. Transformer feed-forward blocks expand each token’s vector to a wider space (often about 3 to 4 times wider) where a nonlinearity can separate features more easily.
- Going down. A 2×3 matrix squeezes 3D into 2D, necessarily losing some information. The feed-forward block’s second matrix compresses back to the original width, keeping what training found useful.
- Lookups. Even the very first step of an LLM, turning a token into a vector, can be written as a matrix multiplication: multiply a one-hot vector (all zeros except a 1 at the token’s index) by the embedding matrix, and you pick out one row. In practice it is implemented as a direct lookup because that is faster.
What it costs
Each output entry of is a dot product of length : multiplications and about additions. An matrix therefore costs about floating-point operations (FLOPs) per input vector, which is two per parameter. That gives a handy rule of thumb you will meet again in scaling laws: running a model on one token costs roughly 2 FLOPs per parameter. For a 7-billion-parameter model, that is about 14 billion operations per token, and modern GPUs do hundreds of trillions of these per second.
Because every row’s dot product is independent of the others, all of them can be computed at the same time. That is why GPUs, with thousands of simple parallel cores, are such a good fit for neural networks, as the history lesson described.
MATH CORNER · optionalMatrix–vector products, composition and the determinant
Matrix–vector product. For an matrix and an -vector , the output has entries:
Each output is the dot product of row with ; equivalently, the output is a weighted sum of the columns.
Worked example. Let (a stretch plus a shear) and .
| view | computation | result |
|---|---|---|
| rows · x | ||
| columns | ||
| determinant | (areas double) | |
| with bias |
Set in the demo and drag to to check.
Composition is multiplication. Doing then is the single matrix (note the order: the matrix applied first is written on the right). For example, rotating by 90° twice, , gives , a rotation by 180°. Determinants multiply too: , which makes sense, since area scale factors compound.
Inverses. If , there is a matrix that undoes . For 2×2:
The factor shows directly why a zero determinant means no inverse.
In code
A whole layer, forward pass included, in a few lines:
import numpy as np
W = np.array([[2.0, 1.0],
[0.0, 1.0]])
x = np.array([1.0, 2.0])
b = np.array([-1.0, 0.5])
print(W @ x) # [4. 2.]
print(W @ x + b) # [3. 2.5] <- a linear layer
print(np.linalg.det(W)) # 2.0
# A real layer: 4096 inputs -> 1024 outputs, applied to a batch of 8 vectors
layer = np.random.randn(1024, 4096) * 0.02
batch = np.random.randn(8, 4096)
out = batch @ layer.T # shape (8, 1024): 8 x 1024 dot products of length 4096
print(out.shape, layer.size) # (8, 1024) 4194304 parameters
# In PyTorch the same layer is: torch.nn.Linear(4096, 1024)
- “A matrix is just a table for storing numbers.” It can be used that way, but in machine learning a weight matrix is best understood as a transformation that moves every input vector to an output vector.
- “Stacking more linear layers makes a model more powerful.” Without nonlinear activations, any stack of linear layers collapses into a single matrix. Depth only helps because of the nonlinearities in between.
- “Matrix multiplication is commutative, like regular multiplication.” In general : rotating then shearing is not the same as shearing then rotating. Order matters.
- “A zero determinant means the matrix is all zeros.” It means the matrix flattens space into fewer dimensions, as the projection preset does. The matrix has non-zero entries and determinant 0.
Check your understanding
Q1.A 2×2 matrix has first column (0, 1) and second column (−1, 0). Where does the vector (1, 0) go?
Q2.A matrix has determinant −2. What does it do to the unit square?
Q3.Why do neural networks put nonlinear activation functions between their matrix layers?
Q4.A layer maps vectors with 512 entries to vectors with 2,048 entries using y = Wx + b. How many parameters does it have?
Further reading
- videoEssence of Linear Algebra, chapter 3: Linear transformations and matrices (3Blue1Brown) — The animated version of this lesson's grid-warping picture.
- videoEssence of Linear Algebra, chapter 6: The determinant (3Blue1Brown) — Why the determinant is an area scale factor.
- bookImmersive Math: Linear algebra with interactive figures — A free interactive linear-algebra textbook.
- docstorch.nn.Linear documentation — The PyTorch layer that computes y = xWᵀ + b.