Chapter 33 of 42 · ~22 min read & lab+85 XP
Chapter 33 · Deep Learning

Self-Attention & Multi-Head Attention: Q, K, V Projections, √d_k Scaling & Causal Masks

The exact mechanism that replaced RNNs across all of AI: how Queries, Keys, and Values compute dynamic context in O(1) sequential path length, why dividing by √d_k saves Softmax gradients, Multi-Head subspaces, and Causal Masking!

Why ML Engineers & Data Scientists Actually Need This

RNNs forced information through a narrow sequential bottleneck step-by-step — Self-Attention connects ANY two tokens in O(1)O(1) hops and parallelizes 100% across GPU Tensor Cores!

ML / AI Engineer

Writing Scaled Dot-Product Attention and Causal Multi-Head Attention from scratch in PyTorch is the #1 most frequently asked Deep Learning coding interview problem!

Data Scientist

Understanding Multi-Head subspaces explains how Transformers simultaneously track syntax, entity coreference, and long-range semantics in a single layer.

Interview & Debug Edge

Guaranteed ML/DL interview question: 'Why do we divide QK⊤QK^\top by dk\sqrt{d_k}, and why must the causal mask be applied BEFORE Softmax using -inf (not 0)?'

Step 0 · Test Your Gut Before Any Math!

Why must future positions in a Causal Attention Mask be set to -inf (not 0) BEFORE applying Softmax?

What You Will Master in This Chapter
  • Derive and implement Scaled Dot-Product Attention: Attn(Q,K,V)=softmax(QK⊤/dk)V\text{Attn}(Q, K, V) = \text{softmax}(QK^\top / \sqrt{d_k}) V
  • Prove why dividing by dk\sqrt{d_k} keeps dot-product variance at 1.0 so Softmax never saturates into vanishing gradients
  • Implement Multi-Head Attention by reshaping (B, T, D) → (B, H, T, d_k), attending in parallel, and mixing with WOW_O
  • Apply an upper-triangular -inf Causal Mask before Softmax so autoregressive decoders never peek at future tokens
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
Attn(Q,K,V)=softmax ⁣(QK⊤dk+M)V\text{Attn}(Q, K, V) = \text{softmax}\!\left(\frac{Q K^\top}{\sqrt{d_k}} + M\right) VSay aloud:“Attention of Q, K, V equals Softmax of Q K-transpose over square root of d-k plus mask, times V”
Plain-English Meaning
Every token emits a Query ('what am I looking for?'), compares it against all Keys ('what do I contain?'), normalizes via Softmax, and blends the Values ('what info do I pass along?').
Everyday Example
In *'The animal didn't cross the street because it was tired'*, it's Query matches animal's Key!
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Think of Self-Attention like a differentiable Python dictionary lookup: your Query (q) doesn't require an exact string match against Keys (k_i) — it computes a soft cosine/dot-product similarity against every key and returns a weighted blend of their Values (v_i)!

1. Scaled Dot-Product Attention (Q, K, V & √d_k)

Scaled Dot-Product Attention: Softmax(QKᵀ / √d_k) · V1. Q, K, VLinear projections2. QKᵀ / √d_kScaled scores3. SoftmaxAttention weights4. Weights · VContext output ✓
Scaled Dot-Product Attention computes pairwise compatibility QKᵀ / √d_k — dividing by √d_k keeps logit variance at 1.0 so Softmax never saturates into vanishing gradients!

Given input X∈RB×T×DX \in \mathbb{R}^{B \times T \times D}, linear projections produce Q=XWQQ = XW_Q, K=XWKK = XW_K, and V=XWVV = XW_V. Computing QK⊤/dkQK^\top / \sqrt{d_k} produces a T×TT \times T affinity matrix whose rows sum to 1.0 after Softmax!

Animated Mini-Lab • Self-Attention

Why We Divide QKᵀ by √d_k

Unscaled std(q·k) = 8.0 (Softmax saturates!) · Scaled by 1/√64 → std = 1.0 ✓

2. Multi-Head Attention (Parallel Subspaces)

Multi-Head Attention: H Parallel Subspaces (d_k = D / H) → Concat → W_OHead 1 (Syntax & Verbs)Head 2 (Pronoun Coreference)Head 3 (Long-Range Context)Concat(H₁..Hₙ) · W_OMixes all heads back to D ✓
Multi-Head Attention splits D into H parallel subspaces (d_k = D / H) so Head 1 tracks syntax, Head 2 tracks coreference, and Head 3 tracks long-range entities simultaneously!

A single attention map can only focus on one relationship per token at a time. Multi-Head Attention slices DD into HH smaller heads (dk=D/Hd_k = D / H, keeping total FLOPs identical!), runs HH independent attentions in parallel, concatenates them, and mixes information through WOW_O!

3. Causal Masking for Autoregressive Decoders

Causal Attention Mask: Upper Triangle = −∞ (Zero Future Peeking!)✓−∞−∞−∞✓✓−∞−∞✓✓✓−∞✓✓✓✓
Autoregressive Causal Masking sets the upper triangle of QKᵀ to −∞ before Softmax so Token t can attend ONLY to tokens 1..t and never peek at future tokens!

During training, we feed the entire sentence into a Decoder in parallel for GPU speed. Adding an upper-triangular -inf mask ensures Token t can ONLY attend to positions 0..t, preventing any cheating from future tokens!

Pause & Check · Quick Intuition Pulse

In Multi-Head Attention with D = 512 and H = 8 heads, what is the per-head dimension d_k and the attention score tensor shape for batch B and length T?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Concatenating [Head_1, Head_2, ..., Head_H] simply places their outputs side-by-side without mixing them. Multiplying by W_O linearly blends insights across all HH heads!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS Multi-Head Self-Attention pipeline transform Q, K, V into context vectors.
Interactive Animation • Attention Deep Lab

Scaled Dot-Product & Multi-Head Self-Attention Pipeline

Follow Q, K, V through √d_k scaling, masking, Softmax, and multi-head concatenation.

Step 1 / 4
1. Project X → Q, K, V and split into H parallel heads (B, H, T, d_k)
2. Compute scaled compatibility scores S = QKᵀ / √d_k (+ causal −∞ mask)
3. Softmax row-wise → probability weights A summing to 1.0
4. Weighted sum A·V → Concat all H heads → Project via W_O ✓
0%
Attention Step 1
Intuition Takeaway: Multi-Head Self-Attention computes parallel QK⊤/dkQK^\top / \sqrt{d_k} lookups across HH subspaces with -inf causal masking, giving Transformers O(1)O(1) path length and massive GPU parallelism.
Where This Powers Real ML, Deep Learning & Generative AI

Core Engine of Every Modern Transformer

Powers BERT, ViT, Whisper, AlphaFold, GPT, Gemini, and Claude across text, vision, audio, and biology.

Production NumPy & PyTorch Code Patterns
import math, torch
import torch.nn.functional as F

def causal_sdpa(Q, K, V):
    # Q, K, V: (B, H, T, d_k)
    d_k = Q.size(-1)
    scores = (Q @ K.transpose(-2, -1)) / math.sqrt(d_k)
    T = Q.size(-2)
    mask = torch.triu(torch.ones(T, T, device=Q.device, dtype=torch.bool), diagonal=1)
    scores = scores.masked_fill(mask, float("-inf"))
    weights = F.softmax(scores, dim=-1)
    return weights @ V
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Applying softmax(dim=-2) (over Queries) instead of softmax(dim=-1) (over Keys).
Best Practice: Each Query row MUST form a valid probability distribution over all Keys — ALWAYS use dim=-1!
Chapter Mastery Check (+85 XP)
Score: 0 / 1
1What happens when d_k is large (e.g., 256) and you OMIT the 1 / √d_k scaling factor before Softmax?

Apply What You Learned — Solve Matching Coding Problems