399. Apply a key padding mask in batched attention
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.
def 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.
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)
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.