Pad & Truncate Token Sequence to Fixed Length

Basics
BasicsBatchingTokenizationOpenAIAnthropicGoogle

Problem

Implement pad_or_truncate(ids, max_len, pad_id=0) so sequences longer than max_len are truncated on the right (ids[:max_len]), and sequences shorter than max_len are right-padded with pad_id to exact length max_len.

Why It Matters: GPUs require rectangular (batch_size, max_len) tensors; every batched Transformer forward pass pads short prompts and truncates overly long sequences to a uniform window.

Function Signature

def pad_or_truncate(ids: list[int], max_len: int, pad_id: int = 0) -> list[int]:
    """Right-truncate or right-pad token IDs to exact length max_len."""

Sample Input & Output

Example 1: Right-Padding a Short Sequence

Input:

ids = [4, 7], max_len = 5, pad_id = 0

Expected Output:

[4, 7, 0, 0, 0]

Explanation: Length 2 < 5, so three 0s are appended on the right.

Example 2: Truncating a Long Sequence

Input:

ids = [4, 7, 9, 2, 8], max_len = 3, pad_id = 0

Expected Output:

[4, 7, 9]

Explanation: Length 5 > 3, so only the first 3 token IDs are kept.

Example 3: Custom pad_id on Empty Input

Input:

ids = [], max_len = 3, pad_id = -1

Expected Output:

[-1, -1, -1]

Explanation: An empty sequence is padded to max_len copies of pad_id.

Constraints & Edge Cases

  • Do not mutate the input list.
  • Return a list of exact length max_len.
  • Do not mutate the original ids list in place.
  • Always returns a list of length max_len.

Constraints & Evaluation Criteria

  • Do not mutate the input list.
  • Return a list of exact length `max_len`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[5, 8], max_len=4
Expected Output / Criteria
[5, 8, 0, 0]