883. Padding mask from sequence lengths
Why it matters Every batched transformer needs a padding mask so attention ignores pad tokens. Building it with broadcasting is a one-liner.
padding_mask(lengths, max_len) returns a boolean mask where mask[b, t] is True if position t is a real token of sequence b (t < lengths[b]) and False for padding.
Inputs: lengths is a list or ndarray of non-negative ints. max_len is an int >= max(lengths) (or any int >= 0 if lengths is empty).
Return an ndarray of bools with shape (len(lengths), max_len).
The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 15 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.
def padding_mask(lengths, max_len)Example 1
Input: padding_mask([2, 0, 3], 3)
Output: [[True, True, False], [False, False, False], [True, True, True]]
Example 2
Input: lengths = [1], max_len = 4
Output: [[True, False, False, False]]
Example 3
Input: lengths = [], max_len = 2
Output: np.zeros((0, 2), dtype=bool)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
np.arange(max_len) gives positions.
Hint 2
Reshape lengths to a column with [:, None].
Hint 3
Compare with <.
Common mistakes
- Using <= and marking one pad token as real.
- Transposing to
(T, B). - Returning ints instead of bools.
Understand the idea
Compare a row of positions [0, 1, ..., T - 1] with a column of lengths. Broadcasting a (1, T) array against a (B, 1) array gives the full (B, T) comparison in one step. The double loop does the same comparison B * T times in Python.
Shapes and data flow
positions: (1, T). lengths: (B, 1). Output: (B, T).