Before you start: four words#
| Word | Plain meaning |
|---|---|
| Scalar | A single number, like 7 or -0.25. |
| Vector | An ordered list of numbers, like [3, -1, 4]. The order matters: position 0 means something different from position 2. |
| Matrix | A rectangular grid of numbers with rows and columns. |
| Shape | The size of each dimension. A matrix with 2 rows and 3 columns has shape (2, 3). |
That is all the vocabulary this lesson needs. The rest is what you can do with these objects.
1. What is it?#
Vectors and matrices are arrays of numbers with a small set of operations defined on them. A language model is, at the level the hardware sees it, almost nothing but:
- Multiply a vector (or a batch of vectors) by a matrix.
- Add a vector.
- Apply a simple function to every number on its own (for example “replace negatives with zero”).
If you understand those three operations you can read any model, including the transformer in 10.i.
2. Why does it exist?#
Because they let you write “apply this transformation to all of these things” as one object. That is:
- Compact to write. One line,
y = W @ x, describes millions of multiplications. - A perfect fit for the hardware. A GPU does thousands of identical operations at once (2.g). A matrix multiplication is thousands of identical multiply-and-add steps. The maths and the machine have the same shape, which is why AI runs on GPUs.
3. Simple analogy#
A vector is a shopping list; a matrix is a set of price lists.
The vector [2, 1, 3] could mean “2 eggs, 1 bag of flour, 3 bags of sugar”.
A matrix whose rows are different shops and whose columns are the same three items holds every shop’s prices. Multiplying the matrix by your list gives the total bill at every shop at once — one operation, many answers. That “one operation, many answers” property is what neural networks exploit and what GPUs are built for.
4. Tiny example#
Vector: v = [3, -1, 4] shape (3,)
Matrix: M = [ 1 2 3 ] shape (2, 3)
[ 4 5 6 ] 2 rows, 3 columns
Element: M[1][2] = 6 (row 1, column 2 — counting from 0)
Row: M[0] = [1, 2, 3]
Column: M[:,1] = [2, 5]The operations you need, each with a worked number:
Addition (elementwise, same shape):
[1,2,3] + [4,5,6] = [5,7,9]
Scalar multiply:
2 × [1,2,3] = [2,4,6]
Dot product (two vectors → one number): multiply matching positions, then add
[1,2,3] · [4,5,6] = 1·4 + 2·5 + 3·6 = 4 + 10 + 18 = 32
Elementwise (Hadamard) product (two vectors → vector):
[1,2,3] ⊙ [4,5,6] = [4,10,18]
Transpose (rows become columns):
[1 2 3]ᵀ = [1 4]
[4 5 6] [2 5]
[3 6]
Norm (length of a vector):
||[3,4]|| = √(3² + 4²) = √25 = 5Matrix × vector is just several dot products. Each row of the matrix is dotted with the vector:
M · v = [ 1·3 + 2·(-1) + 3·4 ] = [ 3 - 2 + 12 ] = [ 13 ]
[ 4·3 + 5·(-1) + 6·4 ] [ 12 - 5 + 24 ] [ 31 ]
shape: (2, 3) times (3,) → (2,)The dot product is the single most important operation in this material. Besides being the building block of matrix multiplication, it measures similarity: large and positive when two vectors point the same way, zero when they are perpendicular, negative when they point opposite ways. Attention (10.h) is built entirely out of dot products between “query” and “key” vectors.
5. Technical explanation#
What a matrix does#
A matrix is a linear transformation: it takes a vector in and gives a vector out, possibly of a different length.
M is (2, 3); v is (3,); M·v is (2,)
→ M turns 3-number vectors into 2-number vectorsFor neural networks, read W @ x as: “build a new vector in which each number is a different
learned mix of the input numbers.” Row i of W is the recipe for output number i. Training
(10.j) is the process of choosing those recipes.
That is why the shapes of a model’s matrices tell you what it does. Using d for the model’s
hidden size (the length of the vector that represents each token, e.g. 4,096), d_ff for the
wider feed-forward size and V for the vocabulary size:
W_q : (d, d) → same size in and out (a "projection")
W_up : (d, d_ff) → widen the vector
W_down : (d_ff, d) → narrow it back
embedding: (V, d) → one row of d numbers for each of V tokens (10.f)
lm_head: (d, V) → turn a hidden vector into one score per vocabulary tokenDot product as similarity#
For vectors of length 1, the dot product equals the cosine of the angle between them:
a · b = cos(θ). Two worked cases:
a = [1, 0], b = [1, 0] → a·b = 1 (same direction)
a = [1, 0], b = [0, 1] → a·b = 0 (perpendicular: unrelated)
a = [1, 0], b = [-1, 0] → a·b = -1 (opposite)In attention:
q · k large → "this query is looking for what this key offers"
q · k small → irrelevantWhy attention divides by √d. If the entries of two random vectors are each around ±1, their
dot product is a sum of d random terms, so its typical size grows like √d. For d = 128 that
is about 11; for d = 4,096, about 64. Large scores make softmax (10.g) put almost all weight on
one item, which stops learning and makes outputs brittle. Dividing by √d_head brings the scores
back to a typical size of about 1. Exercise D below lets you measure this.
Notation you will meet#
Maths papers: y = Wx (column vectors, weight on the left)
PyTorch code: y = x @ W.T nn.Linear stores its weight as (out, in)
Batched code: Y = X @ W.T X is (batch, in), Y is (batch, out)nn.Linear(in_features, out_features) stores weight with shape (out_features, in_features)
and computes x @ weight.T + bias. Knowing this prevents a whole category of confusing bugs when
you read model or kernel code. (Most current large language models leave out the bias term in
their linear layers.)
6. Under the hood#
In memory, a matrix is one flat block of numbers plus a shape and strides — how far to jump to reach the next row or column (2.b):
M = [[1,2,3],[4,5,6]] stored row by row: [1, 2, 3, 4, 5, 6]
strides = (3, 1) → M[i][j] lives at position 3i + jStoring row by row (“row-major”, C order) is the default in PyTorch and NumPy. Storing column by column (“column-major”, Fortran order) is what the classic BLAS maths libraries expected, which is why cuBLAS calls inside framework code often look transposed. Those transposes are usually layout bookkeeping, not maths. 11.g covers layouts in depth.
7. Performance implications#
- A single dot product is the worst possible GPU job. For vectors of length
dit does2doperations but reads2dnumbers, so it does about one operation per number loaded. The GPU’s arithmetic units sit idle waiting for memory (2.e, 2.f). - Batching many dot products into one matrix multiplication reuses each loaded number many times, which is what makes the GPU efficient (2.d, 11.c).
- A transpose is free as metadata, expensive in memory if a later kernel needs the data laid out contiguously and it has to be copied.
- Norms and elementwise operations are memory-bound: they read and write every number once and do little arithmetic. Fuse them into neighbouring operations when you can (11.h).
8. Production implications#
You will read model and kernel code constantly. Fluency with shapes is the difference between “this file is unreadable” and “this projects into the key/value space with 8 heads”.
A practical habit: when you read unfamiliar model code, write the output shape of every line in a comment. It takes two minutes and turns confusion into understanding.
9. Common mistakes#
Confusing the dot product with the elementwise product. a · b is one number; a ⊙ b is a
vector.
Getting the transpose wrong in nn.Linear. The weight is (out, in); the computation is
x @ W.T.
Forgetting the √d scaling in attention. It produces a softmax that puts all weight on one
token, and at inference near-deterministic, poor outputs.
Assuming matrix multiplication is commutative. AB ≠ BA, and often the shapes do not even
allow both.
10. Hands-on exercise#
A. By hand, no computer. Given
A = [1 2] B = [ 3 0 1] v = [2]
[0 -1] [-1 2 4] [5]compute Av, AB, Bᵀ, v · v and ||v||. Check your answers with a few lines in any
language. (Answers: Av = [12, -5], AB = [[1,4,9],[1,-2,-4]], v·v = 29, ||v|| ≈ 5.39.)
B. Shape detective. Load any small open model in PyTorch and print
[(n, tuple(p.shape)) for n, p in model.named_parameters()]. For each parameter, say in words
which transformation it performs and between which sizes.
C. Dot product as similarity. Take five word embeddings from any pretrained model and compute all pairwise cosine similarities. Do the results match your intuition about the words?
D. The √d argument. Generate random vectors of length d ∈ {64, 512, 4096} whose entries are drawn from a normal distribution with mean 0 and standard deviation 1. Measure the standard deviation of their dot products. Confirm that it grows like √d, then explain in one sentence why attention divides by √d_head.
11. Interview questions#
- What does a matrix multiplication represent geometrically?
- Why does attention scale scores by
1/√d_head? - What shape does
nn.Linear(768, 3072)store its weight in, and what does it compute? - Why is a single dot product a poor use of a GPU, and what fixes it?
- What is the difference between row-major and column-major storage, and where does it bite?
12. Further reading#
- [FUNDAMENTAL] 3Blue1Brown, Essence of Linear Algebra — videos 1–4 and 9.
- [REFERENCE] PyTorch
torch.nn.Linear— the(out, in)weight convention. - [REFERENCE] NumPy linear algebra.