Deep Learning · Sequence Models
Study the Transformer as an architecture: self-attention, Q, K and V, position information, multiple heads, residual paths, normalization, feed-forward blocks, masks and encoder–decoder families.
Start From the Attention You Already Know
The previous lesson introduced attention. The Transformer makes attention the main mechanism for exchanging information across a sequence.
For each token representation x, learned projections create q=xWQ, k=xWK and v=xWV. A query describes what the current position needs, a key describes what another position offers, and a value carries the information that may be retrieved.
Query (Q)
What information is this position looking for?
Key (K)
How should this position be matched?
Value (V)
What information should be passed onward?
Attention(Q,K,V) = softmax(QKᵀ / √dk)V
For a sequence of tokens, QKᵀ forms an attention-score matrix: row i records how query i matches every key. Scaling controls score magnitude, softmax turns each row into weights, and multiplying by V gives one weighted value mixture per row.
Self-Attention and Cross-Attention Ask Different Questions
| Attention type | Queries come from | Keys and values come from | What it enables |
|---|---|---|---|
| Encoder self-attention | Source sequence | The same source sequence | Each source token learns source context |
| Masked decoder self-attention | Current target positions | Allowed earlier target positions | Each target position uses only known target context |
| Cross-attention | Decoder states | Encoder source representations | A target token retrieves relevant source information |
The word self means Q, K and V originate from the same sequence representation—not that each token can attend only to itself. Cross means one sequence queries a different sequence.
A Transformer Removes the Recurrent Step-by-Step Encoder
A recurrent encoder must calculate h₁ before h₂. A Transformer encoder instead uses self-attention to connect positions and can process all source positions in parallel during training. Each block combines attention, a position-wise feed-forward network, residual shortcuts and normalization.
The original Transformer is an encoder–decoder built from attention blocks
Encoder stack
1. Input embedding + position
token identity and order
2. Self-attention
source tokens exchange context
3. Add, norm and feed-forward
refine each representation
repeated N layers
keys & values
→
cross-attention bridge
Decoder stack
1. Shifted target + position
known output tokens
2. Masked self-attention
cannot see future targets
3. Cross-attention
read encoder representations
4. Add, norm and feed-forward
refine decoder states
5. Linear + softmax
next-token probabilities
one distribution per target position
Multi-head attention repeats attention using different learned projections. Each head has an opportunity to model different relationships; their outputs are concatenated and projected. Heads are not assigned human labels, so saying one head “is grammar” is an interpretation to test, not a guarantee.
Where head dimensions come from
Suppose the developer chooses model width dmodel=128 and 4 heads. Each head then uses 128÷4=32 features in the usual equal split. Concatenating four 32-feature results restores 4×32=128, so the residual shortcut can add the original 128-feature representation. The weights inside those projections are learned; the width and head count are architecture choices.
What Completes a Transformer Block?
Attention is one part of the block, not the whole block. The remaining parts transform the information, preserve a direct path through the network and keep feature values at a manageable scale.
Attention exchanges information
It lets token positions collect useful information from other allowed positions.
The feed-forward network transforms each position
After attention, the same small neural network is applied independently to each token representation.
A residual connection preserves a direct path
It adds the sublayer input back to its output, helping information and gradients travel through deep stacks. The two tensors must have matching dimensions.
LayerNorm stabilizes each token's features
It normalizes features within one token representation, then applies learned scale and shift parameters.
2D Transformer Block Architecture: Dual Residual Shortcuts & Normalization
True 2D computational topology showing parallel residual gradients bypassing attention and FFN sublayers.
The diagram shows a common post-norm ordering. In a pre-norm block, LayerNorm is applied before attention and before the feed-forward network. Both designs use the same main ingredients, but their exact ordering differs.
Position Information Restores Order
Self-attention alone compares token content without automatically knowing that one token is first and another is fifth. The model therefore adds a position vector to each token embedding. Positions may be fixed, learned or represented through relative/rotary methods in newer architectures.
The original sine–cosine encoding
PE(pos, 2i) = sin(pos / (100002i/dmodel))
PE(pos, 2i+1) = cos(pos / (100002i/dmodel))
pos is token position, i selects a sine/cosine frequency pair, and dmodel is the embedding width. For pos=1 and dmodel=4: the first pair is [sin(1), cos(1)]≈[0.841,0.540]; the second is [sin(0.01),cos(0.01)]≈[0.010,1.000]. Multiple frequencies give each position a distinctive smooth pattern.
Causal Masking Prevents the Decoder From Cheating
During training, the entire correct target sentence is available in the batch. We shift it right: <start>, “la”, “machine”… becomes the decoder input, while “la”, “machine”, “s’est”… is the prediction target. Without a mask, the representation at “la” could read the later correct word “machine.”
A causal mask blocks every future target token
Rows are queries; columns are keys. ✓ can be read and × is hidden.
<start>
the
motor
stopped
Padding mask and causal mask solve different problems
A padding mask hides artificial pad tokens used to make batch lengths equal. A causal mask hides real future tokens. An encoder often needs a padding mask but no causal mask; an autoregressive decoder generally needs both.
Training Is Parallel; Generation Is Autoregressive
Training with teacher forcing
- Feed all shifted correct target tokens.
- Apply the causal mask.
- Predict every next-token distribution together.
- Compute cross-entropy against the target IDs.
Autoregressive generation
- Begin with the start token or prompt.
- Predict a distribution for the next token.
- Select/sample one token and append it.
- Repeat until an end token or length limit.
The mismatch matters: training conditions on correct previous targets, while inference conditions on its own generated history. Search/decoding choices such as greedy decoding, beam search and sampling change outputs without retraining the model.
Choose the Transformer Family From the Output You Need
| Family | Context rule | Output | Typical use |
|---|---|---|---|
| Encoder-only | All input tokens attend bidirectionally | One representation per input token or pooled input | Classification, extraction, embeddings |
| Decoder-only | Causal self-attention over earlier tokens | Next-token distribution at each position | Autoregressive text/code generation |
| Encoder–decoder | Encoder reads source; decoder uses causal and cross-attention | A target sequence conditioned on source | Translation, summarization, structured transformation |
These families are architectural patterns, not guarantees. A pretrained model matched to the language, domain, context length, licence, accuracy needs and hardware is usually a better starting point than training a Transformer from scratch.
Code the Masks Deliberately
PyTorch's reference Transformer expects embedded source and target tensors. The code below shows the important shape and mask relationship; a complete production system also needs tokenization, position encoding, an output vocabulary layer and a training loop.
import torch
from torch import nn
batch, source_len, target_len, width = 8, 12, 9, 128
source = torch.randn(batch, source_len, width)
target_shifted = torch.randn(batch, target_len, width)
model = nn.Transformer(
d_model=width,
nhead=4,
num_encoder_layers=3,
num_decoder_layers=3,
batch_first=True,
)
# 0 where attention is allowed; -inf above the diagonal.
causal_mask = nn.Transformer.generate_square_subsequent_mask(target_len)
# True means “ignore this padded key” for nn.Transformer masks.
source_is_pad = torch.zeros(batch, source_len, dtype=torch.bool)
target_is_pad = torch.zeros(batch, target_len, dtype=torch.bool)
decoder_states = model(
src=source,
tgt=target_shifted,
tgt_mask=causal_mask,
src_key_padding_mask=source_is_pad,
tgt_key_padding_mask=target_is_pad,
memory_key_padding_mask=source_is_pad,
)
print(decoder_states.shape) # [8, 9, 128]What the four dimensions mean
8 is a chosen batch size, 12 and 9 are example source and target lengths, and 128 is a chosen model width. Four heads imply 32 features per head. Three encoder and decoder layers are architecture choices, not values learned from the batch.
What the calls create
randn makes placeholder embedded inputs for shape testing. The mask helper writes 0 on allowed positions and −∞ on future positions; after softmax, e−∞=0 gives blocked tokens zero attention. The final tensor keeps one 128-feature decoder state for each of 9 target positions in each of 8 examples.
Mask conventions differ across APIs: in this module's boolean key-padding masks, True means blocked. Read the exact function documentation instead of reusing a mask by shape alone.
Common Transformer Failure Modes
| Symptom | Likely cause | What to inspect |
|---|---|---|
| Training loss is unrealistically tiny | Decoder can see future target tokens | Visualize the causal mask and run a token-leakage test |
| Output changes when extra padding is added | Pad tokens are not masked | Check padding IDs, mask polarity and source/target/memory masks |
| Word order has little effect | Position information missing or misaligned | Trace token IDs, positions and embeddings after truncation |
| Loss becomes NaN | Large logits, rate instability or all-masked attention row | Inspect activations/gradients and ensure each query has an allowed key |
| Generation repeats forever | No end-token handling or poor decoding settings | Confirm EOS ID, stopping criteria, repetition behavior and training targets |
| Out of memory on long documents | Standard attention score matrix is quadratic | Chunk/retrieve, reduce length/batch, or evaluate sparse/linear/SSM alternatives |
| Fine-tuning forgets useful behavior | Rate too high or too little representative data | Use smaller rates, held-out evaluation and parameter-efficient strategies |
Limits to Keep in View
Self-attention gives direct routes between positions, but standard global attention uses an N×N score matrix and can become expensive for long sequences. Transformers also require substantial data/compute when trained from scratch, can learn spurious correlations, and may generate fluent but unsupported content. Attention weights are not a guarantee of faithful reasoning.
Good systems therefore combine architecture with trustworthy data, task-appropriate metrics, leakage checks, robustness tests, latency/memory measurement and human review where errors carry real consequences.
The Transformer in Seven Sentences
- Learned projections turn each token representation into queries, keys and values.
- Self-attention lets positions in one sequence exchange weighted value information.
- Multiple heads repeat that operation in several learned representation spaces.
- Position information restores order that content-only attention does not supply.
- Residual shortcuts, normalization and position-wise feed-forward networks complete each block.
- Causal and padding masks prevent future-token leakage and hide artificial padding.
- Encoder-only, decoder-only and encoder–decoder families suit different outputs and require task-specific validation.