Self-Attention Mechanism
Volume II, Chapter 8 — Part I (Attention). Scaled dot-product attention from content-based addressing: Q/K/V projections, variance analysis motivating the scale factor, multi-head attention, causal masking, and complexity.
Table of Contents
- Learning Objectives
- Prerequisites
- Notation
- Core Intuition
- The Sequence Modeling Problem
- Content-Based Addressing
- Query, Key, Value Projections
- Attention Scores and Dot Products
- The Scaling Factor: Variance Analysis
- Softmax Normalization
- Scaled Dot-Product Attention
- Multi-Head Attention
- Causal Masking for Autoregressive Models
- Computational Complexity and Memory
- Gradients Through Attention
- Worked Examples
- Connection to the Broader Curriculum
- Common Pitfalls and Misconceptions
- Research Perspective
- Summary of Takeaways
- Exercises
Learning Objectives
After reading this chapter, you should be able to:
- Motivate self-attention as content-based retrieval over a sequence.
- Derive the Q/K/V linear projections and the attention score matrix .
- Prove that under standard initialization and justify scaling by .
- Write the complete scaled dot-product attention formula and multi-head attention.
- Apply causal masking for autoregressive generation.
- Analyze time and memory complexity ( time, memory).
- Explain why multi-head attention adds representational capacity without increasing FLOPs.
Prerequisites
- Vectors, Spans & Linear Independence — dot products, cosine similarity
- Backpropagation — chain rule, softmax gradients
- Logistic Regression — softmax as multiclass generalization
Notation
- — Input sequence embeddings
- — Query, key, value matrices
- — Head dimensions for keys and values
- — Attention score matrix
- — Softmax attention weight
- — Number of attention heads
Core Intuition
A sequence of tokens must be processed so that each position can incorporate context from all other positions. Recurrent networks pass information through sequential steps; self-attention provides direct paths between any pair of positions in computational depth.
The mechanism is elegant: each token asks a query ("what am I looking for?"), advertises a key ("what do I contain?"), and offers a value ("what information do I provide?"). Attention weights measure query–key compatibility; the output is a weighted sum of values.
This is the foundation of Transformers — the architecture behind modern LLMs, vision transformers, and diffusion models. Positional Encoding adds order information; Flash Attention makes long sequences tractable.
Series context. Chapter 8 (Attention & Transformers), Part I in Volume II. Chapter 11 in the full curriculum numbering.
Self-Attention Step-by-Step
The Sequence Modeling Problem
Definition 1 (Sequence Representation). Given token embeddings , compute output representations where row aggregates information from the full sequence relevant to token .
Definition 2 (All-Pairs Interaction). Self-attention computes an matrix of pairwise interactions, allowing token to directly access token for any .
Proposition 1 (RNN Path Length). In an RNN, information from position reaches position through sequential applications of the recurrence. Gradients through this path suffer from vanishing/exploding dynamics (see Backpropagation).
Proposition 2 (Attention Path Length). Self-attention connects any pair in a single layer — path length 1.
Content-Based Addressing
Definition 3 (Content-Based Retrieval). A database consists of keys and values . A query retrieves:
Interpretation. High when is compatible with (large dot product). Softmax ensures and — a convex combination of values.
Self-attention applies this in parallel for all queries, with keys, values, and queries all derived from the same input sequence ("self").
Query, Key, Value Projections
Definition 4 (Linear Projections). From input :
where and are learnable.
Dimensions:
- — one query per token
- — one key per token
- — one value per token
Proposition 3 (Role Separation). Separate projections allow the same embedding to simultaneously serve as query (what to seek), key (what is offered), and value (information content) in different subspaces.
This connects to Matrix Operations: each projection is a linear map to a task-specific subspace.
Attention Scores and Dot Products
Definition 5 (Attention Score Matrix).
Interpretation. measures compatibility between query and key . When , this is proportional to cosine similarity (see Vectors & Linear Independence).
Proposition 4 (Bilinear Form). is a learned similarity kernel over input pairs.
The Scaling Factor: Variance Analysis
Theorem 1 (Score Variance). Assume entries of are independent with , . Then:
Proof.
using independence.
Corollary 1 (Softmax Saturation). When is large, has standard deviation . Large score magnitudes drive softmax into saturated regions where (vanishing gradients).
Definition 6 (Scaled Scores).
Important equation. Scaling by keeps softmax inputs in a well-conditioned regime regardless of head dimension. This is essential for training stability.
Softmax Normalization
Definition 7 (Attention Weights).
applied row-wise. Properties: , .
Proposition 5 (Gradient of Softmax). For cross-entropy or downstream loss :
This Jacobian is well-conditioned when — another reason for scaling.
Scaled Dot-Product Attention
Theorem 2 (Attention Formula).
Row of the output:
A convex combination of value vectors, weighted by query–key compatibility.
Multi-Head Attention
Definition 8 (Multi-Head Attention). With heads, each with projections , :
where and .
Theorem 3 (FLOP Equivalence). Multi-head attention with heads of dimension costs — the same as single-head attention with .
Proof. Each head: . Total: .
Interpretation. Multiple heads learn different attention patterns (syntactic, semantic, positional) in parallel subspaces without extra compute — a representational gain at fixed FLOPs.
Causal Masking for Autoregressive Models
Definition 9 (Causal Mask). For autoregressive models (GPT), token may only attend to tokens :
After softmax: for (since ).
Definition 10 (Causal Attention).
where if and if .
See KV Cache for efficient autoregressive inference.
Computational Complexity and Memory
- — — score matrix
- Softmax — — weights
- — — output
- Total — —
Proposition 6 (Quadratic Bottleneck). For sequence length , storing in FP16 requires GB — often exceeding model weight memory.
Flash Attention computes exact attention in memory via tiling and recomputation.
Gradients Through Attention
Proposition 7 (Output Layer Gradient). With loss and output :
Proposition 8 (Score Gradient). Through softmax:
Proposition 9 (Q/K Gradients).
Full derivation follows Backpropagation through the computation graph.
Worked Examples
Example 1: Single Query, Two Keys
, , , . Scores: , . After scaling: , . Weights: , .
Example 2: Causal Mask
For , causal mask zeroes upper triangle. Row 1 attends only to position 1; row 2 to positions 1–2; row 3 to all.
Example 3: Memory at Scale
Llama 2 70B: layers, heads, , seq_len . Attention matrix per layer: bytes MB. Total across layers dominates KV Cache memory.
Connection to the Broader Curriculum
- Positional information — Positional Encoding, RoPE
- Efficient attention — Flash Attention
- Inference — KV Cache
- Low-rank adaptation — LoRA modifies Q/K/V projections
- Dot products — Vectors & Linear Independence
Common Pitfalls and Misconceptions
Pitfall 1: Omitting scaling. Causes softmax saturation and training instability for large .
Pitfall 2: Confusing self-attention with cross-attention. Self-attention: Q, K, V from same sequence. Cross-attention: Q from one sequence, K/V from another (encoder–decoder).
Pitfall 3: Forgetting causal mask in generation. Without masking, the model sees future tokens — label leakage during training.
Pitfall 4: Assuming attention weights are interpretable. Weights reflect compatibility in learned subspaces, not necessarily human-interpretable relations.
Pitfall 5: Ignoring memory. Long-context models require Flash Attention or sparse attention variants.
Research Perspective
Attention originated in machine translation (Bahdanau et al., 2015). Self-attention and Transformers (Vaswani et al., 2017) replaced recurrence entirely. Universal approximation for Transformers (Yun et al., 2020) extends Universal Approximation Theorem to sequence models.
Modern developments: RoPE, Multi-Query Attention, Flash Attention, linear attention approximations, and state-space models (Mamba) as alternatives to quadratic attention.
Summary of Takeaways
- Projections — , etc.
- Scores —
- Scaling —
- Attention —
- Multi-head — heads, , concat +
- Causal mask — for
- Complexity — time, memory
Next article: Positional Encoding →
Exercises
Exercise 1. Prove Theorem 1 (variance of dot product) without skipping steps.
Exercise 2. Show that attention output lies in the convex hull of .
Exercise 3. Derive (17) — gradient through softmax.
Exercise 4. Prove Theorem 3 (FLOP equivalence of multi-head attention).
Exercise 5. For , write the causal mask matrix explicitly.
Exercise 6. Compute attention output when and with , with and without scaling.
Exercise 7. Explain how LoRA modifies the Q/K/V projections without changing attention structure.
Exercise 8 (Conceptual). Why does self-attention alone not encode token order? How does Positional Encoding fix this?