Attention

EE 641 - Unit 5

Dr. Brandon Franzke

Fall 2026

Outline

The Read

Fixed-Length Context Bottleneck

  • Accuracy against source length

Attention Is Learned Alignment

  • Scores, softmax, weighted sum
  • The grid as an alignment
  • Training the read
  • Training against generation

Kernel Regression

  • Bandwidth as temperature
  • Queries, keys, values

Score Functions and Scaling

  • Additive, bilinear, dot product
  • Published comparison
  • Scaling with key width

Uses and Limits

Attention in Translation

  • Bahdanau and Luong models
  • Weights as explanations
  • Coverage

Implementing Attention

  • Batches, padding, masks
  • Memory and time

Attention over Sets and Images

  • Order of the stored items
  • Captioning and pointers

Recall Without Recurrence

  • Position and the read

Reading List

Fixed-Length Context Bottleneck

Encoder Passes One Context Vector to the Decoder

Encoder-decoder

  • Encoder, the reader of sequence-to-sequence translation: an LSTM over the source
  • Context vector: the encoder’s final state, \(\mathbf{c} = (\mathbf{h}^{\text{enc}}_S, \mathbf{C}^{\text{enc}}_S)\), \(2H\) numbers
  • Decoder, the writer: starts from \(\mathbf{c}\), one target word per step, state \(\mathbf{h}^{\text{dec}}_t\)

Running pair

  • English “the black cat sat on the mat”, \(S = 7\)
  • French “le chat noir s’est assis sur le tapis”, \(T = 8\)

Fixed length

  • \(\mathbf{c}\): the only path from the source to any target word
  • \(2H\) numbers for a source of any length \(S\)

Fixed-Context Accuracy Falls with Source Length

Reverse-copy task

  • Source: \(S\) symbols from 10. Target: the source reversed, then an end token
  • Encoder and decoder LSTMs, \(H = 64\), identical training at every \(S\)
  • Per-word accuracy with the correct previous word fed at each step
  • Chance: 0.1

Measured

  • \(S = 8\): mean 1.00. \(S = 12\): 0.99
  • \(S = 16\): 0.96
  • \(S = 24\): 0.87
  • \(S = 32\): 0.80, worst position 0.73

All \(S\) source words pass through the same 128 numbers

Wider Context Vectors Recover Accuracy at Quadratic Cost

Trainability

  • Fixed context at \(S = 24\), \(H = 64\): every source position at 0.84 or above, against 0.1 for chance
  • Early source words learned: gradient reaches them through the LSTM’s cell path
  • Remaining errors: words the 128 numbers of \(\mathbf{c}\) do not retain

Recency

  • Last three source words at 0.92 to 0.98, earlier words at 0.84 to 0.90
  • Words read last: closest to \(\mathbf{c}\), written first

Width

  • \(H = 128\): mean 0.97
  • \(H = 256\): every word at 0.99 or better, with 11.8 times the recurrent parameters (593,920 against 50,176)
  • Cost per encoder and decoder step: \(O(H^2)\)

Each Output Word Depends on Different Source Words

Per target word

  • “chat” with “cat”, “noir” with “black”, one position earlier in the source
  • “s’est” and “assis” both with “sat”
  • A different source position, or two of them, at almost every step

Encoder states

  • One per source word, \(\mathbf{h}^{\text{enc}}_1, \ldots, \mathbf{h}^{\text{enc}}_S\), each computed right after reading that word
  • Only \(\mathbf{h}^{\text{enc}}_S\) is passed to the decoder

Each row of the grid: a different subset of source positions

Weighted Read Gives Each Target Word Its Own Context Vector

Weighted read

\[\mathbf{c}_t = \sum_{s=1}^{S} a_{t,s}\,\mathbf{h}^{\text{enc}}_s, \qquad a_{t,s} = \frac{\exp(e_{t,s})}{\sum_{s'} \exp(e_{t,s'})}\]

  • Every encoder state kept: \(S\) vectors of \(H\) numbers
  • \(e_{t,s}\): one score per source position, from \(\mathbf{h}^{\text{dec}}_t\) and \(\mathbf{h}^{\text{enc}}_s\)
  • Softmax over \(s\): weights non-negative, summing to one

Per target word

  • A different \(\mathbf{c}_t\) for each target word
  • \([\mathbf{h}^{\text{dec}}_t;\, \mathbf{c}_t]\) into the output layer through one new matrix, \(\mathbf{W}_c \in \mathbb{R}^{H \times 2H}\)
  • Measured model: \(e_{t,s} = (\mathbf{h}^{\text{dec}}_t)^\top \mathbf{h}^{\text{enc}}_s\), no parameters in the score
  • No alignment given: weights computed from the states, trained by the per-word cross-entropy alone

Read Weights Trained Only on the Output Recover the Alignment

Accuracy, \(H = 64\)

  • Weighted read: mean 0.999 or better at every \(S\) from 8 to 32, worst position 0.996
  • Fixed context: 1.00 at \(S = 8\), 0.80 at \(S = 32\)
  • Parameters at \(S = 24\): 59,693 against 51,437, 16% more, all in \(\mathbf{W}_c\)

Read weights, averaged over 200 test sources

  • Correct alignment for reverse-copy: the reversed diagonal
  • Peak weight per row: 0.76 to 0.98
  • From the second output on, the peak sits on the encoder state that read the decoder’s current input, the word written one step earlier
  • That encoder state also depends on the source word before it, the next word to write

Read weights learn the alignment from the data alone

Read Cost Grows as Source Length Times Target Length

Per output step

  • \(S\) scores: \(SH\) multiply-adds
  • Weighted sum: \(SH\)
  • \(\mathbf{W}_c\): \(2H^2\)

Per sentence pair

  • Read: \(O(STH)\), against \(O((S + T)\,H(H + d))\) for the two LSTMs, \(d\) the input width
  • Example (\(S = 24\), \(T = 25\), \(H = 64\), \(d = 32\)): scores and sums 76,800, \(\mathbf{W}_c\) 204,800, both LSTMs 1,204,224 multiply-adds

Memory

  • \(S\) encoder states kept until the decoder finishes: \(SH\) numbers
  • \(S \times T\) weights kept for the backward pass

Crossover

  • \(S = T = n\): the read costs as much as both LSTMs at \(n = 4(H + d) = 384\)
  • Read: all \(S\) positions in parallel. LSTMs: \(S + T\) steps in sequence
  • Parallel training is what made transformers and large models practical

Attention Is Learned Alignment

Pronoun Translation Depends on a Noun Many Words Back

One changed word

  • “tired”: “it” is the animal, French “il” (masculine “l’animal”)
  • “wide”: “it” is the street, French “elle” (feminine “la rue”)
  • Deciding word: three words after the pronoun

For the decoder writing the pronoun

  • Needs the gender of one specific source noun
  • Which noun: set by the meaning of the whole source
  • Distance between noun and pronoun: any

Fixed Context Must Store Every Fact in Advance

Fixed context vector

  • Encoder finishes before the decoder writes anything
  • \(\mathbf{c}\) must already contain the gender of every noun, the referent of every pronoun, the order of every phrase
  • Which of these a target word uses: known only at that word

Measured

  • Fixed-context accuracy falls with source length: 1.00 at 8 symbols, 0.80 at 32, \(H = 64\)

Reading at the step that needs it

  • Keep every encoder state, one per source word
  • At each decoder step, read the encoder states that step needs
  • Decoder state at that step: the record of what has been written, so the quantity that determines what is needed

Each Decoder Step Scores Every Encoder State

Available at decoder step \(t\)

  • Decoder state \(\mathbf{h}^{\text{dec}}_t\): the target words written so far, and the source through the decoder’s initial state
  • Encoder states \(\mathbf{h}^{\text{enc}}_1, \ldots, \mathbf{h}^{\text{enc}}_S\): each one source word in its context

Running pair

  • “the black cat sat on the mat”, \(S = 7\)
  • “le chat noir s’est assis sur le tapis”, \(T = 8\)
  • Step 3 writes “noir”: “le chat” written, “black” needed

Each Decoder Step Needs a Different Source Position

Needed position by step

  • “le”: “the” (1). “chat”: “cat” (3). “noir”: “black” (2)
  • Forward two, then back one: French puts the adjective after the noun
  • “s’est” and “assis”: both “sat” (4)

Consequence

  • Source position: not a function of the step number
  • Depends on what has been written: after “chat”, the adjective
  • Decoder state: the record of what has been written, so it can determine the position

Decoder State’s Projection Is Longest on the Needed Encoder State

Two-dimensional states, set by hand

  • Trained states have hundreds of dimensions. Two let every state be drawn and every number checked by hand
  • Encoder states: unit length, one direction per source word
  • Decoder states: length about 3, drawn shortened

Steps 1 to 3

  • Step 1, “le”: toward “the”
  • Step 2, “chat”: toward “cat”
  • Step 3, “noir”: toward “black”
  • Score: the decoder state’s projection onto each encoder state, longest for the best word

Reading the Source Takes Three Operations per Decoder Step

Step 1: score

  • Compare \(\mathbf{h}^{\text{dec}}_t\) with each \(\mathbf{h}^{\text{enc}}_s\)
  • One number per source word
  • \(S\) scores

Step 2: softmax

  • Scores to weights
  • Non-negative, summing to one
  • \(S\) weights

Step 3: weighted sum

  • Weights times encoder states, summed
  • Context vector \(\mathbf{c}_t\)
  • \(H\) numbers

Readout

  • \(\mathbf{c}_t\) with \(\mathbf{h}^{\text{dec}}_t\)
  • Next-word distribution
  • Repeated at every decoder step

Step 1: Dot Product Compares Two States by Direction and Length

Score

\[e_{t,s} = \big(\mathbf{h}^{\text{dec}}_t\big)^\top \mathbf{h}^{\text{enc}}_s = \|\mathbf{h}^{\text{dec}}_t\|\,\|\mathbf{h}^{\text{enc}}_s\|\cos\theta_{t,s}\]

  • Same direction: large positive
  • Perpendicular: zero
  • Opposite: large negative
  • Longer states: every score scaled up

Cost

  • \(H\) multiply-adds per score, no parameters
  • Decoder and encoder states of the same width

Encoder states in the example, \(H = 2\)

\(s\) word \(\mathbf{h}^{\text{enc}}_s\)
1 the \([-0.17,\ 0.98]\)
2 black \([0.66,\ 0.75]\)
3 cat \([1.00,\ -0.05]\)
4 sat \([0.58,\ -0.81]\)
5 on \([-0.27,\ -0.96]\)
6 the \([-0.92,\ -0.39]\)
7 mat \([-0.88,\ 0.48]\)

Decoder state at step 3, writing “noir”

  • \(\mathbf{h}^{\text{dec}}_3 = [2.0,\ 2.2]\)

Scores at One Step Rank the Source Words

Decoder step 3 (“noir”), all seven scores

word \(e_{3,s}\)
the \(2.0(-0.17) + 2.2(0.98) = 1.82\)
black \(2.0(0.66) + 2.2(0.75) = 2.97\)
cat \(2.0(1.00) + 2.2(-0.05) = 1.89\)
sat \(2.0(0.58) + 2.2(-0.81) = -0.62\)
on \(2.0(-0.27) + 2.2(-0.96) = -2.65\)
the \(2.0(-0.92) + 2.2(-0.39) = -2.70\)
mat \(2.0(-0.88) + 2.2(0.48) = -0.70\)

Ranking

  • Highest: “black”, the word step 3 needs
  • Next: its two neighbors, “the” and “cat”
  • Lowest: “on” and the second “the”, opposite in direction

Step 2: Hard Selection (Argmax) Has No Gradient

Hard selection

  • Read only the highest-scoring encoder state: weight 1 on “black”, 0 elsewhere
  • Weight on “black” against its score: a step at 1.89, the next-highest score
  • Slope zero everywhere except the jump: no gradient to the scores

Soft selection

  • Weight on each encoder state: a smooth, increasing function of its score
  • Slope nonzero at every score: training can move the scores
  • Weights non-negative and summing to one, so the read stays an average

Softmax Concentrates Weight on the Highest Score

Exponentiate, then normalize

\[a_{t,s} = \frac{e^{e_{t,s}}}{\sum_{s'} e^{e_{t,s'}}}\]

  • Exponential: every weight positive, larger scores weighted disproportionately
  • Division by the sum: weights sum to one over the source
  • Smooth in every score

Step 3

word \(e_{3,s}\) \(e^{e_{3,s}}\) \(a_{3,s}\)
the 1.82 6.15 0.184
black 2.97 19.49 0.583
cat 1.89 6.62 0.198
sat \(-0.62\) 0.54 0.016
on \(-2.65\) 0.07 0.002
the \(-2.70\) 0.07 0.002
mat \(-0.70\) 0.50 0.015
  • Sum of exponentials: 33.43
  • 0.58 on “black”, 0.38 on its two neighbors, 0.04 on the rest

Softmax Depends Only on the Differences Between Scores

Shift

  • Adding \(m\) to every score multiplies every \(e^{e_{t,s}}\) by \(e^m\), and the factor cancels
  • Same weights: only differences between scores matter

Scale

  • Scores times 2: 0.82 on “black”
  • Scores times 0.5: 0.39 on “black”
  • Longer decoder states: larger score differences, sharper weights
  • The scale acts as a temperature

Step 3: Context Vector Is a Soft Selection of Encoder States

Weighted sum

\[\mathbf{c}_t = \sum_{s=1}^{S} a_{t,s}\,\mathbf{h}^{\text{enc}}_s\]

  • First coordinate: \(0.184(-0.17) + 0.583(0.66) + 0.198(1.00) + \ldots = 0.545\)
  • Second coordinate: \(0.184(0.98) + 0.583(0.75) + 0.198(-0.05) + \ldots = 0.599\)
  • \(\mathbf{c}_3 = [0.545,\ 0.599]\)

Soft selection

  • Inside the convex hull of the encoder states, nearest “black”
  • One-hot weights would return \(\mathbf{h}^{\text{enc}}_2\) exactly
  • Same width as an encoder state, for any \(S\)

Readout: Context Vector and Decoder State Together Predict the Word

Readout

\[\hat{\mathbf{y}}_t = \mathrm{softmax}\big(\mathbf{W}_{hy} \tanh(\mathbf{W}_c\,[\mathbf{h}^{\text{dec}}_t;\, \mathbf{c}_t])\big)\]

  • \(\mathbf{W}_c \in \mathbb{R}^{H \times 2H}\): combines the decoder state with what was read
  • \(\mathbf{W}_{hy}\): to vocabulary scores, as without attention

Decoder state

  • In the scores: compared with every encoder state, so it sets the weights
  • In the readout: concatenated with the context vector
  • At step 3: “le chat” written, “black” read, “noir” predicted with probability 0.66

Sizes in the measured reverse-copy model, \(H = 64\)

  • \(\mathbf{W}_c\): \(64 \times 128\) plus bias, 8,256 parameters, the only weights attention adds
  • Scores and weighted sum: no parameters

Each Row of the Attention Grid Is One Target Word’s Read

Rows

  • Row \(t\): the read at decoder step \(t\)
  • Each row its own softmax: rows sum to one, columns do not
  • Eight reads, eight context vectors \(\mathbf{c}_1, \ldots, \mathbf{c}_8\)

Columns

  • Column \(s\): how much each target word drew on source word \(s\)
  • “sat” column: large in two rows, “s’est” and “assis”
  • No column has to be used, no column is limited to one row

Attention Grid Is Soft Word Alignment

Word alignment

  • Which source words each target word translates
  • Hard links, one or more per target word
  • Statistical translation systems estimated it as a separate model

Attention grid

  • Same rows and columns, weights instead of links
  • Row maximum on the aligned word
  • Computed at every step from the states, inside the translation model
  • No alignment supplied in training: the grid is whatever the loss makes useful

Gradient Reaches Decoder and Encoder States Through the Scores

Backward through one read, given \(\mathbf{g} = \partial L / \partial \mathbf{c}_t\)

Weighted sum

\[\frac{\partial L}{\partial a_{t,s}} = \big(\mathbf{h}^{\text{enc}}_s\big)^\top \mathbf{g}\]

Softmax

\[\frac{\partial L}{\partial e_{t,s}} = a_{t,s}\Big(\frac{\partial L}{\partial a_{t,s}} - \sum_{s'} a_{t,s'} \frac{\partial L}{\partial a_{t,s'}}\Big)\]

Scores, into the decoder state

\[\frac{\partial L}{\partial \mathbf{h}^{\text{dec}}_t} \mathrel{+}= \sum_s \frac{\partial L}{\partial e_{t,s}}\,\mathbf{h}^{\text{enc}}_s\]

Scores and weighted sum, into each encoder state

\[\frac{\partial L}{\partial \mathbf{h}^{\text{enc}}_s} \mathrel{+}= \frac{\partial L}{\partial e_{t,s}}\,\mathbf{h}^{\text{dec}}_t + a_{t,s}\,\mathbf{g}\]

Terms

  • \(\partial L / \partial a_{t,s}\): how much more weight on encoder state \(s\) lowers the loss
  • Softmax step: each state’s benefit against the weighted average benefit. Weight moves toward states better than average
  • Decoder state: moved along a weighted sum of encoder states, toward those whose weight should rise
  • Encoder state: two paths, through its score and through the weighted sum

Through the decoder

  • \(\partial L / \partial \mathbf{h}^{\text{dec}}_t\) continues into the decoder’s recurrence and its earlier steps

Gradient First Aligns the Decoder State, Then Sharpens Its Weights

Setup

  • Encoder states fixed at the example’s values
  • Decoder state starts between “black” and “cat”: \([2.8,\ 1.2]\), weights 0.44 and 0.44
  • Loss: \(\tfrac12\|\mathbf{c} - \mathbf{h}^{\text{enc}}_{\text{black}}\|^2\), standing in for “noir” needing “black”

Measured

  • Steps 1 to 5: the decoder state turns toward “black”, weight 0.44 to 0.62
  • Steps 5 to 40: it lengthens along “black”, weight 0.62 to 0.72
  • Longer state: larger score differences, a sharper row

In a trained model the same gradient moves the networks that produce the states, which is how the alignment in the reverse-copy weights arose

Matrix Form: Every Read as Two Products

All decoder states known in advance: teacher forcing, and \(\mathbf{c}_t\) not fed back into the decoder

  • Decoder states as rows of \(\mathbf{H}^{\text{dec}} \in \mathbb{R}^{T \times H}\), encoder states as rows of \(\mathbf{H}^{\text{enc}} \in \mathbb{R}^{S \times H}\)

\[\mathbf{E} = \mathbf{H}^{\text{dec}} \big(\mathbf{H}^{\text{enc}}\big)^\top, \qquad \mathbf{A} = \mathrm{softmax}_{\text{rows}}(\mathbf{E}), \qquad \mathbf{C} = \mathbf{A}\,\mathbf{H}^{\text{enc}}\]

  • \(\mathbf{E}, \mathbf{A} \in \mathbb{R}^{T \times S}\): the score and weight grids. \(\mathbf{C} \in \mathbb{R}^{T \times H}\): row \(t\) is \(\mathbf{c}_t\)
  • Example: \(8 \times 2\) times \(2 \times 7\) gives the \(8 \times 7\) grid, times \(7 \times 2\) gives eight context vectors
  • Cost: \(2TSH\) multiply-adds, the \(T \times S\) grid kept for the backward pass

Generation Computes One Row of the Attention Grid per Step

At training time

  • All \(T\) rows at once, one backward pass through the grid

At generation time

  • Decoder state at step \(t\) depends on the word chosen at step \(t-1\)
  • That word depends on \(\mathbf{c}_{t-1}\), the read at step \(t-1\)
  • Row \(t\) of the grid: not computable before row \(t-1\)

Generation cost

  • One row per step: \(S\) scores and one weighted sum, \(2SH\) multiply-adds
  • \(T\) sequential steps per sentence, as without attention
  • Encoder states computed once and kept for every step

Kernel Regression

Weighted Read Looks Like Kernel Regression

Encoder-decoder read

  • Query: the decoder state \(\mathbf{h}^{\text{dec}}_t\)
  • Stored: the encoder states \(\mathbf{h}^{\text{enc}}_s\), compared and averaged
  • Weights: softmax of a score between query and each stored state

Kernel regression (Nadaraya 1964, Watson 1964)

  • Query: an input \(x_0\)
  • Stored: sample pairs \((x_i, y_i)\), inputs compared, outputs averaged
  • Weights: kernel of the distance from \(x_0\) to each \(x_i\), normalized
  • Studied there: weight sharpness, its bias-variance cost, the limits of a fixed similarity

The read is kernel regression, not only like it

Local Regression Averages the Outputs of Nearby Inputs

Stored samples

  • No fitted parameters: every query answered from the \(n\) stored samples
  • Cost per query \(O(n)\), or \(O(nd)\) for \(d\)-dimensional inputs. Memory: all \(n\) samples

Setup

  • \(n\) samples \((x_i, y_i)\), \(y_i = f(x_i) + \varepsilon_i\), noise of variance \(\sigma^2\)
  • Example: \(n = 200\), \(x_i\) uniform on \([0, 1]\), \(\sigma = 0.3\)
  • Query \(x_0\), not among the samples: estimate \(f(x_0)\)

Local averaging

  • \(f\) smooth: inputs close to \(x_0\) have outputs close to \(f(x_0)\)
  • Estimate: the average of the \(y_i\) whose \(x_i\) lie in a window around \(x_0\)
  • A weighted sum of stored outputs: \(1/m\) on the \(m\) samples inside the window, \(0\) elsewhere

Window

  • Its width sets which samples count as near, and so how many are averaged

Smooth Weights Replace the Window’s Equal Weights

Nadaraya-Watson estimator

\[\hat f(x_0) = \sum_{i=1}^{n} w_i(x_0)\, y_i, \qquad w_i(x_0) = \frac{K\!\left(\frac{x_0 - x_i}{b}\right)}{\sum_{j} K\!\left(\frac{x_0 - x_j}{b}\right)}\]

  • \(K\): a kernel, non-negative and peaked at zero. Gaussian: \(K(u) = e^{-u^2/2}\)
  • \(b\): the bandwidth. A sample at distance \(b\) from the query gets \(e^{-1/2} \approx 0.61\) of the weight of a sample at the query itself
  • Gaussian weights: a softmax over the samples of the negative squared distance, \(w_i = \mathrm{softmax}_i\big(-(x_0 - x_i)^2 / 2b^2\big)\)
  • Box window: the kernel \(K(u) = [\,|u| \le 1\,]\)

Properties of the weights

  • Non-negative and summing to one: the estimate is an average of the stored outputs
  • Set by the distance from the query to each stored input, not by the outputs
  • Recomputed for every query: each \(x_0\) gets its own average

Bandwidth Sets the Number of Samples Averaged

Effective number of samples

  • \(p(x)\): density of the inputs, \(p = 1\) in the example
  • Unequal weights count as \(m = 1 / \sum_i w_i^2\) equally weighted samples
  • Sums over samples as integrals: \(\sum_i K_i \approx n\,p\,b\sqrt{2\pi}\), \(\sum_i K_i^2 \approx n\,p\,b\sqrt{\pi}\)
  • Gaussian kernel: \(m \approx 2\sqrt{\pi}\; n\, p(x_0)\, b\)

Bandwidths 0.005, 0.03, 0.15, \(n = 200\)

  • \(b = 0.005\): about 4 samples, the estimate follows their noise
  • \(b = 0.03\): about 21, the estimate close to \(f\) on both halves
  • \(b = 0.15\): about 106, the average includes inputs where \(f\) differs from \(f(x_0)\): peaks flattened, right-half wiggles erased

Bandwidth Trades Variance Against Bias

Variance: averaging noisy outputs

\[\mathrm{Var}\big[\hat f(x_0)\big] = \sigma^2 \sum_i w_i^2 = \frac{\sigma^2}{m} \approx \frac{\sigma^2}{2\sqrt{\pi}\; n\, b\, p(x_0)}\]

  • Independent noise: the variances of the weighted terms add
  • Halving \(b\) halves \(m\) and doubles the variance

Bias: averaging a curved function

\[\mathbb{E}\big[\hat f(x_0)\big] - f(x_0) \approx \tfrac{1}{2}\, f''(x_0)\, b^2 \quad\text{(uniform } p\text{)}\]

  • Inside the window: \(f(x_0 + u) \approx f(x_0) + f'(x_0)\,u + \tfrac12 f''(x_0)\,u^2\)
  • Linear term: averages to zero over a symmetric window
  • Quadratic term: \(\tfrac12 f''(x_0)\) times the window’s second moment, \(b^2\) for the Gaussian
  • Zero where \(f\) is straight, largest where \(f\) curves fast

Best bandwidth

  • Squared bias \(\propto b^4\), variance \(\propto 1/(nb)\): the sum is smallest at \(b^\star \propto n^{-1/5}\)
  • 32 times the data halves \(b^\star\)
  • \(b^\star\) depends on \(f''\) and \(p\), which differ from place to place

Expanding the Square Gives a Dot-Product Score

Expanding the exponent

\[K\!\left(\tfrac{x_0 - x_i}{b}\right) = \exp\!\left(-\frac{x_0^2}{2b^2}\right)\exp\!\left(\frac{x_0\, x_i}{b^2}\right)\exp\!\left(-\frac{x_i^2}{2b^2}\right)\]

  • First factor: the same for every \(i\), cancels in the normalization

\[w_i(x_0) = \frac{\exp\!\big(e_i / b^2\big)}{\sum_j \exp\!\big(e_j / b^2\big)}, \qquad e_i = x_0\, x_i - \tfrac{1}{2} x_i^2\]

  • The weights: a softmax over the stored inputs of a score \(e_i\) divided by \(b^2\)
  • In vectors, \(e_i = \mathbf{x}_0^\top \mathbf{x}_i - \tfrac12\|\mathbf{x}_i\|^2\): a dot product between query and stored input, plus a term in the stored input alone

Equal-norm stored inputs

  • Every \(\|\mathbf{x}_i\|\) the same: the second term cancels too, and the score is the dot product \(\mathbf{x}_0^\top \mathbf{x}_i\)

Bandwidth as temperature

  • \(b^2\) divides every score before the softmax: the softmax temperature
  • \(b \to 0\): all weight on the highest score, the nearest sample alone, a hard lookup
  • \(b \to \infty\): equal weights, the mean of all outputs

Best Bandwidth Differs Between Smooth and Wiggly Regions

One bandwidth, two regions

  • Smooth half: error smallest at \(b = 0.04\)
  • Wiggly half: smallest at \(b = 0.02\) to \(0.03\), the two within 0.4%
  • Smooth half: a wide window, averaging away noise
  • Wiggly half: a narrow window, following the function

Single \(b\)

  • Too wide on the wiggly half or too narrow on the smooth half
  • \(b\) set by hand, the same at every input

Irrelevant Input Dimensions Raise Kernel Regression Error

Isotropic kernel

  • Distance \(\|\mathbf{x}_0 - \mathbf{x}_i\|\) over all \(d\) input coordinates, one bandwidth \(b\)
  • Every coordinate counts equally, whether or not \(f\) depends on it

Measured: example plus \(k\) irrelevant inputs

  • Extra coordinates uniform on \([0, 1]\), \(f\) unchanged, \(n = 200\), 100 repetitions
  • \(k = 0\): best error 0.0070, at \(b = 0.03\)
  • \(k = 1\): 0.034, five times larger, at \(b = 0.06\)
  • \(k = 8\): 0.26, 37 times larger, at \(b = 0.24\)

Mechanism

  • Nearest samples by full distance: spread out in \(x\) once the irrelevant coordinates dominate the distance
  • Wider \(b\): restores the number of samples averaged, adds bias in \(x\)

No fitted parameters: \(b\) is the kernel’s one parameter, the same in every direction

Attention Is a Dictionary Lookup with Soft Matching

Dictionary

  • Stored pairs: a key and its value
  • Lookup table[query]: the one key equal to the query returns its value
  • No equal key: nothing returned. Nothing to differentiate

Soft matching

  • Query scored against every key
  • Softmax of the scores: one weight per stored pair
  • Returned: the weighted mix of all values, dominated by the best-matching keys
  • Low temperature: all weight on the best key, the dictionary lookup again

Names

  • Query: what is looked up
  • Key: what a stored item is matched on
  • Value: what a stored item returns
  • Kernel regression: query \(x_0\), keys \(x_i\), values \(y_i\). Encoder-decoder read: query \(\mathbf{h}^{\text{dec}}_t\), keys and values both \(\mathbf{h}^{\text{enc}}_s\)

Learned Projections Replace the Fixed Kernel

Learned pieces

\[\mathbf{q} = \mathbf{W}_Q\,\mathbf{x}_0, \qquad \mathbf{k}_i = \mathbf{W}_K\,\mathbf{x}_i, \qquad \mathbf{v}_i = \mathbf{W}_V\,\mathbf{x}_i\]

\[\text{output} = \sum_i \mathrm{softmax}_i\!\left(\frac{\mathbf{q}^\top \mathbf{k}_i}{\tau}\right) \mathbf{v}_i\]

  • \(\mathbf{x} \in \mathbb{R}^d\), \(\mathbf{W}_Q, \mathbf{W}_K \in \mathbb{R}^{d_k \times d}\), \(\mathbf{W}_V \in \mathbb{R}^{d_v \times d}\): \(d(2d_k + d_v)\) parameters, trained by the task’s loss
  • Per query over \(n\) stored items, after projection: \(O(n\,d_k)\) for the scores, \(O(n\,d_v)\) for the weighted sum
  • Projections: which directions of the inputs the score uses
  • Score scale, through the projections and \(\tau\): the bandwidth
Kernel regression Attention Encoder-decoder read
query \(x_0\) \(\mathbf{q}\) \(\mathbf{h}^{\text{dec}}_t\)
stored inputs \(x_i\) keys \(\mathbf{k}_i\) \(\mathbf{h}^{\text{enc}}_s\)
stored outputs \(y_i\) values \(\mathbf{v}_i\) \(\mathbf{h}^{\text{enc}}_s\)
weights \(w_i(x_0)\) softmax of \(\mathbf{q}^\top \mathbf{k}_i / \tau\) \(a_{t,s}\)
\(b^2\) \(\tau\) \(1\)

Keys and values

  • Kernel regression: matches on \(x_i\), returns \(y_i\)
  • Same split in attention: \(\mathbf{k}_i\) what a stored item is matched on, \(\mathbf{v}_i\) what it contributes
  • Kernel regression as attention: stored item \(\mathbf{x}_i = [x_i;\, y_i]\), \(\mathbf{W}_K\) selects \(x_i\), \(\mathbf{W}_V\) selects \(y_i\), score equal up to the \(-\tfrac12 x_i^2\) term
  • Encoder-decoder read: \(\mathbf{W}_Q = \mathbf{W}_K = \mathbf{W}_V = \mathbf{I}\), \(\tau = 1\)

Same computation whatever supplies the queries and the stored items: a decoder reading an encoder, or a sequence reading its own positions

Score Functions and Scaling

Score Functions Are Learned Similarities

Score functions for query \(\mathbf{q} \in \mathbb{R}^{d_q}\), key \(\mathbf{k}_s \in \mathbb{R}^{d_k}\)

  • \(e_s\): \(e_{t,s}\) at one step. \(\mathbf{q} = \mathbf{h}^{\text{dec}}_t\), \(\mathbf{k}_s = \mathbf{h}^{\text{enc}}_s\)
  • Additive (Bahdanau et al. 2015): \(e_s = \mathbf{w}^\top \tanh(\mathbf{W}_q \mathbf{q} + \mathbf{W}_k \mathbf{k}_s)\), with \(\mathbf{W}_q \in \mathbb{R}^{d_a \times d_q}\), \(\mathbf{W}_k \in \mathbb{R}^{d_a \times d_k}\), \(\mathbf{w} \in \mathbb{R}^{d_a}\)
  • Bilinear (Luong et al. 2015, “general”): \(e_s = \mathbf{q}^\top \mathbf{W} \mathbf{k}_s\), \(\mathbf{W} \in \mathbb{R}^{d_q \times d_k}\)
  • Dot product: \(e_s = \mathbf{q}^\top \mathbf{k}_s\), no parameters, \(d_q = d_k\)

Relation to projections

  • Bilinear with \(\mathbf{W} = \mathbf{W}_Q^\top \mathbf{W}_K\): the dot product of projected query and key, rank at most the projection width
  • Additive: a one-hidden-layer network on the pair, the only nonlinear score

Same states, different grid

  • Dot product: each row peaks on the source word its query points at
  • Bilinear, \(\mathbf{W}\) a rotation by one word: each row peaks on the following source word, the last row wrapping to the first
  • Learned \(\mathbf{W}\): training sets which key each query matches, not only the nearest
  • Additive: no grid shown, its ranking is a learned nonlinear function of the pair

Additive Scores Need \(d_a\) Times the Memory of Dot-Product Scores

Cost of all \(T \times S\) scores, decoder width \(d_q\), encoder width \(d_k\)

Parameters Per score, after precomputing projections Batched form
Additive \(d_a(d_q + d_k + 1)\) \(O(d_a)\), plus a \(\tanh\) Sum of two projections broadcast to \(B \times T \times S \times d_a\)
Bilinear \(d_q d_k\) \(O(d_q)\) One matrix product, \(B \times T \times S\)
Dot product 0 \(O(d_k)\) One matrix product, \(B \times T \times S\)

Widths with a bidirectional encoder, \(d_q = 512\), \(d_k = 1024\), \(d_a = 256\)

  • Additive: 393,472 parameters
  • Bilinear: 524,288 parameters
  • Dot product: not defined until \(d_q = d_k\)

Memory of the additive intermediate

  • \(B = 64\), \(T = S = 50\), \(d_a = 256\), float32: \(64 \cdot 50 \cdot 50 \cdot 256 \cdot 4\) bytes \(= 164\) MB
  • Kept for the backward pass, for one attention layer
  • Grows as \(T \cdot S\): 655 MB at \(T = S = 100\)

Bilinear and dot product

  • Scores in one matrix product, \(\mathbf{Q}\mathbf{K}^\top\) or \(\mathbf{Q}\mathbf{W}\mathbf{K}^\top\), no \(d_a\) axis
  • \(B \times T \times S\) scores: 0.6 MB at the same sizes

Matrix-product scores run on the hardware’s fastest operation and never form the \(d_a\) axis

Best Score Function Depends on the Attention Variant

Luong et al. 2015, Table 4: English to German, newstest2014, BLEU after unknown-word replacement

Attention Location Dot General (bilinear)
Global: all source positions 19.3 20.5 19.1
Local, monotonic window perplexity > 7.0, no BLEU 20.4
Local, predicted window 19.6 20.9
  • Location: weights from the decoder state alone, \(\mathbf{a}_t = \mathrm{softmax}(\mathbf{W}_a \mathbf{h}^{\text{dec}}_t)\), no comparison with the source
  • Additive (“concat”): perplexity 6.7 to 7.1 against 5.9 to 6.6 for the others, no BLEU reported. The authors attribute it to a simplified implementation
  • Same data and training for every row: 4-layer LSTMs, 1000 units, 4.5M sentence pairs

Reading the table

  • Dot best for global attention, bilinear best for local
  • Spread between content-based scores: 1.3 to 1.4 BLEU
  • Location alone: lowest of the global rows. Comparing with the source matters more than which comparison

Alignment quality (Table 6, 508 hand-aligned sentences)

Model Alignment error rate
Global, location 0.39
Local, monotonic, bilinear 0.34
Ensemble of 8 0.34
Berkeley Aligner 0.32
  • The ensemble translates best (23.0 BLEU) without aligning better: alignment and translation quality are not the same measure

Dot-Product Scores Grow as \(\sqrt{d_k}\)

Variance of a dot product

  • Query and key components independent, mean 0, variance 1
  • Each product \(q_i k_i\): mean 0, variance 1

\[\mathrm{Var}\big[\mathbf{q}^\top \mathbf{k}\big] = \sum_{i=1}^{d_k} \mathrm{Var}[q_i k_i] = d_k\]

  • Standard deviation \(\sqrt{d_k}\): 8 at \(d_k = 64\), 32 at \(d_k = 1024\)

Effect on the softmax, \(S = 50\) random keys

  • Score spread grows, differences between scores grow with it
  • Measured mean of the largest weight: 0.32 at \(d_k = 4\), 0.80 at 64, 0.95 at 1024
  • Divided by \(\sqrt{d_k}\): 0.12 to 0.13 at every \(d_k\)

Sharp Softmax Weights Shrink the Score Gradient

Softmax Jacobian, \(a_j = e^{e_j} / Z\), \(Z = \sum_k e^{e_k}\)

  • \(j = k\): \(\dfrac{\partial a_j}{\partial e_j} = \dfrac{e^{e_j} Z - e^{e_j} e^{e_j}}{Z^2} = a_j(1 - a_j)\)
  • \(j \ne k\): \(\dfrac{\partial a_j}{\partial e_k} = -\dfrac{e^{e_j} e^{e_k}}{Z^2} = -a_j a_k\)

\[\frac{\partial a_j}{\partial e_k} = a_j(\delta_{jk} - a_k), \qquad \nabla_{\mathbf{e}} L = \mathbf{a} \odot \big(\nabla_{\mathbf{a}} L - (\mathbf{a}^\top \nabla_{\mathbf{a}} L)\,\mathbf{1}\big)\]

One-hot and uniform

  • One-hot, \(a_j = 1\): every entry \(a_j(\delta_{jk} - a_k)\) is zero, the gradient to every score is zero
  • Uniform, \(a_j = 1/S\): entries of order \(1/S\), small for long inputs
  • Largest Jacobian between the two

Measured, \(S = 50\)

  • Raw scores: Jacobian norm 0.30 at \(d_k = 16\), 0.064 at \(d_k = 1024\)
  • Scaled scores: 0.20 at every \(d_k\)

Scaling by \(\sqrt{d_k}\) Sets the Softmax Temperature

Scaled dot product (Vaswani et al. 2017)

\[e_s = \frac{\mathbf{q}^\top \mathbf{k}_s}{\sqrt{d_k}}, \qquad \mathrm{Var}[e_s] = \frac{d_k}{d_k} = 1\]

  • Temperature \(\tau = \sqrt{d_k}\) in the kernel form, fixed by the width instead of tuned
  • Same spread of weights at every \(d_k\), so the same Jacobian norm
  • \(d_k = 64\) per head in the base transformer: raw score standard deviation 8, scaled 1

Assumption

  • Unit-variance, independent components: true near initialization, not after training
  • After training, the scale of \(\mathbf{W}_Q\) and \(\mathbf{W}_K\) sets the sharpness: the bandwidth is learned

Attention in Translation

Bahdanau Attention Reads Before the Decoder Updates

Bahdanau et al. 2015

  • Encoder: forward and backward recurrences, \(\mathbf{h}_s = [\overrightarrow{\mathbf{h}}_s;\ \overleftarrow{\mathbf{h}}_s]\)
  • Score: additive, on the previous decoder state \(\mathbf{s}_{t-1}\) (the paper’s symbol for \(\mathbf{h}^{\text{dec}}_{t-1}\))
  • Read before update: \(\mathbf{s}_t = f(\mathbf{s}_{t-1}, y_{t-1}, \mathbf{c}_t)\)
  • 1000 units per direction, decoder 1000, 30,000-word vocabularies, English to French

Both directions

  • Pronoun example: the word deciding the referent (“tired”, “wide”) comes after “it”
  • Forward state at “it”: that word not yet read
  • Backward half of \(\mathbf{h}_s\): everything to the right of \(s\)

Luong et al. 2015: read after the update

  • Query: the current state \(\mathbf{h}^{\text{dec}}_t\)
  • Score: dot, bilinear (“general”), or additive
  • Context into the readout, \(\tanh(\mathbf{W}_c[\mathbf{c}_t; \mathbf{h}^{\text{dec}}_t])\), not the recurrence
  • The form of the measured reverse-copy and synthetic-pair models

Read Gradient Has One Factor at Any Distance

Paths from a target word back to the source

\[\frac{\partial L_t}{\partial \mathbf{h}^{\text{enc}}_s} = \underbrace{a_{t,s}\,\frac{\partial L_t}{\partial \mathbf{c}_t}}_{\text{through the read}} + \underbrace{\frac{\partial L_t}{\partial \mathbf{h}^{\text{enc}}_S}\,\prod_{s'=s+1}^{S} \frac{\partial \mathbf{h}^{\text{enc}}_{s'}}{\partial \mathbf{h}^{\text{enc}}_{s'-1}}}_{\text{through the recurrence}} + \ldots\]

  • Through the read: one factor, the weight \(a_{t,s}\), at any distance between \(s\) and \(t\)
  • Through the recurrence: a product of \(S - s\) encoder Jacobians, then the decoder’s steps, as with the fixed context
  • Where the weight is large, the read path supplies the gradient regardless of source length

Consequence for training

  • Recurrence path: shrinks geometrically with distance, as measured for recurrent units
  • Read path: no product over distance
  • Words far from the end of the source get gradient comparable to near ones once their weights are large

The weights themselves

  • \(a_{t,s}\) depends on the states through the scores, so the same gradient also moves where each target word reads
  • Backpropagation through softmax and dot products: no new training procedure

Attention Raises BLEU Most on Long Sentences

English to French, WMT’14 test set (Bahdanau et al. 2015, Table 1)

Model All sentences No unknown words
Encoder-decoder, trained to 30 words 13.93 24.19
Attention, trained to 30 words 21.50 31.44
Encoder-decoder, trained to 50 words 17.82 26.71
Attention, trained to 50 words 26.75 34.16
  • Scores: BLEU, n-gram overlap with a reference translation
  • Same data, same sizes, attention the only difference

By sentence length (the paper’s Figure 2)

  • Encoder-decoder: “performance dramatically drops as the length of the sentences increases”
  • Attention trained to 50 words: “no performance deterioration even with sentences of length 50 or more”
  • Same shape as the reverse-copy sweep: fixed context 1.00 at 8 symbols, 0.80 at 32, the read 0.999 at every length

Limits

  • Training on sentences of at most 30 or 50 words
  • Unknown words replaced by one token: scores computed with and without them

Learned Translation Alignment Reverses Adjective-Noun Order

Paper’s alignment

  • Learned weights for this sentence: largest along the diagonal, except the boxed block
  • “zone économique européenne” reads “Area”, “Economic”, “European” in reverse order
  • “a été” reads “was” twice: one source word, two target words

Learned from sentence pairs

  • Reordering, many-to-one and one-to-many correspondences
  • From sentence pairs alone, with no alignment supplied

Synthetic Pair Tests Reordering, Agreement, and a Distant Referent

Source and target

  • Source: “the A N₁ [with the A N]⁰⁻⁴ did not cross the [A] N₂ because it was P”
  • Target: French word order and agreement, generated by rule
  • Example: “the black dog with the white cow with the grey bridge did not cross the street because it was tired”
  • Target: “le chien noir avec la vache blanche avec le pont gris n’ a pas traversé la rue parce qu’ il était fatigué”

Properties

  • Reordering: adjective after the noun, “black dog” to “chien noir”
  • Agreement: adjective and article take the noun’s gender, “blanc” or “blanche”
  • Distant referent: “il” or “elle” takes the gender of N₁ when P is “tired” or “hungry”, of N₂ when P is “wide” or “long”

Pronoun dependence

  • Referent decided by the last source word, after the pronoun
  • Referent’s noun up to 24 words before the pronoun

Models, trained identically

  • Bidirectional GRU encoder (32 per direction), dot-product attention
  • Same encoder, fixed context only
  • Forward-only GRU encoder (64), dot-product attention
  • Decoder GRU of width 64, 4,000 steps of 64 pairs, cross-entropy on the target words only

Sources: 12 to 29 words. Vocabulary: 24 source, 35 target words

Fixed Context Fails on Agreement and Pronouns

Accuracy on 2,000 test pairs, correct previous word given

Model All words Adjectives Pronouns
Bidirectional, attention 1.000 1.000 1.000
Forward-only, attention 1.000 1.000 1.000
Bidirectional, fixed context 0.841 0.682 0.766
  • Fixed context: adjectives worst, each must recover its noun’s gender from one vector
  • Either encoder with attention: every word right

  • No trend with distance for the fixed context: the limit is what one vector contains, not how far back the noun is

Trained Weights Align Some Words and Not Others

Rows on the translated word

  • Bidirectional: “noir”-“black” 0.99, “rue”-“street” 0.94, “fatigué”-“tired” 0.87
  • Forward-only: “vache”-“cow” 1.00, “pont”-“bridge” 1.00

Rows elsewhere

  • Bidirectional: “pont” reads “not” 0.98
  • Forward-only: “chien” and “noir” read “with”, 0.98 and 1.00

Mechanism

  • An encoder state contains more than its own word: the whole sentence (bidirectional) or everything up to that word (forward-only)
  • A read from any state that contains the needed fact gives the right word
  • Accuracy 1.000 for both: the loss does not prefer the aligned state
  • Clean alignment in the reverse-copy model and in Bahdanau et al.: one solution the loss allows, not the one it forces

Attention Weights Are Not Explanations

Measured on the pronoun

  • Bidirectional: “il” reads “did”, “elle” reads “because”
  • Forward-only: “il” reads “cross”, “elle” reads “wide”
  • No row peaks on “dog” or “street”, whose gender the pronoun takes. The deciding information is in the states read, not in which words they belong to

Published

  • Jain & Wallace 2019: weights often uncorrelated with gradient-based importance. Very different weight rows can give the same prediction
  • Wiegreffe & Pinter 2019: depends on what “explanation” means. Tests: uniform-weight baseline, variance across seeds, frozen weights

Content of the weights

  • Where the read is taken from
  • Not which information in that state was used, nor whether the output depended on it

Reading attention heatmaps in papers

  • A clean alignment is consistent with, not proof of, word-for-word dependence
  • Encoder design (one direction or two) changes the grid without changing accuracy

Each Row’s Softmax Has No Record of Earlier Reads

Repetition

  • Grid: two consecutive rows peak on the same source word
  • Output: “le chat noir noir s’est assis …”
  • The second row’s softmax has no record that “black” was just read

Dropped word

  • Grid: one source column receives almost no weight in any row
  • Output: “le chat s’est assis sur le tapis”, “black” never translated
  • Each row sums to one, nothing requires each column to be used

Drift

  • Grid: the row maximum leaves its path and returns to an earlier position
  • Output: “… s’est chat noir s’est chat …”, a span translated again, often without end
  • A wrong word changes the next decoder state, which changes the next read: errors compound

Common cause

  • Each row’s softmax is computed from \(\mathbf{h}^{\text{dec}}_t\) and the encoder states alone
  • Nothing in the score records how much each source word has already been read

Coverage Sums the Weight Each Source Word Has Received

Coverage vector (Tu et al. 2016)

\[\mathbf{u}_t = \sum_{\tau < t} \mathbf{a}_\tau \in \mathbb{R}^S, \qquad u_{t,s}: \text{total weight on word } s \text{ so far}\]

  • Fed into the score: \(e_{t,s} = \mathbf{w}^\top \tanh(\mathbf{W}\mathbf{s}_{t-1} + \mathbf{U}\mathbf{h}_s + \mathbf{v}\,u_{t,s})\)
  • A word already read can score lower, a word never read higher

Coverage loss (See et al. 2017)

\[L_{\text{cov}} = \sum_t \sum_s \min(a_{t,s},\ u_{t,s})\]

  • Penalizes weight on words already covered

Effect

  • The read at step \(t\) depends on all previous reads, not only on \(\mathbf{s}_{t-1}\)
  • Repetition and dropped words become visible to the score
  • Cost: one running vector of \(S\) numbers per sentence

Unchanged

  • Rows still sum to one
  • Nothing forces each word to be read exactly once: one-to-many and many-to-one remain possible

Reads Can Be Limited to One Position or a Window

Soft attention: the weighted read over all positions

  • Weighted sum over all \(S\) positions, differentiable, cost \(O(S)\) per read

Hard attention (Xu et al. 2015)

  • Sample one position \(s \sim \mathbf{a}_t\), read \(\mathbf{h}^{\text{enc}}_s\) alone
  • Sampling has no gradient: trained with a score-function estimator, higher variance
  • Cost of the read: one state instead of \(S\)

Local attention (Luong et al. 2015)

  • Predict a center \(p_t = S \cdot \sigma\big(\mathbf{w}_p^\top \tanh(\mathbf{W}_p \mathbf{h}^{\text{dec}}_t)\big)\)
  • Read only a window \([p_t - D,\ p_t + D]\), weights multiplied by a Gaussian centered at \(p_t\)
  • Differentiable, cost \(2D + 1\) positions instead of \(S\)

Implementing Attention

Batched Attention Runs the Three Steps on 3-D Tensors

First version

import math
import torch

def attention_v1(Q, K, V):
    # Q: (B, T, d)  K, V: (B, S, d)
    scores = Q @ K.transpose(-2, -1) / math.sqrt(Q.shape[-1])   # (B, T, S)
    weights = scores.softmax(dim=-1)                            # rows sum to 1
    return weights @ V                                          # (B, T, d)

Same steps, one more axis

  • @ on 3-D tensors: \(B\) independent matrix products in one call
  • Softmax along the last axis: each of the \(B \times T\) rows normalized alone
  • Encoder-decoder read: \(\mathbf{Q}\) the decoder states, \(\mathbf{K} = \mathbf{V}\) the encoder states, \(d = H\)

Cost per batch

  • \(2\,B\,T\,S\,d\) multiply-adds
  • \(B \times T \times S\) weights kept for the backward pass

Unmasked Padding Gets Weight in Proportion to Its Length

Unequal lengths

  • One tensor per batch: every source padded to the longest
  • attention_v1 scores padded positions like words

Measured, 64 synthetic sources padded to 29 words

  • Padding: 27% of key positions, 27% of the weight
  • Shortest source, 12 words: 59% padding, 58% of its weight on padding
  • Weight on padding: read from states of no word, the same sentence translated differently depending on its batch

One Masked Fill Removes Padding from Every Read

Second version: one added line

def attention(Q, K, V, key_mask=None):
    # Q: (B, T, d)  K, V: (B, S, d)  key_mask: (B, S), True at real positions
    scores = Q @ K.transpose(-2, -1) / math.sqrt(Q.shape[-1])   # (B, T, S)
    if key_mask is not None:
        scores = scores.masked_fill(~key_mask[:, None, :], float('-inf'))   # new
    weights = scores.softmax(dim=-1)
    return weights @ V, weights

Broadcasting

  • key_mask: \(B \times S\), one flag per source position
  • key_mask[:, None, :]: \(B \times 1 \times S\), copied across the \(T\) query rows
  • One mask per sentence applies to every target word

Measured

  • 64-source batch: weight on padding 27% without the mask, exactly 0 with it
  • Against torch.nn.functional.scaled_dot_product_attention: maximum difference 0.0
  • Rows sum to one within \(1.2 \times 10^{-7}\)

Fill value and empty rows

  • float16 maximum magnitude 65,504: a fill of \(-10^4\) fits, \(-10^9\) does not
  • A row with every key masked: \(0/0\), NaN
  • Causal mask: the triangle in the figure, through the same masked_fill

Subtracting the Row Maximum Prevents Softmax Overflow

Exponential of a large score

  • \(e^{x}\) exceeds the largest float32 at \(x = 88.7\), the largest float16 at \(x = 11.1\)
  • Overflow: \(\infty / \infty\), NaN for the whole row and everything after it
  • Half precision with unscaled dot products of width 64: standard deviation 8, so overflow on ordinary inputs

Third version: the stable softmax inside the function

m = scores.amax(dim=-1, keepdim=True)         # row maximum, (B, T, 1)
z = (scores - m).exp()                        # largest entry exp(0) = 1
weights = z / z.sum(dim=-1, keepdim=True)
  • Same weights: the shift changes nothing (shift invariance, step 2)
  • torch.softmax subtracts the maximum internally. The two match to rounding
  • Masked entries: \(-\infty - m = -\infty\), still weight 0

  • Crosses: where the naive version first returns NaN

Stored Weights Outgrow the States Beyond \(n = 3d\)

Bytes kept for the backward pass, float32, one attention layer

  • Weights: \(4\,B\,T\,S\)
  • Queries, keys, values: \(4\,B\,(T + 2S)\,d\)

With \(B = 32\), \(d = 512\), \(T = S = n\)

\(n\) Weights Queries, keys, values
100 1.3 MB 19.7 MB
512 33.6 MB 100.7 MB
1,000 128 MB 197 MB
4,000 2.05 GB 786 MB
  • Weights grow as \(n^2\), states as \(n\)
  • Weights pass one of the three state tensors at \(n = d\), all three at \(n = 3d\)
  • With \(h\) heads: \(h\) grids, all three passed at \(n = 3d/h\)

Beyond \(n = 3d\) the weight grid sets the memory limit on sequence length

Batched Call Runs 3.5 to 10.6 Times Faster Than a Loop

Loop and batched product, teacher forcing

  • Loop: for each target word, one \(1 \times S\) score row, softmax, weighted sum
  • Batched: one \(T \times S\) score grid, one row softmax, one product

Measured, \(B = 32\), \(d = 64\), \(S = T\), median of 20 runs

\(T\) Loop Batched Ratio
25 1.68 ms 0.16 ms 10.2
50 3.62 ms 0.34 ms 10.6
100 9.56 ms 2.70 ms 3.5
200 22.8 ms 6.01 ms 3.8
  • Same arithmetic: the loop incurs a fixed overhead per call, \(T\) times
  • At generation the loop is unavoidable: row \(t\) depends on the word chosen at \(t - 1\)

  • Hardware: arm64 CPU, 4 threads, PyTorch 2.8.0, float32

LSTM Steps Take 88 to 94 Percent of the Forward Time

Measured, \(H = 64\), \(B = 64\), same hardware

\(S = T\) LSTMs Attention Attention share
24 13.1 ms 0.80 ms 5.8%
48 28.8 ms 1.87 ms 6.1%
96 48.8 ms 6.46 ms 11.7%

Sequential steps

  • Encoder and decoder: \(S + T\) steps, each waiting for the previous one
  • Reads: one batched product per batch, all target words at once
  • Attention share grows with length, its cost quadratic, the LSTMs’ linear

With attention in place, the recurrence is the part that cannot run in parallel: 192 sequential steps per pair at \(S = T = 96\)

Attention over Sets and Images

Reordering the Stored Items Leaves Every Read Unchanged

Permute keys and values together, permutation \(\pi\) of the \(S\) positions

\[\sum_{s} \mathrm{softmax}_s\big(\mathbf{q}^\top \mathbf{k}_{\pi(s)}\big)\, \mathbf{v}_{\pi(s)} = \sum_{s} \mathrm{softmax}_s\big(\mathbf{q}^\top \mathbf{k}_{s}\big)\, \mathbf{v}_{s}\]

  • Each score depends on its own key only: the weights are permuted with the keys
  • The sum does not depend on the order of its terms
  • Every read: unchanged by reordering the stored items

Permute the queries

  • Row \(t\) of the output depends only on query \(t\)
  • Reordered queries: the same outputs, reordered the same way

Consequence

  • The read treats its input as a set: positions enter only if the stored vectors contain them
  • In the encoder-decoder, the recurrence put order into the encoder states
  • “The vector retrieved from our memory would not change if we randomly shuffled the memory” (Vinyals, Bengio, Kudlur 2016)

Image Regions Become the Stored Items

Synthetic scenes for the measurement

  • 4 × 4 cells, three objects: shape (square, circle, triangle) and colour (red, green, blue)
  • Each cell’s features: its own shape, colour, row and column, nothing from other cells

Show, Attend and Tell (Xu et al. 2015)

  • VGG convolutional features: a 14 × 14 × 512 map, flattened to 196 stored items of 512 numbers
  • LSTM decoder writes the caption, one read over the 196 items per word
  • Grid: caption words against image regions. Each row reshaped to 14 × 14: a map over the image

Total weight per region

  • Penalty \(\lambda \sum_{i=1}^{196} \big(1 - \sum_t \alpha_{t,i}\big)^2\): every region’s weight over the whole caption near 1
  • The image counterpart of coverage: no region ignored, none read for every word

Cost

  • 196 scores and one weighted sum of 512-wide vectors per word

Weights Land on the Named Object When Regions Do Not Mix

Measured, trained captioner, 4,000 steps

  • Per-word accuracy: 0.989
  • Mean weight on the cell of the object being named: 0.85, over 200 scenes
  • “blue” and “circle”: 1.00 on their cell. “green” and “square”: 0.92 and 0.93
  • Second “green”: 0.39 on the first green object, before “triangle” puts 0.77 on its own cell

Contrast with the translation models

  • There: encoder states mixed the sentence, and weights landed on any state containing the needed fact
  • Here: each cell’s features describe that cell alone. Only the object’s own cell contains its shape and colour
  • No mixing: the read has one place to look, and the weights align with the object

Colour words first

  • “green” names two objects. Until the shape is written, both match

Identical Objects Leave the Read Without a Unique Match

Two red squares

  • First “red square”: its own cell, 0.78 and 0.80
  • Second “red”: 0.44 on the blue triangle
  • Second “square”: 0.53 on the first red square
  • Caption still correct

Mechanism

  • Score: content match between the decoder state and each cell
  • Two cells with the same shape and colour differ only in their row and column features
  • The decoder state after “red square ,” does not encode which of the two was already named
  • Correct output, wrong-looking map: the weights again show where the read was taken, not what decided the word

Pointer Output Is the Attention Distribution

Output a position, not a word

  • Tasks whose answer is a position in the input: sorting, selecting points, copying a word
  • Pointer network (Vinyals, Fortunato, Jaitly 2015): the softmax over input positions is the prediction

\[p(y_t = s \mid \ldots) = \mathrm{softmax}_s\big(\mathbf{w}^\top \tanh(\mathbf{W}_1 \mathbf{h}^{\text{enc}}_s + \mathbf{W}_2 \mathbf{h}^{\text{dec}}_t)\big)\]

  • No vocabulary: the output size is the input length, whatever it is
  • Tasks in the paper: convex hull, Delaunay triangulation, travelling salesman. Sorting: Vinyals, Bengio, Kudlur 2016

Measured sorter

  • Input: a set of numbers in \([0, 1]\). Output: their positions in increasing order of value
  • Bidirectional GRU encoder, GRU decoder, dot-product scores over input positions, trained on sets of 8

  • Each row: weight on the next smallest remaining number
  • Example sorted exactly, largest weights 0.65 to 1.00

Pointer-Generator Mixes Copying with Generating

Vocabulary and copy distributions (See, Liu, Manning 2017)

  • Vocabulary distribution \(P_{\text{vocab}}(w)\): the decoder’s readout, as in translation
  • Copy distribution: the attention weights, summed over the source positions holding word \(w\)

\[P(w) = p_{\text{gen}}\, P_{\text{vocab}}(w) + (1 - p_{\text{gen}}) \sum_{i:\, w_i = w} a_{t,i}\]

\[p_{\text{gen}} = \sigma\big(\mathbf{w}_{c}^\top \mathbf{c}_t + \mathbf{w}_s^\top \mathbf{s}_t + \mathbf{w}_x^\top \mathbf{x}_t + b\big)\]

  • \(p_{\text{gen}}\): from the context vector, the decoder state, and the decoder input

Words outside the vocabulary

  • Names, numbers, rare terms in the source: \(P_{\text{vocab}} = 0\), copy probability \(> 0\)
  • Output vocabulary extended per input by the source words
  • Summarization, where source names and figures reappear in the summary

Same weights, two uses

  • Inside the read: they form the context vector
  • As output: they are the copy distribution
  • With coverage, as in the translation failures: copying plus a record of what has been read

Sorting Accuracy Collapses Beyond the Training Length

Measured, 1,000 sets per size, trained on sets of 8

Set size Positions correct Sorted exactly
4 0.957 0.916
8 0.926 0.731
12 0.235 0.000
16 0.126 0.000

Where the length enters

  • Scores and softmax: defined for any number of positions
  • Encoder and decoder recurrences: trained only on 8 steps, their states after step 8 never seen
  • The read handles any set size. The recurrences that produce the queries and keys do not

Recall Without Recurrence

Recurrent State Loses Key-Value Pairs as the Sequence Grows

Recall task

  • \(n\) pairs (key, value), then a query key. Answer: the value paired with it
  • Keys: distinct symbols from 40. Values: digits 0 to 9. Chance: 0.10
  • GRU of width 64, answer from its last state, trained on 2 to 32 pairs

Measured, 2,000 sequences per \(n\)

  • Accuracy 0.38 at 4 pairs, 0.31 at 8, 0.23 at 16, 0.18 at 32
  • Every pair must remain in one state until the query arrives

Read over the Recurrent States Recalls Every Value

Recurrent model plus a read

  • GRU states kept, one per token: the encoder states of the encoder-decoder read
  • Query: the query key, projected. Keys and values: the GRU states
  • Weight 0.93 on the state at the matching value: the state that has just read it

Measured

  • Accuracy 1.000 at 4, 8, 16 and 32 pairs

Cost

  • \(2n\) sequential GRU steps before the read can start
  • At \(n = 32\): 64 steps, each waiting for the one before
  • The read itself: \(2n\) scores in one product

What each part does

  • Read: finds the pair, at any distance
  • Recurrence: turns tokens into states, one step at a time

Read over the Pairs Needs No Recurrence for Recall

Read alone

  • Query \(\mathbf{q} = \mathbf{W}_Q\,\mathbf{e}(q)\), keys \(\mathbf{k}_i = \mathbf{W}_K\,\mathbf{e}(k_i)\), values \(\mathbf{v}_i = \mathbf{W}_V\,\mathbf{e}(v_i)\)
  • Answer from \(\sum_i \mathrm{softmax}_i(\mathbf{q}^\top \mathbf{k}_i / \sqrt{32})\,\mathbf{v}_i\)
  • The input format pairs each key with its value

Measured

  • Accuracy 1.000 at every \(n\), the same as recurrent + read
  • No sequential steps: \(n\) scores and one weighted sum

Reordering the Pairs Leaves the Read Unchanged

Same pairs, new order

  • Weight 0.98 moves with k37:3, answer unchanged
  • Each score compares the query with one key, and position does not enter
  • For recall, order is irrelevant: the read is exact at any length and in any order

Recurrent States Tell the Read Which Occurrence Came Later

Latest-value task, 8 pairs, each key twice

  • Answer: the value of the later occurrence of the query key. Coin flip between the two: 0.50
Model Accuracy
Read alone 0.543
Recurrent + read 0.9995
Recurrent alone 0.353

Read alone

  • Both occurrences have the same key vector: equal scores, weight 0.50 each
  • Nothing in a stored pair says where it was in the sequence

Recurrent + read

  • Each GRU state has read everything before it: the later occurrence’s state differs from the earlier one’s
  • Weight 0.68 on the later occurrence, 0.32 on the earlier

The recurrence supplied order and the read supplied lookup. A read without recurrence needs position inside the stored vectors