BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Attention and transformers22 of 23 in topic

799. Compute batched attention scores with einsum

EasyAttention and transformers

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.

Functiondef 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

  • Q has shape (B, H, Tq, d)
  • K has 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.

Worked example

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)
Topics
Attention and transformers
Similar questions
  • Generate sinusoidal position encodingsEasy
  • Measure how focused each attention row is with entropyEasy
  • Count attention FLOPs for a sequenceEasy
  • Add token and position embeddings for a GPT input batchEasy
All Attention and transformers problems
Report
799 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def attn_scores(Q, K):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 4 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS