PIXELBANKv9.1.0
Menu

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:

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:
  • We start by creating tensors Q, K, V of shape (2, 4, 8) and computing attention scores using torch.einsum('bqd,bkd->bqk', Q, K) / sqrt(8), resulting in a tensor of shape (2, 4, 4).
  • The scores are then passed through a softmax function along the last dimension, yielding attention weights of the same shape (2, 4, 4).
  • We compute the output by multiplying the attention weights with V using torch.einsum('bqk,bkd->bqd', attn_weights, V), resulting in a tensor of shape (2, 4, 8).
  • Finally, we calculate the sum of each row of the attention weights for the first batch, which should all be approximately 1.01.0 due to the properties of the softmax function, and return the required information in a dictionary.

Constraints:

  • Use einsum for Q@K^T and attn@V
  • Scale by sqrt(d_k)
  • Apply softmax for attention weights
๐Ÿ”’

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

0/0
Run code to see test results.
Attention Score Computation with Einsum - Hard | PixelBank