v9.1.1
Menu

Chapter 6: Attention Mechanisms

Week 6

Master the attention mechanism from Bahdanau alignment scores to the full Transformer architecture. Learn self-attention, multi-head attention, positional encoding, and the encoder-decoder framework that powers modern NLP.

Topics
6
Demos
3
Videos
3
Min read
50

Chapter Overview

Attention mechanisms solved the fundamental bottleneck of sequence-to-sequence models: compressing an entire input sequence into a single fixed-length vector. Instead of forcing the encoder to pack everything into one representation, attention allows the decoder to dynamically focus on different parts of the input at each generation step. This simple idea --- letting the model learn where to look --- transformed machine translation and laid the groundwork for the Transformer.

The Transformer architecture, introduced in "Attention Is All You Need" (Vaswani et al., 2017), took this further by replacing recurrence entirely with self-attention. Each token in a sequence attends to every other token, computing relevance scores via query-key-value projections. Multi-head attention runs several attention functions in parallel, capturing different types of relationships. Combined with positional encodings, layer normalization, and residual connections, this produces a highly parallelizable architecture that scales to massive datasets.

This chapter traces the evolution from additive (Bahdanau) attention through scaled dot-product self-attention to the full Transformer encoder-decoder. You will also study the major variants --- BERT, GPT, and T5 --- that adapt the Transformer to different tasks by choosing which blocks to keep and how to mask attention.

Chapter Roadmap

Click any topic to jump in

Explainer videoInteractive demo
1
Attention Basics

Alignment scores, softmax weighting, and context vectors — the core attention computation.

Alignment Score FunctionAttention Weights via SoftmaxContext VectorAdditive vs. Multiplicative Attention
Attending within a sequence

Self-attention and parallel heads for richer representations

2
Self-Attention

Query-key-value projections and scaled dot-product attention within a single sequence.

Query, Key, Value ProjectionsScaled Dot-Product AttentionAttention Matrix and MaskingComputational Complexity
3
Multi-Head Attention

Running parallel attention heads to capture different relationship types simultaneously.

Multi-Head ComputationHead Independence and SpecializationOutput Projection
Adding position awareness
4
Positional Encoding

Injecting position information into permutation-invariant attention via sinusoidal or learned encodings.

Sinusoidal Positional EncodingRelative Position PropertyLearned Positional EmbeddingsRotary Positional Embeddings (RoPE)
The full architecture and its variants

Assembling components into complete models

5
Transformer Architecture

Residual connections, layer normalization, and FFN layers assembled into the full Transformer.

Residual ConnectionsLayer NormalizationPosition-wise Feed-Forward NetworkEncoder-Decoder Structure
6
Transformer Variants

BERT (encoder-only), GPT (decoder-only), T5 (encoder-decoder), and efficient approximations.

BERT: Encoder-OnlyGPT: Decoder-OnlyT5: Text-to-Text Encoder-DecoderEfficient Transformers

Topics

6 topics in this chapter

Before attention, encoder-decoder models compressed the entire source sentence into a single context vector --- the final hidden state of the encoder RNN. This created an information bottleneck: long sentences lost detail, and translation quality degraded as sentence length increased. Bahdanau et al. (2015) proposed a solution: let the decoder look back at all encoder hidden states and compute a weighted combination at each decoding step.

The mechanism works by learning an alignment model that scores how well each encoder hidden state matches the current decoder state. These scores are normalized via softmax into attention weights, then used to compute a context vector as a weighted sum of encoder states. The context vector changes at every decoding step, allowing the model to focus on different source words as it generates different parts of the translation.

This additive attention mechanism demonstrated dramatic improvements on long sentences and established the attention pattern --- score, normalize, aggregate --- that became the foundation for all subsequent attention variants. The alignment weights also provide interpretable visualizations showing which source words the model focuses on for each target word.

Definition

Attention is a mechanism that lets a decoder build a fresh context vector at every output step: it scores each encoder state hjh_j against the current decoder state, normalizes the scores with softmax into weights αij\alpha_{ij}, and returns the weighted sum ci=∑jαijhjc_i = \sum_j \alpha_{ij} h_j. Score, normalize, aggregate is the pattern behind every later variant.

In this topic

  1. 1Alignment Score Function
  2. 2Attention Weights via Softmax
  3. 3Context Vector
  4. 4Additive vs. Multiplicative Attention
1 of 4
Alignment Score Function

eij=a(si−1,hj)=va⊤tanh⁡(Wasi−1+Uahj)e_{ij} = a(s_{i-1}, h_j) = v_a^\top \tanh(W_a s_{i-1} + U_a h_j)

The alignment model aa computes a scalar score eije_{ij} indicating how well the encoder hidden state hjh_j matches the decoder state si−1s_{i-1} at time step ii. In Bahdanau's additive formulation, both states are projected through learned matrices WaW_a and UaU_a, summed, passed through tanh⁡\tanh, and reduced to a scalar by the learned vector vav_a. This is called additive attention because the two projections are summed rather than multiplied. The alignment model is jointly trained with the rest of the network via backpropagation.

Mathematical Intuition

The additive score eij=va⊤tanh⁡(Wasi−1+Uahj)e_{ij} = v_a^\top \tanh(W_a s_{i-1} + U_a h_j) first projects decoder and encoder states into a shared dad_a-dimensional space, sums them (enabling interaction), passes through tanh (bounding the interaction signal), and reduces to a scalar via vav_a. This is equivalent to a one-hidden-layer neural network with dad_a units that takes the concatenated states as input. The tanh nonlinearity allows the network to learn non-trivial alignment patterns — for instance, that a French adjective (decoder state) should align with the English noun it modifies (encoder state) even though they may be far apart.

Example:

Given decoder state s2=[0.5,−0.3]s_2 = [0.5, -0.3] and encoder state h4=[0.8,0.1]h_4 = [0.8, 0.1], with Wa=[[0.2,0.1],[0.3,−0.2]]W_a = [[0.2, 0.1], [0.3, -0.2]], Ua=[[0.1,0.4],[−0.1,0.3]]U_a = [[0.1, 0.4], [-0.1, 0.3]], and va=[0.5,−0.6]v_a = [0.5, -0.6], compute the alignment score e3,4e_{3,4}.

2 of 4
Attention Weights via Softmax

αij=exp⁡(eij)∑k=1Txexp⁡(eik)\alpha_{ij} = \frac{\exp(e_{ij})}{\sum_{k=1}^{T_x} \exp(e_{ik})}

The raw alignment scores eije_{ij} are normalized across all source positions using softmax to produce attention weights αij\alpha_{ij}. These weights form a probability distribution over the source sequence: they are non-negative and sum to 1 for each decoder time step ii. A sharp distribution (one weight close to 1) means the model is focusing on a single source word, while a flat distribution means it is spreading attention across many words. The softmax temperature is implicitly 1, but scaling the scores (as in scaled dot-product attention) effectively adjusts this temperature.

Mathematical Intuition

The softmax αij=exp⁡(eij)/∑kexp⁡(eik)\alpha_{ij} = \exp(e_{ij}) / \sum_k \exp(e_{ik}) converts raw scores to a probability distribution over source positions. The exponential function ensures all weights are positive, and normalization ensures they sum to 1. The softmax temperature is implicitly 1; higher scores create sharper distributions (attending to fewer positions) while lower scores create flatter distributions (spreading attention). The entropy H(αi)=−∑jαijlog⁡αijH(\alpha_i) = -\sum_j \alpha_{ij} \log \alpha_{ij} measures the "sharpness" of attention — low entropy means focused attention, high entropy means diffuse attention.

Example:

Given alignment scores e3,1=1.2e_{3,1} = 1.2, e3,2=0.5e_{3,2} = 0.5, e3,3=2.1e_{3,3} = 2.1, e3,4=0.3e_{3,4} = 0.3 for decoder step 3, compute the attention weights.

3 of 4
Context Vector

ci=∑j=1Txαijhjc_i = \sum_{j=1}^{T_x} \alpha_{ij} h_j

The context vector cic_i is a weighted sum of all encoder hidden states, using the attention weights αij\alpha_{ij} as coefficients. This produces a different context for each decoder time step, allowing the model to access different parts of the source sequence as needed. The context vector is concatenated with the decoder's current input embedding and fed into the decoder RNN to produce the next hidden state. The dimensionality of cic_i matches the encoder hidden state dimension, regardless of source sequence length.

Mathematical Intuition

The context vector ci=∑jαijhjc_i = \sum_j \alpha_{ij} h_j is a weighted average in the encoder's representation space. Geometrically, it is a point in the convex hull of the encoder hidden states — the set of all possible weighted averages. When attention is sharp (one α≈1\alpha \approx 1), the context vector is close to a single encoder state. When attention is diffuse, it is a blend. The dimensionality of cic_i matches the encoder hidden dimension dhd_h, so no information-theoretic bottleneck constrains how much source information reaches the decoder at each step.

Example:

With attention weights α=[0.1,0.7,0.2]\alpha = [0.1, 0.7, 0.2] and encoder states h1=[1,0]h_1 = [1, 0], h2=[0,1]h_2 = [0, 1], h3=[1,1]h_3 = [1, 1], compute the context vector cc.

4 of 4
Additive vs. Multiplicative Attention

eijadd=va⊤tanh⁡(Wasi+Uahj)eijmult=si⊤Wahje_{ij}^{\text{add}} = v_a^\top \tanh(W_a s_i + U_a h_j) \qquad e_{ij}^{\text{mult}} = s_i^\top W_a h_j

There are two main families of attention scoring functions. Additive (Bahdanau) projects both vectors and combines them with tanh⁡\tanh and a learned vector --- it has more parameters but handles cases where decoder and encoder dimensions differ. Multiplicative (Luong) computes a bilinear form or simple dot product, which is faster because it leverages optimized matrix multiplication. Luong et al. (2015) showed that multiplicative attention performs comparably to additive attention and is computationally cheaper, especially for high-dimensional states. The Transformer's scaled dot-product attention is a variant of multiplicative attention.

Mathematical Intuition

Additive attention uses da(ds+dh)+dad_a(d_s + d_h) + d_a parameters, while plain dot-product attention uses none and computes s⊤h=∥s∥∥h∥cos⁡θs^\top h = \lVert s \rVert \lVert h \rVert \cos\theta. If the components of ss and hh are independent with zero mean and unit variance, the dot product has mean 0 and variance dd, so its standard deviation grows as d\sqrt{d}: about 2 at d=4d = 4, 8 at d=64d = 64, and 22.6 at d=512d = 512. Such large scores push softmax into saturation, where gradients almost vanish. The Transformer divides by dk\sqrt{d_k}, which brings the standard deviation back to about 1 at every dimension.

Example:

Compare the parameter counts for additive vs. multiplicative attention when ds=dh=512d_s = d_h = 512 and the alignment dimension is da=256d_a = 256.

Theory Exercise

Problem:

Explain why attention improves performance on long sentences compared to fixed-context encoder-decoder models. What specific limitation does it address, and what is the computational trade-off?

Hints:
  • Think about what happens to information as sequence length grows in a fixed-size vector

Coding Exercise

Problem:

Implement Bahdanau (additive) attention in PyTorch. Create a module that takes encoder hidden states and a decoder state, computes alignment scores, and returns the context vector and attention weights.

Hints:
  • Project both encoder and decoder states to an intermediate dimension

Related Problems on PixelBank