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!
RNNs forced information through a narrow sequential bottleneck step-by-step — Self-Attention connects ANY two tokens in hops and parallelizes 100% across GPU Tensor Cores!
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!
Understanding Multi-Head subspaces explains how Transformers simultaneously track syntax, entity coreference, and long-range semantics in a single layer.
Guaranteed ML/DL interview question: 'Why do we divide by , and why must the causal mask be applied BEFORE Softmax using -inf (not 0)?'
Why must future positions in a Causal Attention Mask be set to -inf (not 0) BEFORE applying Softmax?
- Derive and implement Scaled Dot-Product Attention:
- Prove why dividing by keeps dot-product variance at
1.0so 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 - Apply an upper-triangular
-infCausal Mask before Softmax so autoregressive decoders never peek at future tokens
it's Query matches animal's Key!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)
Given input , linear projections produce , , and . Computing produces a affinity matrix whose rows sum to 1.0 after Softmax!
Why We Divide QKᵀ by √d_k
2. Multi-Head Attention (Parallel Subspaces)
A single attention map can only focus on one relationship per token at a time. Multi-Head Attention slices into smaller heads (, keeping total FLOPs identical!), runs independent attentions in parallel, concatenates them, and mixes information through !
3. Causal Masking for Autoregressive Decoders
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!
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?
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 heads!
Scaled Dot-Product & Multi-Head Self-Attention Pipeline
Follow Q, K, V through √d_k scaling, masking, Softmax, and multi-head concatenation.
-inf causal masking, giving Transformers path length and massive GPU parallelism.Core Engine of Every Modern Transformer
Powers BERT, ViT, Whisper, AlphaFold, GPT, Gemini, and Claude across text, vision, audio, and biology.
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
softmax(dim=-2) (over Queries) instead of softmax(dim=-1) (over Keys).dim=-1!d_k is large (e.g., 256) and you OMIT the 1 / √d_k scaling factor before Softmax?