Skip to content
AriadneTechnology

The Inner Ring · Chamber 9 of 9

Reading the Equations of a Paper

Put it all together: decode attention, Adam and the ELBO symbol by symbol, then turn equations into working code.

45 min 60 XP + 11 questions + 1 challengeNotationVideoPapersProofsCodeLab

In this chamber you will

  • Apply a six-step protocol to any equation in any paper
  • Build a notation table for a paper you are reading
  • Implement Adam and attention from their equations
  • Spot overloaded symbols and abuses of notation
DiscoverLearnRead beyondPapers & lecturesYour turn

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

Attention(Q,K,V)=softmax(QKTdk)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}(\frac{QK^T}{\sqrt{d_k}})V
Vaswani et al. (2017), “Attention Is All You Need”, Equation 1

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 TT is a transpose rather than a power (Chamber 6), dkd_k is a dd 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.

Quick check +20 XP

Suppose Q∈Rn×dkQ \in \mathbb{R}^{n \times d_k} and K∈Rm×dkK \in \mathbb{R}^{m \times d_k}. What is the shape of QK⊤QK^\top?

DiscoverLearnRead beyondPapers & lecturesYour turn

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

    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

    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

    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

    4. Work a tiny example by hand

    Choose the smallest inputs that aren't trivial: two or three numbers, 2×22 \times 2 matrices. Compute the result with pen and paper.

  5. 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

    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 dkd_k, and values of dimension dvd_v”, and in practice the queries are “packed together into a matrix QQ”, with the keys and values packed into matrices KK and VV.

Step 2: types and shapes. Say there are nn queries and mm keys, each key with its own value. Packing one vector per row:

Q∈Rn×dk,K∈Rm×dk,V∈Rm×dv.Q \in \mathbb{R}^{n \times d_k}, \qquad K \in \mathbb{R}^{m \times d_k}, \qquad V \in \mathbb{R}^{m \times d_v}.

Now follow the shapes through the equation:

ExpressionShapeWhat it holds
QKTQK^T(n×dk)(dk×m)=n×m(n \times d_k)(d_k \times m) = n \times mthe dot product of every query with every key
QKT/dkQK^T / \sqrt{d_k}n×mn \times mthe same scores, scaled down by a number
softmax(…)\mathrm{softmax}(\ldots)n×mn \times meach row turned into weights that sum to 1
softmax(…) V\mathrm{softmax}(\ldots)\,V(n×m)(m×dv)=n×dv(n \times m)(m \times d_v) = n \times d_vone 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 dk=dv=2d_k = d_v = 2:

Q=(11),K=(111−1),V=(100010).Q = \begin{pmatrix} 1 & 1 \end{pmatrix}, \qquad K = \begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix}, \qquad V = \begin{pmatrix} 10 & 0 \\ 0 & 10 \end{pmatrix}.

The scores are QKT=(1⋅1+1⋅1, 1⋅1+1⋅(−1))=(2,0)QK^T = (1 \cdot 1 + 1 \cdot 1,\ 1 \cdot 1 + 1 \cdot (-1)) = (2, 0). Dividing by 2\sqrt{2} gives (1.414,0)(1.414, 0). The softmax gives weights (e1.414e1.414+e0,e0e1.414+e0)≈(0.804,0.196)\big(\frac{e^{1.414}}{e^{1.414} + e^{0}}, \frac{e^{0}}{e^{1.414} + e^{0}}\big) \approx (0.804, 0.196). The output is 0.804⋅(10,0)+0.196⋅(0,10)≈(8.04,1.96)0.804 \cdot (10, 0) + 0.196 \cdot (0, 10) \approx (8.04, 1.96). The query points the same way as the first key, so the output is mostly the first value.

Step 5: code. Symbol by symbol:

Python
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 1m\frac{1}{m}, and the output is the plain average of the rows of VV. If you multiply QQ 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 VV, its entries can never leave the range of VV'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 dk\sqrt{d_k} in its footnote 4, with a probability argument you can now follow in full. Suppose the entries of a query qq and a key kk are independent random variables, each with mean 0 and variance 1. Their dot product is q⋅k=∑i=1dkqikiq \cdot k = \sum_{i=1}^{d_k} q_i k_i.

Each term has mean zero, because independence lets the expectation of a product split: E[qiki]=E[qi] E[ki]=0\mathbb{E}[q_i k_i] = \mathbb{E}[q_i]\,\mathbb{E}[k_i] = 0. Its variance is

Var(qiki)=E[qi2ki2]−(E[qiki])2=E[qi2] E[ki2]−0=1⋅1=1,\mathrm{Var}(q_i k_i) = \mathbb{E}[q_i^2 k_i^2] - \big(\mathbb{E}[q_i k_i]\big)^2 = \mathbb{E}[q_i^2]\,\mathbb{E}[k_i^2] - 0 = 1 \cdot 1 = 1,

using the variance shortcut of Chamber 8 and independence again. The dkd_k terms are independent, and the variances of independent variables add, so

Var(q⋅k)=dk,soVar(q⋅kdk)=dkdk=1.\mathrm{Var}(q \cdot k) = d_k, \qquad \text{so} \qquad \mathrm{Var}\Big(\frac{q \cdot k}{\sqrt{d_k}}\Big) = \frac{d_k}{d_k} = 1.

In the paper each head has dk=64d_k = 64, 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 dk\sqrt{d_k} 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:

softmax(z)i=exp⁡(zi)∑jexp⁡(zj).\mathrm{softmax}(\mathbf{z})_i = \frac{\exp(z_i)}{\sum_j \exp(z_j)}.

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

qi=exp(zi/T)∑jexp(zj/T)q_i = \frac{exp(z_i/T)}{\sum_j exp(z_j/T)}
Hinton, Vinyals & Dean (2015), “Distilling the Knowledge in a Neural Network”, Equation 1

Here TT is a temperature, “normally set to 1”, as the paper says. (Notice that the paper sets expexp in italics, which strictly reads as e⋅x⋅pe \cdot x \cdot p. By Chamber 1's rules it should be upright, exp⁡\exp. 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 z=(3,1,0)\mathbf{z} = (3, 1, 0):

Temperature TTq1q_1q2q_2q3q_3
0.50.9800.0180.002
10.8440.1140.042
20.6290.2310.140
100.3910.3200.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.

Quick check +20 XP

In qi=exp⁡(zi/T)∑jexp⁡(zj/T)q_i = \frac{\exp(z_i/T)}{\sum_j \exp(z_j/T)}, what happens to the probabilities as the temperature TT grows very large?

A proof: softmax ignores shifts

Claim. For any logits z=(z1,…,zK)\mathbf{z} = (z_1, \ldots, z_K) and any real number cc, adding cc to every logit leaves softmax unchanged: softmax(z+c1)=softmax(z)\mathrm{softmax}(\mathbf{z} + c\mathbf{1}) = \mathrm{softmax}(\mathbf{z}).

Proof. Take any entry ii. By the definition of softmax, and then the rule ea+b=eaebe^{a + b} = e^a e^b (Chamber 4),

softmax(z+c1)i=exp⁡(zi+c)∑j=1Kexp⁡(zj+c)=ecexp⁡(zi)∑j=1Kecexp⁡(zj)=ecexp⁡(zi)ec∑j=1Kexp⁡(zj)=softmax(z)i.\mathrm{softmax}(\mathbf{z} + c\mathbf{1})_i = \frac{\exp(z_i + c)}{\sum_{j=1}^{K} \exp(z_j + c)} = \frac{e^{c}\exp(z_i)}{\sum_{j=1}^{K} e^{c}\exp(z_j)} = \frac{e^{c}\exp(z_i)}{e^{c}\sum_{j=1}^{K} \exp(z_j)} = \mathrm{softmax}(\mathbf{z})_i.

The third step pulls the constant ece^c out of the sum (Chamber 5's linearity), and the last cancels it, which is allowed because ec>0e^c > 0. Since ii was arbitrary, every entry is unchanged. ■\blacksquare

The proof has a very practical use. A computer can't represent exp⁡(1000)\exp(1000): it overflows to infinity, and infinity divided by infinity is “not a number”. Choosing c=−max⁡jzjc = -\max_j z_j 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 1Read aloudNumPy
t←t+1t \leftarrow t + 1t gets t plus onet += 1
gt←∇θft(θt−1)g_t \leftarrow \nabla_\theta f_t(\theta_{t-1})g t gets the gradient, w.r.t. theta, of f t at the previous thetag = grad(theta)
mt←β1⋅mt−1+(1−β1)⋅gtm_t \leftarrow \beta_1 \cdot m_{t-1} + (1 - \beta_1) \cdot g_ta running average of gradientsm = beta1 * m + (1 - beta1) * g
vt←β2⋅vt−1+(1−β2)⋅gt2v_t \leftarrow \beta_2 \cdot v_{t-1} + (1 - \beta_2) \cdot g_t^2a running average of squared gradientsv = beta2 * v + (1 - beta2) * g**2
m^t←mt/(1−β1t)\hat{m}_t \leftarrow m_t / (1 - \beta_1^t)m hat: the bias-corrected averagem_hat = m / (1 - beta1**t)
v^t←vt/(1−β2t)\hat{v}_t \leftarrow v_t / (1 - \beta_2^t)v hat: the same correctionv_hat = v / (1 - beta2**t)
θt←θt−1−α⋅m^t/(v^t+ϵ)\theta_t \leftarrow \theta_{t-1} - \alpha \cdot \hat{m}_t / (\sqrt{\hat{v}_t} + \epsilon)the update you decoded in Chamber 1theta = theta - alpha * m_hat / (np.sqrt(v_hat) + eps)

Before the loop, m0m_0, v0v_0 and tt start at 0. The paper's defaults are α=0.001\alpha = 0.001, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999 and ϵ=10−8\epsilon = 10^{-8}.

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 gt2g_t^2 “indicates the elementwise square”, that “all operations on vectors are element-wise”, and that β1t\beta_1^t and β2t\beta_2^t mean “β1\beta_1 and β2\beta_2 to the power tt”. That last one is Chamber 1's warning about powers and positions, stated by the authors themselves: the tt on mtm_t is an index, but the tt on β1t\beta_1^t is a power.

Step 6 of the protocol, sanity checks, reveals something neat. On the very first step, m1=(1−β1) g1m_1 = (1 - \beta_1)\,g_1, so m^1=g1\hat{m}_1 = g_1 exactly. Likewise v^1=g12\hat{v}_1 = g_1^2. Ignoring the tiny ϵ\epsilon, the first update is α⋅g1/∣g1∣=±α\alpha \cdot g_1 / |g_1| = \pm\alpha for every parameter, whatever the size of its gradient. Without the hats, m1=0.1 g1m_1 = 0.1\,g_1 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

E[mt]=(1−β1t) E[g],\mathbb{E}[m_t] = (1 - \beta_1^t)\,\mathbb{E}[g],

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.

Quick check +20 XP

Adam's Algorithm 1 updates vt←β2⋅vt−1+(1−β2)⋅gt2v_t \leftarrow \beta_2 \cdot v_{t-1} + (1 - \beta_2) \cdot g_t^2, where gtg_t is the gradient vector. What is gt2g_t^2?

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 JJ in its Eq. (10) but only says “Let JJ be the dimensionality of z\mathbf{z}” in Appendix B. Its Figure 2 caption calls the same quantity NzN_{\mathbf{z}}.

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:

SymbolRead asType and shapeMeaningDefined in
x(i)\mathbf{x}^{(i)}x ivectorthe ii-th of NN i.i.d. data points§2.1
z\mathbf{z}zvector in RJ\mathbb{R}^Jthe unobserved latent code§2.1
JJ (also NzN_{\mathbf{z}})Jintegerthe dimension of z\mathbf{z}Appendix B
θ\boldsymbol{\theta}thetaparametersthe generative model (decoder)§2.1
ϕ\boldsymbol{\phi}phiparametersthe recognition model (encoder)§2.1
pθ(x∣z)p_{\boldsymbol{\theta}}(\mathbf{x} \mid \mathbf{z})p theta of x given zdistribution over x\mathbf{x}the decoder§2.1
qϕ(z∣x)q_{\boldsymbol{\phi}}(\mathbf{z} \mid \mathbf{x})q phi of z given xdistribution over z\mathbf{z}the encoder, approximating pθ(z∣x)p_{\boldsymbol{\theta}}(\mathbf{z} \mid \mathbf{x})§2.1
L(θ,ϕ;x(i))\mathcal{L}(\boldsymbol{\theta}, \boldsymbol{\phi}; \mathbf{x}^{(i)})L of theta and phi at x ia numberthe 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, pθ(x)=∫pθ(z) pθ(x∣z) dzp_{\boldsymbol{\theta}}(\mathbf{x}) = \int p_{\boldsymbol{\theta}}(\mathbf{z})\, p_{\boldsymbol{\theta}}(\mathbf{x} \mid \mathbf{z})\, d\mathbf{z}, and the true posterior with Bayes' rule, pθ(z∣x)=pθ(x∣z) pθ(z)/pθ(x)p_{\boldsymbol{\theta}}(\mathbf{z} \mid \mathbf{x}) = p_{\boldsymbol{\theta}}(\mathbf{x} \mid \mathbf{z})\, p_{\boldsymbol{\theta}}(\mathbf{z}) / p_{\boldsymbol{\theta}}(\mathbf{x}). You can read both now.

Papers also lean on a stock of shorthand that rarely gets defined at all:

Shorthand from real papers
  • w.r.t.\text{w.r.t.}“with respect to”
    Names the variable a derivative or an optimisation is taken over. The Adam paper computes “gradients w.r.t. stochastic objective”.
    ∇θf is the gradient w.r.t. θ\nabla_\theta f \text{ is the gradient w.r.t. } \theta
  • min⁡xf(x) s.t. x≥0\min_{x} f(x) \ \text{s.t.}\ x \ge 0“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(⋅)f(\cdot)“f of dot”
    The dot is a placeholder for “whatever argument goes here”, so f(⋅)f(\cdot) means the function itself, not a value of it. The same dot turns up in norms, ∥⋅∥2\|\cdot\|_2.
    ∥⋅∥2\|\cdot\|_2
  • x1:Tx_{1:T}“x one to T”
    The whole sequence x1,x2,…,xTx_1, x_2, \ldots, x_T. Colon ranges are everywhere in papers on sequences.
    p(x1:T)p(x_{1:T})
  • x<tx_{<t}“x before t”
    Everything before position tt: x1,…,xt−1x_1, \ldots, x_{t-1}. The notation of language models, which predict each token from the ones before it.
    p(x1:T)=∏t=1Tp(xt∣x<t)p(x_{1:T}) = \prod_{t=1}^{T} p(x_t \mid x_{<t})
  • const\text{const}“plus a constant”
    Terms that don't depend on the variable of interest, lumped together and ignored because they don't change the argmin.
    log⁡p(x)=−12x2+const\log p(x) = -\tfrac{1}{2}x^2 + \text{const}
  • [z]+[z]_+“the positive part of z”
    Shorthand for max⁡(0,z)\max(0, z), the ReLU of Chamber 4 in different clothes. Common in hinge losses.
    [1−y y^]+[1 - y\,\hat{y}]_+
  • ≃\simeq“sim-equals, is estimated by”
    A cousin of ≈\approx, called “sim-equals” after its LaTeX name, \simeq. The VAE paper uses it for “this sample average stands in for that expectation”.
    E[f(z)]≃1L∑l=1Lf(z(l))\mathbb{E}[f(z)] \simeq \frac{1}{L}\sum_{l=1}^{L} f(z^{(l)})
Symbols decoded in this chamber
  • QQ“Q, the queries”
    In attention, a matrix with one row per position that is asking: shape n×dkn \times d_k.
    Q∈Rn×dkQ \in \mathbb{R}^{n \times d_k}
  • KK“K, the keys”
    One row per position that can be looked up, compared with every query: shape m×dkm \times d_k.
    K∈Rm×dkK \in \mathbb{R}^{m \times d_k}
  • VV“V, the values”
    The content that gets mixed, one row per key: shape m×dvm \times d_v.
    V∈Rm×dvV \in \mathbb{R}^{m \times d_v}
  • dkd_k“d k, the key dimension”
    The length of each query and key vector. The Transformer uses dk=64d_k = 64 per head.
    dk=8\sqrt{d_k} = 8
  • gt2g_t^2“g t squared, element by element”
    In Adam, the square of every entry of the gradient vector (gt⊙gtg_t \odot g_t), not a dot product.
    vt←β2vt−1+(1−β2) gt2v_t \leftarrow \beta_2 v_{t-1} + (1 - \beta_2)\, g_t^2
  • qϕ(z∣x)q_{\boldsymbol{\phi}}(\mathbf{z} \mid \mathbf{x})“q phi of z given x, the encoder”
    In a VAE, the encoder: a distribution over codes z\mathbf{z} for the input x\mathbf{x}, with parameters ϕ\boldsymbol{\phi}.
  • pθ(x∣z)p_{\boldsymbol{\theta}}(\mathbf{x} \mid \mathbf{z})“p theta of x given z, the decoder”
    In a VAE, the decoder: how likely the input x\mathbf{x} is to be rebuilt from the code z\mathbf{z}.
  • L(θ,ϕ;x(i))\mathcal{L}(\boldsymbol{\theta}, \boldsymbol{\phi}; \mathbf{x}^{(i)})“the ELBO, L of theta and phi at x i”
    The evidence lower bound for data point ii: the number a VAE maximises. Parameters before the semicolon, data after (Chamber 4's f(x;θ)f(x; \theta) 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 σ\sigma for the sigmoid in one equation and a standard deviation in the next. TT can be a transpose, a temperature or the number of time steps. pp 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. ∣⋅∣|\cdot| is an absolute value on a number and a size on a set (Chamber 2), and the double bar is a norm in ∥x∥\Vert\mathbf{x}\Vert but only a separator in DKL(p ∥ q)D_{\mathrm{KL}}(p \,\Vert\, q). 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 θ\theta and write p(y∣x)p(y \mid x) for pθ(y∣x)p_\theta(y \mid x).” The model still depends on θ\theta. The notation just stops saying so.
  • One letter for many functions. p(x)p(\mathbf{x}) and p(z)p(\mathbf{z}) are different distributions that share the letter pp (Chamber 8).
  • Loose indices. The VAE paper's Eq. (2) has x(i)\mathbf{x}^{(i)} on its left-hand side but writes qϕ(z∣x)q_{\boldsymbol{\phi}}(\mathbf{z} \mid \mathbf{x}) on the right, meaning the same data point. The dropout paper writes y~l\widetilde{\mathbf{y}}^{l} in one line where it means y~(l)\widetilde{\mathbf{y}}^{(l)}.
  • Unstated conventions. Attention's row-wise softmax, or log⁡\log with no base (in machine learning it's almost always the natural log).
DiscoverLearnRead beyondPapers & lecturesYour turn

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 Paper

S. 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 Transformer

Sasha 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 Symbols

Marc 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-VAE

Lilian 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.

DiscoverLearnRead beyondPapers & lecturesYour turn

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 h=8h = 8 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 z=μ+σ⊙ϵ\mathbf{z} = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\epsilon} 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, 2017

The 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, 2014

The 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, 2015

How 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 Need

Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin · NIPS, 2017

+30 XP
Attention(Q,K,V)=softmax(QKTdk)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}(\frac{QK^T}{\sqrt{d_k}})V

Chamber 1 showed you this line and promised you'd read it. Now read it with shapes: nn queries, mm keys and values, keys of length dkd_k and values of length dvd_v. Match each piece to its meaning.

QQ
KK
VV
QKTQK^T
dk\sqrt{d_k}
softmax\mathrm{softmax}
Attention(Q,K,V)\mathrm{Attention}(Q, K, V)

Options

Decode the paper · Eq. (3), Section 2.2

Auto-Encoding Variational Bayes

Diederik P. Kingma, Max Welling · ICLR, 2014

+30 XP
L(θ,ϕ;x(i))=−DKL(qϕ(z∣x(i))∣∣pθ(z))+Eqϕ(z∣x(i))[log⁡pθ(x(i)∣z)]\mathcal{L}(\boldsymbol{\theta}, \boldsymbol{\phi}; \mathbf{x}^{(i)}) = - D_{KL}(q_{\boldsymbol{\phi}}(\mathbf{z}|\mathbf{x}^{(i)}) || p_{\boldsymbol{\theta}}(\mathbf{z})) + \mathbb{E}_{q_{\boldsymbol{\phi}}(\mathbf{z}|\mathbf{x}^{(i)})}\left[\log p_{\boldsymbol{\theta}}(\mathbf{x}^{(i)} | \mathbf{z})\right]

A variational autoencoder squeezes each input x(i)\mathbf{x}^{(i)} into a random code z\mathbf{z} 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.

L(θ,ϕ;x(i))\mathcal{L}(\boldsymbol{\theta}, \boldsymbol{\phi}; \mathbf{x}^{(i)})
ϕ\boldsymbol{\phi}
θ\boldsymbol{\theta}
qϕ(z∣x(i))q_{\boldsymbol{\phi}}(\mathbf{z}|\mathbf{x}^{(i)})
pθ(z)p_{\boldsymbol{\theta}}(\mathbf{z})
pθ(x(i)∣z)p_{\boldsymbol{\theta}}(\mathbf{x}^{(i)} | \mathbf{z})
DKLD_{KL}

Options

Watch

Attention in transformers, step-by-step | Deep Learning Chapter 63Blue1Brown · 26 min

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 QKTQK^T. Pause and name the shape of every matrix on screen.

Attention Is All You NeedYannic Kilcher · 27 min

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.

DiscoverLearnRead beyondPapers & lecturesYour turn

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

20 symbols, one at a time. Pick how each is read aloud. Score 18 or more to pass. Speed is optional, but the clock is running…
Challenge: Notation marathonScore at least 18 out of 20 in a sprint over the whole course's notation.+60 XP

Match · Paper ↔ NumPy

From the paper to NumPy

+25 XP

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.

QKTdk\frac{QK^T}{\sqrt{d_k}}
exp⁡(zi)∑jexp⁡(zj)\frac{\exp(z_i)}{\sum_j \exp(z_j)} for every ii
qi=exp⁡(zi/T)∑jexp⁡(zj/T)q_i = \frac{\exp(z_i/T)}{\sum_j \exp(z_j/T)}
gt2g_t^2
mt←β1⋅mt−1+(1−β1)⋅gtm_t \leftarrow \beta_1 \cdot m_{t-1} + (1 - \beta_1) \cdot g_t
v^t←vt/(1−β2t)\hat{v}_t \leftarrow v_t / (1 - \beta_2^t)

Options

Match · Symbol in context ↔ Meaning

Same symbol, different jobs

+25 XP

Every one of these symbols has more than one job in machine-learning papers. Use the context to match each to its meaning.

σ\sigma in σ(Wx+b)\sigma(W\mathbf{x} + \mathbf{b})
σ\sigma in N(μ,σ2)\mathcal{N}(\mu, \sigma^2)
TT in QKTQK^T
TT in exp⁡(zi/T)\exp(z_i / T)
TT in t=1,…,Tt = 1, \ldots, T
pp in dropout's Bernoulli(p)\mathrm{Bernoulli}(p)
p in PyTorch's nn.Dropout(p=0.5)

Options

Proofs

The puzzle proves why Adam's bias correction divides by 1−β1t1 - \beta_1^t. It starts from the unrolled form of the moving average, which you then prove yourself by induction.

Proof puzzle

Why Adam divides by 1 − β₁ᵗ

+25 XP

Claim

In Adam, let m0=0m_0 = 0 and mt=β1mt−1+(1−β1)gtm_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t with 0≤β1<10 \le \beta_1 < 1. If the gradients are stationary, meaning E[gi]=E[g]\mathbb{E}[g_i] = \mathbb{E}[g] for every step ii, then E[mt]=(1−β1t) E[g].\mathbb{E}[m_t] = (1 - \beta_1^t)\,\mathbb{E}[g].

Tap lines in the order they should appear. Not every line belongs. Tap a line in your proof to send it back.

Your proof

  1. Pick the first line below.

Available lines

Prove it yourself

Unrolling a moving average

+40 XP

Claim

Let m0=0m_0 = 0 and mt=β mt−1+(1−β) gtm_t = \beta\, m_{t-1} + (1 - \beta)\, g_t for t≥1t \ge 1. Prove by induction that for every t≥1t \ge 1, mt=(1−β)∑i=1tβt−igi.m_t = (1 - \beta)\sum_{i=1}^{t} \beta^{t-i} g_i. (Section 3 of the Adam paper states this form for the squared-gradient average vtv_t, as its Eq. (1), without proof.)

Preview

Your typeset proof appears here.

Code it up

Problem 25·Warm-up

Softmax at a thousand degrees

+20 XP

Apply the paper. Hinton, Vinyals and Dean soften a network's outputs with a temperature TT (their Eq. 1):

qi=exp⁡(zi/T)∑jexp⁡(zj/T).q_i = \frac{\exp(z_i/T)}{\sum_j \exp(z_j/T)}.

A very confident network produces the logits z=(2000,2001,2002)\mathbf{z} = (2000, 2001, 2002). With T=2T = 2, compute q3q_3, the probability of the third class, to 4 decimal places.

Beware: in double-precision floating point, exp(709) is about 8×103078 \times 10^{307}, and anything much larger overflows to infinity. Code that works on small logits can fail on these.

A number, rounded to 4 decimal places

Problem 26·Standard

Attention by hand, then by code

+35 XP

Compute scaled dot-product attention (Vaswani et al., Eq. 1),

Attention(Q,K,V)=softmax(QK⊤dk)V,\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\Big(\frac{QK^\top}{\sqrt{d_k}}\Big)V,

with softmax applied to each row separately, for

Q=(1002),K=(112003),V=(123−104).Q = \begin{pmatrix} 1 & 0 \\ 0 & 2 \end{pmatrix}, \quad K = \begin{pmatrix} 1 & 1 \\ 2 & 0 \\ 0 & 3 \end{pmatrix}, \quad V = \begin{pmatrix} 1 & 2 \\ 3 & -1 \\ 0 & 4 \end{pmatrix}.

Here dk=2d_k = 2, the number of columns of QQ and KK. The output is a 2×22 \times 2 matrix. Give the sum of its four entries to 4 decimal places.

A number, rounded to 4 decimal places

Problem 27·Challenge

Adam, line by line

+50 XP

Chamber 1 promised this one. Implement Algorithm 1 of Kingma and Ba's Adam paper exactly as written:

gt←∇θft(θt−1)mt←β1⋅mt−1+(1−β1)⋅gtvt←β2⋅vt−1+(1−β2)⋅gt2m^t←mt/(1−β1t)v^t←vt/(1−β2t)θt←θt−1−α⋅m^t/(v^t+ϵ)\begin{aligned} g_t &\leftarrow \nabla_\theta f_t(\theta_{t-1}) \\ m_t &\leftarrow \beta_1 \cdot m_{t-1} + (1 - \beta_1) \cdot g_t \\ v_t &\leftarrow \beta_2 \cdot v_{t-1} + (1 - \beta_2) \cdot g_t^2 \\ \hat{m}_t &\leftarrow m_t / (1 - \beta_1^t) \\ \hat{v}_t &\leftarrow v_t / (1 - \beta_2^t) \\ \theta_t &\leftarrow \theta_{t-1} - \alpha \cdot \hat{m}_t / (\sqrt{\hat{v}_t} + \epsilon) \end{aligned}

for t=1,2,…t = 1, 2, \ldots, starting from m0=v0=0m_0 = v_0 = \mathbf{0}. All operations on vectors are element-wise, and β1t\beta_1^t is a power.

Minimise f(θ)=(θ1−1)2+10 (θ2+2)2f(\theta) = (\theta_1 - 1)^2 + 10\,(\theta_2 + 2)^2 over θ=(θ1,θ2)∈R2\theta = (\theta_1, \theta_2) \in \mathbb{R}^2 (the same ff at every step, so ft=ff_t = f). Start at θ0=(0,0)\theta_0 = (0, 0) and use α=0.1\alpha = 0.1, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, ϵ=10−8\epsilon = 10^{-8}. After exactly 50 steps, report f(θ50)f(\theta_{50}) to 4 decimal places.

A number, rounded 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, QKTQK^T is n×mn \times m, the softmax runs along each row, and the output is n×dvn \times d_v. The paper states none of these shapes: you work them out.
  • Softmax ignores shifts, which is why stable code subtracts the maximum. A temperature TT sharpens it (small TT) or flattens it (large TT).
  • Adam's hats divide out a geometric series: with stationary gradients, E[mt]=(1−β1t) E[g]\mathbb{E}[m_t] = (1 - \beta_1^t)\,\mathbb{E}[g].
  • 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.

0/8
Question 1 of 8 +20 XP

You meet an unfamiliar equation in a paper. What is the first step of the reading protocol?

Question 2 of 8 +20 XP

In softmax(QK⊤dk)V\mathrm{softmax}\big(\frac{QK^\top}{\sqrt{d_k}}\big)V, take Q∈R10×64Q \in \mathbb{R}^{10 \times 64}, K∈R20×64K \in \mathbb{R}^{20 \times 64} and V∈R20×32V \in \mathbb{R}^{20 \times 32}. What is the shape of the output?

Question 3 of 8 +20 XP

Which change to the logits z\mathbf{z} always leaves softmax(z)\mathrm{softmax}(\mathbf{z}) unchanged?

Question 4 of 8 +20 XP

The Transformer paper supposes that the entries of q,k∈Rdkq, k \in \mathbb{R}^{d_k} are independent random variables with mean 0 and variance 1. With dk=64d_k = 64, what is the standard deviation of the dot product q⋅k=∑i=1dkqikiq \cdot k = \sum_{i=1}^{d_k} q_i k_i, before scaling?

Question 5 of 8 +20 XP

Run Adam's Algorithm 1 for one step on a single parameter with α=0.01\alpha = 0.01, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999 and ϵ=10−8\epsilon = 10^{-8}. The first gradient is g1=250g_1 = 250. By how much does the parameter change, ∣θ1−θ0∣|\theta_1 - \theta_0|? (Ignore the effect of ϵ\epsilon.)

Question 6 of 8 +20 XP

Every gradient equals 2: g1=g2=g3=2g_1 = g_2 = g_3 = 2. With m0=0m_0 = 0 and mt=β1mt−1+(1−β1)gtm_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t for β1=0.9\beta_1 = 0.9, what is m3m_3 (before bias correction)?

Question 7 of 8 +20 XP

A paper says: “To lighten notation, we drop the subscript θ\theta and write p(y∣x)p(y \mid x) for pθ(y∣x)p_\theta(y \mid x).” What has changed?

Question 8 of 8 +20 XP

The VAE paper's Eq. (10) contains the term 12∑j=1J(1+log⁡((σj)2)−(μj)2−(σj)2)\frac{1}{2} \sum_{j=1}^{J} \big(1 + \log((\sigma_j)^2) - (\mu_j)^2 - (\sigma_j)^2\big), which equals −DKL-D_{KL} between the encoder and the prior. Take J=2J = 2, μ=(1,2)\boldsymbol{\mu} = (1, 2) and σ=(1,1)\boldsymbol{\sigma} = (1, 1). What is DKLD_{KL} itself?

End of the chamber

Clear this chamber

+60 XPThe Six-Step ProtocolThe Notation TableAbuse of Notation