Complete the canonical attention formula: Attention(Q, K, V) = ___(QKᵀ / ___) · V
Same topic, related formats. Practice these next.
Same topic, related formats. Practice these next.
Attention(Q, K, V) = softmax(QKᵀ / √d_k) · V. The softmax turns raw scores into weights; the √d_k stabilizes the variance so softmax doesn't saturate.
Picture a chef tasting a row of sauces to decide how much of each to ladle into a final stew. Each sauce gets a raw 'matches my dish' score, but those scores can be wildly different in scale, so the chef shrinks them down to a fair size first. Then the chef turns the scores into percentages that add up to 100%, and finally pours each sauce into the stew in those proportions. That whole tasting and mixing routine is what the attention formula does.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example. Click to expand.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example.
Everything important, quickly.
Walk shape flow, justify the √d_k from variance, note the row-wise softmax, and mention FlashAttention as the modern exact-implementation.
import torch, torch.nn.functional as F
def attention(Q, K, V):
# Q, K: (..., n, d_k); V: (..., n, d_v)
d_k = Q.size(-1)
scores = (Q @ K.transpose(-2, -1)) / (d_k ** 0.5)
weights = F.softmax(scores, dim=-1) # row-wise over keys
return weights @ VReal products, models, and research that use this idea.
What an interviewer would ask next. Try answering before peeking at the approach.
Red flags and common mistakes that signal junior thinking. Click to expand.
Forgetting the √d_k or putting d_k instead of √d_k: the square root matters. Or applying softmax over the wrong axis.
The night-before-the-interview bullets. Scan these on the way to the call.
Primary sources. Skim if you want the original framing.