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.

Signaturedef padded_attention(Q, K, V, lengths)

Example

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

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. Rule: 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)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplepadded_attention(_Q[:1], _K[:1], _V[:1], [1])
  • Sample 2: mixed lengthspadded_attention(_Q, _K, _V, [2, 4])
  • Test 3: fullpadded_attention(_Q, _K, _V, [4, 4])