Part 12 / Topic 4 of 6
Attention
Attention lets every token gather information from every other token, weighted by relevance. Each token emits a query ("what am I looking for?"), a key ("what do I contain?") and a value ("what do I offer?"). Scores = queries · keys, scaled, softmaxed into weights, applied to values:
# examples/02_scaled_dot_product_attention_from_scratch.py (core)
scores = Q @ K.T / math.sqrt(d) # how much each token attends to each other
weights = torch.softmax(scores, dim=-1) # each row sums to 1
out = weights @ V
# attention weights for token 0: [0.121, 0.741, 0.106, 0.032]
# row sums: [1.0, 1.0, 1.0, 1.0]
# matches PyTorch: True
Three lines, verified identical to F.scaled_dot_product_attention. The √d divisor keeps dot products from growing with dimension, which would saturate the softmax into near-one-hot weights and kill gradients.
🧪 Quick quiz
- In scaled dot-product attention, why divide by √d?
Show the answer
To keep dot products from growing with dimension, which would saturate the softmax — and the from-scratch formula softmax(QKᵀ/√d)V matched PyTorch's built-in exactly.
Done here? The practice set for Part 12 — 4 exercises with solutions — is on the part page.