799. Compute batched attention scores with einsum
Why it matters Every transformer layer computes this score tensor before the softmax.
Attention code is full of einsum calls because they name every axis. For a batch of multi-head queries and keys the score tensor is the dot product of each query with each key, scaled by 1 / sqrt(d).
Write attn_scores(Q, K) where Q has shape (B, H, Tq, d) and K has shape (B, H, Tk, d). Return scores of shape (B, H, Tq, Tk) with scores[b, h, i, j] = Q[b, h, i] . K[b, h, j] / sqrt(d). np.einsum("bhqd,bhkd->bhqk", ...) does it in one line.
def attn_scores(Q, K)Example 1
Input: attn_scores([[[[1.0, 0.0, 0.0, 0.0]]]], [[[[2.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]]]])
Output: [[[[1.0, 0.0]]]]
Constraints
Qhas shape(B, H, Tq, d)Khas shape(B, H, Tk, d)- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
The d axis is the one that gets summed.
Hint 2
Write the subscripts for Q, then K, then the output, leaving d out of the output.
Hint 3
np.einsum('bhqd,bhkd->bhqk', Q, K) / np.sqrt(d).
Common mistakes
- Using Q @ K without transposing K's last two axes.
- Dividing by d instead of
sqrt(d).
Understand the idea
einsum names each axis with a letter. Axes that appear in both inputs but not in the output are summed. Here d is summed, b and h are kept, and q and k become the two score axes.
one batch, one head, query [1, 0, 0, 0], keys [2, 0, 0, 0] and [0, 1, 0, 0], d = 4. Dot products are 2 and 0, divided by sqrt(4) = 2 gives [1, 0].
scores = einsum('bhqd,bhkd->bhqk', Q, K) / sqrt(d)Shapes and data flow
Q (B, H, Tq, d), K (B, H, Tk, d) -> (B, H, Tq, Tk)