Chapter 6: Attention Mechanisms
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
Attention Basics
Alignment scores, softmax weighting, and context vectors — the core attention computation.
Self-attention and parallel heads for richer representations
Self-Attention
Query-key-value projections and scaled dot-product attention within a single sequence.
Multi-Head Attention
Running parallel attention heads to capture different relationship types simultaneously.
Positional Encoding
Injecting position information into permutation-invariant attention via sinusoidal or learned encodings.
Assembling components into complete models
Transformer Architecture
Residual connections, layer normalization, and FFN layers assembled into the full Transformer.
Transformer Variants
BERT (encoder-only), GPT (decoder-only), T5 (encoder-decoder), and efficient approximations.
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 against the current decoder state, normalizes the scores with softmax into weights , and returns the weighted sum . Score, normalize, aggregate is the pattern behind every later variant.
In this topic
- 1Alignment Score Function
- 2Attention Weights via Softmax
- 3Context Vector
- 4Additive vs. Multiplicative Attention
Alignment Score Function
The alignment model computes a scalar score indicating how well the encoder hidden state matches the decoder state at time step . In Bahdanau's additive formulation, both states are projected through learned matrices and , summed, passed through , and reduced to a scalar by the learned vector . 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.
The additive score first projects decoder and encoder states into a shared -dimensional space, sums them (enabling interaction), passes through tanh (bounding the interaction signal), and reduces to a scalar via . This is equivalent to a one-hidden-layer neural network with 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.
Given decoder state and encoder state , with , , and , compute the alignment score .
Attention Weights via Softmax
The raw alignment scores are normalized across all source positions using softmax to produce attention weights . These weights form a probability distribution over the source sequence: they are non-negative and sum to 1 for each decoder time step . 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.
The softmax 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 measures the "sharpness" of attention — low entropy means focused attention, high entropy means diffuse attention.
Given alignment scores , , , for decoder step 3, compute the attention weights.
Context Vector
The context vector is a weighted sum of all encoder hidden states, using the attention weights 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 matches the encoder hidden state dimension, regardless of source sequence length.
The context vector 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 ), the context vector is close to a single encoder state. When attention is diffuse, it is a blend. The dimensionality of matches the encoder hidden dimension , so no information-theoretic bottleneck constrains how much source information reaches the decoder at each step.
With attention weights and encoder states , , , compute the context vector .
Additive vs. Multiplicative Attention
There are two main families of attention scoring functions. Additive (Bahdanau) projects both vectors and combines them with 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.
Additive attention uses parameters, while plain dot-product attention uses none and computes . If the components of and are independent with zero mean and unit variance, the dot product has mean 0 and variance , so its standard deviation grows as : about 2 at , 8 at , and 22.6 at . Such large scores push softmax into saturation, where gradients almost vanish. The Transformer divides by , which brings the standard deviation back to about 1 at every dimension.
Compare the parameter counts for additive vs. multiplicative attention when and the alignment dimension is .
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
Self-attention extends the attention idea from cross-sequence alignment to within a single sequence. Instead of a decoder attending to an encoder, each token in a sequence attends to every other token in the same sequence, computing a new representation that incorporates information from the entire context. This is the core mechanism of the Transformer.
The key innovation is the query-key-value (QKV) framework. Each token's embedding is linearly projected into three vectors: a query (what am I looking for?), a key (what do I contain?), and a value (what information do I carry?). Attention scores are computed as dot products between queries and keys, scaled by to prevent softmax saturation, then used as weights to aggregate values. The result is a context-aware representation for each token.
Self-attention has a critical advantage over RNNs: it connects every pair of positions with sequential operations (all pairs can be computed in parallel), whereas an RNN requires sequential steps to propagate information from one end of a sequence to the other. This enables efficient training on long sequences and is the reason Transformers can be scaled to billions of parameters.
Definition
Self-attention is attention in which a sequence attends to itself: each token's embedding is projected into a query, a key, and a value, and every output position is a softmax-weighted sum of all values, . Any two positions interact in one parallel step, with cost quadratic in sequence length.
In this topic
- 1Query, Key, Value Projections
- 2Scaled Dot-Product Attention
- 3Attention Matrix and Masking
- 4Computational Complexity
Query, Key, Value Projections
Given an input matrix (one row per token), self-attention projects it into three matrices using learned weight matrices and . The query represents what each token is searching for, the key represents what each token offers, and the value carries the actual content. The separation into three roles allows the model to learn different matching and content functions. Typically where is the number of attention heads.
The projections , , create three different "views" of each token. The query asks "what am I looking for?", the key advertises "what do I contain?", and the value carries "what information do I provide?". By using separate projections, the model decouples the matching criterion () from the information retrieved (). If , attention would degenerate into a simple similarity-weighted average of the inputs. The learned projections allow asymmetric relationships: token A can strongly attend to token B without B equally attending to A.
For a sequence of 4 tokens with and , what are the shapes of , , and ?
Scaled Dot-Product Attention
The attention function computes dot products between all query-key pairs, forming a attention matrix. Dividing by is critical: without scaling, when is large, the dot products grow in magnitude, pushing the softmax into regions where its gradients are extremely small (vanishing gradient problem). The factor keeps the variance of the dot products at approximately 1, regardless of dimension. After softmax normalization, each row of the resulting matrix gives the attention weights for one token, and multiplying by produces the output --- a weighted mixture of value vectors.
The formula has a crucial scaling factor . Without scaling, the dot products have variance (assuming unit-variance components), meaning for , scores have standard deviation . Feeding these into softmax produces extremely peaked distributions where one position gets weight and the rest get , making gradients vanishingly small. Dividing by normalizes the variance to 1, keeping softmax in a regime with meaningful gradients.
Given , , with , compute the attention output.
Attention Matrix and Masking
The attention matrix is an matrix where entry is the weight that token places on token . In the encoder, all positions can attend to all other positions (bidirectional). In the decoder, causal masking prevents position from attending to positions by setting those entries to before softmax (which maps them to 0). This ensures autoregressive generation: each token can only depend on previously generated tokens. Padding masks are also applied to ignore padding tokens in variable-length batches.
The attention matrix is an matrix where is how much token attends to token . Causal masking sets for by adding to those positions before softmax, preventing information leakage from future tokens during autoregressive generation. Padding masks set for padding positions to prevent the model from attending to meaningless tokens. Both masks operate in the score space (before softmax), ensuring the resulting weights still form a valid probability distribution over the unmasked positions.
For a 4-token decoder sequence, what does the causal attention mask look like?
Computational Complexity
Self-attention has time and memory complexity , where is the sequence length and is the model dimension. The term arises from computing all pairwise dot products in . For short sequences (), this is highly efficient because the entire computation can be parallelized on GPUs. For very long sequences (), the quadratic cost becomes a bottleneck, motivating efficient attention variants like linear attention, sparse attention, and Flash Attention. By contrast, RNNs are --- linear in sequence length but sequential, preventing parallelization.
Self-attention computes , an matrix from inputs, costing operations. The dependence on sequence length is the fundamental bottleneck: doubling the sequence length quadruples the computation and memory. For a 4096-token sequence with , the attention matrix alone requires entries. This quadratic cost motivates efficient attention variants (Linformer, FlashAttention) that reduce the complexity to or by approximating or restructuring the full attention computation.
Compare the number of operations for self-attention vs. an RNN layer with , .
Theory Exercise
Problem:
Explain why the scaling factor in dot-product attention is necessary. What happens if you remove it, and how does the scaling relate to the variance of dot products?
Hints:
- Assume query and key components are independent with mean 0 and variance 1
Coding Exercise
Problem:
Implement scaled dot-product self-attention from scratch in PyTorch. Include optional causal masking for decoder-style attention.
Hints:
- Compute QK^T, scale by sqrt(d_k), optionally apply mask, then softmax, then multiply by V
A single attention head can only focus on one type of relationship at a time. Multi-head attention addresses this by running attention functions in parallel, each with its own learned QKV projection matrices. This allows the model to simultaneously attend to information from different representation subspaces at different positions --- one head might capture syntactic dependencies while another captures semantic similarity.
Each head operates on a reduced dimension , so the total computation is equivalent to a single head with full dimensionality. The outputs of all heads are concatenated and projected through a final linear layer to produce the output. This design is parameter-efficient: heads with dimension each use the same number of parameters as one head with dimension .
Empirically, multi-head attention consistently outperforms single-head attention. Analysis of trained Transformers shows that different heads learn complementary functions: some track subject-verb agreement, others handle coreference, and some focus on positional patterns. This division of labor is emergent --- the model discovers it through training.
Definition
Multi-head attention runs scaled dot-product attention functions in parallel, each with its own projections into a dimensional subspace, then concatenates the outputs and mixes them with a learned matrix . Each head can learn a different relation at about the same total cost as one full-width head.
In this topic
- 1Multi-Head Computation
- 2Head Independence and Specialization
- 3Output Projection
Multi-Head Computation
Each head computes its own attention: where and . The heads are concatenated along the feature dimension to produce an matrix, then projected through to restore the original dimension. In the standard Transformer, with heads.
With heads each of dimension , the total parameter count for QKV projections is , identical to a single head with full dimension. The key insight is that each head operates in a lower-dimensional subspace of dimension , enabling it to specialize in different relationship types. Empirically, heads learn distinct patterns: some capture syntactic dependencies (subject-verb), others capture positional proximity, and others track coreference chains. The diversity of independent attention patterns is more expressive than a single -dimensional attention.
With and , calculate the per-head dimensions, the concatenated dimension, and the total parameter count for multi-head attention.
Head Independence and Specialization
Each head has independent projection matrices, so they learn to extract different features from the same input. Research by Voita et al. (2019) and Clark et al. (2019) shows that heads specialize: some attend to the adjacent token, others to syntactic heads (e.g., a verb attending to its subject), and others form broad attention patterns that aggregate global context. Pruning experiments reveal that not all heads are equally important --- some can be removed with minimal performance loss, while others are critical. This suggests learned redundancy provides robustness.
Each head computes independently, meaning different heads can assign completely different attention patterns to the same input. Research on BERT shows that early layers develop heads for short-range syntactic relations (determiner-noun, adjective-noun) while later layers develop heads for long-range semantic dependencies (coreference, discourse structure). Some heads become "positional" (attending to adjacent tokens regardless of content) while others become "content-based" (attending based on semantic similarity).
In a 12-head model processing "The cat that I saw yesterday was black", describe three plausible head specializations.
Output Projection
The output projection serves two purposes: it mixes information across heads (since concatenation keeps them separate) and projects back to to maintain consistent dimensions for residual connections. Without , the model could not combine insights from different heads --- each head's contribution would remain in its own subspace. The optional bias adds a learnable shift. The output of multi-head attention has the same shape as the input, enabling the residual connection .
The concatenation combines outputs of dimension back to . The output projection is a learnable linear transformation that mixes information across heads. Without , the model could only use per-head information independently. With , the model can combine evidence from multiple heads — for instance, using one head's syntactic signal together with another head's semantic signal to make a joint decision.
If head 1 outputs and head 2 outputs with , compute the final output.
Theory Exercise
Problem:
Prove that multi-head attention with heads and dimension has the same parameter count and compute cost as single-head attention with dimension . Why is multi-head preferred despite equivalent cost?
Hints:
- Count parameters for single-head: 3 weight matrices of size d_model x d_model
Coding Exercise
Problem:
Implement the full multi-head attention module in PyTorch, including QKV projections, per-head attention, concatenation, and output projection.
Hints:
- Reshape Q, K, V to split the last dimension into (h, d_k) using view and transpose
Self-attention is inherently permutation-invariant: shuffling the input tokens produces the same attention weights (just reordered). This means a Transformer without positional information treats "dog bites man" and "man bites dog" identically. Positional encodings inject sequence order into the model by adding a position-dependent signal to each token embedding before it enters the attention layers.
The original Transformer uses sinusoidal positional encodings --- fixed functions of position and dimension that create unique, smooth patterns for each position. The key design insight is that relative positions can be represented as linear transformations of the encoding vectors: can be expressed as a linear function of for any fixed offset . This allows the model to learn to attend by relative position.
Alternative approaches include learned positional embeddings (treating positions like vocabulary tokens with trainable vectors), relative positional encodings (encoding the distance between tokens rather than absolute positions), and rotary positional embeddings (RoPE) used in modern LLMs. Each approach has trade-offs in terms of generalization to unseen sequence lengths, computational cost, and empirical performance.
Definition
A positional encoding is a position-dependent signal that makes a Transformer sensitive to word order, which plain self-attention ignores. It is either added to the token embeddings, as with fixed sinusoids or learned vectors, or applied inside attention, as with rotary embeddings that rotate queries and keys by angles proportional to position.
In this topic
- 1Sinusoidal Positional Encoding
- 2Relative Position Property
- 3Learned Positional Embeddings
- 4Rotary Positional Embeddings (RoPE)
Sinusoidal Positional Encoding
Self-attention treats its input as a set, so position must be injected explicitly. The sinusoidal scheme gives position a -dimensional vector whose dimension pair holds the sine and cosine of , with frequency . The first pair has wavelength and changes sharply from one token to the next; the last pair has wavelength near and changes very slowly, so together the pairs act like the hands of a clock running at many speeds. The base 10000 makes the slowest wavelengths far longer than any training sequence, so positions do not repeat. The vector is added to the token embedding, with no learned parameters.
The encoding and uses different frequencies for different dimensions. Low-index dimensions oscillate rapidly (capturing fine position differences), while high-index dimensions oscillate slowly (capturing coarse position structure). The base is chosen so that the wavelengths range from (dimension 0) to (dimension ), spanning from character-level to document-level position sensitivity.
Compute the first 4 dimensions of the positional encoding for position 3 with .
Relative Position Property
A crucial property of sinusoidal encodings is that the encoding at position can be expressed as a linear transformation of the encoding at position . Specifically, for each frequency pair , the relationship is a 2D rotation matrix: where . This means the model can learn to compute relative positions through linear operations on the encodings, without explicitly being given relative position information.
The key property is that can be expressed as a linear transformation of : specifically, where is a rotation matrix that depends only on the offset , not on the absolute position . This means the dot product is a function of alone — the model can learn to detect "3 positions apart" regardless of where in the sequence those positions are. This translation-invariant property is why sinusoidal encodings generalize to sequence lengths not seen during training.
Show that the dot product depends only on the offset , not on .
Learned Positional Embeddings
An alternative to fixed sinusoidal encodings is to learn a positional embedding matrix where is the maximum sequence length. Position uses the -th row of as its encoding, and the values are learned during training via backpropagation. BERT and GPT-2 use this approach. The advantage is flexibility --- the model can learn arbitrary positional patterns. The disadvantage is that it cannot generalize to positions beyond without interpolation or extrapolation tricks. Empirically, learned and sinusoidal encodings perform similarly for lengths within the training range.
Learned positional embeddings assign a trainable vector to each position , adding parameters: 393,216 for BERT's and . Position has no embedding, so the model cannot be applied directly to longer inputs. Vaswani et al. found learned and sinusoidal encodings nearly identical on translation within the training range. Sinusoidal vectors exist for every position, but Press et al. (2022) showed that sinusoidal models' perplexity still rises quickly beyond the training length, which motivated relative schemes such as ALiBi and rotary embeddings.
A model with learned positional embeddings was trained with . What happens if you try to process a 1024-token sequence?
Rotary Positional Embeddings (RoPE)
RoPE (Su et al., 2021) applies position-dependent rotations directly to query and key vectors rather than adding encodings to inputs. Each pair of dimensions is rotated by an angle proportional to position and frequency . The key property is that the dot product depends only on the relative position , naturally encoding relative distance. RoPE is used in LLaMA, PaLM, and most modern LLMs because it combines the best of both worlds: it encodes relative position like relative encodings while being as simple to implement as absolute encodings.
RoPE encodes position by rotating query and key vectors in 2D subspaces: where is the position. The dot product depends on the relative position through the angle . Unlike additive positional encodings that inject position information once and hope it propagates through layers, RoPE applies the rotation at every attention layer, ensuring position information is never lost. The rotation preserves vector norms (), so position encoding does not distort the magnitude-based similarity signal.
For a 2D vector at position with , compute the rotated query .
Theory Exercise
Problem:
Compare sinusoidal, learned, and rotary positional encodings along three dimensions: (1) generalization to unseen lengths, (2) encoding of relative vs. absolute position, and (3) where in the model the position information is injected.
Hints:
- Sinusoidal: added to input, absolute, but relative via dot product
Coding Exercise
Problem:
Implement sinusoidal positional encoding in PyTorch and visualize the encoding matrix as a heatmap to observe the frequency patterns.
Hints:
- Create a matrix of shape (max_len, d_model)
Related Problems on PixelBank
The Transformer combines all the components covered so far --- multi-head self-attention, positional encoding, feed-forward networks, layer normalization, and residual connections --- into a unified encoder-decoder architecture. Introduced by Vaswani et al. (2017), it achieved state-of-the-art results on machine translation while being significantly more parallelizable than recurrent models.
The encoder consists of identical layers, each containing a multi-head self-attention sublayer followed by a position-wise feed-forward network (FFN). Each sublayer is wrapped in a residual connection and layer normalization: . The decoder has the same structure but adds a third sublayer for cross-attention over the encoder output, and applies causal masking to the self-attention to preserve autoregressive generation.
The feed-forward network in each layer is a simple two-layer MLP applied independently to each position: . The inner dimension provides a capacity bottleneck that forces the model to compress and then reconstruct information. Together, the attention sublayer (which mixes information across positions) and the FFN (which transforms information within each position) form a powerful feature extraction pipeline.
Definition
The Transformer is an encoder-decoder network built only from attention and feed-forward layers. Each of its layers wraps a multi-head attention sublayer and a position-wise feed-forward network in residual connections with layer normalization, and the decoder adds masked self-attention plus cross-attention over the encoder output.
In this topic
- 1Residual Connections
- 2Layer Normalization
- 3Position-wise Feed-Forward Network
- 4Encoder-Decoder Structure
Residual Connections
Every sublayer (attention and FFN) is wrapped in a residual connection that adds the sublayer input to its output. This creates shortcut paths for gradient flow, enabling training of deep networks. Without residual connections, stacking 6+ layers leads to vanishing or exploding gradients. The residual design also means each sublayer only needs to learn the "residual" --- the difference between the desired output and the input --- which is typically easier than learning the full transformation. Pre-norm (applying LayerNorm before the sublayer) and post-norm (after) are two variants; pre-norm is more stable and used in most modern implementations.
The residual connection ensures that the gradient always includes an identity component. This means gradients can flow through the network unimpeded regardless of how many layers there are — the identity path provides a gradient highway analogous to the LSTM cell state. Without residual connections, a 12-layer Transformer would suffer from vanishing gradients just like a 12-step RNN. The additive structure also enables layer dropout, where entire sublayers can be skipped without catastrophically breaking the forward pass.
With input and sublayer output , compute the post-norm residual output assuming LayerNorm normalizes to mean 0 and variance 1.
Layer Normalization
Layer normalization computes the mean and variance across the feature dimension for each token independently (unlike batch normalization, which computes across the batch). The learned scale and shift allow the model to undo the normalization if needed. LayerNorm stabilizes training by reducing internal covariate shift --- it ensures that each sublayer receives inputs with consistent statistics, regardless of the magnitudes produced by previous layers. The (typically ) prevents division by zero.
Layer normalization computes where and are the mean and standard deviation across the dimensions of a single token. Unlike batch normalization (which normalizes across the batch), layer normalization normalizes each token independently, making it suitable for variable-length sequences. Pre-norm Transformers apply LN before the sublayer: , which stabilizes training for deep models because the sublayer input always has unit variance, preventing activation explosions that compound through many layers.
Apply LayerNorm to with and .
Position-wise Feed-Forward Network
The FFN is a two-layer MLP applied independently to each token position. The first layer expands the dimension from to (4x expansion), applies ReLU, then the second layer projects back to . This expansion-compression pattern creates a bottleneck that forces the model to form useful intermediate representations. The FFN is where most of the model's parameters reside and where factual knowledge is believed to be stored. Recent work replaces ReLU with GELU or SwiGLU for better performance.
The FFN with and expands the representation to and then compresses back. This expansion-compression pattern creates a bottleneck where the ReLU activation selects which of the intermediate features to activate. Research shows that the FFN layers act as key-value memories: keys match input patterns, and the corresponding values add information to the residual stream. The FFN accounts for ~2/3 of the Transformer's parameters ( vs. for attention).
For a Transformer with , , and layers, calculate the total FFN parameter count.
Encoder-Decoder Structure
The complete Transformer has an encoder stack and a decoder stack. The encoder processes the source sequence with bidirectional self-attention (every token sees all others). The decoder processes the target sequence with causal self-attention (each token sees only previous tokens) plus cross-attention where decoder queries attend to encoder key-value pairs. This cross-attention is the bridge between the two stacks: decoder tokens ask questions (queries) that are answered by the encoder representations (keys and values). During inference, the encoder runs once and the decoder generates tokens autoregressively, attending to the cached encoder output at each step.
The Transformer encoder-decoder uses three types of attention: encoder self-attention (each source token attends to all source tokens), decoder causal self-attention (each target token attends to previous target tokens only), and encoder-decoder cross-attention (each target token attends to all source tokens). The cross-attention layer uses queries from the decoder and keys/values from the encoder, implementing the same attend-to-source mechanism as Bahdanau attention but with learned QKV projections instead of additive scoring. The encoder processes the full source in parallel, then the decoder generates autoregressively, attending to the frozen encoder representations at each step.
In a translation model, how many attention computations occur per decoder layer when translating a 10-word source sentence into a 15-word target?
Theory Exercise
Problem:
Compare pre-norm and post-norm Transformer architectures. Where is LayerNorm applied in each, and why does pre-norm lead to more stable training in deep models?
Hints:
- Post-norm: LN(x + Sublayer(x)). Pre-norm: x + Sublayer(LN(x))
Coding Exercise
Problem:
Build a complete Transformer encoder layer in PyTorch with multi-head self-attention, feed-forward network, residual connections, and layer normalization (pre-norm variant).
Hints:
- Apply LayerNorm before each sublayer, add residual after
The original Transformer encoder-decoder architecture was designed for sequence-to-sequence tasks like machine translation. Subsequent work showed that using only the encoder or only the decoder, with appropriate pretraining objectives, produces powerful general-purpose language models. This insight led to three major architectural families that dominate modern NLP.
BERT (encoder-only) uses bidirectional self-attention and is pretrained with masked language modeling --- predicting randomly masked tokens from their full bidirectional context. This produces rich contextual representations ideal for understanding tasks like classification, question answering, and named entity recognition. GPT (decoder-only) uses causal (left-to-right) self-attention and is pretrained with next-token prediction. This autoregressive design excels at text generation and, at sufficient scale, exhibits few-shot and zero-shot learning abilities. T5 (encoder-decoder) frames every NLP task as text-to-text, using the full Transformer with prefix-based task instructions.
Beyond architectural choices, efficiency improvements have been critical for scaling Transformers. Flash Attention optimizes GPU memory access patterns, sparse attention reduces the complexity, and mixture-of-experts (MoE) architectures activate only a subset of parameters per token. These innovations enable training models with hundreds of billions of parameters on sequences of millions of tokens.
Definition
Transformer variants are the families that keep the Transformer's layers but change which stacks are used and what they are pretrained to do: encoder-only models such as BERT trained with masked language modeling, decoder-only models such as GPT trained on next-token prediction, and encoder-decoder models such as T5 trained on text-to-text span corruption.
In this topic
- 1BERT: Encoder-Only
- 2GPT: Decoder-Only
- 3T5: Text-to-Text Encoder-Decoder
- 4Efficient Transformers
BERT: Encoder-Only
BERT (Devlin et al., 2019) uses only the Transformer encoder with bidirectional self-attention. During pretraining, 15% of tokens are randomly masked and the model predicts them from their full surrounding context. This masked language modeling (MLM) objective forces the model to build deep bidirectional representations. BERT also uses a next-sentence prediction (NSP) task during pretraining, though later work (RoBERTa) showed NSP is unnecessary. For downstream tasks, BERT is fine-tuned by adding a task-specific head (e.g., a classification layer) on top of the encoder output. BERT-base has 12 layers, 768 dimensions, and 110M parameters.
BERT uses only the Transformer encoder with bidirectional self-attention — every token attends to every other token. This is optimal for understanding tasks (classification, NER, QA) because the representation of each token incorporates full context from both directions. The masked language modeling objective randomly masks 15% of tokens and trains the model to predict them, creating a denoising autoencoder. The key trade-off: BERT cannot generate text autoregressively because it was never trained to predict the next token — only to fill in blanks.
Given "The [MASK] sat on the mat", how does BERT use bidirectional context to predict the masked token?
GPT: Decoder-Only
GPT (Radford et al., 2018) uses only the Transformer decoder with causal self-attention masking. The causal language modeling (CLM) objective trains the model to predict each token given all previous tokens. This autoregressive design is naturally suited for generation: at inference time, the model generates tokens one by one, each conditioned on everything generated so far. GPT-2 (1.5B params) demonstrated strong zero-shot performance, and GPT-3 (175B params) showed that scaling decoder-only models produces emergent few-shot learning --- the model can perform tasks from just a few examples in the prompt, without any gradient updates.
GPT uses only the Transformer decoder with causal (left-to-right) attention masking. Each token can only attend to itself and preceding tokens, making the architecture naturally suited for autoregressive generation. The causal LM objective trains the model to predict the next token, which is exactly the inference-time task. This train-test alignment (unlike BERT's mask-then-predict vs. no-masks-at-inference mismatch) is one reason why scaling GPT-style models has been so effective — the pretraining objective directly optimizes the capability used at deployment.
How does GPT-3 perform sentiment analysis in a zero-shot setting without any fine-tuning?
T5: Text-to-Text Encoder-Decoder
T5 (Raffel et al., 2020) uses the full encoder-decoder architecture and frames every NLP task as a text-to-text problem. Classification becomes "classify: The movie was great" "positive". Translation, summarization, and question answering all follow the same format with different text prefixes. T5 is pretrained with a span corruption objective: random spans of input tokens are replaced with sentinel tokens, and the decoder predicts the original spans. This is more efficient than BERT's MLM because it masks contiguous spans (15% of tokens in fewer mask operations) and trains the decoder to generate the missing text. T5 demonstrated that a single architecture with a unified text interface can match or exceed specialized models across dozens of benchmarks.
T5 frames every NLP task as text-to-text: classification becomes "sentiment: [text]" -> "positive", translation becomes "translate English to French: [text]" -> "[french]", and summarization becomes "summarize: [text]" -> "[summary]". The encoder processes the full input bidirectionally, and the decoder generates the output autoregressively with cross-attention to the encoder. This unified interface means a single model architecture and training procedure handles all tasks. The encoder-decoder split is advantageous when the input and output have different lengths or structures — the encoder provides rich input representations while the decoder handles generation.
Show how T5 handles three different NLP tasks using the text-to-text format.
Efficient Transformers
The attention complexity becomes a bottleneck for long sequences. Several approaches address this. Sparse attention (Longformer, BigBird) restricts each token to attend to a fixed window plus a few global tokens, reducing complexity to . Linear attention (Performers, Katharopoulos et al.) approximates softmax attention with kernel functions, enabling computation. Flash Attention (Dao et al., 2022) does not change the algorithm but optimizes GPU memory access by tiling the attention computation to maximize use of fast SRAM, achieving 2-4x speedup with exact attention. Mixture of Experts (MoE) routes each token to a subset of FFN experts, increasing model capacity without proportionally increasing computation. These efficiency techniques are essential for training and serving modern LLMs.
The attention cost has spawned many efficient variants. Linformer projects keys and values to a lower dimension , reducing attention to . Performer uses random feature maps to approximate softmax attention in . Longformer combines local sliding-window attention ( for window size ) with global attention on special tokens. FlashAttention does not change the mathematical computation but restructures it to minimize GPU memory transfers (HBM to SRAM), achieving 2--4x wall-clock speedups while computing exact attention. The practical winner is often FlashAttention because it is exact and requires no architectural changes.
Compare memory usage for standard attention vs. Flash Attention on a sequence of length 4096 with in float16.
Theory Exercise
Problem:
For a given NLP task (e.g., named entity recognition), explain why you would choose BERT over GPT. Then describe a task where GPT is clearly better than BERT. What fundamental property of each architecture drives this difference?
Hints:
- Think about bidirectional vs. unidirectional context
Coding Exercise
Problem:
Use Hugging Face Transformers to compare BERT and GPT-2 on a fill-in-the-blank task. Show how BERT uses bidirectional context while GPT-2 can only use left context.
Hints:
- Use pipeline('fill-mask') for BERT and pipeline('text-generation') for GPT-2