Machine learning building blocks
Scaled dot-product attention
ml.attentionAlso called attention, scaled dot product attention, sdpa, self attention
Each query row of Q takes a weighted average of the rows of V, weighted by the softmax over keys of its scaled dot products with the rows of K. The softmax runs along each row (over keys).
Notation
queries, one per row
Q ∈ ℝm×d
keys, one per row
K ∈ ℝn×d
values, one per row
V ∈ ℝn×e
number of queries
Size, at least 1
number of keys
Size, at least 1
query and key dimension
Size, at least 1
value dimension
Size, at least 1
Result: one output row per query
matrix
Worked examples
Each result is solved exactly and confirmed by two independent computations.
Given
Result
Given
Result
Given
Result
Given
Result
Common mistakes
Omits the 1/√dk scale
The dot products are not divided by √dk, which sharpens the softmax.
Fix: Divide QKT by √dk before the softmax.
Divides by dk instead of √dk
The dot products are divided by dk.
Fix: Divide by the square root of dk.
Softmax over queries instead of keys
The softmax normalizes each column of QKT (over queries) instead of each row (over keys).
Fix: Apply the softmax along the last axis, dim=−1.
Source
Vaswani et al. 2017, eq. 1
Vaswani, Ashish et al. Attention is All you Need. In Advances in Neural Information Processing Systems 30, pp. 5998-6008, 2017.