Lesson 6 of 117 min
Matrix multiplication
Each number a matrix gives is one row's dot product with the input, so a layer is one multiplication, and two moves, one after another, are one matrix.
After this lesson you can multiply matrices and read one network layer as one multiplication.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
A matrix times a matrix, by hand
The video made one matrix from two moves by following the arrows. Number by number, it is the same rule as before: the number in row i and column j is row i of the left matrix times column j of the right one, a dot product. Here it is for wide @ turn.
import numpy as np
turn = np.array([[0, -1], [1, 0]])
wide = np.array([[2, 0], [0, 1]])
out = np.zeros((2, 2), dtype=int)
for i in range(2):
for j in range(2):
out[i, j] = wide[i] @ turn[:, j]
print(out)
print(wide @ turn)[[ 0 -2] [ 1 0]] [[ 0 -2] [ 1 0]]
The inside numbers must match
A matrix of shape (3, 2) takes 2 numbers in, so the 2s must meet in the middle: (3, 2) @ (2,) works. Turn it around and NumPy stops with an error that names the two sizes. When you see it, print both shapes and check which side each one belongs on.
friends = np.array([[2, 1], [-1, 2], [-2, -1]])
you = np.array([2, 1])
print(friends.shape, you.shape)
print(friends @ you)
you @ friends(3, 2) (2,) [ 5 0 -5] ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, … (size 3 is different from 2)
Older ways to write @
Tutorials and older code often write np.dot or np.matmul where you would write @. For a matrix and a vector, all three give the same answer. @ is the one to use in your own code.
print(np.dot(friends, you))
print(np.matmul(friends, you))
print(friends @ you)[ 5 0 -5] [ 5 0 -5] [ 5 0 -5]
The same numbers every run
A new layer starts from random numbers, so the video's board prints other numbers each time. torch.manual_seed fixes them, so your numbers match the ones here. .detach() takes the numbers out of PyTorch's learning, which NumPy needs. And np.allclose checks two results agree, without asking every tiny digit to match.
import torch
torch.manual_seed(0)
layer = torch.nn.Linear(2, 3)
matrix = layer.weight.detach().numpy()
added = layer.bias.detach().numpy()
inputs = np.arange(8).reshape(4, 2)
mine = inputs @ matrix.T + added
theirs = layer(torch.Tensor(inputs)).detach().numpy()
print(mine[0])
print(np.allclose(mine, theirs))[0.36531285 0.04027003 0.12686437] True
Why layers need a bend between them
Two layers with nothing between them are one matrix: second @ first does both, like the turn and the stretch. So a network puts a bend between its layers. A common one sets every number below zero to zero. After the bend, no single matrix gives the same answer. The Deep Learning course takes this further.
first = np.array([[1, -1], [2, 0], [0, 1]])
second = np.array([[1, 1, -1]])
x = np.array([1, 3])
print(second @ (first @ x))
print(second @ first, (second @ first) @ x)
bent = np.maximum(0, first @ x)
print(first @ x, bent, second @ bent)[-3] [[ 3 -2]] [-3] [-2 2 3] [0 2 3] [-1]
Run on Python 3.13, NumPy 2.5.5 and PyTorch 2.15.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: The dot product
You rate a comedy and a horror movie [2, 1]. Sam rates them exactly like you: dot product 5. Max rates them [2, 2]: dot product 6. Does Max's taste fit yours better than Sam's?
2 of 3
turn turns the zero on its side, and wide makes it twice as wide. In wide @ turn @ p, which move happens to the point p first?
3 of 3
Three friends' ratings are the rows of M: Sam [2, 1], Kai [-1, 2], Ola [-2, -1]. Your ratings are you = [2, 1]. What is the third number of M @ you?
The ideas in this lesson
- Matrix times vector
- Each number out is one row's dot product with the vector: `@` in NumPy, never `*`.
- A layer
- A layer of a neural network is one matrix times its input, plus a number added to each output.
- Matrix times matrix
- One move after another is one matrix: the one next to the vector acts first, and the order matters.
It leans on
- Reading a PyTorch class
Transcript
What the video says, part by part. Press a time to watch from there.
The game
Here's a game. Take an AI model that writes text. It keeps each word as a long list of numbers. One of its layers turns that list into a longer one. Here are the two sizes. How many multiplications does that layer do, for one word?
One row, one number
Keep your guess in mind.
Start small, with a handwritten zero on a grid. A matrix moves every point of it, and this one, a quarter turn, moves the point at one, two.
Where does that point land?
Let's work it out, one number at a time. Take the first row of the matrix, zero and minus one, and the point. Multiply the matching numbers and add them up. Zero times one is zero. Minus one times two is minus two.
Add them: minus two. That's a dot product.
The second row is one and zero. Try it yourself.
One times one is one. Zero times two is zero. So: one. The point lands on minus two, one.
Each number that comes out is one row's dot product with the point.
Check it with the columns
Now mix the columns instead: one of the first column, plus two of the second. The same point?
Yes. Minus two, one, again.
This is called a matrix times a vector. In NumPy, it's the at sign.
One row for each number
A matrix doesn't have to be square. Here are three friends. Each one scored two movies, a comedy and a horror movie, between minus two and plus two. Put their ratings in the rows, one row for each friend. Now multiply by your ratings, two and one. You get three dot products at once: five, zero, and minus five. That's how much you agree with each friend. Two numbers go in, and three come out. So the matrix has one row for each number that comes out.
Not the star
NumPy has a star sign too, for multiplying. Write a star instead of the at sign, and it runs, with no error. But look at what comes out.
Six numbers, not three.
The star multiplies each friend's ratings by yours, number by number... and never adds them up.
You get the six products, not the three sums. For a matrix times a vector, use the at sign.
A layer
So what does a layer of a neural network do?
The networks inside today's AI models are built from layers. Each one does what you just saw. Plus one thing: after the matrix, it adds one number to each output.
The rows aren't friends' ratings. The model learned them from many examples.
You can think of each row as a pattern. Each number that comes out says how much the input agrees with that pattern.
So a whole layer... is one matrix times a vector.
Back to GPT-2
Now, back to the layer. It's from GPT-2, a model that writes text.
Seven hundred and sixty-eight numbers go in. Three thousand and seventy-two come out.
So its matrix has a row for each number that comes out.
And each row has a number for each one that goes in.
Each row is one dot product: seven hundred and sixty-eight multiplications, added up.
And there's one for every row.
That's almost two and a half million multiplications... for one word.
If you guessed a few thousand, you counted the numbers that go in and come out. But every number that comes out needs all the numbers that go in. In PyTorch code, this is a Linear layer. One matrix times a vector... made of millions of small multiplications.
One move after another
Back to the zero. Turn it, then make it twice as wide. Can one matrix do both?
One matrix for two moves
Turn the zero, then make it twice as wide. Follow the two arrows through both moves. The arrow across: the turn sends it up, and twice as wide leaves it there. The arrow up: the turn sends it left, and twice as wide doubles it. So the arrow up ends on minus two, zero. The zero comes out lying wide: wider than it is tall.
Those two landing places are the columns of one matrix, which does both moves. A matrix times a matrix. In NumPy, it's wide, at, turn. The one next to the point acts first.
The order
With numbers, two times three is three times two. So try the other order: twice as wide first, then the turn. Will you get the same zero?
No. Twice as wide doubles the arrow across, and then the turn sends it up. The arrow up stays, and then the turn sends it left. This time the zero comes out standing: taller than it is wide. So with moves, the order matters.
In NumPy: a layer on many inputs
Back to layers, in real code. Here's a layer made in PyTorch: two numbers in, three out. These two lines give us its matrix, and the numbers that get added, as NumPy arrays.
Here are four inputs, one in each row. This line runs the layer on all four. Dot T turns the matrix's rows into columns, so each input meets them all.
Then it adds the three numbers.
So what will it print? How many rows, and how many numbers in each?
Four rows of three. One for each input. A matrix times a matrix runs the layer on all four at once.
And PyTorch's own layer gives the same numbers. When GPT-2 reads a sentence, all its words go through a layer like this at once: one row for each word.
So a Linear layer... is that one line.
What you saw
So here's what you saw. Each number a matrix gives you is one row's dot product with the input. Use the at sign, not the star.
A layer of a network is one matrix times a vector, plus a number added to each output. And one move after another is one matrix. But the order matters.
One row, one dot product
So each number a matrix gives you is one row's dot product. A whole layer of a network is just that. Now try it on this lesson's page, and take the quiz. Find two different moves whose order doesn't matter.
You use this lesson in Lab 2: A small layer, and a cheap change to it, after Rank and low-rank matrices.
Facts last checked on .
