Session S14
Deep Learning · CS 4715/5715 · University of Idaho
Today starts from S13's recurrent neural network (RNN). A token is one element of the sequence: here a word; S17 shows how text is split into tokens.
\[\mathbf{h}_t=\tanh\left(W_{hh}\,\mathbf{h}_{t-1}+W_{xh}\,\mathbf{x}_t+\mathbf{b}\right)\]One hidden state carries everything read so far, updated once per token.
What happens when two tokens are far apart, such as token 3 and token 300?
5.47e-29.Information and gradient both have to survive every step in between.
S13's long short-term memory (LSTM) adds a cell state \(\mathbf{c}_t\), updated by gated addition: \(\mathbf{c}_t=\mathbf{f}\odot\mathbf{c}_{t-1}+\mathbf{i}\odot\mathbf{g}\), with \(\mathbf{f}\) the forget gate, \(\mathbf{i}\) the input gate and \(\mathbf{g}\) the candidate values (S13).
T RNN LSTM LSTM fb=2
80 5.47e-29 5.27e-18 3.12e-03
Gating made the relay survivable; it did not give step 300 a direct path to step 3.
S13's second limitation is time. \(\mathbf{h}_t\) needs \(\mathbf{h}_{t-1}\), so the \(T\) steps run one after another, with gates or without.
| \(T\) | serial loop (ms) | all at once (ms) |
|---|---|---|
| 128 | 5.23 | 0.46 |
| 256 | 9.77 | 0.70 |
| 512 | 19.07 | 1.18 |
| 1024 | 36.91 | 2.22 |
Both columns do the same arithmetic, two matrix products and a \(\tanh\) per position for 32 sequences with \(d=256\), but only the loop waits for the previous \(\mathbf{h}\). These times come from one Apple GPU used through MPS (Metal Performance Shaders), PyTorch's backend for Apple GPUs; they vary by machine, and the doubling of the serial column is the point.
The wish S13 ended on: let step 300 look at step 3 directly, and let every step compute at once. Today's attention does both.
Beyond S13's two limitations there is a third: how much one state can hold.
This is the one-vector bottleneck, and translation shows it most clearly.
Today's running example is translation: a model reads the English the black cat and writes the French le chat noir, one word at a time.
1 · Where to look. When the model writes noir, how does it know to read black and not the?
2 · Keeping it trainable. That choice is made by numbers the model learns. What keeps those numbers learnable by gradient descent?
3 · The cost. If every word may look at every other word, how does the work grow when the sentence doubles in length?
Every part today answers one of these three questions or sets one up.
The first pages showed what RNNs and LSTMs cannot do. Each of the eight parts below answers one of the three questions or sets one up.
| part | what happens | question |
|---|---|---|
| 1 | Translation models that compress each sentence into one vector fail on long sentences. | sets up Q1 |
| 2 | The first attention model scores every source word, turns the scores into weights, and averages. | Q1 |
| 3 | The recipe becomes a dozen lines of NumPy, checked on a case you can do by hand. | Q1 |
| 4 | One scale factor keeps the learned scores trainable. | Q2 |
| 5 | A softmax over the wrong axis still runs, and a one-line test catches it. | Q1 |
| 6 | Attention can read another sentence or its own sentence. | sets up Q3 |
| 7 | Measurements show how the work grows with length. | Q3 |
| 8 | The close answers the three questions and lists what attention still lacks. | all three |
Attention came from translation, so Part 1 starts there.
Part 1 · One vector per sentence. Attention entered deep learning through translation. In 2014, neural translation used S13's many-to-many, unaligned wiring: an encoder RNN reads the whole source sentence, then a decoder RNN writes a target sentence, whose length can differ.
Every word and every grammatical agreement (noir matches chat) must be carried by one fixed-size vector, and the first source word reaches it only through S13's relay. This is Limitation 3 as it looks in translation.
That design breaks on long sentences, and a bigger vector would not fix it.
| producing | le | chat | noir |
|---|---|---|---|
| needs | the | cat | black |
| at source position | 1 | 3 | 2 |
The order differs too: target word 2 needs source word 3, target word 3 needs source word 2.
Each target word needs a different part of the source. One static summary, however large, serves every request with the same vector.
Both problems come from summarizing once, up front. So do not summarize: keep all \(T\) encoder states \(\mathbf{h}_1,\dots,\mathbf{h}_T\), one per source token, and let the decoder look back at them at every step.
The open question is how step \(t\) chooses its weights.
Part 2 · Choosing where to look. Follow one decoder step with made-up scores. The decoder is about to write noir, and its hidden state before this step is \(\mathbf{s}_{t-1}\).
Scores are any numbers; the softmax turns them into weights that sum to 1; the weights pick what to average.
Bahdanau, Cho & Bengio wrote that step as three formulas in "Neural Machine Translation by Jointly Learning to Align and Translate" (preprint Sep 2014, ICLR 2015). Here every state has \(d\) entries; in the paper the encoder's and the decoder's sizes differ.
The softmax runs over \(i\), the source positions, one decoder step at a time. The score function is still open: it maps two vectors to one number.
The recipe leaves \(\operatorname{score}(\mathbf{s},\mathbf{h})\) open: any function that maps a decoder state and an encoder state to one number. Bahdanau used a small network.
The other common choice has no parameters: \(\operatorname{score}(\mathbf{s},\mathbf{h})=\mathbf{s}^\top\mathbf{h}\), the dot product.
In 2014–15, attention was still an add-on between two RNNs. Next, the recipe drops them.
Without the two RNNs, the recipe is a lookup: a query is compared with stored keys, and their values come back. Vaswani et al. (2017) named the three roles query, key and value.
dict) matches the query to exactly one key and returns its value.Query \(\mathbf{q}\)
what this position is looking for; each looking position has one
Key \(\mathbf{k}_i\)
what stored item \(i\) advertises; it is used only for scoring
Value \(\mathbf{v}_i\)
what item \(i\) hands over when it is read
In translation, the query is the decoder state for noir; the keys are what the, black and cat advertise; the values are what each hands over. Bahdanau used the encoder states \(\mathbf{h}_i\) as both keys and values. In practice learned projections produce all three, so keys and values can differ.
Keys decide where to look; values decide what comes back.
Write the soft lookup as a formula with the dot-product score, starting with one query.
Stack the \(n_q\) queries as the rows of \(\textcolor{#8250df}{Q}\), the \(n_k\) keys as the rows of \(\textcolor{#c2410c}{K}\), and their values, each with \(d_v\) entries, as the rows of \(\textcolor{#1a7f37}{V}\).
Each row of the table is one operation of the attention formula, for \(n_q\) queries and \(n_k\) keys; queries and keys have \(d_k\) entries, and values have \(d_v\).
| step | what it does | kind | result |
|---|---|---|---|
| \(\textcolor{#8250df}{Q}\textcolor{#c2410c}{K}^\top\) | \(\textcolor{#8250df}{Q}\) (n_q, d_k) times \(\textcolor{#c2410c}{K}^\top\) (d_k, n_k) | matrix product | dot products (n_q, n_k) |
| \(/\sqrt{d_k}\) | every dot product divided by one number | elementwise | scores (n_q, n_k) |
| softmax, 1 | exponentiate every score | elementwise | (n_q, n_k) |
| softmax, 2 | sum each row, over the keys | reduction | (n_q, 1) |
| softmax, 3 | divide each entry by its row's sum | elementwise (broadcast) | weights (n_q, n_k), rows sum to 1 |
| weights \(\cdot\,\textcolor{#1a7f37}{V}\) | weights times \(\textcolor{#1a7f37}{V}\) (n_k, d_v) | matrix product | output (n_q, d_v) |
axis=-1, the last axis, which runs over the keys.These six rows are the whole mechanism. The next page writes the same steps in NumPy.
Part 3 · The mechanism in code (reading 3.2). The softmax function first subtracts each row's largest score, which is S03's fix: np.exp overflows for large scores, and shifting a whole row by one number does not change its softmax.
import numpy as np
def softmax(z, axis=-1):
z = z - z.max(axis=axis, keepdims=True) # numerical stability
e = np.exp(z)
return e / e.sum(axis=axis, keepdims=True)
def scaled_dot_product_attention(Q, K, V):
d_k = K.shape[-1]
scores = Q @ K.T / np.sqrt(d_k) # (n_q, n_k)
weights = softmax(scores, axis=-1) # each row sums to 1
return weights @ V, weights
Q, K, V are the matrices \(\textcolor{#8250df}{Q}\), \(\textcolor{#c2410c}{K}\), \(\textcolor{#1a7f37}{V}\) of the formula.K.T is \(\textcolor{#c2410c}{K}^\top\); @ is the matrix product; K.shape[-1] is \(d_k\).axis=-1 works along each row, over the keys. keepdims=True keeps the row sums as (n_q, 1), so the division broadcasts across each row.(n_q, d_v) and the weights, so you can read them.Before trusting the function, run it where you know the answer (reading 3.2's example, \(d_k=4\)). A key's first and third entries mean roughly "animal-ish", and its second and fourth mean "place-ish".
# np: from the previous page
K = np.array([[1.0, 0.0, 1.0, 0.0], # key 0: "animal-ish"
[0.0, 1.0, 0.0, 1.0], # key 1: "place-ish"
[1.0, 0.0, 0.9, 0.1]]) # key 2: also "animal-ish"
V = np.array([[1.0, 0.0], # value carried by key 0
[0.0, 1.0], # value carried by key 1
[0.5, 0.5]]) # value carried by key 2
The animal query is \(\mathbf{q}=[2,0,2,0]\). Which keys win, and roughly what weight does each get?
Answer: keys 0 and 2, almost evenly. Apply the attention formula one step at a time, with \(\textcolor{#8250df}{\mathbf{q}}=[2,0,2,0]\) and the previous page's \(\textcolor{#c2410c}{K}\) and \(\textcolor{#1a7f37}{V}\):
The output blends values 0 and 2, with a trace of value 1.
The same function runs on three queries, each a (1, 4) row (reading 3.2's loop).
# np, scaled_dot_product_attention, K, V: from the previous pages
queries = {"query ~ animal": np.array([[2.0, 0.0, 2.0, 0.0]]),
"query ~ place": np.array([[0.0, 2.0, 0.0, 2.0]]),
"query ~ mixed": np.array([[1.0, 1.0, 1.0, 1.0]])}
for name, Q in queries.items(): # Q: (1, 4)
out, w = scaled_dot_product_attention(Q, K, V) # w (1, 3), out (1, 2)
print(f"{name}: weights = {np.round(w[0], 4)} -> output = {np.round(out[0], 4)}")
query ~ animal: weights = [0.4902 0.0663 0.4435] -> output = [0.7119 0.2881]
query ~ place: weights = [0.1053 0.7783 0.1164] -> output = [0.1635 0.8365]
query ~ mixed: weights = [0.3333 0.3333 0.3333] -> output = [0.5 0.5]
Why did dot-product scores survive, and not Bahdanau's additive network? Reading 3.2 runs both on these keys with the animal query (additive weights random, as at initialization) and counts operations for \(T\) queries against \(T\) keys. Here \(W_q\), \(W_k\) and \(\mathbf{v}\) are the \(W_s\), \(W_h\) and \(\mathbf{v}\) of the additive score in Part 2, and the hidden size \(d_a\) is 8.
| dot product | additive (hidden size 8) | |
|---|---|---|
| score | \(\mathbf{q}\cdot\mathbf{k}/\sqrt{d_k}\) | \(\mathbf{v}^\top\tanh(W_q\mathbf{q}+W_k\mathbf{k})\) |
| weights | [0.4902 0.0663 0.4435] | [0.4324 0.1537 0.4139] |
| parameters | 0 | \(W_q\), \(W_k\) (\(8\times4\) each), \(\mathbf{v}\) (8): \(32+32+8=72\) |
| operations, \(T=4096\) | \(T^2d_k=4096^2\cdot4\approx67.1\)M | \(T^2\cdot2\cdot8+2T\cdot8\cdot4\approx268.7\)M |
| intermediate | the \(T\times T\) scores | \(T\times T\times8\) float32: \(4096^2\cdot8\cdot4\) bytes \(\approx0.54\) GB |
float32 number is 4 bytes, and a GB is \(10^9\) bytes.With the mechanism settled, two of its properties shape the rest of the course. First: does the output depend on the order of the stored items? Swap items 0 and 1:
# np, scaled_dot_product_attention, K, V, queries: earlier pages
Q = np.vstack(list(queries.values())) # (3, 4): three queries
perm = [1, 0, 2] # swap items 0 and 1
out, _ = scaled_dot_product_attention(Q, K, V)
out_kv, _ = scaled_dot_product_attention(Q, K[perm], V[perm])
out_k, _ = scaled_dot_product_attention(Q, K[perm], V)
print(np.abs(out_kv - out).max()) # keys and values moved
print(np.round(out_k, 4)) # keys moved alone
0.0
[[0.2881 0.7119]
[0.8365 0.1635]
[0.5 0.5 ]]
The claim is exactly this: permuting key and value rows together, with the queries fixed, changes no output. S16 states what shuffling a whole input sequence does.
Second property: can training change where a query looks?
Differentiable is not enough: the gradient must also be usefully large.
Part 4 · Keeping it trainable. Question 2 asks what keeps "where to look" trainable. The gradient must pass through the softmax, and a softmax that puts almost all weight on one key passes almost none (the Jacobian later in this part shows why). That happens when the scores are large, so first: how large is a dot product?
For \(d_k=64\) independent entries of mean 0 and variance 1, is \(\mathbf{q}\cdot\mathbf{k}\) typically 1, 8 or 64?
Do dot products of size \(\sqrt{d_k}\) matter? Another reading 3.2 script tests it (excerpt without the header's print; seed 0; n_keys = 16, trials = 200; softmax as on the NumPy page): each \(d_k\) gets 200 draws of a query and 16 keys, entries of mean 0 and variance 1. "max weight" averages the top key's softmax weight over the draws.
for d_k in [4, 16, 64, 256, 1024]:
max_raw, max_scaled, dots_all = [], [], []
for _ in range(trials):
q = np.random.randn(d_k)
K = np.random.randn(n_keys, d_k)
dots = K @ q
dots_all.append(dots)
max_raw.append(softmax(dots).max())
max_scaled.append(softmax(dots / np.sqrt(d_k)).max())
print(f"{d_k:>5} {np.concatenate(dots_all).std():>11.2f} "
f"{np.mean(max_raw):>17.4f} {np.mean(max_scaled):>20.4f}")
d_k std of q.k max weight (raw) max weight (scaled)
4 1.93 0.4271 0.2341
16 4.01 0.7050 0.2501
64 7.86 0.8271 0.2422
256 16.03 0.9164 0.2460
1024 31.95 0.9651 0.2499
This page reads the previous page's table one column at a time.
std of q.k column reads 1.93, 4.01, 7.86, 16.03 and 31.95 against \(\sqrt{d_k}=2,4,8,16,32\), so the derivation holds.Property 2 needs a usable gradient, and the next page shows what a weight near 1 does to it.
Property 2's gradient reaches the scores \(z_i\) through the softmax's Jacobian (quotient rule on \(p_i=e^{z_i}/\sum_j e^{z_j}\), key \(i\)'s weight; S03 met \(p\,(1-p)\) in the sigmoid):
Reading 3.2 prints the top key's own entry for one random query and 16 keys (seed 0):
gradient factor p*(1-p) at the winning key:
d_k = 4, raw: max p = 0.404117, p*(1-p) = 0.240806
d_k = 4, scaled: max p = 0.234212, p*(1-p) = 0.179357
d_k = 256, raw: max p = 0.999238, p*(1-p) = 0.000762
d_k = 256, scaled: max p = 0.180193, p*(1-p) = 0.147724
A saturated softmax can barely learn where to look, which is the mechanism's whole job.
Dividing by \(\sqrt{d_k}\) keeps every score's variance at 1, so the softmax starts spread out and its Jacobian is not near 0.
torch.nn.functional.scaled_dot_product_attention does the same. Its docstring (torch 2.13.0) says of the scale argument: "If None, the default value is set to" \(1/\sqrt{E}\), where \(E\), our \(d_k\), is the number of entries in each query and key.The scale sets how peaked each query's weights are. The softmax's axis sets which numbers sum to 1, and that is where the classic bug lives.
axis=-1Part 5 · The classic bug. Bahdanau's softmax ran over the source positions \(i\) with the decoder step \(t\) fixed, so each step got weights over all encoder states. In attention, one query's weights over all keys fill one row of the scores.
The grid holds the three queries' scores \(QK^\top/\sqrt4\) (the animal row is the hand computation's). The softmax turns each boxed row into weights that sum to 1, so scores of shape (n_q, n_k) need softmax(scores, axis=-1). The classic bug writes softmax(scores, axis=0), which normalizes each column (each key, over the queries) instead of each row.
With axis=0 instead, does the code run? Do the right keys still get the most weight?
axis=0 the code still runs, and the right keys still winAnswer: yes, and yes. The code stacks the three queries and takes the softmax over the query axis:
# np, softmax, K, queries: from the worked example
Q = np.vstack(list(queries.values())) # (3, 4): three queries
scores = Q @ K.T / np.sqrt(4) # (3, 3)
w_bad = softmax(scores, axis=0) # BUG: over the query axis
print(np.round(w_bad, 4))
print(np.round(w_bad.sum(axis=-1), 2)) # one sum per query (row)
[[0.6652 0.09 0.6362]
[0.09 0.6652 0.1052]
[0.2447 0.2447 0.2587]]
[1.39 0.86 0.75]
Reading the weights did not catch the bug; one line does.
weights.sum(axis=-1) is all ones. With queries stacked, a wrong-axis softmax can still let the right keys win, as on the previous page.
# np, softmax, scores, w_bad: the previous page
w = softmax(scores, axis=-1) # the right axis
print(np.allclose(w.sum(axis=-1), 1))
print(np.allclose(w_bad.sum(axis=-1), 1)) # the bug
True
False
assert np.allclose(weights.sum(axis=-1), 1). It passes on the right axis and fails on the bug (rows 1.39, 0.86, 0.75).Right shapes, running code and plausible weights do not catch the wrong axis; the row sums do. Attention is now built, run and tested. Next: where do its \(\textcolor{#8250df}{Q}\), \(\textcolor{#c2410c}{K}\) and \(\textcolor{#1a7f37}{V}\) come from?
Part 6 · Two wirings. The attention formula does not say where \(\textcolor{#8250df}{Q}\), \(\textcolor{#c2410c}{K}\) and \(\textcolor{#1a7f37}{V}\) come from. Bahdanau's decoder reading the encoder is the first wiring.
(n_target, d_k), \(\textcolor{#c2410c}{K}\) is (n_source, d_k) and \(\textcolor{#1a7f37}{V}\) is (n_source, d_v), so the scores are (n_target, n_source); the two lengths may differ.Information flows across, from the sequence that holds \(\textcolor{#c2410c}{K}\) and \(\textcolor{#1a7f37}{V}\) to the sequence that asks.
The second wiring takes all three from one sequence \(X\) of \(T\) tokens, one row of \(d\) numbers per token, each through its own learned projection:
Self-attention
\(\textcolor{#8250df}{Q}=XW_Q,\quad \textcolor{#c2410c}{K}=XW_K,\quad \textcolor{#1a7f37}{V}=XW_V\)
\(\textcolor{#8250df}{Q}\), \(\textcolor{#c2410c}{K}\) and \(\textcolor{#1a7f37}{V}\) all come from the same sequence \(X\): every token asks, and every token answers.
(T, d_k) and \(\textcolor{#1a7f37}{V}\) is (T, d_v). Scores \(\textcolor{#8250df}{Q}\textcolor{#c2410c}{K}^\top/\sqrt{d_k}\) are (T, T): every position scores every position, itself included, and its new representation is a weighted average of all positions' values.The two wirings give a rule: when \(\textcolor{#c2410c}{K}\) and \(\textcolor{#1a7f37}{V}\) come from the same sequence as \(\textcolor{#8250df}{Q}\), it is self-attention, and when they come from a different sequence, it is cross-attention.
(a) A translation decoder's state queries the encoder's states.
(b) Every word of a sentence queries the same sentence.
(c) Each word the decoder has written so far queries those earlier words.
(a) Cross: \(\textcolor{#8250df}{Q}\) comes from the decoder, \(\textcolor{#c2410c}{K}\) and \(\textcolor{#1a7f37}{V}\) from the encoder's states.
(b) Self: \(\textcolor{#8250df}{Q}\), \(\textcolor{#c2410c}{K}\) and \(\textcolor{#1a7f37}{V}\) all come from the sentence.
(c) Self: \(\textcolor{#8250df}{Q}\), \(\textcolor{#c2410c}{K}\) and \(\textcolor{#1a7f37}{V}\) all come from the decoder's own words.
Self-attention lets every position score every position; the next part counts the cost.
Part 7 · The price. In self-attention every position scores every position. Count the work for \(T\) tokens, one head, \(Q\), \(K\), \(V\) each (T, d) (here \(d_k=d_v=d\)); a multiply-accumulate (MAC) is one multiply and one add.
Reading 3.2 prints this table for \(d=64\), with M = \(10^6\) and MB = \(10^6\) bytes:
T score+mix MACs vs prev score matrix
256 8M - 0.3 MB
512 34M 4.0x 1.0 MB
1024 134M 4.0x 4.2 MB
2048 537M 4.0x 16.8 MB
4096 2147M 4.0x 67.1 MB
The table counts operations. Reading 3.2 also times the computation at \(T=256,\dots,4096\) (best of 5 runs) and classifies the median growth per doubling of \(T\) (linear 2×, quadratic 4×, cubic 8×):
measured median time growth per doubling of T: quadratic-like (about 4x per doubling)
| RNN (S13) | self-attention | |
|---|---|---|
| work per token | the same for any \(T\): one update | linear in \(T\): its query scores \(T\) keys; double \(T\), double the work |
| work per sequence | linear in \(T\) | quadratic in \(T\): double \(T\), 4× the work and the score memory |
| serial steps | \(T\) | none: all \(T\) positions at once, in two matrix products |
| path, step 3 to 300 | 297 multiplications | 1 dot product |
Attention buys path length 1 and parallel computation and pays with \(T^2\), which is why context length (\(T\)) is among the first numbers given for a model. The next page returns to today's three questions.
Part 8 · Close. This page answers the three questions from the start of the session.
\[\boxed{\;\operatorname{attention}(\textcolor{#8250df}{Q},\textcolor{#c2410c}{K},\textcolor{#1a7f37}{V})=\operatorname{softmax}\!\left(\frac{\textcolor{#8250df}{Q}\textcolor{#c2410c}{K}^\top}{\sqrt{d_k}}\right)\textcolor{#1a7f37}{V}\;}\]Two questions ask where to look (the weights, and the test of their axis), and one asks about the cost.
(a) Find the scores and weights by hand for \(\mathbf{q}=[1,0]\), \(\mathbf{k}_1=[2,0]\), \(\mathbf{k}_2=[0,2]\), \(d_k=2\).
(b) A colleague's attention trains to a mediocre loss, and its weights look plausible. Which one-line assert do you add?
(c) The context doubles from 2048 to 4096 tokens. What happens to the float32 score matrix's memory, and to the work per token?
(a) Scores \((2/\sqrt2,\ 0)=(\sqrt2,\ 0)\approx(1.414,\ 0)\); weights \(e^{1.414}/(e^{1.414}+1)\approx0.804\) and \(0.196\).
(b) The row-sum check on the weights w, which a wrong-axis softmax fails:
assert np.allclose(w.sum(axis=-1), 1)
(c) \(2048^2\cdot4\) bytes \(\approx16.8\) MB becomes \(4096^2\cdot4\approx67.1\) MB (×4). Work per token doubles: each query scores twice the keys.
A self-attention layer (Part 6) answers the three questions. Three things still keep it from being a model.