scaled dot-product attention, written down
attention takes queries , keys , and values and computes
why ?
if the entries of and are independent with mean and variance , then
so dot products grow like . large logits push softmax into saturated regions where gradients vanish. dividing by brings the variance back to .
in code
import torch
def attention(q, k, v):
d_k = q.size(-1)
scores = q @ k.transpose(-2, -1) / d_k**0.5
return scores.softmax(dim=-1) @ v
takeaway: scaling is about keeping softmax in its useful range, not about the math being wrong without it.
the trick goes back to the original transformer paper.1
Footnotes
-
vaswani et al., “attention is all you need”, 2017. ↩