BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Optimization challenges12 of 14 in topic

883. Padding mask from sequence lengths

EasyOptimization challenges

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.

Functiondef 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).
Topics
Optimization challenges
Similar questions
  • Rolling mean with a cumulative sumEasy
  • Count token frequencies fastEasy
  • Batched softmax without the row loopEasy
  • Confusion matrix in one passEasy
All Optimization challenges problems
Report
883 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
10
import numpy as np
​
def padding_mask(lengths, max_len):
lens = np.asarray(lengths, dtype=int)
mask = np.zeros((len(lens), max_len), dtype=bool)
for b in range(len(lens)):
for t in range(max_len):
mask[b, t] = t < lens[b]
return mask
​

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

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