From the original sequence-to-sequence bottleneck to multi-head self-attention, sparse attention, and beyond — the complete mathematical and visual guide to how neural networks learn to focus.
If you're coming from the LSTM world, this section bridges the conceptual gap. Every design choice in Transformers is a direct response to an LSTM limitation.
| Aspect | LSTM | Transformer | Why It Matters |
|---|---|---|---|
| Processing | Sequential (one token at a time) | Parallel (all tokens at once) | Transformers train 100× faster on GPUs |
| Long-range deps | Token 1 → Token 100: info passes through 99 cells | Token 1 → Token 100: direct attention in 1 step | No information degradation over distance |
| Memory | Fixed-size hidden state ht (e.g., 512 dims) | Full context window (all tokens visible) | No forgetting — every token is always accessible |
| Gradient flow | BPTT through time steps (vanishing with depth) | Residual connections (direct gradient highway) | Can train 100+ layer models stably |
| Position info | Inherent (sequential processing = position) | Explicit positional encoding needed | Tradeoff: must add PE, but gains parallelism |
| Training paradigm | Task-specific (train separate model per task) | Pre-train once → fine-tune for any task | 1 model handles 100s of tasks |
LSTMs solved vanishing gradients with gates. Transformers solve it with residual connections. Both create "gradient highways," but residuals are simpler and scale better:
In LSTMs, information flows through time — each cell passes its understanding forward. In Transformers, information flows through attention — every token directly queries every other token. This is why Transformers need positional encoding (they have no inherent sense of order) but gain massive parallelism and perfect long-range access.
Before attention, sequence-to-sequence models compressed an entire input sentence into a single fixed-size vector — the final hidden state of the encoder RNN. This created a devastating information bottleneck: as sentences grew longer, the model forgot earlier tokens.
The attention mechanism solves this by letting the decoder look back at all encoder hidden states and decide which ones are most relevant for each output token.
Introduced by Bahdanau et al. (2014), this was the first attention mechanism for neural machine translation. It computes alignment scores using a learned feed-forward network:
Where:
The alignment model is a small neural network itself — it learns which source tokens are relevant for each target token during training. This is "additive" because it uses a sum inside the tanh.
Luong et al. (2015) simplified the alignment function. Instead of a neural network, they proposed three score functions:
The dot variant is the simplest and most efficient — just a dot product between decoder and encoder states. The general variant adds a learned weight matrix. The concat variant is similar to Bahdanau.
The dot-product variant is much faster than Bahdanau because it avoids the forward pass through a neural network — it's just matrix multiplication, which GPUs excel at.
This is the attention mechanism used in Transformers, introduced in "Attention Is All You Need" (2017). It takes Luong's dot-product attention and adds a critical scaling factor:
Where:
When is large, the dot products grow in magnitude, pushing the softmax into regions where its gradients are extremely small. Dividing by keeps the variance at 1:
Let's compute attention for a tiny 3-token sequence with :
In self-attention, the queries, keys, and values all come from the same sequence. Each token attends to every other token in the sequence (including itself):
Where is the input sequence and are learned projection matrices.
Self-attention computes a weight matrix showing how much each token attends to every other token. Hover over cells to see exact values:
Unlike RNNs that process tokens sequentially, self-attention computes all pairwise relationships in parallel. A token at position 1 can directly attend to a token at position 100 — no information needs to travel through 99 intermediate steps.
Instead of computing a single attention function, multi-head attention runs parallel attention heads, each with its own learned projections. This lets the model attend to information from different representation subspaces:
With and heads, each head operates on dimensions.
Think of each attention head as a different "lens" examining the sentence. One head might focus on subject-verb agreement, another on adjective-noun relationships, and another on long-distance dependencies. Together, they give the model a rich understanding.
Self-attention has no inherent notion of token order — it treats the input as a set, not a sequence. Positional encoding injects position information into the model.
The original Transformer uses sine and cosine functions of different frequencies:
This creates a unique encoding for each position. The key property: can be represented as a linear function of , allowing the model to learn relative positions.
Models like BERT and GPT learn a separate embedding for each position (up to a maximum sequence length). Simpler to implement, works well in practice, but can't extrapolate to unseen positions.
Modern models (Qwen, LLaMA) use RoPE, which encodes positions by rotating the query and key vectors. We'll cover this in detail in the Qwen chapter.
In autoregressive models (like GPT), each token should only attend to tokens at earlier positions — it cannot peek at the future. Masked self-attention enforces this with a triangular mask:
Where is the mask matrix:
We add −∞ before the softmax, not after. Since , this perfectly zeroes out future positions. Setting weights to 0 after softmax would break the probability distribution.
In cross-attention (also called encoder-decoder attention), the queries come from one sequence and the keys/values come from a different sequence:
This is the mechanism that lets a Transformer decoder attend to the encoder's output. It's also used in:
Standard self-attention has complexity — every token attends to every other token. For long sequences (4K, 16K, 100K+ tokens), this becomes prohibitively expensive. Sparse attention restricts which token pairs can attend to each other.
Introduced in Sparse Transformers (Child et al., 2019). Each token attends to a fixed local window plus tokens at fixed stride intervals:
Longformer (Beltagy et al., 2020) combines local windowed attention with global attention on special tokens (like [CLS]). Complexity drops from to .
BigBird (Zaheer et al., 2020) adds random attention connections to the local + global pattern. Theoretically, random graphs ensure that information can flow between any two tokens in a small number of steps.
Linear attention replaces the softmax with a kernel function, enabling complexity through clever matrix associativity:
The key insight: by computing first (an operation), we avoid materializing the attention matrix entirely.
Linear attention is dramatically faster for long sequences but often underperforms standard softmax attention on shorter sequences. Models like RWKV and Mamba build on this idea with architectural innovations.
Standard multi-head attention uses separate K, V projections for each head. GQA (Ainslie et al., 2023) groups multiple query heads to share a single K, V head, reducing memory during inference:
GQA reduces from (e.g., 32) to a smaller number (e.g., 8), cutting KV cache memory by 4× with minimal quality loss.
Introduced in DeepSeek-V2 (2024), MLA compresses the KV cache even further by projecting keys and values into a low-rank latent space:
Only the compressed vectors need to be stored in the KV cache — a massive reduction from standard MHA. We cover this in full in the DeepSeek article.
Flash Attention (Dao et al., 2022) doesn't change the math — it produces exact same results as standard attention. The innovation is a GPU-aware algorithm that avoids materializing the full attention matrix in HBM (high-bandwidth memory).
GPU computation is fast, but memory access is the bottleneck. Standard attention writes the attention matrix to slow HBM, then reads it back — an I/O disaster.
Flash Attention computes attention in tiles that fit in fast SRAM (on-chip memory), using an online algorithm to compute softmax incrementally without needing the full matrix:
Flash Attention achieves 2-4× wall-clock speedup and enables training on sequences 4-16× longer at the same memory budget. It's now the default attention implementation in most frameworks.
| Mechanism | Complexity | KV Cache | Key Innovation | Used In |
|---|---|---|---|---|
| Bahdanau | O(n·m) | — | Additive alignment score | Early NMT |
| Scaled Dot-Product | O(n²) | Full | √d_k scaling | Transformer |
| Multi-Head | O(n² · h) | Full per head | Parallel subspaces | All Transformers |
| Masked | O(n²) | Full | Causal mask for autoregression | GPT, Decoder models |
| Sparse | O(n√n) | Sparse | Restricted attention patterns | Longformer, BigBird |
| Linear | O(n) | Compressed | Kernel approximation | RWKV, Mamba |
| GQA | O(n²) | Shared groups | Grouped KV sharing | LLaMA 2, Qwen |
| MLA | O(n²) | Low-rank latent | Latent KV compression | DeepSeek-V2/V3 |
| Flash Attention | O(n²) exact | Full (tiled) | IO-aware tiled computation | Universal (impl.) |
Here's how each attention mechanism looks in PyTorch. Copy-paste and run these — they're complete and working.
import torch import torch.nn.functional as F import math def scaled_dot_product_attention(Q, K, V, mask=None): """Core attention: Attention(Q,K,V) = softmax(QK^T / √d_k) V""" d_k = Q.size(-1) scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k) if mask is not None: scores = scores.masked_fill(mask == 0, -1e9) attn_weights = F.softmax(scores, dim=-1) output = torch.matmul(attn_weights, V) return output, attn_weights # Example usage Q = torch.randn(1, 4, 64) # (batch, seq_len, d_k) K = torch.randn(1, 4, 64) V = torch.randn(1, 4, 64) out, weights = scaled_dot_product_attention(Q, K, V) print(f"Output: {out.shape}") # (1, 4, 64) print(f"Weights: {weights.shape}") # (1, 4, 4)
class MultiHeadAttention(torch.nn.Module): def __init__(self, d_model=512, n_heads=8): super().__init__() self.n_heads = n_heads self.d_k = d_model // n_heads # 64 per head # Learned projections for Q, K, V, and output self.W_q = torch.nn.Linear(d_model, d_model) self.W_k = torch.nn.Linear(d_model, d_model) self.W_v = torch.nn.Linear(d_model, d_model) self.W_o = torch.nn.Linear(d_model, d_model) def forward(self, x, mask=None): B, T, C = x.shape # Project and reshape to (B, n_heads, T, d_k) Q = self.W_q(x).view(B, T, self.n_heads, self.d_k).transpose(1, 2) K = self.W_k(x).view(B, T, self.n_heads, self.d_k).transpose(1, 2) V = self.W_v(x).view(B, T, self.n_heads, self.d_k).transpose(1, 2) # Attention per head out, _ = scaled_dot_product_attention(Q, K, V, mask) # Concat heads and project out = out.transpose(1, 2).contiguous().view(B, T, C) return self.W_o(out) # 8-head attention on 512-dim input mha = MultiHeadAttention(512, 8) x = torch.randn(2, 10, 512) # (batch=2, seq=10, d_model=512) print(mha(x).shape) # (2, 10, 512)
def causal_attention(Q, K, V): """GPT-style: each token can only attend to itself and earlier tokens""" T = Q.size(-2) # Create causal mask: lower-triangular = 1, upper = 0 causal_mask = torch.tril(torch.ones(T, T)) # [[1, 0, 0, 0], # [1, 1, 0, 0], # [1, 1, 1, 0], # [1, 1, 1, 1]] return scaled_dot_product_attention(Q, K, V, mask=causal_mask)