A neural-network layer, an attention score table, and a batch of embeddings are all the same object: a grid of numbers that turns vectors into other vectors. Most "my model crashed" errors are really shape errors.
In M1 you worked with vectors and the dot product: a vector is a list of numbers, and a dot product multiplies two same-length lists entry by entry and adds the results. A matrix is what you get when you stack several such lists. Almost everything a neural network does in a forward pass is matrix arithmetic, so this lesson builds three habits: reading a matrix as a function, multiplying by hand without losing track, and tracking shapes before code runs. M3 then asks what a matrix does geometrically at its core (eigenvectors, SVD, low-rank).
A matrix is a rectangular grid of numbers. An m×n matrix has m rows and n columns, and the entry in row i, column j is written Aij. A vector is the special case of one column (n×1) or one row (1×n).
As data, a matrix is a table: 3 rows of embeddings, each with 2 dimensions, is a 3×2 matrix. As a function, a matrix takes a vector in and produces a vector out. A 2×2 matrix takes any 2-D vector to another 2-D vector; a 3×2 matrix takes a 2-D vector to a 3-D vector. Section 2 shows the arithmetic. First, the picture.
Take the unit square with corners (0,0), (1,0), (1,1), (0,1) and push every corner through a matrix. The coloured arrows below show where the two basis vectors e1 = (1,0) and e2 = (0,1) land. They always land on the columns of the matrix, which is why the columns tell you everything about what the matrix does.
Dashed: the original unit square. Purple: the square after the matrix. Blue arrow: where e1 = (1,0) lands (column 1). Green arrow: where e2 = (0,1) lands (column 2). Straight edges stay straight and the origin stays put — that is what "linear" means.
Multiplying a matrix A (m×n) by a vector x (length n) gives a vector of length m. There are two equivalent ways to compute it; you should be able to do both, because different problems make one of them obvious.
Each output entry is the dot product (M1) of one row of A with x. Take A = [[3, 1], [0, 2]] and an embedding x = (2, −1):
The entries of x are weights, and the output is the sum of the columns of A scaled by those weights:
Same answer. The row view is how you compute it; the column view is how you understand it: the output is built from the columns, and x says how much of each to mix in. This is the same picture as section 1: the output is a blend of where the basis vectors went.
A matrix does not have to be square. Let W be 3×2, which maps a 2-D input to a 3-D output, and let x = (4, 2):
Shape check: (3×2)(2×1) = (3×1). The 2s in the middle matched and disappeared; the outer numbers 3 and 1 give the result's shape. A 2-D input became a 3-D output, so a non-square matrix changes dimension. That is exactly what a layer that expands or compresses an embedding does.
To multiply two matrices, treat the right-hand one as a set of column vectors and multiply A by each in turn. Entry (i, j) of AB is the dot product of row i of A with column j of B. For this to work, a row of A and a column of B must have the same length. That is the shape rule:
Applying a matrix is a function; multiplying two matrices is composing two functions. AB means "apply B first, then A". Take A = [[1, 2], [0, 1]] (a shear) and B = [[0, 1], [1, 0]] (swap the two coordinates):
AB ≠ BA. Order matters: "shear, then swap" is a different transformation from "swap, then shear". Matrix multiplication is not commutative. It is associative, (AB)C = A(BC), which is why frameworks are free to regroup the multiplications for speed.
The transpose AT flips a matrix over its diagonal: rows become columns. An m×n matrix becomes n×m.
Two facts you will use constantly: the dot product from M1 is a matrix product, x·y = xTy (a 1×n times an n×1 gives a 1×1), and a product reverses under transpose: (AB)T = BTAT.
Before you run anything, write the shape of each operand and check that the inner numbers match. This table covers the errors you will actually see in model code. Here B is a batch size, and a weight matrix is stored as (out × in).
The inner dimension (yellow) is consumed by the sum inside each dot product; the outer dimensions survive.
| What you wrote | Shapes | What happens | Fix |
|---|---|---|---|
X @ W with W stored (out×in) | (32×512) @ (256×512) | Error: inner 512 ≠ 256 | Transpose: X @ W.T gives (32×256) |
W @ x with a batch | (256×512) @ (32×512) | Error: inner 512 ≠ 32 | Put examples in rows and use X @ W.T, or transpose X |
| Bias of wrong shape | (32×256) + (32,) | Error, or a silent wrong broadcast if sizes happen to line up | Bias has one entry per output: shape (256,) |
Q @ K instead of Q @ K.T | (n×d) @ (n×d) | Error unless n = d; if n = d it runs and is silently wrong | Transpose K: (n×d) @ (d×n) = (n×n) |
* instead of @ | (2×2) * (2×2) | Runs: multiplies entry by entry, not a matrix product | Use @ for matrix products |
A fully connected layer computes y = W x + b. x is the input vector, W is the weight matrix (learned), b is the bias vector (learned), and y is the output. Say a toy layer takes 3 input features and produces 2 outputs, so W is 2×3 (out × in), b has length 2, and x has length 3.
Shapes: (2×3)(3) + (2) = (2). The layer has 2×3 + 2 = 8 learnable numbers. Training (M4 onward, and the statistics course, Lesson 8, The Statistics Behind Training a Model) is the search for good values for exactly these entries. Row i of W is the "detector" for output i: its dot product with the input says how much the input matches that pattern.
Models process many examples at once. Stack 3 inputs as the rows of a matrix X (shape 3×3: batch × features). Because W is stored out×in, you compute Y = X WT + b, adding b to every row:
The first row of Y matches the single-example result above. A batch costs the same arithmetic per example, but one big matrix product runs far faster on a GPU than many small ones. Hence the convention: the first axis of every tensor is the batch.
In a transformer, each token gets a query vector and a key vector. A token's score for another token is the dot product of its query with the other's key. All scores at once are one matrix product, Q KT. This lesson only tracks the shapes; how the scores are used is a different topic.
Toy case: 3 tokens, 2 dimensions per vector. Q and K are each 3×2 (tokens × dims):
Entry (i, j) is "how strongly token i's query matches token j's key." The result is always n×n for n tokens, no matter how many dimensions the vectors have. The dimension d is the inner dimension and vanishes. This is why long contexts are expensive: at n = 4,096 tokens the score table has 4,096² = 16,777,216 entries per attention head, and doubling the context quadruples that.
The identity matrix I has 1s on the diagonal and 0s elsewhere. It does nothing: I x = x and AI = IA = A. It is the matrix version of the number 1.
The inverse A−1 of a matrix A undoes it: A−1A = A A−1 = I. For a 2×2 matrix [[a, b], [c, d]] the inverse is 1/(ad − bc) × [[d, −b], [−c, a]]. The number ad − bc is the determinant.
Only a square matrix can have an inverse, and even then only if its determinant is not zero. Zero determinant means the matrix squashes space and loses information. Take S = [[1, 2], [2, 4]]: its second column is twice its first, so it flattens the whole plane onto a line. Its determinant is 1×4 − 2×2 = 0, and it sends the nonzero vector (2, −1) to (1×2 + 2×(−1), 2×2 + 4×(−1)) = (0, 0). Two different inputs now give the same output, so no function can recover which one you started with. This situation, redundant columns, is called rank deficiency; M3 makes it precise.
solve or lstsq), which finds x directly and more accurately. Writing A−1b on paper is fine; calling inv in code usually is not.A function f is linear if f(a x + c y) = a f(x) + c f(y): scaling and adding inputs scales and adds outputs. Every matrix is linear. (With the bias b it is technically "affine", a linear map plus a shift, and the argument below still holds.)
Here is the consequence. Stack two layers with no activation between them. Let layer 1 be W1 = [[1, 2], [0, 1]] and layer 2 be W2 = [[3, 0], [1, 1]], and feed in x = (1, −1):
Two layers are one layer, W = W2W1. With biases it is the same: W2(W1x + b1) + b2 = (W2W1)x + (W2b1 + b2). A hundred linear layers are still one matrix, so depth buys nothing. Now put a ReLU between them, a function that replaces every negative entry with 0:
No matrix could produce both this result and the earlier one, because a matrix sends (1, −1) to one fixed place. The ReLU bends space, and that bend is what lets a stack of layers represent things a single matrix cannot. Matrices do the mixing; the non-linearity (activation function) makes depth worth having.
A layer from 768 inputs to 3,072 outputs has a 3,072×768 weight matrix plus 3,072 biases: 3,072 × 768 + 3,072 = 2,362,368 parameters. You can size a model from its shapes alone, without running it.
Annotate each line, for example # (B, T, d) @ (d, d_ff) -> (B, T, d_ff). If the inner dimensions do not match when you write the comment, the code will not run either. This habit catches the silent cases from section 3 before they cost a training run.
You now know what a matrix does to one vector. M3 asks the follow-up: for a given matrix, which directions does it only stretch (eigenvectors), how can any matrix be split into rotate-stretch-rotate steps (SVD), and why a big matrix with redundant columns can be replaced by two thin ones (low-rank, the idea behind LoRA-style fine-tuning).
1. A weight matrix W has shape (256×512) and a batch X has shape (32×512). Which expression gives a valid (32×256) result?
2. Using A = [[3, 1], [0, 2]] and x = (2, −1), what is A x?
3. For 3 tokens with 64-dimensional query and key vectors, what is the shape of Q KT, and what happens to the 64?
4. Which matrix has no inverse?
5. A network has 10 layers of the form y = Wx + b and no activation functions. How does it compare to a single layer?