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

399. Apply a key padding mask in batched attention

MediumAttention and transformers
Asked atAnthropicMeta

Why it matters Every encoder model served in batches (BERT, embedding models) relies on this mask.

In a padded batch, queries must not attend to padding keys.

Write padded_attention(Q, K, V, lengths). Q, K, V are (B, T, d), lengths is (B,). Scores Q K^T / sqrt(d). Set scores for key positions >= lengths[b] to -1e9, softmax over keys, return (B, T, d) outputs.

Functiondef padded_attention(Q, K, V, lengths)

Example 1

with lengths [1] every query in the batch attends only to key 0, so every output row equals V[0, 0].

Constraints

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 3 tests to be accepted.
Hint 1

Mask shape (B, 1, T) broadcasts over queries.

Hint 2

Scores have shape (B, T, T).

Hint 3

The mask indexes the key axis.

Common mistakes
  • Masking the query axis.
  • Masking after the softmax.
Understand the idea

Batches pad short sequences to a common length. Padding positions are fake, so no query should give them any attention weight. You mask keys, not queries: for each batch row, score columns at or beyond the real length are set to a huge negative number before the softmax, which makes their weight about zero.

Worked example

one batch row with T = 3 and length 2. Suppose a query's scaled scores are [1, 1, 5]. Key 2 is padding, so it becomes [1, 1, -1e9]. Softmax gives [0.5, 0.5, 0], and the output is the average of V[0] and V[1]. Without the mask, the large score 5 on padding would dominate.

S = Q K^T / sqrt(d) with shape (B, T, T); build a key mask of shape (B, 1, T) that is True where key index >= lengths[b]; set those scores to -1e9; softmax over the last axis (subtract the max for stability); output = weights @ V

Every query, including padded ones, uses the same key mask for its row. Used in: BERT style encoders and any batched transformer with variable-length inputs.

Shapes and data flow
S (B, T_q, T_k)
keep (B, 1, T_k) broadcast over queries
P (B, T_q, T_k) @ V (B, T_k, d) -> (B, T_q, d)
Topics
Attention and transformers
Companies2
  • Anthropic a candidate reported this question Anthropic Senior SWE phone screen experience (Screna)
  • Meta a candidate reported this question Machine Learning interview questions, page 10 (KatKat)

From public interview reports and guides. Not affiliated with or endorsed by these companies.

Similar questions
  • GPT decoder: causal self-attention for one headMedium
  • Split and merge attention headsMedium
  • Build the ALiBi attention bias for every headMedium
  • Bucket relative positions like T5Medium
All Attention and transformers problems
Report
399 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def padded_attention(Q, K, V, lengths):
# your code here
pass
​
padded_attention(_Q[:1], _K[:1], _V[:1], [1])

This case uses generated data, so it runs as written. Press + to add your own case.

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

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