vikram

scaled dot-product attention, written down

1 min#ml#math

attention takes queries Q∈Rn×dkQ \in \mathbb{R}^{n \times d_k}, keys KK, and values VV and computes

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) V

why dk\sqrt{d_k}?

if the entries of qq and kk are independent with mean 00 and variance 11, then

Var⁡(q⋅k)=∑i=1dkVar⁡(qiki)=dk\operatorname{Var}(q \cdot k) = \sum_{i=1}^{d_k} \operatorname{Var}(q_i k_i) = d_k

so dot products grow like dk\sqrt{d_k}. large logits push softmax into saturated regions where gradients vanish. dividing by dk\sqrt{d_k} brings the variance back to 11.

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 dk\sqrt{d_k} trick goes back to the original transformer paper.1

Footnotes

  1. vaswani et al., “attention is all you need”, 2017. ↩