Discover: counting what you can't yet read
Here is a line from the Transformer paper, the one whose Equation 1 opened Chamber 1:
Spotted in the wild
You don't know yet what a “query projection” is, and you don't need to. Every piece of this line is notation you have already met, and Chamber 2's paper decoder took it apart as set membership. is a capital letter with a subscript and a superscript label (Chamber 1). The symbol says “is an element of”, and is the set of grids of real numbers with rows and columns (Chamber 2). So the line is a list of shapes.
Shapes are more informative than they look. The paper sets in Section 3.1, and a few lines after this one it uses heads with . That's enough to answer a real question about the model:
Take a guess before reading on. The Transformer paper declares and uses , and . The in the superscript is a product, times . How many numbers does the matrix hold?
This chamber teaches you to read vectors and matrices the way researchers do: as named objects with shapes, whose entries you can address one at a time. The next course, Linear Algebra for Machine Learning, explains what these objects do. Here you learn to read and write them.
Learn: vectors are columns of numbers
A vector is an ordered list of numbers. Chamber 1's typeface rule says it's printed in bold, and Chamber 2 gave you the set it lives in: , read “x in R n”, means is a list of real numbers. By convention the list stands up, as a column:
The entries are single numbers, so they're printed plain. Columns eat vertical space, so in running text authors lay the vector down and add a transpose sign: . The little , read “transpose”, turns a row into a column and back. It is never a power.
A few vectors are so common they have their own names:
- “x in R n”is a list of real numbers: a vector with entries. Unless a paper says otherwise, it stands as a column, .
- “x sub i”The -th entry of . It's a single number, so it's printed plain, not bold.
- “x transpose”The same numbers laid out as a row, . Also printed , or . It is never a power.
- “the zero vector”Every entry is . Its length comes from context, or a subscript: .
- “the ones vector”Every entry is . Handy for sums: .
- “e sub i”The -th standard basis vector: zeros everywhere except a in position . In ML it's a one-hot vector.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “x in R n” | is a list of real numbers: a vector with entries. Unless a paper says otherwise, it stands as a column, . | ||
| “x sub i” | The -th entry of . It's a single number, so it's printed plain, not bold. | ||
| “x transpose” | The same numbers laid out as a row, . Also printed , or . It is never a power. | ||
| “the zero vector” | Every entry is . Its length comes from context, or a subscript: . | ||
| “the ones vector” | Every entry is . Handy for sums: . | ||
| “e sub i” | The -th standard basis vector: zeros everywhere except a in position . In ML it's a one-hot vector. |
The one-hot vector is how a class label becomes something a network can use: in a problem with 5 classes, label 3 is .
Let , a column vector as usual. What is the shape of ?
Learn: lengths and dot products
Two vectors of the same length can be combined into a single number by multiplying matching entries and adding. This is the dot product, and it has three common spellings:
The first spelling is the one ML papers use most, because it's a matrix product in disguise: a row times an column is , a single number. The is Chamber 5's loop, with as the dummy index.
A vector also has sizes, called norms. The subscript says which one:
- “the two-norm of x”The ordinary length, . Often written just .
- “the one-norm of x”Add up the sizes of the entries: .
- “the squared two-norm of x”, with no square root. Squared errors and weight penalties are written this way.
- “the inner product of x and y, in angle brackets”Multiply matching entries and add: . Both vectors need the same length.
- “x transpose y”The same number as , written as a matrix product: a row times an column.
- “x dot y”A third name for the same number, the dot product. Physics and school books prefer this one.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “the two-norm of x” | The ordinary length, . Often written just . | ||
| “the one-norm of x” | Add up the sizes of the entries: . | ||
| “the squared two-norm of x” | , with no square root. Squared errors and weight penalties are written this way. | ||
| “the inner product of x and y, in angle brackets” | Multiply matching entries and add: . Both vectors need the same length. | ||
| “x transpose y” | The same number as , written as a matrix product: a row times an column. | ||
| “x dot y” | A third name for the same number, the dot product. Physics and school books prefer this one. |
Notation earns its keep when it makes long things short. Here is a derivation you'll see in the opening pages of many papers: the sum of squared errors, rewritten as a norm.
Let hold a model's predictions and the true values, and call the difference , the residual, so . Then
Step (1) uses the definition of , and (2) says a square is a number times itself. Step (3) recognises the dot product of with itself, (4) is the definition of the two-norm, squared, and (5) substitutes back in.
So the mean squared error, , is written : one symbol for a whole loop. In the same spirit, adds up the entries of , so the mean of is .
Learn: matrices, entries, rows and columns
A matrix is a grid of numbers. , read “A is an m by n matrix”, means rows and columns, rows first, always. The entry in row and column is :
For example, if
Papers often need a whole row or a whole column at once, and have borrowed the colon from code for it: is row 2, and is column 3. The transpose flips the grid across its diagonal, so the rows become columns:
- “A is an m by n matrix”A grid of real numbers with rows and columns: numbers in all. Rows first, always.
- “A sub i j”The entry in row , column . Also written , or .
- “row i of A”The whole -th row, a row. The colon means “every index here”, just as in NumPy.
- “column j of A”The whole -th column, an column.
- “A transpose”Flip across the diagonal: . Rows become columns, so an matrix becomes .
- “the identity matrix”Square, with ones on the diagonal and zeros elsewhere, so . Written when the size matters.
- “diag of d”The square matrix with the entries of down its diagonal and zeros everywhere else.
- “the data matrix X”A dataset of examples with features each: one example per row, one feature per column.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “A is an m by n matrix” | A grid of real numbers with rows and columns: numbers in all. Rows first, always. | ||
| “A sub i j” | The entry in row , column . Also written , or . | ||
| “row i of A” | The whole -th row, a row. The colon means “every index here”, just as in NumPy. | ||
| “column j of A” | The whole -th column, an column. | ||
| “A transpose” | Flip across the diagonal: . Rows become columns, so an matrix becomes . | ||
| “the identity matrix” | Square, with ones on the diagonal and zeros elsewhere, so . Written when the size matters. | ||
| “diag of d” | The square matrix with the entries of down its diagonal and zeros everywhere else. | ||
| “the data matrix X” | A dataset of examples with features each: one example per row, one feature per column. |
The data matrix ties this chamber to Chamber 1's bracketed superscripts. With examples , each a vector of features, stacks them as rows. The entry is feature of example , the same number as .
Learn: products are sums over indices
Here is the most important formula in the chamber. A matrix times a vector is a new vector, and for and its -th entry is a sum over :
Read it aloud: “entry of A x is the sum over of A i j times x j.” Fix a row , walk along it with , multiply each entry by the matching entry of , and add. In other words, entry is row of dotted with . For instance,
Let and . Using , what is ?
A matrix times a matrix works the same way, one entry at a time. For and ,
Look at where the indices sit. The free indices and pick the entry; the dummy index is summed away, running along row of and down column of . For that to work, the row of and the column of must have the same length, . That single fact is the shape rule:
The inner sizes must match and disappear; the outer sizes survive. It also shows why order matters. If is and is , then is while doesn't even exist.
Let and . Which statement is true?
Two more operations complete the toolkit, and both have a stricter rule. Addition and the Hadamard product work entry by entry, so the two sides must have exactly the same shape:
And watch where the transpose goes on a pair of vectors. is , a single number. is , a whole matrix, the outer product. Same letters, same transpose, completely different objects.
- “A times x”A new vector whose -th entry is row of dotted with . Needs 's column count to equal 's length.
- “A times B”. Shapes: . The inner sizes must match; the outer ones survive.
- “A Hadamard B”Multiply entry by entry: . Both must have the same shape. Also called the element-wise product.
- “A plus B”Add entry by entry. As with , both must have exactly the same shape.
- “the outer product of x and y”A column times a row makes a whole matrix: . For and it is .
- “the transpose of A B is B transpose A transpose”Transposing a product reverses the order of the factors. Proved in this chamber, entry by entry.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “A times x” | A new vector whose -th entry is row of dotted with . Needs 's column count to equal 's length. | ||
| “A times B” | . Shapes: . The inner sizes must match; the outer ones survive. | ||
| “A Hadamard B” | Multiply entry by entry: . Both must have the same shape. Also called the element-wise product. | ||
| “A plus B” | Add entry by entry. As with , both must have exactly the same shape. | ||
| “the outer product of x and y” | A column times a row makes a whole matrix: . For and it is . | ||
| “the transpose of A B is B transpose A transpose” | Transposing a product reverses the order of the factors. Proved in this chamber, entry by entry. |
Learn: the transpose of a product
Now a proof, entirely by indices. It's short, but it's a model for how most matrix facts are proved: check the shapes, then compare one arbitrary entry.
Claim. For any and , .
Proof. First the shapes. is , so is . On the other side, is and is : the inner sizes match, so exists and is too. Two matrices of the same shape are equal when every entry agrees, so take any row and column :
Step (1) is the definition of the transpose and (2) the definition of the product. Step (3) swaps two numbers, which is allowed because multiplication of numbers commutes. Step (4) uses the definition of the transpose twice, and (5) recognises the definition of the product. Since and were arbitrary, every entry agrees, and .
The step that does the work is (3). To recognise a product in step (5), we need the pattern “row index , summed index , column index ”, and that pattern only appears once comes first. Swapping the two numbers is what reverses the order of the matrices. It's the same as socks and shoes: you put on socks, then shoes, and to undo it you take off the shoes first.
Learn: become a shape detective
Every matrix expression in a paper can be checked in a few seconds, and experienced readers do it without thinking. The routine:
- 1
Write the shape under every symbol
Vectors are columns unless the paper says otherwise. A transpose swaps the two numbers.
- 2
Multiply left to right with the shape rule
Inner sizes must match and vanish; outer sizes survive. Products are associative, so for the shape it doesn't matter which pair you do first.
- 3
Sums and ⊙ need identical shapes
If they differ, the expression is undefined in mathematics, even if NumPy would happily broadcast it (more on that below).
- 4
Read the result
is a number, a vector, anything else a matrix.
Try it on the heart of LoRA, the paper you'll read later in this chamber. With , and :
Both junctions match (, ), so the result is a -dimensional vector. Swap the first two and fails immediately: needs . Now it's your turn.
Interactive lab
Shape detective
Expression 1 of 8: what is the shape of
Learn: tensors, batches and code
Real models push notation one step further. A tensor is a grid with three or more indices. A batch of sentences, each tokens long, each token a -dimensional vector, is a single tensor , with entries . Code almost always puts the batch dimension first, so that is one whole example.
This is also where papers and code part ways on rows and columns. PyTorch's nn.Linear documentation states its formula as , with a weight of shape (out_features, in_features) and inputs whose last axis holds the features. That's the row convention, and the transpose is exactly the one from the insight box above.
The third difference is broadcasting. In strict matrix algebra, adding a vector to a matrix is undefined. Deep-learning writing relaxes this on purpose. Goodfellow, Bengio and Courville's Deep Learning allows , meaning : add to every row. NumPy does the same automatically. It compares shapes from the right, and two sizes are compatible when they are equal or one of them is 1, which is then stretched to fit.
- “X is B by n by d”A tensor: a grid with three indices. Here, a batch of sequences, each of tokens, each token a -dimensional vector.
- “X b colon colon”Fix the first index and keep the rest: example of the batch, an matrix.
- “A plus b, broadcast”Deep-learning shorthand (and NumPy behaviour): add the vector to every row of . Strict matrix algebra would call it undefined.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “X is B by n by d” | A tensor: a grid with three indices. Here, a batch of sequences, each of tokens, each token a -dimensional vector. | ||
| “X b colon colon” | Fix the first index and keep the rest: example of the batch, an matrix. | ||
| “A plus b, broadcast” | Deep-learning shorthand (and NumPy behaviour): add the vector to every row of . Strict matrix algebra would call it undefined. |
Read beyond the course
These all use exactly the notation of this chamber. Read them with a pencil, writing the shape under each symbol as you go.
Book · free online · ~30 min
Deep Learning, Chapter 2: Linear AlgebraIan Goodfellow, Yoshua Bengio & Aaron Courville · Sections 2.1–2.3
Scalars, vectors, matrices and tensors, the matrix product as a sum, the transpose of a product, and the broadcasting convention quoted in this chamber. It's the notation most deep-learning papers copy, written by people who use it every day.
Lecture notes · free online · ~35 min
Linear Algebra Review and ReferenceZico Kolter, updated by Chuong Do (Stanford CS229) · Sections 1–2, then 3.1–3.2
Famously compact. Section 1 is a notation page much like this chamber's tables, and Section 2 shows four different ways to read a matrix product. Stop before the determinant; the Linear Algebra course picks up from there.
Book · free online · ~30 min
Mathematics for Machine LearningMarc Peter Deisenroth, A. Aldo Faisal & Cheng Soon Ong · Section 2.2: Matrices
Matrix addition, multiplication, transposes and the identity, with small worked examples. A gentler pace than the CS229 notes, and the book you'll keep using in the Linear Algebra course.
Tool · free online · ~15 min
BroadcastingNumPy documentation
The official rules, with pictures of arrays being stretched. Ten minutes here prevents hours of debugging. Try each example in a Python shell and predict the shape before you run it.
Article · free online · ~20 min
Einsum is All you Need: Einstein Summation in Deep LearningTim Rocktäschel
Index formulas like translate almost letter for letter into code with einsum. This post shows how, and it will change how you read every formula in this chamber.
Papers and lectures
You can read a real paper's shapes today. Open the LoRA paper and look first at Figure 1 on page 1: the frozen weights are drawn as a big square, and the two small trainable matrices and as thin slabs. Then read the first paragraph of Section 4.1, which ends in Equation (3). It's a string of statements followed by one equation, and you now know everything in it. Skip the experiments (Sections 5 onwards) for now. Afterwards, open the Transformer paper at Section 3.2.2 and read the last paragraph, where the Discover line comes from.
LoRA: Low-Rank Adaptation of Large Language ModelsEdward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen · ICLR, 2022Fine-tunes giant language models by training two thin matrices per layer instead of the full weights. Its central idea is stated almost entirely in shapes, which makes it a perfect first paper to read for notation.
Attention Is All You NeedAshish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin · NIPS, 2017The Transformer. Section 3.2 declares the shape of every matrix in multi-head attention, and footnote 4 writes a dot product as the sum . Chamber 9 decodes its Equation 1.
Decode the paper · Eq. (3), Section 4.1
LoRA: Low-Rank Adaptation of Large Language ModelsEdward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen · ICLR, 2022
Just before this equation the paper declares its shapes: , , , with the rank . The equation is the forward pass of one adapted layer. Match each symbol to its meaning.
Options
Watch
The video starts at 15:18, where transposes come in. Watch how a neural network becomes one matrix equation, then how the same shapes explain PyTorch's nn.Linear documentation and its error messages. The first fifteen minutes (linear transformations) are good preparation for the Linear Algebra course.
A short recap of the same notation from a different teacher. Pause whenever a symbol appears and say it aloud before the narrator does.
Your turn
Translate between symbols, words and code, then prove two shape facts and compute your way through three problems, one of them straight from LoRA.
Match · Symbols ↔ Read aloud as
Say it aloud
Match each piece of notation to the way you'd read it, and what it means.
Options
Match · Maths ↔ NumPy
From notation to NumPy
Match each piece of notation to the NumPy that computes it. Remember that papers count from 1 and Python counts from 0, and that in NumPy * is entry by entry while @ is the matrix product.
Options
Proofs
Both proofs use the same two moves: check the shapes, then expand into indices. The puzzle has a line or two that don't belong.
Proof puzzle
Adding up every entry
Claim
For any , with and the all-ones vectors,
Tap lines in the order they should appear. Not every line belongs. Tap a line in your proof to send it back.
Your proof
- Pick the first line below.
Available lines
Prove it yourself
A number is its own transpose
Claim
For any , and :
Your typeset proof appears here.
Code it up
Each problem has a single answer. The index formulas from this chamber are all you need, plus a loop or two. NumPy is available in the browser runner if you want it.
Problem 16·Warm-up
One attention score
Attention compares a query vector with a key vector using their dot product. Footnote 4 of the Transformer paper writes it as a sum,
and Equation 1 then divides by .
Take and, for ,
Compute the scaled score . It comes out exact: give it as a decimal with 3 decimal places.
Problem 17·Standard
LoRA's budget, from shapes alone
Section 4.1 of the LoRA paper keeps a pre-trained weight matrix frozen and learns an update , where and . So fine-tuning directly would train numbers, while LoRA trains the entries of and instead.
A 12-layer Transformer the size of BERT-base has, in every layer, four attention matrices and two feed-forward matrices and . Apply LoRA with rank to all six matrices in all 12 layers. (The paper itself adapts only and ; here we adapt all six.)
What fraction of the entries of those 72 matrices does LoRA train? That is, compute
Give it as a reduced fraction, like 3/7.
Problem 18·Challenge
Where to put the brackets
Multiplying a matrix by a matrix with the index formula takes multiplications for each of the entries: scalar multiplications in all.
Matrix products are associative, so a chain can be bracketed however you like. The answer never changes, but the cost does. LoRA is the classic case: with , and , computing costs multiplications, while costs only .
Now take the chain , where and
Over all ways of bracketing the product, what is the smallest number of scalar multiplications needed to compute it? Give an integer.
Key takeaways
- is a column of numbers. is one entry, is the same numbers as a row, and , and are the named vectors.
- has rows and columns, rows first. is an entry, a row, a column, and .
- Products are sums over indices: and . is a number; is a matrix.
- The shape rule: , while and need identical shapes. Transposing a product reverses it: .
- Code differs from papers: batch first, examples as rows ( rather than ), and broadcasting stretches shapes that mathematics would reject. Check shapes on paper and with
.shape.
Checkpoint
Prove it to the labyrinth
Answer every question to clear this chamber. First-try answers earn the most XP.
Let and . What is ?
Let . What is ?
A paper writes . What does it mean?
Let and . What is ?
Let and . Which expression equals ?
In NumPy, a has shape (3,) and b has shape (3, 1). What is the shape of a + b?
LoRA writes a weight update as with and . For and , how many numbers do and hold together?
A batch holds 32 sequences of 128 tokens, each token a 512-dimensional vector. What is the shape of ?
End of the chamber
Clear this chamber
- Questions in this chamber (0/12 solved)Next unsolved
- Bonus: Shape detective (+40 XP)
- Bonus: Problem 16: One attention score (+20 XP)
- Bonus: Problem 17: LoRA's budget, from shapes alone (+35 XP)
- Bonus: Problem 18: Where to put the brackets (+50 XP)
- Bonus: Proof: Adding up every entry (+25 XP)
- Bonus: Proof: A number is its own transpose (+40 XP)
- Bonus: Decode the paper (+30 XP)
- Bonus: Match: Say it aloud (+25 XP)
- Bonus: Match: From notation to NumPy (+25 XP)