Stream Token Lists into Fixed-Size Blocks with a Validity Mask
Arrays & HashingAuto-graded · 21 test casesLast updated
Concatenate truncated token lists into equal-length blocks, zero-pad the last one, and build a parallel 0/1 mask marking real tokens versus padding.
Fixed-Size Block Packing with a Mask
A training pipeline feeds token sequences of different lengths to a model. To avoid wasting compute on padding, the sequences are joined end to end and cut into blocks that all have the same length.
Write a function that takes a list of token sequences and a block length, and returns the packed blocks together with a mask for each block.
Rules
- Process the sequences in the given order.
- Skip any empty sequence.
- If a sequence has more than
block_lentokens, keep only its firstblock_lentokens and discard the rest. This truncation is applied to each sequence individually, before it is joined to the stream. - Append the remaining tokens, in order, to one continuous stream. A block is filled completely before the next block is started. A sequence is not kept whole: if it does not fit in the space left in the current block, its tokens continue at the start of the next block.
- Every block has exactly
block_lenentries. If the final block is not full once all tokens have been placed, fill the rest of it with the padding value0. - Never produce a block that consists only of padding. If there are no tokens at all, there are no blocks.
- For each block, produce a mask of the same length:
1at positions holding a real token and0at padding positions. The mask depends on position only, not on token value, so a real token whose value is0still gets mask1.
Input
sequences: a list of lists of integers.block_len: a positive integer, the length of every block.
Output
Return a two-element list [blocks, masks], where:
blocksis a list of blocks, each a list ofblock_lenintegers.masksis a list of masks, each a list ofblock_lenvalues from{0, 1}, withmasks[i]describingblocks[i].
If nothing is packed, return [[], []].
Constraints
block_len >= 1- Each sequence is a (possibly empty) list of integers.
- Token order must be preserved exactly.
- The return value must be a list (not a tuple) of two lists.
Examples
Example 1
Input: pack_into_blocks([[1, 2], [3, 4, 5], [6]], 4)
Output: [[[1, 2, 3, 4], [5, 6, 0, 0]], [[1, 1, 1, 1], [1, 1, 0, 0]]]
Example 2
Input: pack_into_blocks([[1, 2, 3, 4, 5]], 3)
Output: [[[1, 2, 3]], [[1, 1, 1]]]
Example 3
Input: pack_into_blocks([[], [7], [], [8, 9]], 4)
Output: [[[7, 8, 9, 0]], [[1, 1, 1, 0]]]
Hints
Hint 1
Think of the input as one long stream of tokens that you pour into a buffer of size block_len, rather than as items you must keep together.
Hint 2
Truncate each sequence to its first block_len tokens before streaming it. Skip empty ones.
Hint 3
Build the mask in step with the tokens (append 1 for each real token) instead of deriving it from token != 0. When the final buffer is non-empty, pad both the tokens and the mask with zeros.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the input as a single stream of tokens and fill one block at a time.
- For each sequence, skip it if it is empty; otherwise take only its first
block_lentokens. - Append each kept token to a current buffer, and append
1to a parallel mask buffer. - Before appending a token, check whether the buffer already has
block_lenentries. If so, save the buffer and its mask as a finished block and start new empty buffers. - After all sequences are processed, if the buffer is non-empty, extend both the tokens and the mask with
0until they reachblock_len, then save them.
Closing a block only when the next token arrives (rather than right after it fills) guarantees that no empty or all-padding block is ever created, including when the total token count is an exact multiple of block_len.
Why it is correct
- Block length: a block is saved mid-stream only when it holds exactly
block_lenentries, and the last one is padded to that length. - Order: tokens are appended in input order and blocks are saved in creation order.
- Mask: each real token gets a
1at the moment it is placed, and only the tail padding gets0. Because the mask is built by position, a genuine token with value0is still marked1. - Truncation: slicing with
seq[:block_len]limits each sequence's contribution. Such a sequence can still straddle two blocks if the current block was partly filled.
Complexity
Let T be the total number of kept tokens, sum(min(len(s), block_len)).
- Time: O(T + block_len), since each token is handled once and the final padding costs at most
block_len. - Space: O(T + block_len) for the output; extra working space is O(block_len).
Reference solution
from typing import List
def pack_into_blocks(sequences: List[List[int]], block_len: int) -> List[List[List[int]]]:
blocks = []
masks = []
current = []
current_mask = []
for seq in sequences:
if not seq:
continue
for token in seq[:block_len]:
if len(current) == block_len:
blocks.append(current)
masks.append(current_mask)
current = []
current_mask = []
current.append(token)
current_mask.append(1)
if current:
pad = block_len - len(current)
current.extend([0] * pad)
current_mask.extend([0] * pad)
blocks.append(current)
masks.append(current_mask)
return [blocks, masks]