A matrix times a vector does several dot products for one vector. A matrix times a matrix does them for many vectors at once: every row of the first meets every column of the second. That one operation is the workhorse of modern AI. A layer of a neural network applied to a whole batch of examples is one matrix multiplication, and the attention inside a transformer is a few more. GPUs are, more or less, machines built to do it fast. This lesson builds it from shopping bills, works it by hand with the size rule as a guide, writes it as three loops and then as one @, and finishes by pushing four pictures through a layer in a single line, in NumPy and in PyTorch.
What you'll be able to do
Multiply two matrices: entry (i, j) is row i of the first dotted with column j of the second
Use the size rule: inner sizes must match, and the outer sizes give the answer's size
Compute A @ B with a triple loop and with @, time the two, and know that A @ B and B @ A usually differ
Run a batch of pictures through a layer at once, Z = X W + b, and get the same scores from PyTorch's nn.Linear
Quick check
Have a guess before you start. A 2 × 3 matrix times a 3 × 2 matrix. How many numbers are in the answer?
4
6
9
12
Show the answer
4
The answer is 2 × 2: one entry for each row of the first (2) and each column of the second (2).
The math: every row meets every column
Purpose. Many bills at once. Three hikers each buy some energy bars, apples and nuts, recorded in A, one row per hiker. Two shops price the three items, recorded in B, one column per shop:
A=205142310B=1.50.53.02.00.42.5
Hiker 1's bill at shop 1 is a dot product, row 1 of A with column 1 of B: 2 × 1.5 + 1 × 0.5 + 3 × 3 = 12.5. Do that for every hiker and every shop and you have six bills in a 3 × 2 table. That table is the matrix product AB.
Quick check
From lesson 55: a 3 × 3 matrix times a vector of 3. How many numbers come out?
3
6
9
1
Show the answer
3
One dot product per row. A matrix product is that, repeated for every column of the second matrix.
The picture. Step through the six bills. The first step checks the sizes; each later step lights a row of A and a column of B, pairs them up, and drops their dot product into the answer. The drawing lays the three tables out so they meet: B sits above the answer and A to its left, with an empty corner between them (the arrows "B →" and "A ↓" point across it), and each bill shows ? until it's made. Row i of A runs straight across to row i of the answer, and column j of B runs straight down to its column j, so the cell where they cross is the bill they make.
Try it now
Then set matrix B to two lines, 1 0 and 0 1, and press Use these numbers: the first step refuses, because the inner sizes no longer match.
Symbols and formula. For A of size m × n and B of size n × p:
Cij=k=1∑nAikBkj
In plain words: row i of A dotted with column j of B. Some people say "over and down": go across the row, down the column, multiplying pairs as you go.
The size rule. Write the sizes side by side, (m × n)(n × p). The inner sizes must match, because each row of A has n entries and each column of B has n entries to pair with them. The outer sizes give the answer: m × p. (3 × 3)(3 × 2) gives 3 × 2; (2 × 3)(2 × 3) can't be done.
The size rule as a picture. Think of a matrix product as a machine that a table travels through. The arrow into the machine carries the first table's size; the machine holds the second table; the arrow out carries the answer's size. Step through three uses of it.
Quick check
Can a 2 × 3 matrix multiply another 2 × 3 matrix?
Yes: the two sizes are exactly the same
Yes, giving a 2 × 3 answer
Yes, giving a 3 × 3 answer
No: the inner sizes, 3 and 2, don't match
Show the answer
No: the inner sizes, 3 and 2, don't match
(2 × 3)(2 × 3): the inner sizes are 3 and 2. A row of 3 has nothing to pair with in a column of 2.
Order matters. With numbers, 3 × 4 = 4 × 3. With matrices, AB and BA are usually different, and often only one of them can even be formed. For P = [[1, 2], [3, 4]] and Q = [[0, 1], [1, 0]], PQ = [[2, 1], [4, 3]] swaps P's columns, while QP = [[3, 4], [1, 2]] swaps its rows. Always multiply in the order the problem gives.
A named mistake: multiplying matching cells. It's tempting to multiply entry by entry, as adding does. That's a different operation with a different answer, and it only works when both matrices are the same size.
In your own words
In your own words: why must the inner sizes match in a matrix product?
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: three loops, then @
Purpose. Six bills by hand is fine; six million is not.
The formula has three letters, i, j and k, so a direct translation has three loops:
import numpy as np
A = np.array([[2, 1, 3], [0, 4, 1], [5, 2, 0]])
B = np.array([[1.5, 2.0], [0.5, 0.4], [3.0, 2.5]])
C = np.zeros((3, 2))
for i inrange(3):
for j inrange(2):
for k inrange(3):
C[i, j] = C[i, j] + A[i, k] * B[k, j]
print(C.tolist())
print((A @ B).tolist(), np.allclose(C, A @ B))
It runs right here in your browser, with nothing to install.
@ does the same work in one character, and much faster. np.allclose checks two arrays are equal up to tiny float differences, which is the right test for decimals.
Code flow. Step through the three loops for the first two hikers, a line at a time. i picks a hiker, j a shop, and k runs along the hiker's row and down the shop's column together, adding one pair's product to C[i, j] on each pass. That's the math part's row meeting a column, one product at a time.
How much faster is @? Time both on bigger tables. time.perf_counter() reads a stopwatch in seconds, so the difference between two readings is how long the lines between them took. np.ones makes tables full of 1s, and @ is timed over 100 runs, because one run is too quick to measure well.
import time
import numpy as np
X = np.ones((40, 30))
W = np.ones((30, 20))
start = time.perf_counter()
Z = np.zeros((40, 20))
for i inrange(40):
for j inrange(20):
for k inrange(30):
Z[i, j] = Z[i, j] + X[i, k] * W[k, j]
loop_time = time.perf_counter() - start
start = time.perf_counter()
for rep inrange(100):
Z2 = X @ W
at_time = (time.perf_counter() - start) / 100print(np.allclose(Z, Z2), loop_time > at_time)
print("loop:", round(loop_time * 1000, 2), "ms @:", round(at_time * 1000, 4), "ms")
The loop works through 40 × 20 × 30 = 24,000 products one at a time in Python; @ hands the whole job to NumPy's compiled code. Your times change from run to run, but the loop is always far slower. Swapping a Python loop for one array operation like this is called vectorization, and it's why real code never multiplies matrices by loop.
Print the shapes. The size rule in code is a rule about .shape:
import numpy as np
A = np.array([[2, 1, 3], [0, 4, 1], [5, 2, 0]])
B = np.array([[1.5, 2.0], [0.5, 0.4], [3.0, 2.5]])
print(A.shape, B.shape, (A @ B).shape)
print(A.shape[1] == B.shape[0])
When the inner sizes differ, @ stops with an error that mentions a "mismatch in its core dimension". Read it as "the inner sizes don't match", and print both shapes.
A named mistake: * where @ was meant. On two matrices of the same shape, A * B runs happily and multiplies matching cells. It's not a matrix product, and it gives different numbers. A product of a 2 × 2 and a 2 × 2 is a 2 × 2 either way, so the shape won't warn you; only the values will.
Worked example
Worked example: @ against *, and the order
Multiply two 2 × 2 matrices both ways round with @, and compare with *.
P @ Q swaps P's two columns, and Q @ P swaps its two rows: the order changes the answer. P * Q multiplies matching cells, keeping only the entries where Q has a 1, which is neither product. Q is a "swap" matrix; lesson 58 shows that every matrix is a movement like this, and multiplying them chains the movements.
Quick check
What does this print?
import numpy as np
A = np.array([[1, 2, 3],
[4, 5, 6]])
B = np.array([[1, 0],
[0, 1],
[2, 1]])
print((A @ B).shape, (A @ B).tolist()[1])
(2, 3) [4, 0, 12]
(2, 2) [7, 5]
(2, 2) [16, 11]
(3, 3) [16, 11]
Show the answer
(2, 2) [16, 11]
(2 × 3)(3 × 2) gives 2 × 2. Row 2 of A with each column of B: 4 + 0 + 12 = 16 and 0 + 5 + 6 = 11.
Quick check
A has shape (5, 8) and B has shape (8, 3). What is the shape of A @ B?
(8, 8)
(3, 5)
(5, 8)
(5, 3)
Show the answer
(5, 3)
The inner 8s match and disappear; the outer sizes, 5 and 3, are left.
Drill
The size rule as code
Write can_multiply(a_shape, b_shape), True when the inner sizes match, and result_shape(a_shape, b_shape), the answer's shape as a tuple, or None when they can't be multiplied. Shapes are tuples like (3, 2).
In the lesson, your code is checked as you write it.
In your own words
Why doesn't the shape catch a * written where @ was meant, for two square matrices?
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML: a layer is one matrix multiplication
Purpose. Run a whole batch of examples through a layer at once.
Stack four pictures, each unrolled to 25 pixels, as the rows of X (4 × 25). Give a layer with three outputs a weight matrix W of 25 × 3: one column of 25 weights per output, the transpose of lesson 55's layout. Then
Z=XW+b
In plain words: every picture's row meets every output's column, and each output's bias is added to its column. Z is 4 × 3: one row of three scores per picture.
Here it is on a tiny batch of two examples with three features each, so every step is visible. The picture draws the layer as a network: the current example's numbers fill the circles on the left, each column of W rides the lines into one output on the right, and each output starts at its bias. The examples pass through one at a time.
Now the real sizes. The weights here are the three sign templates from lesson 55, one per column:
import numpy as np
cross = np.array([[1,0,0,0,1],[0,1,0,1,0],[0,0,1,0,0],[0,1,0,1,0],[1,0,0,0,1]])
arrow = np.array([[0,0,1,0,0],[0,1,1,1,0],[1,0,1,0,1],[0,0,1,0,0],[0,0,1,0,0]])
box = np.array([[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1]])
W = np.array([cross.flatten(), arrow.flatten(), box.flatten()]).T
X = np.array([arrow.flatten(), box.flatten(), cross.flatten(), arrow.flatten()])
b = np.array([0, 0, 0])
Z = X @ W + b
print(X.shape, W.shape, Z.shape)
print(Z.tolist())
Each row of Z is one picture's three scores, and the biggest in each row names its sign: arrow, box, cross, arrow.
Quick check
What does this print?
import numpy as np
X = np.array([[1, 2], [0, 1], [3, 0]])
W = np.array([[1, 0, 1], [0, 1, 1]])
print((X @ W).shape, (X @ W).tolist()[2])
(2, 2) [3, 0, 3]
(3, 3) [3, 0, 3]
(3, 2) [3, 0]
(3, 3) [1, 2, 3]
Show the answer
(3, 3) [3, 0, 3]
(3 × 2)(2 × 3) gives 3 × 3. Row 3 of X, (3, 0), meets each column of W: 3, 0 and 3.
In PyTorch. PyTorch's layer, nn.Linear(25, 3), stores its weights the way lesson 55 did, as (out, in): one row of 25 per output, 3 × 25. That's the transpose of this part's W. So for a batch whose examples are rows, the layer computes X @ layer.weight.T + layer.bias: the same Z = XW + b, with W written as the transpose of what it stores. The cell loads the three templates as the layer's rows, works the formula by hand, and checks it against layer(X). torch.stack stacks tensors as rows and .float() makes them decimals, as in lesson 55.
import torch
import torch.nn as nn
cross = torch.tensor([[1,0,0,0,1],[0,1,0,1,0],[0,0,1,0,0],[0,1,0,1,0],[1,0,0,0,1]]).float()
arrow = torch.tensor([[0,0,1,0,0],[0,1,1,1,0],[1,0,1,0,1],[0,0,1,0,0],[0,0,1,0,0]]).float()
box = torch.tensor([[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1]]).float()
X = torch.stack([arrow.flatten(), box.flatten(), cross.flatten(), arrow.flatten()])
layer = nn.Linear(25, 3)
with torch.no_grad():
layer.weight.copy_(torch.stack([cross.flatten(), arrow.flatten(), box.flatten()]))
layer.bias.fill_(0)
Z = X @ layer.weight.T + layer.bias
print(layer.weight.shape, Z.shape)
print(Z.tolist())
print(torch.equal(Z, layer(X)))
Z holds the scores the NumPy cell printed, now as decimals: arrow, box, cross, arrow again. torch.equal says the formula and layer(X) agree exactly. That one line, X @ W.T + b on a whole batch, is what every nn.Linear in a real model computes.
Quick check
The layer above is changed to have 10 outputs instead of 3. What shape must this part's W be, for X @ W?
(10, 25)
(4, 10)
(25, 10)
(25, 3)
Show the answer
(25, 10)
W needs one row per input pixel (25) and one column per output (10). PyTorch's nn.Linear(25, 10) would store its transpose, (10, 25).
Drill
Score a new batch
Three smudged pictures are in Xb, one per row. Set Z to the layer's scores, X @ W + b, and labels to the position of the largest score in each row, as a list.
import numpy as np
cross = np.array([[1,0,0,0,1],[0,1,0,1,0],[0,0,1,0,0],[0,1,0,1,0],[1,0,0,0,1]])
arrow = np.array([[0,0,1,0,0],[0,1,1,1,0],[1,0,1,0,1],[0,0,1,0,0],[0,0,1,0,0]])
box = np.array([[1,1,1,1,1],[1,0,0,0,1],[1,0,0,0,1],[1,0,0,0,1],[1,1,1,1,1]])
W = np.array([cross.flatten(), arrow.flatten(), box.flatten()]).T
b = np.array([0, 0, 0])
a2 = arrow.copy()
a2[0, 0] = 1
b2 = box.copy()
b2[2, 2] = 1
Xb = np.array([a2.flatten(), b2.flatten(), cross.flatten()])
Z = Xb * W + b
labels = [0, 0, 0]
print(Z, labels)
In the lesson, your code is checked as you write it.
In your own words
Why is it useful that a whole batch goes through a layer as one matrix product, instead of one picture at a time?
Write a sentence or two, then compare it with a good answer in the lesson.
31Formulas with fractions: clear them firstFreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
37Inverse functions, lines and scalingFreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
38Sequences and sums: find n, a, d and rFreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
40Review: rearrange anything (algebra)FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
41Coordinates and distanceFreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
42Angles, degrees and radiansFreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
43Sine and cosineFreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
44Waves: height, speed and shiftFreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
68Vector equations: rearranging with arrowsFreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
87Counting: choices, orders and groupsFreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
88Probability: from counts to chancesFreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
89Combining events: and, or, independentFreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
100Maximum likelihoodFreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
101Linear regression: the best lineFreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
109One neuron, start to finishFreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
111Training a small networkFreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
112The same network in PyTorchFreenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
113Attention as matrix mathFreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
114Residual connections and layer normFreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
115A transformer block, start to finishFreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
117Final test: transpose any formulaFreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
Learn the math behind AI from arithmetic up: numbers, algebra, vectors and matrices, calculus, probability and statistics, each shown as numbers moving and checked in Python, ending with a network you build and train from the formulas.
See the course →
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write