Attention Score Computation with Einsum
Problem Statement
Compute scaled dot-product attention scores using einsum, as used in Transformers.
Background
Attention computes softmax(Q @ K^T / sqrt(d_k)) @ V. Einsum handles the batched transpose elegantly by specifying which indices to sum over and which to keep.
Your Task
The starter code creates Q, K, V tensors (batch=2, seq=4, d_k=8). Use einsum to compute scaled dot-product attention: compute Q·K^T scores (scaled by sqrt(d_k)), apply softmax, then multiply by V.
Output Format
Returns a dictionary with "score_shape", "attn_shape", "output_shape", and "attn_row_sums" (should all be 1.0).
Example
None
{'score_shape': [2, 4, 4], 'attn_shape': [2, 4, 4], 'output_shape': [2, 4, 8], 'attn_row_sums': [1.0, 1.0, 1.0, 1.0]}- Inputs: three random tensors , , , each : batch 2, 4 positions, an 8-dimensional vector per position ().
- Scores: entry is the dot product , divided by . Summing away leaves : every query against every key. For batch 0, query 0 against key 0 the raw dot product is , giving ; that whole row is .
- Weights: exponentiate each score and divide by its row total. That row becomes : query 0 attends mostly to key 0. Shape unchanged.
- Output: position gets , a weighted average of the 4 value vectors, so the key index disappears and the shape is .
- Notice that each of the 4 rows of batch 0 sums to exactly 1 by construction, which is why
attn_row_sumsis[1.0, 1.0, 1.0, 1.0]after rounding to 2 decimal places.
Constraints
- Use einsum for Q@K^T and attn@V
- Scale by sqrt(d_k)
- Apply softmax for attention weights