Attention Is All You Need
Goal
Translate a sequence of tokens into another sequence using only attention, without any recurrence or convolution.
Transformer Structure
Encoder
- Stack of identical layers (usually 6)
- Each layer has:
- Multi-Head Self-Attention
- Position-wise Feed-Forward Network
Decoder
- Stack of identical layers
- Each layer has:
- Masked Self-Attention (to block future tokens)
- Cross-Attention over encoder outputs
- Feed-Forward Network
Each sublayer is wrapped with residual connections + layer normalization.
Scaled Dot-Product Attention
Given queries ( Q ), keys ( K ), and values ( V ):
- is the key dimension
- The scaling by stabilizes gradients
Multi-Head Attention
Instead of a single attention, we use multiple “heads”:
Each head can focus on different relations in the sentence.
Positional Encoding
Since there’s no recurrence, position info is added using sine and cosine functions:
This is added to token embeddings at the input.
Feed-Forward Network
Each position passes through the same small neural network:
Masking in Decoder
To prevent seeing future tokens, apply a causal mask ( M ):
where if , otherwise 0.
Training
- Teacher forcing during training
- Cross-entropy loss for next-token prediction
- Label smoothing for better generalization
- Adam optimizer with warmup and inverse-sqrt learning rate schedule
Why It Works Well
- Fully parallelizable, unlike RNNs
- Handles long-range dependencies directly
- Multiple heads learn different linguistic patterns
Complexity
For sequence length ( n ) and model size ( d ):
- Time:
- Memory: This comes from the attention matrix of size ( n \times n ).
Quick Algorithm Summary
- Embed tokens and add positional encodings.
- Encoder: repeat [MHA + AddNorm, FFN + AddNorm] ( L ) times.
- Decoder: repeat [Masked MHA, Cross MHA, FFN] with AddNorm each.
- Final linear + softmax for output probabilities.
Key Formulas