Pad variable-length token lists into a batch with a mask
Sequences in a batch have different lengths, but a model wants one rectangular array.
Write pad_batch(seqs, pad_id=0). seqs is a list of lists of ints. Return a tuple (ids, mask): ids is an int array of shape (len(seqs), max_len) with each sequence left-aligned and filled with pad_id, mask is an int array of the same shape with 1 for real tokens and 0 for padding. If seqs is empty, return two arrays of shape (0, 0).
def pad_batch(seqs, pad_id=0)Example
pad_batch([[5, 6], [7]]) gives ids [[5, 6], [7, 0]] and mask [[1, 1], [1, 0]].
Understand the idea
Token sequences in a batch have different lengths, but a model needs one rectangular array. So shorter sequences are padded at the end with a pad id, and a mask records which positions are real (1) and which are padding (0). Later layers use the mask to ignore padding in attention and in the loss. Worked example: seqs = [[3], [4, 5, 6]], pad_id 0. max_len = 3. ids = [[3, 0, 0], [4, 5, 6]]. mask = [[1, 0, 0], [1, 1, 1]]. Rule: max_len = longest sequence; ids starts filled with pad_id at shape (batch, max_len), and each sequence is copied in from the left; mask[i, j] = 1 when j < len(seqs[i]), which you can build by comparing a row of positions 0 to max_len - 1 with a column of lengths; both arrays are int. An empty list returns two (0, 0) arrays. Note pad_id can be any value, so never build the mask by checking ids != pad_id: a real token could equal the pad id. Right-padding with a mask is the standard layout for training batches in transformer data loaders.