Session S14

Attention

Deep Learning · CS 4715/5715 · University of Idaho

Recap: an RNN reads one token at a time

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)\]
h0 Whh, WxhWhh, WxhWhh, Wxh h1h2h3 x1x2x3 theblackcat
  • At step \(t\) the RNN reads token \(t\), as the vector \(\mathbf{x}_t\), and updates its hidden state from \(\mathbf{h}_{t-1}\) to \(\mathbf{h}_t\) with the same \(W_{hh}\) and \(W_{xh}\) at every step.

One hidden state carries everything read so far, updated once per token.

Limitation 1, from S13: token 3 reaches token 300 by a relay of 297 updates

What happens when two tokens are far apart, such as token 3 and token 300?

forward: 297 updates, each a multiplication by Whh h3h4h5h299h300 ⋯ backward: the gradient takes the same 297 steps
  • Token 3 reaches token 300 only through the hidden state: \(300-3=297\) updates, each a multiplication by \(W_{hh}\).
  • The gradient decays along the same path. In S13's printout (reading 3.1), the gradient norm at an RNN's first input after \(T=80\) steps was 5.47e-29.

Information and gradient both have to survive every step in between.

LSTM eased Limitation 1, the relay; it did not remove it

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

  • What it fixed: along the cell, each step multiplies the gradient by \(\mathrm{diag}(\mathbf{f})\), not by \(W_{hh}\) and a \(\tanh\) derivative, so the gradient reaches further back. S13's printout (reading 3.1) at \(T=80\), where fb=2 is the LSTM with its forget-gate bias set to 2:

   T         RNN        LSTM   LSTM fb=2
  80    5.47e-29    5.27e-18    3.12e-03
  
  • What it did not fix: the cell is still a relay. Every step multiplies by a forget gate, and gates below 1 still shrink the gradient geometrically.
  • Step 300 still reaches step 3 only through the 297 updates in between.

Gating made the relay survivable; it did not give step 300 a direct path to step 3.

Limitation 2, from S13: each step must wait for the step before it

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.

serial loop h1h2h3hT ⋯ each step waits for the step before it all at once T × d: rows given in advance one matrix product for all T rows; no row waits
\(T\)serial loop (ms)all at once (ms)
1285.230.46
2569.770.70
51219.071.18
102436.912.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.

Limitation 3: everything read must fit in one fixed-size state

Beyond S13's two limitations there is a third: how much one state can hold.

5 words 12345 500 words 12345678499500 ⋯ state: dh entriesstate: dh entries the same size each box is one token read by the RNN; the arrow ends in the state after the last token
  • An RNN's \(\mathbf{h}_t\), and an LSTM's \(\mathbf{h}_t\) and \(\mathbf{c}_t\), have \(d_h\) entries at every step.
  • After 5 words or after 500 words, the state has the same size, and everything read so far must be stored in it.

This is the one-vector bottleneck, and translation shows it most clearly.

Today's three questions

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.

Today's route

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.

partwhat happensquestion
1Translation models that compress each sentence into one vector fail on long sentences.sets up Q1
2The first attention model scores every source word, turns the scores into weights, and averages.Q1
3The recipe becomes a dozen lines of NumPy, checked on a case you can do by hand.Q1
4One scale factor keeps the learned scores trainable.Q2
5A softmax over the wrong axis still runs, and a one-line test catches it.Q1
6Attention can read another sentence or its own sentence.sets up Q3
7Measurements show how the work grows with length.Q3
8The close answers the three questions and lists what attention still lacks.all three

Attention came from translation, so Part 1 starts there.

Translation in 2014: the whole source passes through one vector

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.

encoderencoderencoder one vector hT fixed size, any length decoderdecoderdecoder theblackcat lechatnoir
  • Sutskever, Vinyals & Le and Cho et al. built sequence-to-sequence (seq2seq) in 2014.
  • The decoder sees the source only through the encoder's final hidden state.

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.

The vector has one size for every length and is made too early

That design breaks on long sentences, and a bigger vector would not fix it.

  • (a) One size for every length. As Limitation 3 showed, 500 words must fit where 5 do; Cho et al. (2014) reported translation quality falling off as sentences grew longer.
  • (b) Summarized too early. The encoder summarizes before the decoder asks for anything, yet which source words matter depends on which target word is being produced. For the black cat → le chat noir:
producinglechatnoir
needsthecatblack
at source position132

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.

The fix: keep every encoder state, and average them step by step

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.

h1h2h3 theblackcat αt,1αt,2αt,3 ct weighted average decoder, step t: noir thick: the weight we would want largest for noir (← black)
  • At decoder step \(t\) the decoder receives \(\mathbf{c}_t=\sum_{i=1}^{T}\alpha_{t,i}\,\mathbf{h}_i\), a weighted average of the states with weights \(\alpha_{t,i}\ge0\) that sum to 1 over \(i\).
  • Each step gets new weights: noir wants black's state most, and chat wants cat's.

The open question is how step \(t\) chooses its weights.

One decoder step with numbers: most weight goes to black

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}\).

st−1 decoder state scores h1, h2, h3 theblackcat h1h2h3 score 0.2score 2.0score 0.5 softmax weight 0.12weight 0.72weight 0.16 ct weighted average of h1, h2, h3 decoder: noir
  • The scores \(e=(0.2,\ 2.0,\ 0.5)\) become the weights \(\alpha\approx(0.12,\ 0.72,\ 0.16)\).
  • \(\mathbf{c}_t=0.12\,\mathbf{h}_1+0.72\,\mathbf{h}_2+0.16\,\mathbf{h}_3\) is mostly black's state.

Scores are any numbers; the softmax turns them into weights that sum to 1; the weights pick what to average.

Bahdanau's recipe symbol by symbol: each symbol has a shape

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.

  1. Score every encoder state \(\mathbf{h}_i\in\mathbb{R}^d\) against \(\mathbf{s}_{t-1}\in\mathbb{R}^d\), the decoder RNN's hidden state before step \(t\). Each \(e_{t,i}=\operatorname{score}(\mathbf{s}_{t-1},\mathbf{h}_i)\) is one number, for source positions \(i=1,\dots,T\).
  2. Softmax (S03's) runs over the source positions \(i\) with \(t\) fixed: \(\alpha_{t,i}=\exp(e_{t,i})\big/\sum_{j=1}^{T}\exp(e_{t,j})\). Step \(t\)'s weights \(\boldsymbol{\alpha}_t\) have \(T\) entries, all positive, summing to 1.
  3. Average: the context vector \(\mathbf{c}_t=\sum_{i=1}^{T}\alpha_{t,i}\,\mathbf{h}_i\in\mathbb{R}^d\) is fed to the decoder at step \(t\).

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.

Additive score: a small network computes the score

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.

sh dsdh WsWh dada + tanh da dot with v one number red symbols are learned; each small blue d is the number of entries on its arrow
\[\operatorname{score}(\mathbf{s},\mathbf{h})=\mathbf{v}^\top\tanh\left(W_s\mathbf{s}+W_h\mathbf{h}\right)\]
  • \(\mathbf{s}\in\mathbb{R}^{d_s}\) and \(\mathbf{h}\in\mathbb{R}^{d_h}\) (both \(d\) on the previous page). \(W_s\) is \(d_a\times d_s\), \(W_h\) is \(d_a\times d_h\), and \(\mathbf{v}\in\mathbb{R}^{d_a}\), where \(d_a\) is the network's hidden size.
  • \(W_s\), \(W_h\) and \(\mathbf{v}\) are learned together with the rest of the translation model.
  • Adding the two projections before the \(\tanh\) gives the name "additive attention".

Dot-product score: it measures how aligned two vectors are

The other common choice has no parameters: \(\operatorname{score}(\mathbf{s},\mathbf{h})=\mathbf{s}^\top\mathbf{h}\), the dot product.

  • For vectors of the same length, the more they point the same way, the larger their dot product; a longer vector also gives a larger dot product.
  • For example, with \(\mathbf{s}=(1,0)\), the vectors \((2,0)\), \((0,2)\) and \((-2,0)\), all of length 2, give the dot products \(2\), \(0\) and \(-2\).
  • It needs \(\mathbf{s}\) and \(\mathbf{h}\) to have the same number of entries.
  • With no parameters, one matrix product scores every position at once. Luong, Pham & Manning (EMNLP 2015) found that it worked as well as the additive network.
  • Alignment (which source word matches each target word): without alignment labels, the weights still landed on the word a translator would pick, e.g. black for noir.

In 2014–15, attention was still an add-on between two RNNs. Next, the recipe drops them.

Without the RNNs: a soft lookup with queries, keys and values

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.

  • A hash map (a Python dict) matches the query to exactly one key and returns its value.
  • Attention scores the query against every key, turns the scores into positive weights that sum to 1, and returns the weighted average of all values: a soft dictionary lookup.

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.

One query scores every key, then averages the values

Write the soft lookup as a formula with the dot-product score, starting with one query.

q one query k1k2k3 q · k1 / √dkq · k2 / √dkq · k3 / √dk softmax α1α2α3 ××× v1v2v3 Σ one output vector
  1. One query \(\textcolor{#8250df}{\mathbf{q}}\) is scored against keys \(\textcolor{#c2410c}{\mathbf{k}_1},\dots,\textcolor{#c2410c}{\mathbf{k}_{n_k}}\), each with \(d_k\) entries; the scores are \(\textcolor{#8250df}{\mathbf{q}}\cdot\textcolor{#c2410c}{\mathbf{k}_i}/\sqrt{d_k}\). Why divide by \(\sqrt{d_k}\) is Part 4's subject; for now it is a constant.
  2. The weights \(\alpha_i\) are the softmax of the scores over \(i\), the keys, so they are positive and sum to 1. The output \(\sum_i\alpha_i\,\textcolor{#1a7f37}{\mathbf{v}_i}\) is one vector.

Many queries at once: attention is \(\operatorname{softmax}(\textcolor{#8250df}{Q}\textcolor{#c2410c}{K}^\top/\sqrt{d_k})\,\textcolor{#1a7f37}{V}\)

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}\).

× = qa · ki softmax each row × = Qnq × dk K⊤dk × nk scoresnq × nk weightsnq × nk Vnk × dv outputnq × dv row a: query a's weights and output
  • Entry \((a,i)\) of \(\textcolor{#8250df}{Q}\textcolor{#c2410c}{K}^\top\) is \(\textcolor{#8250df}{\mathbf{q}_a}\cdot\textcolor{#c2410c}{\mathbf{k}_i}\), so one matrix product computes every dot product. Row \(a\) of the softmax holds query \(a\)'s weights, and multiplying by \(\textcolor{#1a7f37}{V}\) gives every output at once:
\[\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}\;}\]

The attention formula is two matrix products and one row-wise softmax

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\).

stepwhat it doeskindresult
\(\textcolor{#8250df}{Q}\textcolor{#c2410c}{K}^\top\)\(\textcolor{#8250df}{Q}\) (n_q, d_k) times \(\textcolor{#c2410c}{K}^\top\) (d_k, n_k)matrix productdot products (n_q, n_k)
\(/\sqrt{d_k}\)every dot product divided by one numberelementwisescores (n_q, n_k)
softmax, 1exponentiate every scoreelementwise(n_q, n_k)
softmax, 2sum each row, over the keysreduction(n_q, 1)
softmax, 3divide each entry by its row's sumelementwise (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 productoutput (n_q, d_v)
  • \(n_q\) and \(n_k\) may differ, and \(d_v\) need not equal \(d_k\). In NumPy, "along each row" is 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.

The attention formula takes a dozen lines of 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
  
  • The arguments 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.
  • It returns the output (n_q, d_v) and the weights, so you can read them.
  • HW3 (out at S18) builds on this function.

Check by hand: two keys are animal-ish, and one is place-ish

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
  
K V animalplaceanimalplace key 0key 1key 2 1.00.01.00.01.00.00.01.00.01.00.01.01.00.00.90.10.50.5 darker cells hold larger entries; keys 0 and 2 share one pattern
  • Keys are numbered from 0, as in the code. Keys 0 and 2 point in nearly the same direction; key 1 points elsewhere.
  • Each key carries a distinctive 2-entry value, so the output shows exactly what it mixes.

The animal query is \(\mathbf{q}=[2,0,2,0]\). Which keys win, and roughly what weight does each get?

The animal query puts 49% on key 0, 44% on key 2 and 7% on key 1

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}\):

  1. Dot products \(\textcolor{#8250df}{\mathbf{q}}\cdot\textcolor{#c2410c}{\mathbf{k}_i}\): key 0: \(2\cdot1+2\cdot1=4\); key 1: \(0\); key 2: \(2\cdot1+2\cdot0.9=3.8\). Together \((4,\,0,\,3.8)\).
  2. Divide by \(\sqrt{d_k}=\sqrt{4}=2\): the scores \((2,\,0,\,1.9)\).
  3. Exponentiate: \(e^{2},\,e^{0},\,e^{1.9}\approx7.39,\ 1,\ 6.69\); their sum is \(7.39+1+6.69=15.08\).
  4. Divide by the sum: \(7.39/15.08\approx0.49\), \(1/15.08\approx0.07\), \(6.69/15.08\approx0.44\).
  5. Output \(\sum_i\alpha_i\textcolor{#1a7f37}{\mathbf{v}_i}=0.49\,[1,0]+0.07\,[0,1]+0.44\,[0.5,0.5]=[0.71,\ 0.29]\).

The output blends values 0 and 2, with a trace of value 1.

The place query picks key 1, and the mixed query averages all values

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]
  
  • Animal repeats the hand computation to four decimals; its first output entry is \(0.4902+0.5\cdot0.4435\approx0.712\).
  • Place, \([0,2,0,2]\), puts 78% on key 1, so its output is close to key 1's value \([0,1]\).
  • Mixed, \([1,1,1,1]\), has every dot equal to 2.0 (\(1+1\), \(1+1\), \(1+0.9+0.1\)), so each weight is exactly \(1/3\) and the output is the plain average of the values, \([0.5,0.5]\).

The dot product survived with no parameters and fewer operations

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 productadditive (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]
parameters0\(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
intermediatethe \(T\times T\) scores\(T\times T\times8\) float32: \(4096^2\cdot8\cdot4\) bytes \(\approx0.54\) GB
  • The additive count projects each query and key once (\(2T\cdot8\cdot4\)), then spends about \(2\cdot8\) operations per pair. A float32 number is 4 bytes, and a GB is \(10^9\) bytes.
  • Both favor keys 0 and 2 here: the dot product does because they align with the query, and the random additive scorer does by chance, until training teaches it relevance.

Property 1: move keys and values together, and no output changes

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
  
originalK, Vk0v0k1v1k2v2each key sitsbeside its valuetogetherK[perm], V[perm]k1v1k0v0k2v2pairs kept, sooutputs staykeys aloneK[perm], Vk1v0k0v1k2v2pairs broken, sooutputs swap

0.0
[[0.2881 0.7119]
 [0.8365 0.1635]
 [0.5    0.5   ]]
  
  • Together: no output changes; each key still brings its own value.
  • Keys alone: the pairs break. The animal query still finds the animal key, but that key now sits beside the place item's value, so the animal and place outputs swap their entries. Mixed stays, since its weights are all \(1/3\).

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.

Property 2: differentiable, so where to look is learned by backprop

Second property: can training change where a query looks?

WQWKWVQKVscoressoftmaxweightsoutputlossbackward: the gradient reaches the learned projections (red); WV decides what comes back
  • Every step of the attention formula has a derivative, the softmax included.
  • The formula itself has no parameters. The gradient flows through the scores to the queries and keys, and on to the learned projections that produce \(\textcolor{#8250df}{Q}\), \(\textcolor{#c2410c}{K}\) and \(\textcolor{#1a7f37}{V}\) (Part 2); training changes those projections, so "where to look" is learned jointly with everything else.
  • Bahdanau's model learned to align this way, with no alignment labels.
  • A hard lookup (an argmax, with weight 1 on the top key and 0 elsewhere) has zero gradient almost everywhere: scores \((2,0,1.9)\) and \((2.01,0,1.9)\) both give weights \((1,0,0)\).

Differentiable is not enough: the gradient must also be usefully large.

Why divide by \(\sqrt{d_k}\): how large is a dot product of \(d_k\) random terms?

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?

  1. Each term of \(\mathbf{q}\cdot\mathbf{k}=\sum_{j=1}^{d_k}q_jk_j\) has mean \(0\) and variance \(1\cdot1=1\) (\(q_j\), \(k_j\) independent, mean 0).
  2. The \(d_k\) terms are independent, so their variances add: \(\mathrm{Var}(\mathbf{q}\cdot\mathbf{k})=d_k\). The standard deviation, a typical size, is \(\sqrt{d_k}\): about 8 at \(d_k=64\).
  3. Real models use \(d_k=64\) to \(128\) per head (S16 runs several attention computations in parallel, each a head), giving standard deviations \(\sqrt{64}=8\) to \(\sqrt{128}\approx11.3\).
  4. Dividing by \(\sqrt{d_k}\) gives \(\mathrm{Var}(\mathbf{q}\cdot\mathbf{k}/\sqrt{d_k})=d_k/(\sqrt{d_k})^2=1\) at every \(d_k\).

Measured: unscaled, the top weight climbs toward 1 as \(d_k\) grows

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
  

Unscaled, the softmax is nearly a hard argmax at initialization

This page reads the previous page's table one column at a time.

  • The 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.
  • Unscaled, the top key's weight grows with \(d_k\): 0.43 at \(d_k=4\), 0.83 at 64, 0.92 to 0.97 at 256 to 1024. An even spread over 16 keys would give each \(1/16\approx0.06\). With nearly all the weight on one key, the softmax is saturated, which makes it nearly a hard argmax at initialization, before anything is learned.
  • Scaled, the top weight stays between 0.23 and 0.25 at every \(d_k\), so the weights stay softly peaked: dividing by \(\sqrt{d_k}\) sets the score variance to \(d_k/(\sqrt{d_k})^2=1\) at every \(d_k\).

Property 2 needs a usable gradient, and the next page shows what a weight near 1 does to it.

Saturated softmax: every Jacobian entry has a factor near 0

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

\[\frac{\partial p_i}{\partial z_i}=p_i\,(1-p_i),\qquad \frac{\partial p_i}{\partial z_j}=-p_i\,p_j\quad(j\ne i)\]
z1z2z3p1p1(1−p1)−p1 p2 −p1 p3 p2−p2 p1 p2(1−p2)−p2 p3 p3−p3 p1 −p3 p2 p3(1−p3)
  • When key 1 wins (\(p_1\) near 1), every entry has a factor near 0, shown in red.

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
  
  • At \(d_k=256\) the entry is 0.000762 unscaled and 0.147724 scaled.
  • For this draw that is about 200 times smaller: \(0.147724/0.000762\approx194\).

A saturated softmax can barely learn where to look, which is the mechanism's whole job.

The fix: divide by \(\sqrt{d_k}\), as Vaswani et al. (2017) and PyTorch do

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.

  • Its source: Vaswani et al. (2017), "Attention Is All You Need", introduced the scale for this reason: with large \(d_k\) the dot products grow large and push the softmax into regions where its gradients are extremely small. The scale depends only on the dimension \(d_k\); it does not look at the data or rescale any feature.
  • In PyTorch, 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.
  • What the scale does not do: dividing all dot products by the same positive number never changes which key scores highest. It changes how peaked the weights are, not their order.

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.

Each row of weights sums to 1, so the softmax uses axis=-1

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

columns: keys (axis 1, the last one: -1) rows: queries (axis 0) key 0key 1key 2 animalplacemixed 201.9020.1111 axis=-1: each row sums to 1, one query across the keys (correct) axis=0: the wrong numbers sum to 1

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?

With axis=0 the code still runs, and the right keys still win

Answer: 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]
  
  • The shapes are right, the code runs, and here the right keys still win, because in this small, nearly symmetric example every column's sum is about the same.
  • Only the sums show the bug: columns sum to 1 (\(0.6652+0.09+0.2447\approx1\)), rows to 1.39, 0.86, 0.75.
  • The model still trains, to a mediocre loss (reading 3.2).

Catching it before training: assert that every row sums to 1

Reading the weights did not catch the bug; one line does.

  • Test like the worked example: build a case where you know which key should win, read the weights, and assert 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
  
  • In a test: 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?

Cross-attention takes \(\textcolor{#8250df}{Q}\) from one sequence and \(\textcolor{#c2410c}{K}\) and \(\textcolor{#1a7f37}{V}\) from another

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.

target side: Q lechatnoir source side: K, V theblackcat the query of noir scores every source key
  • \(\textcolor{#8250df}{Q}\) is (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.
  • Other uses condition a caption on an image (queries from the caption's words, keys and values from image features) or an answer on retrieved documents.

Information flows across, from the sequence that holds \(\textcolor{#c2410c}{K}\) and \(\textcolor{#1a7f37}{V}\) to the sequence that asks.

Self-attention takes \(\textcolor{#8250df}{Q}\), \(\textcolor{#c2410c}{K}\) and \(\textcolor{#1a7f37}{V}\) from the same sequence

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.

position 1position 2position 3position 4position 5 X: position 5's query scores every key of the same sequence, its own included; every position does the same
  • \(W_Q\), \(W_K\) are \(d\times d_k\), \(W_V\) is \(d\times d_v\), so \(\textcolor{#8250df}{Q}\), \(\textcolor{#c2410c}{K}\) are (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.
  • Step 300's query scores step 3's key directly, a path of length 1, not 297 multiplications. All \(T\) rows come out of two matrix products at once, with no serial loop.

Self-check: name the wiring by where \(\textcolor{#c2410c}{K}\) and \(\textcolor{#1a7f37}{V}\) come from

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.

The price of looking everywhere: \(T\) queries × \(T\) keys = \(T^2\) scores

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.

  • \(QK^\top\) gives \(T\cdot T\) scores, each a length-\(d\) dot product: \(T\cdot T\cdot d\) MACs. Weights times \(V\) gives \(T\cdot d\) outputs, each a sum over \(T\) keys: another \(T\cdot T\cdot d\), so the total is \(2T^2d\).
  • The float32 score matrix holds \(T^2\) numbers of 4 bytes each.
T keysTquerieseach row holds one query's T scoresall rows hold T2 scores

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 \(T=4096\) row checks out: \(2\cdot4096^2\cdot64\approx2147\)M MACs and \(4096^2\cdot4\) bytes \(\approx67.1\) MB.
  • Doubling \(T\) multiplies \(T^2\) by 4, as the 4.0x column shows.
  • The counts are for one head and one sequence.

Doubling \(T\) doubles the work per token and quadruples it per sequence

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 tokenthe same for any \(T\): one updatelinear in \(T\): its query scores \(T\) keys; double \(T\), double the work
work per sequencelinear 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 300297 multiplications1 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.

The attention formula answers 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}\;}\]
  • 1 · Where to look. When the model writes noir, its query's dot product with black's key is the largest, so the softmax puts most of that row's weight on black; training shapes the queries and keys this way.
  • 2 · Keeping it trainable. Every step is differentiable (Property 2), and the \(\sqrt{d_k}\) keeps the score variance at 1 at initialization, so the softmax starts unsaturated.
  • 3 · The cost. A sequence of \(T\) tokens needs \(T^2\) scores (\(2T^2d\) MACs), so doubling the sentence quadruples the work, while each token's work grows linearly. S20 shows how generation reuses keys and values.

Self-check: three questions test the weights, the axis and the cost

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.

Attention still lacks order, several lookups and a nonlinearity

A self-attention layer (Part 6) answers the three questions. Three things still keep it from being a model.

  • No notion of order: shuffle the tokens of \(X\) and each token's output shuffles with it, unchanged otherwise (S16 states this precisely). Positional encodings fix this.
  • One lookup per position: each query gets one weighted average, when a word may need its subject, its modifiers and its coreferents (other words for the same thing) at once. Multi-head attention fixes this.
  • Linear in the values once the weights are fixed: one layer is a weighted average of value rows, and no nonlinearity is applied to the values themselves. Stacked blocks with feedforward layers fix this.
  • Together, the three fixes make the Transformer (S16–S17).

For next time

  • Next session (S16) is Transformer I, built from today's self-attention; S15 is not held this term.
  • Read 3.3 Transformer I.
  • Review the S13 block of the S15 review guide (3.1 RNNs and LSTMs, on Quiz 3).
  • Quiz 3 (Module 3, at S23) covers today's material.
  • HW2 is due next week (S18). HW3 goes out that session; scaled dot-product attention is its innermost component.