
EE 641 - Unit 5
Fall 2026
Fixed-Length Context Bottleneck
Attention Is Learned Alignment
Attention over Sets and Images
[Alignment] D. Bahdanau, K. Cho, and Y. Bengio, “Neural machine translation by jointly learning to align and translate,” in International Conference on Learning Representations, 2015.
[Scores] M.-T. Luong, H. Pham, and C. D. Manning, “Effective approaches to attention-based neural machine translation,” in Proceedings of the 2015 Conference on Empirical Methods in Natural Language Processing, 2015, pp. 1412–1421.
[Kernels] A. Zhang, Z. C. Lipton, M. Li, and A. J. Smola, “Attention mechanisms and transformers,” ch. 11 in Dive into Deep Learning. Cambridge University Press, 2023.
[Explanation] S. Jain and B. C. Wallace, “Attention is not explanation,” in Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers), 2019, pp. 3543–3556.
[Images] K. Xu, J. Ba, R. Kiros, K. Cho, A. Courville, R. Salakhutdinov, R. Zemel, and Y. Bengio, “Show, attend and tell: Neural image caption generation with visual attention,” in Proceedings of the 32nd International Conference on Machine Learning, PMLR vol. 37, 2015, pp. 2048–2057.
[Pointers] O. Vinyals, M. Fortunato, and N. Jaitly, “Pointer networks,” in Advances in Neural Information Processing Systems, vol. 28, 2015.
[Copying] A. See, P. J. Liu, and C. D. Manning, “Get to the point: Summarization with pointer-generator networks,” in Proceedings of the 55th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), 2017, pp. 1073–1083.

Encoder-decoder
Running pair
Fixed length

Reverse-copy task
Measured
All \(S\) source words pass through the same 128 numbers
Trainability
Recency
Width


Per target word
Encoder states
Each row of the grid: a different subset of source positions

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'})}\]
Per target word

Accuracy, \(H = 64\)
Read weights, averaged over 200 test sources
Read weights learn the alignment from the data alone
Per output step
Per sentence pair
Memory

Crossover

One changed word
For the decoder writing the pronoun
Fixed context vector

Measured
Reading at the step that needs it


Available at decoder step \(t\)
Running pair

Needed position by step
Consequence

Two-dimensional states, set by hand
Steps 1 to 3

Step 1: score
Step 2: softmax
Step 3: weighted sum
Readout
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}\]
Cost
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”
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

Hard selection
Soft selection

Exponentiate, then normalize
\[a_{t,s} = \frac{e^{e_{t,s}}}{\sum_{s'} e^{e_{t,s'}}}\]
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 |
Shift
Scale

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


Readout
\[\hat{\mathbf{y}}_t = \mathrm{softmax}\big(\mathbf{W}_{hy} \tanh(\mathbf{W}_c\,[\mathbf{h}^{\text{dec}}_t;\, \mathbf{c}_t])\big)\]
Decoder state
Sizes in the measured reverse-copy model, \(H = 64\)

Rows
Columns

Word alignment
Attention grid
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
Through the decoder

Setup
Measured
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
All decoder states known in advance: teacher forcing, and \(\mathbf{c}_t\) not fed back into the decoder
\[\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}}\]

At training time
At generation time
Generation cost


Encoder-decoder read
Kernel regression (Nadaraya 1964, Watson 1964)
The read is kernel regression, not only like it

Stored samples
Setup
Local averaging
Window
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)}\]
Properties of the weights


Effective number of samples
Bandwidths 0.005, 0.03, 0.15, \(n = 200\)
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)}\]
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{)}\]

Best bandwidth
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)\]
\[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\]
Equal-norm stored inputs
Bandwidth as temperature


One bandwidth, two regions
Single \(b\)
Isotropic kernel
Measured: example plus \(k\) irrelevant inputs
Mechanism

No fitted parameters: \(b\) is the kernel’s one parameter, the same in every direction
Dictionary
table[query]: the one key equal to the query returns its valueSoft matching
Names

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\]
| 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
Same computation whatever supplies the queries and the stored items: a decoder reading an encoder, or a sequence reading its own positions
Score functions for query \(\mathbf{q} \in \mathbb{R}^{d_q}\), key \(\mathbf{k}_s \in \mathbb{R}^{d_k}\)
Relation to projections

Same states, different grid
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\)
Memory of the additive intermediate
Bilinear and dot product
Matrix-product scores run on the hardware’s fastest operation and never form the \(d_a\) axis
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 |
Reading the table
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 |
Variance of a dot product
\[\mathrm{Var}\big[\mathbf{q}^\top \mathbf{k}\big] = \sum_{i=1}^{d_k} \mathrm{Var}[q_i k_i] = d_k\]
Effect on the softmax, \(S = 50\) random keys

Softmax Jacobian, \(a_j = e^{e_j} / Z\), \(Z = \sum_k e^{e_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

Measured, \(S = 50\)
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\]
Assumption


Bahdanau et al. 2015
Both directions
Luong et al. 2015: read after the update
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\]
Consequence for training
The weights themselves
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 |
By sentence length (the paper’s Figure 2)
Limits

Paper’s alignment
Learned from sentence pairs
Source and target
Properties
Pronoun dependence
Models, trained identically
Sources: 12 to 29 words. Vocabulary: 24 source, 35 target words
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 |


Rows on the translated word
Rows elsewhere
Mechanism

Measured on the pronoun
Published
Content of the weights
Reading attention heatmaps in papers

Repetition
Dropped word
Drift
Common cause
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}\]
Coverage loss (See et al. 2017)
\[L_{\text{cov}} = \sum_t \sum_s \min(a_{t,s},\ u_{t,s})\]
Effect
Unchanged
Soft attention: the weighted read over all positions
Hard attention (Xu et al. 2015)
Local attention (Luong et al. 2015)


First version
Same steps, one more axis
@ on 3-D tensors: \(B\) independent matrix products in one callCost per batch

Unequal lengths
attention_v1 scores padded positions like wordsMeasured, 64 synthetic sources padded to 29 words
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, weightsBroadcasting
key_mask: \(B \times S\), one flag per source positionkey_mask[:, None, :]: \(B \times 1 \times S\), copied across the \(T\) query rows
Measured
torch.nn.functional.scaled_dot_product_attention: maximum difference 0.0Fill value and empty rows
masked_fillExponential of a large score
Third version: the stable softmax inside the function
torch.softmax subtracts the maximum internally. The two match to rounding
Bytes kept for the backward pass, float32, one attention layer
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 |

Beyond \(n = 3d\) the weight grid sets the memory limit on sequence length
Loop and batched product, teacher forcing
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 |


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
With attention in place, the recurrence is the part that cannot run in parallel: 192 sequential steps per pair at \(S = T = 96\)
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}\]
Permute the queries
Consequence


Synthetic scenes for the measurement
Show, Attend and Tell (Xu et al. 2015)
Total weight per region
Cost

Measured, trained captioner, 4,000 steps
Contrast with the translation models
Colour words first

Two red squares
Mechanism
Output a position, not a word
\[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)\]
Measured sorter

Vocabulary and copy distributions (See, Liu, Manning 2017)
\[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)\]
Words outside the vocabulary
Same weights, two uses

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

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

Recurrent model plus a read
Measured
Cost
What each part does

Read alone
Measured

Same pairs, new order

Latest-value task, 8 pairs, each key twice
| Model | Accuracy |
|---|---|
| Read alone | 0.543 |
| Recurrent + read | 0.9995 |
| Recurrent alone | 0.353 |
Read alone
Recurrent + read
The recurrence supplied order and the read supplied lookup. A read without recurrence needs position inside the stored vectors