Data & Features ยท Easy
Sequence Padding
Pad or truncate variable-length token sequences and build attention masks.
Task
Implement sequence_padding(sequences: list[list[int]], max_length: int, padding_value: int, padding_side: str, truncation_side: str) -> tuple[list[list[int]], list[list[int]]]. Convert variable-length token sequences into fixed-width rows and return an attention mask that distinguishes retained tokens from padding.
Requirements
- max_length is a non-negative integer.
- padding_side and truncation_side are each either "left" or "right".
- When a sequence is longer than max_length, right truncation keeps its prefix and left truncation keeps its suffix.
- When a retained sequence is shorter than max_length, add padding_value on the requested padding side.
- Return one mask row per output row, using 1 for retained input tokens and 0 for padding positions.
- A retained token equal to padding_value still receives mask value 1.
- Every output value row and mask row must have exactly max_length entries.
- Preserve sequence order and do not mutate the input sequences.
- Return two empty outer lists when sequences is empty.
Example
sequence_padding(
[[11, 12, 13], [21]],
2,
0,
"right",
"right",
)
# ([[11, 12], [21, 0]], [[1, 1], [1, 0]])