v9.1.1
Menu

Attention Score Computation with Einsum

hardPROEinsum OperationsPyTorch Advanced

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

Input
None
Output
{'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]}
Reasoning
  • Inputs: three random tensors QQ, KK, VV, each 2×4×82 \times 4 \times 8: batch 2, 4 positions, an 8-dimensional vector per position (dk=8d_k = 8).
  • Scores: entry (b,i,j)(b, i, j) is the dot product ∑d=18QbidKbjd\sum_{d=1}^{8} Q_{bid} K_{bjd}, divided by 8≈2.8284\sqrt{8} \approx 2.8284. Summing away dd leaves 2×4×42 \times 4 \times 4: every query against every key. For batch 0, query 0 against key 0 the raw dot product is 3.42813.4281, giving 3.4281/2.8284≈1.21203.4281 / 2.8284 \approx 1.2120; that whole row is [1.2120,0.7364,−0.3090,−0.8766][1.2120, 0.7364, -0.3090, -0.8766].
  • Weights: exponentiate each score and divide by its row total. That row becomes [0.5092,0.3165,0.1113,0.0631][0.5092, 0.3165, 0.1113, 0.0631]: query 0 attends mostly to key 0. Shape unchanged.
  • Output: position ii gets ∑jwbijVbj⋅\sum_j w_{bij} V_{bj\cdot}, a weighted average of the 4 value vectors, so the key index jj disappears and the shape is 2×4×82 \times 4 \times 8.
  • Notice that each of the 4 rows of batch 0 sums to exactly 1 by construction, which is why attn_row_sums is [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

Learn this in

More from PyTorch Advanced

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.