Linear algebra for LLMsPart 0: Start here
Notation
6 min
Scalars, vectors, matrices
- A scalar is one number. Lowercase italic: .
- A vector is a list of numbers. Lowercase: (some books use bold x).
- A matrix is a grid of numbers. Uppercase: .
Write
Shapes are (rows, columns)
W has 2 rows and 3 columns. Its shape is 2 × 3, rows first, always. In PyTorch, W.shape is torch.Size([2, 3]).
Write
Indexing: math counts from 1, code from 0
is the entry in row 2, column 3: here −1. In code the same entry is W[1, 2], because Python counts from 0.
Write
W[1, 2] (code) = −1.Papers: column vectors, y = Wx
Most math books and many papers treat a vector as a column and put the matrix on the left: . W maps 3 inputs to 2 outputs, so its shape is (outputs × inputs).
Code: row vectors, y = xW
Code stores one example (one token) per row, so the vector comes first: , with W shaped (inputs × outputs). It’s the same map, transposed: . Same numbers: 7 and −1.
Write
This course uses the code convention
A sequence of T tokens is a matrix X with one row per token and one column per feature, so its shape is . A layer with weight W computes : every row passes through W at once.
Write
nn.Linear stores its weight as (out, in)
lin = torch.nn.Linear(in_features=4, out_features=2)
lin.weight.shape # torch.Size([2, 4]) (out, in)
y = x @ lin.weight.T + lin.bias # what lin(x) computesPyTorch keeps the paper’s (out × in) layout for the weight and transposes it in the forward pass: . So a checkpoint’s q_proj.weight of shape [4096, 4096] reads as (out, in).
Write
nn.Linear: weight is (out, in); .The letters you'll see
| Letter | Means | Example size |
|---|---|---|
| T | tokens in the sequence | 2,048 |
| d | model width (d_model) | 4,096 |
| , | width of one attention head | 128 |
| h | attention heads | 32 |
| V | vocabulary size | 128,256 |
| B | batch size | 8 |
| L | layers | 32 |
| N | parameters in the model |
The example sizes are a Llama 3 8B-style model (except T and B, which you choose).
Write
📌 Recap
Notation in one card
- Scalars , vectors , matrices . Shapes are (rows, columns).
- Math indexes from 1 (), code from 0 (
W[1, 2]). - Papers: with W as (out × in). Code: with W as (in × out).
- This course: one row per token, is , a layer computes .
nn.Linearstores (out, in) and computes .
Write