Linear algebra for LLMsPart 0: Start here

Notation

6 min

Scalars, vectors, matrices

a=3a = 3
  • A scalar is one number. Lowercase italic: aa.
  • A vector is a list of numbers. Lowercase: xx (some books use bold x).
  • A matrix is a grid of numbers. Uppercase: WW.

Write

aa = scalar, xx = vector, WW = matrix.

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

Shape (2, 3) = 2 rows, 3 columns. Rows first.

Indexing: math counts from 1, code from 0

W23W_{23} 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

W23W_{23} (math) = 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: y=Wxy = Wx. 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: y=xWy = xW, with W shaped (inputs × outputs). It’s the same map, transposed: (Wx)⊤=x⊤W⊤(Wx)^\top = x^\top W^\top. Same numbers: 7 and −1.

Write

Papers: y=Wxy = Wx, W is (out × in). Code: y=xWy = xW, W is (in × out).

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 T×dT \times d. A layer with weight W computes XWXW: every row passes through W at once.

Write

XX is T×dT \times d: one row per token. A layer computes XWXW.

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

PyTorch keeps the paper’s (out × in) layout for the weight and transposes it in the forward pass: y=xW⊤+by = xW^\top + b. So a checkpoint’s q_proj.weight of shape [4096, 4096] reads as (out, in).

Write

nn.Linear: weight is (out, in); y=xW⊤+by = xW^\top + b.

The letters you'll see

Letter Means Example size
T tokens in the sequence 2,048
d model width (d_model) 4,096
dkd_k, dhd_h 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 8×1098 \times 10^9

The example sizes are a Llama 3 8B-style model (except T and B, which you choose).

Write

TT tokens, dd width, dhd_h head width, hh heads, VV vocab, BB batch, LL layers, NN params.

📌 Recap

Notation in one card

  • Scalars aa, vectors xx, matrices WW. Shapes are (rows, columns).
  • Math indexes from 1 (W23W_{23}), code from 0 (W[1, 2]).
  • Papers: y=Wxy = Wx with W as (out × in). Code: y=xWy = xW with W as (in × out).
  • This course: one row per token, XX is T×dT \times d, a layer computes XWXW.
  • nn.Linear stores (out, in) and computes xW⊤+bxW^\top + b.

Write

The five lines above.