Discover: a promise from Chamber 1
In the very first chamber you met this line, and a promise that by Chamber 9 you'd read it like an ordinary sentence and turn it into working code. Here it is again, exactly as the paper prints it:
Spotted in the wild
Try reading it aloud now: “Attention of Q, K and V equals softmax of Q K transpose over the square root of d k, all times V.” You can say it, and you know what every piece of notation does. Upright words are function names (Chamber 1), the is a transpose rather than a power (Chamber 6), is a with a label, and a fraction divides.
But saying it isn't the same as being able to compute it. To compute it, you need to know what kind of object each letter is, and above all its shape. The paper never writes the shapes down. Before reading on, see if you can work out the first one.
Suppose and . What is the shape of ?
Learn: a protocol for any equation
Experienced researchers don't read a hard equation once, top to bottom, and hope. They interrogate it in a fixed order. Here is that order as six steps. Each one uses skills from an earlier chamber.
- 1
1. Find where each symbol is defined
Look in the notation section if there is one, then in the sentences just before the equation, in algorithm boxes and their captions, and sometimes in an appendix. Never guess a symbol's meaning from habit alone: habits are good hints (Chamber 1), not definitions.
- 2
2. Give each symbol a type and a shape
Is it a number, a vector, a matrix, a set, a function or a distribution? If it's an array, what are its dimensions (Chamber 6)? Then check that every operation in the equation is legal for those shapes.
- 3
3. Read it aloud
Turn the line into a sentence, and then into plain English: what does it do? If you can't say it, go back to step 1.
- 4
4. Work a tiny example by hand
Choose the smallest inputs that aren't trivial: two or three numbers, matrices. Compute the result with pen and paper.
- 5
5. Code it
Translate symbol by symbol, then run it on your tiny example and check that it matches your hand calculation.
- 6
6. Sanity-check special cases
What should happen when inputs are all equal, zero, huge or tiny? Do probabilities sum to 1? Do the shapes come out right? Does the formula reduce to something you already know?
It feels slow the first few times. That's normal, and it gets faster with practice. After a dozen equations the first three steps take seconds, and steps 4 to 6 are where your understanding actually comes from.
Learn: the protocol on attention
Let's run all six steps on the equation above.
Step 1: definitions. The paper has no notation section. The definitions are in the prose of Section 3.2.1: “The input consists of queries and keys of dimension , and values of dimension ”, and in practice the queries are “packed together into a matrix ”, with the keys and values packed into matrices and .
Step 2: types and shapes. Say there are queries and keys, each key with its own value. Packing one vector per row:
Now follow the shapes through the equation:
| Expression | Shape | What it holds |
|---|---|---|
| the dot product of every query with every key | ||
| the same scores, scaled down by a number | ||
| each row turned into weights that sum to 1 | ||
| one output row per query |
Notice one thing the paper leaves unsaid: softmax is applied to each row separately, one row per query. The equation's notation doesn't say so, and the prose only implies it (“to obtain the weights on the values”). Silent conventions like this are common, and step 2 is where you catch them.
Step 3: read aloud. “For each query, score every key by its dot product with the query, scale the scores down, turn them into weights with a softmax, and return the weighted average of the values.” Attention is a soft lookup: every value contributes, weighted by how well its key matches the query.
Step 4: a tiny example. One query and two keys, with :
The scores are . Dividing by gives . The softmax gives weights . The output is . The query points the same way as the first key, so the output is mostly the first value.
Step 5: code. Symbol by symbol:
import numpy as np
def attention(Q, K, V):
d_k = K.shape[1]
S = Q @ K.T / np.sqrt(d_k) # (n, m) scores
S = S - S.max(axis=1, keepdims=True) # safe: softmax ignores shifts (proof below)
W = np.exp(S) / np.exp(S).sum(axis=1, keepdims=True) # each row sums to 1
return W @ V # (n, d_v)
Q = np.array([[1.0, 1.0]])
K = np.array([[1.0, 1.0], [1.0, -1.0]])
V = np.array([[10.0, 0.0], [0.0, 10.0]])
print(attention(Q, K, V)) # [[8.044 1.956]]
Step 6: sanity checks. If every key is identical, every score in a row is equal, the weights are all , and the output is the plain average of the rows of . If you multiply by 100, the scores spread out, the softmax puts almost all its weight on the best-matching key, and attention becomes a hard lookup. And since each output row is a weighted average of rows of , its entries can never leave the range of 's columns. All three are quick tests of your code.
Why divide by the square root of d k? A derivation
The paper justifies the in its footnote 4, with a probability argument you can now follow in full. Suppose the entries of a query and a key are independent random variables, each with mean 0 and variance 1. Their dot product is .
Each term has mean zero, because independence lets the expectation of a product split: . Its variance is
using the variance shortcut of Chamber 8 and independence again. The terms are independent, and the variances of independent variables add, so
In the paper each head has , so raw scores would have a standard deviation of 8. Scores that far apart push softmax to nearly 0 or 1, where, in the paper's words, it has “extremely small gradients”. Dividing by keeps the scores at a comfortable scale however long the vectors are.
Learn: softmax, temperature and a proof
Chamber 4 previewed softmax. Now it's time to take it apart. Softmax turns any list of real numbers (logits) into probabilities:
Read it “softmax of z, entry i”. Exponentiating makes every entry positive, and dividing by the total makes them sum to 1. Larger logits get larger probabilities. A 2015 paper on distilling large networks into small ones adds a knob:
Spotted in the wild
Here is a temperature, “normally set to 1”, as the paper says. (Notice that the paper sets in italics, which strictly reads as . By Chamber 1's rules it should be upright, . Nobody is confused, because context rescues the reader: that's how small slips survive in published papers.) Here's what the temperature does to the logits :
| Temperature | |||
|---|---|---|---|
| 0.5 | 0.980 | 0.018 | 0.002 |
| 1 | 0.844 | 0.114 | 0.042 |
| 2 | 0.629 | 0.231 | 0.140 |
| 10 | 0.391 | 0.320 | 0.289 |
Low temperatures sharpen the distribution towards the largest logit. High temperatures flatten it towards uniform. Distillation trains a small network to match a large network's softened outputs, which carry more information than hard labels: they say which wrong answers were nearly right.
In , what happens to the probabilities as the temperature grows very large?
A proof: softmax ignores shifts
Claim. For any logits and any real number , adding to every logit leaves softmax unchanged: .
Proof. Take any entry . By the definition of softmax, and then the rule (Chamber 4),
The third step pulls the constant out of the sum (Chamber 5's linearity), and the last cancels it, which is allowed because . Since was arbitrary, every entry is unchanged.
The proof has a very practical use. A computer can't represent : it overflows to infinity, and infinity divided by infinity is “not a number”. Choosing makes the largest shifted logit exactly 0, so no exponential can overflow, and the proof guarantees the answer hasn't changed. That's the S - S.max(...) line in the code above. Problem 1 below puts it to work.
Learn: Adam's Algorithm 1, line by line
In Chamber 1 you decoded the last line of Adam and were promised the rest. Here is the loop of Algorithm 1 from Kingma and Ba's paper, with a reading and a line of NumPy for each step.
| Line of Algorithm 1 | Read aloud | NumPy |
|---|---|---|
| t gets t plus one | t += 1 | |
| g t gets the gradient, w.r.t. theta, of f t at the previous theta | g = grad(theta) | |
| a running average of gradients | m = beta1 * m + (1 - beta1) * g | |
| a running average of squared gradients | v = beta2 * v + (1 - beta2) * g**2 | |
| m hat: the bias-corrected average | m_hat = m / (1 - beta1**t) | |
| v hat: the same correction | v_hat = v / (1 - beta2**t) | |
| the update you decoded in Chamber 1 | theta = theta - alpha * m_hat / (np.sqrt(v_hat) + eps) |
Before the loop, , and start at 0. The paper's defaults are , , and .
The caption of Algorithm 1 is a small notation section of its own, and it answers exactly the questions step 2 of the protocol would ask. It says that “indicates the elementwise square”, that “all operations on vectors are element-wise”, and that and mean “ and to the power ”. That last one is Chamber 1's warning about powers and positions, stated by the authors themselves: the on is an index, but the on is a power.
Step 6 of the protocol, sanity checks, reveals something neat. On the very first step, , so exactly. Likewise . Ignoring the tiny , the first update is for every parameter, whatever the size of its gradient. Without the hats, would badly underestimate the gradient. How big is that bias at later steps? If the gradients are stationary (their expected value doesn't change), then
which is exactly the factor the hat divides out. The proof is a geometric series (Chamber 5), and you'll assemble it yourself in the proof puzzle below.
Adam's Algorithm 1 updates , where is the gradient vector. What is ?
Learn: notation sections, and your own notation table
Step 1 of the protocol is a search, and it helps to know where definitions hide.
- A notation section or table of symbols at the front: textbooks such as Deep Learning and Mathematics for Machine Learning have one, and so do some long papers.
- A “Preliminaries” or “Background” section that fixes notation before the method.
- The prose just before an equation, like attention's Section 3.2.1.
- Algorithm captions, like Adam's.
- An appendix. The VAE paper (Kingma and Welling), which you'll decode below, uses in its Eq. (10) but only says “Let be the dimensionality of ” in Appendix B. Its Figure 2 caption calls the same quantity .
When a paper doesn't give you a table, build your own as you read. It takes a few minutes and pays for itself on the second page. Here is one for the core of the VAE paper, with one row per symbol:
| Symbol | Read as | Type and shape | Meaning | Defined in |
|---|---|---|---|---|
| x i | vector | the -th of i.i.d. data points | §2.1 | |
| z | vector in | the unobserved latent code | §2.1 | |
| (also ) | J | integer | the dimension of | Appendix B |
| theta | parameters | the generative model (decoder) | §2.1 | |
| phi | parameters | the recognition model (encoder) | §2.1 | |
| p theta of x given z | distribution over | the decoder | §2.1 | |
| q phi of z given x | distribution over | the encoder, approximating | §2.1 | |
| L of theta and phi at x i | a number | the variational lower bound | §2.2 |
Section 2.1 of that paper is also a good test of Chamber 8. In a few lines it writes a marginal likelihood as an integral, , and the true posterior with Bayes' rule, . You can read both now.
Papers also lean on a stock of shorthand that rarely gets defined at all:
- “with respect to”Names the variable a derivative or an optimisation is taken over. The Adam paper computes “gradients w.r.t. stochastic objective”.
- “minimise f of x subject to x at least zero”In an optimisation problem, “s.t.” means subject to: it introduces the constraints the answer must satisfy. (In a definition, the same letters mean “such that”, as in Chamber 3.)
- “f of dot”The dot is a placeholder for “whatever argument goes here”, so means the function itself, not a value of it. The same dot turns up in norms, .
- “x one to T”The whole sequence . Colon ranges are everywhere in papers on sequences.
- “x before t”Everything before position : . The notation of language models, which predict each token from the ones before it.
- “plus a constant”Terms that don't depend on the variable of interest, lumped together and ignored because they don't change the argmin.
- “the positive part of z”Shorthand for , the ReLU of Chamber 4 in different clothes. Common in hinge losses.
- “sim-equals, is estimated by”A cousin of , called “sim-equals” after its LaTeX name,
\simeq. The VAE paper uses it for “this sample average stands in for that expectation”.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “with respect to” | Names the variable a derivative or an optimisation is taken over. The Adam paper computes “gradients w.r.t. stochastic objective”. | ||
| “minimise f of x subject to x at least zero” | In an optimisation problem, “s.t.” means subject to: it introduces the constraints the answer must satisfy. (In a definition, the same letters mean “such that”, as in Chamber 3.) | ||
| “f of dot” | The dot is a placeholder for “whatever argument goes here”, so means the function itself, not a value of it. The same dot turns up in norms, . | ||
| “x one to T” | The whole sequence . Colon ranges are everywhere in papers on sequences. | ||
| “x before t” | Everything before position : . The notation of language models, which predict each token from the ones before it. | ||
| “plus a constant” | Terms that don't depend on the variable of interest, lumped together and ignored because they don't change the argmin. | ||
| “the positive part of z” | Shorthand for , the ReLU of Chamber 4 in different clothes. Common in hinge losses. | ||
| “sim-equals, is estimated by” | A cousin of , called “sim-equals” after its LaTeX name, \simeq. The VAE paper uses it for “this sample average stands in for that expectation”. |
- “Q, the queries”In attention, a matrix with one row per position that is asking: shape .
- “K, the keys”One row per position that can be looked up, compared with every query: shape .
- “V, the values”The content that gets mixed, one row per key: shape .
- “d k, the key dimension”The length of each query and key vector. The Transformer uses per head.
- “g t squared, element by element”In Adam, the square of every entry of the gradient vector (), not a dot product.
- “q phi of z given x, the encoder”In a VAE, the encoder: a distribution over codes for the input , with parameters .
- “p theta of x given z, the decoder”In a VAE, the decoder: how likely the input is to be rebuilt from the code .
- “the ELBO, L of theta and phi at x i”The evidence lower bound for data point : the number a VAE maximises. Parameters before the semicolon, data after (Chamber 4's the other way round).
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “Q, the queries” | In attention, a matrix with one row per position that is asking: shape . | ||
| “K, the keys” | One row per position that can be looked up, compared with every query: shape . | ||
| “V, the values” | The content that gets mixed, one row per key: shape . | ||
| “d k, the key dimension” | The length of each query and key vector. The Transformer uses per head. | ||
| “g t squared, element by element” | In Adam, the square of every entry of the gradient vector (), not a dot product. | ||
| “q phi of z given x, the encoder” | In a VAE, the encoder: a distribution over codes for the input , with parameters . | ||
| “p theta of x given z, the decoder” | In a VAE, the decoder: how likely the input is to be rebuilt from the code . | ||
| “the ELBO, L of theta and phi at x i” | The evidence lower bound for data point : the number a VAE maximises. Parameters before the semicolon, data after (Chamber 4's the other way round). |
Learn: overloaded symbols and abuse of notation
There are more ideas than letters, so symbols get reused. A single paper might use for the sigmoid in one equation and a standard deviation in the next. can be a transpose, a temperature or the number of time steps. is a probability, a distribution, or dropout's keep probability, and PyTorch's nn.Dropout(p=0.5) uses p for the probability of dropping a unit, the opposite of the dropout paper's convention. is an absolute value on a number and a size on a set (Chamber 2), and the double bar is a norm in but only a separator in . These are overloaded symbols. Context almost always settles them, and your notation table records which meaning this paper uses.
An abuse of notation is a deliberate shortcut: writing something that isn't strictly correct, because the correct version would be cluttered and the meaning is clear anyway. You've met several already:
- Dropping subscripts. “We drop the and write for .” The model still depends on . The notation just stops saying so.
- One letter for many functions. and are different distributions that share the letter (Chamber 8).
- Loose indices. The VAE paper's Eq. (2) has on its left-hand side but writes on the right, meaning the same data point. The dropout paper writes in one line where it means .
- Unstated conventions. Attention's row-wise softmax, or with no base (in machine learning it's almost always the natural log).
Read beyond the course
These four show the protocol from different distances: a method for whole papers, a paper turned line by line into code, a model notation table, and one more derivation read closely.
Paper · free online · ~15 min
How to Read a PaperS. Keshav, ACM SIGCOMM Computer Communication Review (2007) · The whole note (three pages)
The three-pass method for reading research papers, from a five-minute skim to a full re-implementation in your head. This chamber's protocol is what you do with each equation during the second and third passes.
Article · free online · ~30 min
The Annotated TransformerSasha Rush; updated by Austin Huang, Suraj Subramanian, Jonathan Sum, Khalid Almubarak & Stella Biderman (Harvard NLP) · Part 1: Model Architecture, the Attention section
The Transformer paper interleaved with working PyTorch, one paragraph at a time. Its attention function is steps 1 to 5 of the protocol done for you. Compare it line by line with the NumPy version above.
Book · free online · ~10 min
Mathematics for Machine Learning: Table of SymbolsMarc Peter Deisenroth, A. Aldo Faisal & Cheng Soon Ong · Front matter, after the Foreword
A two-column table of every symbol the book uses and its typical meaning. Nearly all of it is readable to you now, which is a good measure of how far you've come. It's also a model for the tables you'll build yourself.
Article · free online · ~25 min
From Autoencoder to Beta-VAELilian Weng · Notation, then “VAE: Variational Autoencoder” and “Loss Function: ELBO”
A careful blog post that opens with its own notation table, then derives the ELBO step by step. Read it after the VAE decoder below to see the same equation written in a second notation.
Papers and lectures
For the Transformer paper, read Section 3.2 on attention, about a page and a half with Figure 2, and use the shape table above as your notation table. Section 3.2.2 on multi-head attention is just the same function run times in parallel on smaller projections. Skip positional encodings and the experiments for now.
For the VAE paper, read Section 2.1 (the problem and its notation), Section 2.2 (the variational bound, Equations 1 to 3) and Section 3 (the Gaussian example). Build your notation table as you go, or check it against the one above. The reparameterisation trick in Section 2.4 is the you met in Chamber 8.
The distillation paper is short and friendly: the first three paragraphs of Section 2 surround the temperature equation above.
Attention Is All You NeedAshish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin · NIPS, 2017The paper that introduced the Transformer. You can now read its central equation with shapes, and implement it.
Auto-Encoding Variational BayesDiederik P. Kingma, Max Welling · ICLR, 2014The variational autoencoder: a generative model trained by maximising a lower bound. Almost every symbol of probability notation appears in its first five pages.
Distilling the Knowledge in a Neural NetworkGeoffrey Hinton, Oriol Vinyals, Jeff Dean · NIPS 2014 Deep Learning Workshop, 2015How to compress a large model into a small one by training on softened outputs. The source of softmax with temperature.
Decode the paper · Eq. (1), Section 3.2.1
Attention Is All You NeedAshish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin · NIPS, 2017
Chamber 1 showed you this line and promised you'd read it. Now read it with shapes: queries, keys and values, keys of length and values of length . Match each piece to its meaning.
Options
Decode the paper · Eq. (3), Section 2.2
Auto-Encoding Variational BayesDiederik P. Kingma, Max Welling · ICLR, 2014
A variational autoencoder squeezes each input into a random code and tries to rebuild it. This line, the evidence lower bound or ELBO, is what it maximises. Every symbol comes from Chambers 1 to 8.
Options
Watch
A visual walk through attention. Watch for the grid of dot products between queries and keys, and the moment softmax turns that grid into weights: that grid is . Pause and name the shape of every matrix on screen.
A researcher walking through the paper itself, page by page. Run the protocol alongside him: whenever an equation appears, pause the video and name each symbol's type and shape before he explains it.
Your turn
The last round of practice before the Sphinx. First a marathon over every symbol in the course, then two matching sets, two proofs about Adam, and three problems that implement this chamber's papers.
Interactive lab
Notation marathon
Match · Paper ↔ NumPy
From the paper to NumPy
Match each line from this chamber's papers to the NumPy that computes it. Assume Q, K, z, g, m and v are arrays, and that softmax(z) is the stable function from Problem 1.
Options
Match · Symbol in context ↔ Meaning
Same symbol, different jobs
Every one of these symbols has more than one job in machine-learning papers. Use the context to match each to its meaning.
p in PyTorch's nn.Dropout(p=0.5)Options
Proofs
The puzzle proves why Adam's bias correction divides by . It starts from the unrolled form of the moving average, which you then prove yourself by induction.
Proof puzzle
Why Adam divides by 1 − β₁ᵗ
Claim
In Adam, let and with . If the gradients are stationary, meaning for every step , then
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
Unrolling a moving average
Claim
Let and for . Prove by induction that for every , (Section 3 of the Adam paper states this form for the squared-gradient average , as its Eq. (1), without proof.)
Your typeset proof appears here.
Code it up
Problem 25·Warm-up
Softmax at a thousand degrees
Apply the paper. Hinton, Vinyals and Dean soften a network's outputs with a temperature (their Eq. 1):
A very confident network produces the logits . With , compute , the probability of the third class, to 4 decimal places.
Beware: in double-precision floating point, exp(709) is about , and anything much larger overflows to infinity. Code that works on small logits can fail on these.
Problem 26·Standard
Attention by hand, then by code
Compute scaled dot-product attention (Vaswani et al., Eq. 1),
with softmax applied to each row separately, for
Here , the number of columns of and . The output is a matrix. Give the sum of its four entries to 4 decimal places.
Problem 27·Challenge
Adam, line by line
Chamber 1 promised this one. Implement Algorithm 1 of Kingma and Ba's Adam paper exactly as written:
for , starting from . All operations on vectors are element-wise, and is a power.
Minimise over (the same at every step, so ). Start at and use , , , . After exactly 50 steps, report to 4 decimal places.
Key takeaways
- Use the six-step protocol: find the definitions, give everything a type and shape, read it aloud, work a tiny example, code it, and sanity-check special cases.
- Shapes first. In attention, is , the softmax runs along each row, and the output is . The paper states none of these shapes: you work them out.
- Softmax ignores shifts, which is why stable code subtracts the maximum. A temperature sharpens it (small ) or flattens it (large ).
- Adam's hats divide out a geometric series: with stationary gradients, .
- Definitions hide in notation sections, prose, captions and appendices. When there's no table, build one.
- Symbols are overloaded, and notation gets abused on purpose. Read by context, and write the precise version in your notation table.
Checkpoint
Prove it to the labyrinth
Answer every question to clear this chamber. First-try answers earn the most XP.
You meet an unfamiliar equation in a paper. What is the first step of the reading protocol?
In , take , and . What is the shape of the output?
Which change to the logits always leaves unchanged?
The Transformer paper supposes that the entries of are independent random variables with mean 0 and variance 1. With , what is the standard deviation of the dot product , before scaling?
Run Adam's Algorithm 1 for one step on a single parameter with , , and . The first gradient is . By how much does the parameter change, ? (Ignore the effect of .)
Every gradient equals 2: . With and for , what is (before bias correction)?
A paper says: “To lighten notation, we drop the subscript and write for .” What has changed?
The VAE paper's Eq. (10) contains the term , which equals between the encoder and the prior. Take , and . What is itself?
End of the chamber
Clear this chamber
- Questions in this chamber (0/11 solved)Next unsolved
- Bonus: Notation marathon (+60 XP)
- Bonus: Problem 25: Softmax at a thousand degrees (+20 XP)
- Bonus: Problem 26: Attention by hand, then by code (+35 XP)
- Bonus: Problem 27: Adam, line by line (+50 XP)
- Bonus: Proof: Why Adam divides by 1 − β₁ᵗ (+25 XP)
- Bonus: Proof: Unrolling a moving average (+40 XP)
- Bonus: Decode the paper (1) (+30 XP)
- Bonus: Decode the paper (2) (+30 XP)
- Bonus: Match: From the paper to NumPy (+25 XP)
- Bonus: Match: Same symbol, different jobs (+25 XP)