Lesson 2 of 7 · Math for AI: Linear Algebra & Calculus Essentials

Matrices: Transformations, Layers & Why Shapes Matter

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).

1. A matrix is a grid of numbers — and a function

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.

Stretch Rotate 90° Shear [[2, 0], [0, 1]] (1,1) → (2,1) [[0, -1], [1, 0]] (1,1) → (-1,1) [[1, 1], [0, 1]] (1,1) → (2,1)

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.

Key Insight Reading a matrix column by column tells you its geometry: column 1 is where (1,0) goes, column 2 is where (0,1) goes. In a neural-network layer the same reading applies in higher dimensions: each column is how much one input feature contributes to every output.

2. Matrix–vector multiplication: two ways to read the same arithmetic

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.

Way 1: by rows (a stack of dot products)

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):

row 1 · x = 3×2 + 1×(−1) = 6 − 1 = 5
row 2 · x = 0×2 + 2×(−1) = 0 − 2 = −2
A x = (5, −2)

Way 2: by columns (a weighted sum of columns)

The entries of x are weights, and the output is the sum of the columns of A scaled by those weights:

2 × column 1 + (−1) × column 2
= 2 × (3, 0) + (−1) × (1, 2)
= (6, 0) + (−1, −2)
= (5, −2)

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 non-square example: 3×2

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):

W = [[ 1, 0],
[ 2, 1],
[−1, 3]]
By rows: (1×4 + 0×2, 2×4 + 1×2, −1×4 + 3×2)
= (4, 10, 2)
By columns: 4×(1, 2, −1) + 2×(0, 1, 3)
= (4, 8, −4) + (0, 2, 6)
= (4, 10, 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.

3. Matrix–matrix multiplication and the shape rule

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:

(m × n) · (n × p) = (m × p)
↑ ↑
inner dimensions must match, then disappear

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: row 1 of A with columns of B: (1×0+2×1, 1×1+2×0) = (2, 1)
row 2 of A with columns of B: (0×0+1×1, 0×1+1×0) = (1, 0)
AB = [[2, 1], [1, 0]]
BA: row 1 of B with columns of A: (0×1+1×0, 0×2+1×1) = (0, 1)
row 2 of B with columns of A: (1×1+0×0, 1×2+0×1) = (1, 2)
BA = [[0, 1], [1, 2]]

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

The transpose AT flips a matrix over its diagonal: rows become columns. An m×n matrix becomes n×m.

A = [[1, 2, 3], AT = [[1, 4],
[4, 5, 6]] [2, 5],
[3, 6]]
2 × 3 3 × 2

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.

Debugging shape errors

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).

XB × 3 × WT3 × 2 = YB × 2 3 = 3: match, then vanish result takes the outer numbers: B and 2

The inner dimension (yellow) is consumed by the sum inside each dot product; the outer dimensions survive.

What you wroteShapesWhat happensFix
X @ W with W stored (out×in)(32×512) @ (256×512)Error: inner 512 ≠ 256Transpose: X @ W.T gives (32×256)
W @ x with a batch(256×512) @ (32×512)Error: inner 512 ≠ 32Put 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 upBias 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 wrongTranspose K: (n×d) @ (d×n) = (n×n)
* instead of @(2×2) * (2×2)Runs: multiplies entry by entry, not a matrix productUse @ for matrix products

4. A neural-network layer, worked by hand

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.

W = [[0.5, −1.0, 2.0], b = (−1, −2) x = (2, 1, 4)
[1.0, 0.5, −0.5]]
W x, row 1: 0.5×2 + (−1.0)×1 + 2.0×4 = 1 − 1 + 8 = 8
W x, row 2: 1.0×2 + 0.5×1 + (−0.5)×4 = 2 + 0.5 − 2 = 0.5
W x = (8, 0.5)
y = W x + b = (8 − 1, 0.5 − 2)
y = (7, −1.5)

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.

Batches are matrices

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:

X = [[2, 1, 4], [0, 2, 1], [1, 1, 1]] (3×3: batch × features)
example 2: row 1 of W: 0×0.5 + 2×(−1) + 1×2 = 0; row 2: 0 + 1 − 0.5 = 0.5
example 3: row 1 of W: 0.5 − 1 + 2 = 1.5; row 2: 1 + 0.5 − 0.5 = 1
X WT = [[8, 0.5], [0, 0.5], [1.5, 1]] (3×3)(3×2) = (3×2)
add b = (−1, −2) to every row:
Y = [[7, −1.5], [−1, −1.5], [0.5, −1]]

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.

5. Attention scores: shape bookkeeping only

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):

Q = [[1, 0], [0, 1], [1, 1]] K = [[2, 1], [0, 3], [1, 1]]
KT = [[2, 0, 1],
[1, 3, 1]] (2×3)
token 1: q = (1,0): (1×2+0×1, 1×0+0×3, 1×1+0×1) = (2, 0, 1)
token 2: q = (0,1): (0+1, 0+3, 0+1) = (1, 3, 1)
token 3: q = (1,1): (2+1, 0+3, 1+1) = (3, 3, 2)
Q KT = [[2, 0, 1], [1, 3, 1], [3, 3, 2]] (3×2)(2×3) = (3×3)

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.

6. Identity and inverse

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.

A = [[2, 1], [1, 1]] determinant = 2×1 − 1×1 = 1
A−1 = (1/1) × [[1, −1], [−1, 2]]
A A−1 = [[2×1+1×(−1), 2×(−1)+1×2],
[1×1+1×(−1), 1×(−1)+1×2]]
= [[1, 0], [0, 1]] = I

When an inverse exists

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.

Why you almost never compute one in ML

7. Linear vs. non-linear: why layers need an activation

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):

Layer by layer:
W1 x = (1×1+2×(−1), 0×1+1×(−1)) = (−1, −1)
W2(W1 x) = (3×(−1)+0, 1×(−1)+1×(−1)) = (−3, −2)
Multiply the matrices first:
W2 W1 = [[3×1+0×0, 3×2+0×1], [1×1+1×0, 1×2+1×1]] = [[3, 6], [1, 3]]
(W2 W1) x = (3×1+6×(−1), 1×1+3×(−1))
= (−3, −2) same answer

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:

W1 x = (−1, −1) → ReLU → (0, 0) → W2 (0, 0) = (0, 0)
With ReLU the output is (0, 0), not (−3, −2): no single matrix does this.

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.

Key Insight A network is alternating matrix multiplications (linear mixing) and simple non-linear functions. The matrices carry the learned parameters; the non-linearities are what stop the whole thing from collapsing into one matrix.

8. Why this matters for building AI systems

Why This Matters Nearly all the compute in a neural network is matrix multiplication, and nearly all the confusing errors are shape mismatches. Fluent shape-reading saves more debugging time than any other single skill in this lesson.

Parameter counts are shape arithmetic

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.

Write the shape in a comment

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.

What comes next

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).

Recap

✅ Check Yourself

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?

X @ W
W @ X
X @ W.T

2. Using A = [[3, 1], [0, 2]] and x = (2, −1), what is A x?

(5, −2)
(6, −2)
(7, 0)

3. For 3 tokens with 64-dimensional query and key vectors, what is the shape of Q KT, and what happens to the 64?

(3×64); the 64 stays as a column count
(3×3); the 64 is the inner dimension and vanishes
(64×64); the 3 is the inner dimension and vanishes

4. Which matrix has no inverse?

[[2, 1], [1, 1]], determinant 1
[[1, 0], [0, 1]], the identity
[[1, 2], [2, 4]], determinant 0

5. A network has 10 layers of the form y = Wx + b and no activation functions. How does it compare to a single layer?

It can represent strictly more functions, because each layer adds capacity
It can represent only what one layer of the form y = Mx + c can, because the matrices multiply into one
It cannot be trained, because the matrices do not commute