Scaled Dot-Product Attention
Implement Scaled Dot-Product Attention from the Transformer architecture.
Given query matrix , key matrix , and value matrix :
where is the dimension of the keys (number of columns in K).
Steps:
- Compute (matrix multiplication)
- Scale by
- Apply softmax row-wise (each row sums to 1)
- Multiply by
Return the attention output matrix, rounded to 4 decimal places.
Example
Q = [[1, 0]] K = [[1, 0], [0, 1]] V = [[1, 2], [3, 4]]
[[1.6605, 2.6605]]
- We start by computing the matrix product , which is .
- Then, we scale this result by , yielding .
- Next, we apply the softmax function row-wise: since is a single row, this results in after normalization, but because we apply softmax to we actually calculate , which then gets multiplied by V.
- Finally, multiplying this result by yields $[[\frac{e^{\frac{1}{\sqrt{2}}}}{e^{\frac{1}{\sqrt{2}}} + 1}, \frac{1}{e^{\frac{1}{\sqrt{2}}} + 1}]] \cdot [[1, 2], [3, 4]] = [[\frac{e^{\frac{1}{\sqrt{2}}}}{e^{\frac{1}{\sqrt{2}}} + 1} \cdot 1 + \frac
Constraints
- Q: 2D list (n x d_k)
- K: 2D list (m x d_k)
- V: 2D list (m x d_v)
- Return 2D list (n x d_v) rounded to 4 decimal places
- Use numerical stability trick for softmax