864. Fix attention scores without the transpose
Why it matters Shape bugs that happen to run on square inputs are the worst kind: they pass a quick smoke test and fail in production.
The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.
attention(q, k, v) should compute scaled dot-product attention without a mask: softmax(q @ k.T / sqrt(d)) @ v, where the softmax runs over keys (the last axis) and d is the size of the last axis of q.
Inputs: q is a list or ndarray of shape (Tq, d). k and v have shape (Tk, d) and (Tk, dv). Tq and Tk can differ.
Return an ndarray of floats with shape (Tq, dv). No rounding.
def attention(q, k, v)Example 1
Input: attention([[1.0, 0.0]], [[1.0, 0.0], [1.0, 1.0]], [[10.0], [20.0]])
Output: [[15.0]]
Example 2
Input: q = [[1.0, 2.0], [0.0, 1.0]], k = [[1.0, 0.0], [3.0, 1.0]], v = [[1.0, 0.0], [0.0, 1.0]]
Output: [[0.055807, 0.944193], [0.330238, 0.669762]]
Example 3
Input: q = [[0.5, 0.5, 0.0]], k = [[1.0, 2.0, 0.0], [0.0, 1.0, 0.0], [3.0, 0.0, 1.0]], v = [[1.0, 1.0], [2.0, 0.0], [0.0, 3.0]]
Output: [[0.828758, 1.561656]]
Constraints
vhas shape(Tk, d)- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Write down the shape of every intermediate.
Hint 2
Each score is a dot product of a query row and a key row.
Hint 3
Transpose k before the matmul.
Common mistakes
- Transposing q instead.
- Softmax over the query axis.
- Scaling by
sqrt(Tk)instead ofsqrt(d).
Understand the idea
q @ k multiplies a (Tq, d) matrix by a (Tk, d) matrix. That only runs when d equals Tk, and even then it computes the wrong thing. Each query must be dotted with each key, which is q @ k.T with shape (Tq, Tk). Tests with Tq != Tk or non-symmetric k catch the bug.
Shapes and data flow
q: (Tq, d). k: (Tk, d). v: (Tk, dv). scores: (Tq, Tk). Output: (Tq, dv).