Chapter 01 — Foundations

The Attention Mechanism:
Every Type Explained

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.

From RNNs/LSTMs to Transformers

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.

Quick LSTM Recap

x₁
→
LSTM
cell
→
x₂
→
LSTM
cell
→
x₃
→
LSTM
cell
→ h₃
Sequential: must process x₁ before x₂ before x₃

Why Transformers Replaced LSTMs

AspectLSTMTransformerWhy 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

Gradient Flow: LSTM Gates vs Residual Connections

LSTMs solved vanishing gradients with gates. Transformers solve it with residual connections. Both create "gradient highways," but residuals are simpler and scale better:

LSTM: Multiplicative Gates
∂L/∂c0 = ∂L/∂cT × ∏t ft

If ft = 0.9 for T=100:
0.9100 = 0.0000265

← gradient still vanishes
for very long sequences!
Transformer: Additive Residual
∂L/∂x = ∂L/∂output × (1 + ∂f/∂x)

After 100 layers:
gradient = 1.0 + accumulated

← the "1" ensures gradient
always flows directly!

Hidden State vs Context Window

LSTM Hidden State
Fixed-size vector (e.g., 512 dims).
Must compress entire history into one vector.
Lossy — early tokens get "overwritten."
Like remembering a book through a summary.
Transformer Context Window
All tokens visible simultaneously (e.g., 128K).
Every token can directly attend to any other.
Lossless within window.
Like reading the book with all pages open.
🔑 The Core Mental Shift

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.

The Bottleneck Problem

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.

h₁
h₂
h₃
h₄
h₅ = c
↓ entire sequence compressed into one vector
s₁
s₂
s₃
Fig 1. The encoder compresses all information into a single context vector c = h₅. Information about early tokens is lost.

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.

Bahdanau (Additive) Attention

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:

💡 Key Insight

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 (Multiplicative) Attention

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.

⚡ Performance

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.

Scaled Dot-Product Attention

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:

The core Transformer attention equation

Where:

Why Scale by √d_k?

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:

Concrete example (dk = 64):

Without scaling: q·k ≈ N(0, 64) → std dev = 8.0
Typical scores: [−12.3, 15.7, 2.1, −8.4]
softmax → [0.000, 1.000, 0.000, 0.000] ← saturated!
∂softmax/∂z ≈ 1e-14 → gradients vanish 💀

With √dk scaling: scores/8 → [−1.54, 1.96, 0.26, −1.05]
softmax → [0.03, 0.55, 0.10, 0.27] ← smooth!
∂softmax/∂z ≈ 0.25 → healthy gradients ✓

Step-by-Step Numerical Example

Let's compute attention for a tiny 3-token sequence with :

Interactive Walkthrough

Self-Attention

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.

Attention Weight Heatmap

Self-attention computes a weight matrix showing how much each token attends to every other token. Hover over cells to see exact values:

Hover to Explore
Fig 2. Self-attention weights for "The cat sat on the mat". Notice how "sat" attends strongly to "cat" (its subject).
🔑 Why Self-Attention Matters

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.

Multi-Head Attention

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.

Head 1
Syntactic
Head 2
Semantic
Head 3
Positional
Head 4
Coreference
···
Head h
Other
↓ Concat
Linear Projection WO
Fig 3. Each head learns to attend to different types of relationships — syntactic structure, semantic similarity, position-based patterns, etc.
💡 Intuition

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.

Positional Encoding

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.

Sinusoidal Encoding (Original Transformer)

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.

Positional Encoding Heatmap
Fig 4. Sinusoidal positional encoding for 50 positions across 64 dimensions. Each row is a position, each column is a dimension. Low-frequency patterns (left) capture broad position, high-frequency patterns (right) capture fine-grained position.

Learned Positional Embeddings

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.

Rotary Position Embedding (RoPE)

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.

Masked Self-Attention

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:

Causal Mask Visualization
Fig 5. The causal mask ensures that predicting token i can only use tokens 1...i. Adding −∞ before softmax drives those attention weights to 0.
⚠️ Why −∞ and not 0?

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.

Cross-Attention

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:

ENCODER OUTPUT
Le
chat
est
noir
→ K, V
⟹
DECODER
The
cat
is
→ Q
Fig 6. In cross-attention, the decoder's queries attend to the encoder's keys and values. Here, "cat" in the decoder might attend strongly to "chat" in the encoder.

Sparse Attention

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.

Types of Sparse Patterns

Strided (Fixed) Sparse Attention

Introduced in Sparse Transformers (Child et al., 2019). Each token attends to a fixed local window plus tokens at fixed stride intervals:

Longformer Attention

Longformer (Beltagy et al., 2020) combines local windowed attention with global attention on special tokens (like [CLS]). Complexity drops from to .

BigBird

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

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.

⚡ Key Trade-off

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.

Grouped-Query Attention (GQA)

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:

MULTI-HEAD (MHA)
Q₁ K₁ V₁
Q₂ K₂ V₂
Q₃ K₃ V₃
Q₄ K₄ V₄
GROUPED-QUERY (GQA)
Q₁ K₁ V₁
Q₂ K₁ V₁
Q₃ K₂ V₂
Q₄ K₂ V₂
MULTI-QUERY (MQA)
Q₁ K₁ V₁
Q₂ K₁ V₁
Q₃ K₁ V₁
Q₄ K₁ V₁
Fig 7. MHA = each head has unique K,V. GQA = groups of query heads share K,V. MQA = all heads share one K,V. GQA is the sweet spot.

GQA reduces from (e.g., 32) to a smaller number (e.g., 8), cutting KV cache memory by 4× with minimal quality loss.

Multi-Head Latent Attention (MLA)

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

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).

The Memory Hierarchy Problem

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.

The Solution: Tiling + Online Softmax

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:

⚡ Impact

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.

Attention Mechanisms Compared

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.)
💻 PyTorch Code Implementations

Code: Attention from Scratch

Here's how each attention mechanism looks in PyTorch. Copy-paste and run these — they're complete and working.

Scaled Dot-Product Attention

Python
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)

Multi-Head Attention

Python
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)

Causal (Masked) Attention

Python
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)