Pack unequal-length token sequences into one rectangular array while distinguishing real tokens from padding.
Problem
Input. A finite collection sequences of integer sequences and an integer pad_value, defaulting to zero.
Output. Return (tokens, mask): an integer array and an equally shaped Boolean validity array.
Each row represents one sequence; the width is the longest sequence length.
Rules. Preserve token order, align sequences on the left, and pad on the right without truncation.
The mask is True exactly where a token came from input, even if its value equals pad_value.
Preserve inputs. Empty sequences form padded rows; an empty collection returns arrays shaped (0, 0).
Example. With sequences [[3, 4], [], [9]] and padding zero, tokens are [[3, 4], [0, 0], [9, 0]].
The mask is [[True, True], [False, False], [True, False]].
Picture
Lengths 2, 0, 1 require a 3 × 2 rectangle.
Initialize tokens to zero and validity to false; copy each row and mark the identical half-open slice.
Problem trace
Separate real-zero case: length, not pad value, determines validity
Reference drawing
Problem trace
The mask distinguishes real zeros from zero-valued padding
Execution trace
- fill cursor
- (0, 0)
- input
- sequences=[[3,0],[],[9]], pad_value=0
- lengths
- [2,0,1]
- shapes
- not shown→tokens (3,2); mask (3,2)
- lengths
- [2,0,1]→not shown
- arithmetic
- max(2,0,1) = 2→not shown
- fill cursor
- (0, 0)→(0, 1)
- assignment
- not shown→tokens[0,:2]=[3,0]; mask[0,:2]=True
- shapes
- tokens (3,2); mask (3,2)→not shown
- fill cursor
- (0, 1)→(1, 0)
- assignment
- tokens[0,:2]=[3,0]; mask[0,:2]=True→tokens[1,:0]=[]; mask[1,:0]=True
- decision
- not shown→empty slice changes nothing
- fill cursor
- (1, 0)→(2, 0)
- assignment
- tokens[1,:0]=[]; mask[1,:0]=True→tokens[2,:1]=[9]; mask[2,:1]=True
- decision
- empty slice changes nothing→not shown
- fill cursor
- (2, 0)→(2, 1)
- tokens
- not shown→[[3,0],[0,0],[9,0]]
- mask
- not shown→[[T,T],[F,F],[T,F]]
- Recognize it
- Use padding plus a mask when variable-length sequences must enter rectangular tensor operations without treating synthetic pad cells as data.
- Keep true
- After processing row r, tokens[r,:len(sequence)] equals the original sequence and mask is true on exactly that slice; every remaining cell retains the pad value and false mask.
- Reuse it
- For ragged-to-dense conversion, derive one shared extent, initialize safe defaults, and update data and validity metadata with the exact same slices.
The result is [[3, 4], [0, 0], [9, 0]], with mask [[True, True], [False, False], [True, False]].
After each row, only its copied positions are valid; untouched cells remain padding.
Code
Keep token and mask slices aligned, including the empty slice :0.
from collections.abc import Sequence
import numpy as np
def pad_sequences(
sequences: Sequence[Sequence[int]], pad_value: int = 0
) -> tuple[np.ndarray, np.ndarray]:
width = max((len(sequence) for sequence in sequences), default=0)
tokens = np.full((len(sequences), width), pad_value, dtype=int)
mask = np.zeros((len(sequences), width), dtype=bool)
for row, sequence in enumerate(sequences):
tokens[row, : len(sequence)] = sequence
mask[row, : len(sequence)] = True
return tokens, mask
For batch size and width , time is and output storage is .
Change alignment or width
1. Left-pad
New task: align sequence endings at the right edge.
Picture and change: start at width - length; move data and validity together.
def left_pad_sequences(sequences, pad_value=0):
width = max(map(len, sequences), default=0)
tokens = np.full((len(sequences), width), pad_value, dtype=int)
mask = np.zeros((len(sequences), width), dtype=bool)
for row, sequence in enumerate(sequences):
start = width - len(sequence)
tokens[row, start:width] = sequence
mask[row, start:width] = True
return tokens, mask
Check: [9] becomes [0, 9], with mask [False, True].
An empty row remains invalid throughout; avoid the misleading slice -0:.
Use when: the consumer requires right-aligned endings.
2. Fix width and report truncation
New task: retain each sequence’s prefix within a requested width.
Picture and change: copy at most width positions and report information loss per row.
def pad_fixed_width(sequences, width, pad_value=0):
if width < 0:
raise ValueError("negative width")
tokens = np.full((len(sequences), width), pad_value, dtype=int)
mask = np.zeros((len(sequences), width), dtype=bool)
truncated = []
for row, sequence in enumerate(sequences):
length = min(width, len(sequence))
tokens[row, :length] = sequence[:length]
mask[row, :length] = True
truncated.append(len(sequence) > width)
return tokens, mask, truncated
Check: [[3, 4, 5], []] at width 2 reports [True, False].
Width zero still reports truncation of nonempty inputs.
Use when: a hard width is part of the caller contract.
Failure and transfer
Why cannot tokens != pad_value recover validity?
Check your answer
Input [[0], []] produces two zero cells, but masks [True] and [False].
Only original lengths identify which zero was copied.
Consumer contracts
No input rows produce shape (0, 0); two empty rows produce (2, 0).
Do not collapse batch cardinality because width is zero.
Inputs must be nested integer sequences within NumPy’s machine-integer range. This reference casts values; it does not validate a general token schema. Fixed width must be a nonnegative integer.
Some attention APIs use True for blocked positions, unlike this validity mask.
Coordinate mask polarity, position IDs and padding conventions with the consumer.
Changing padding side alone does not settle those contracts.