18. 使用 mask 将变长 token 列表填充为 batch
Batch 中的序列长度不同,但模型需要一个矩形数组。
编写 pad_batch(seqs, pad_id=0)。seqs 是一个 int 类型的嵌套列表。返回一个元组 (ids, mask):ids 是一个 shape 为 (len(seqs), max_len) 的 int 数组,每个序列左对齐并用 pad_id 填充;mask 是一个 shape 相同的 int 数组,真实 token 处为 1,padding 处为 0。如果 seqs 为空,返回两个 shape 为 (0, 0) 的数组。
def pad_batch(seqs, pad_id=0)示例 1
输入: pad_batch([[5, 6], [7]])
输出: ids [[5, 6], [7, 0]] and mask [[1, 1], [1, 0]]
示例 2
输入: seqs = [[1], [2, 3, 4], []], pad_id = -1
输出: ([[1, -1, -1], [2, 3, 4], [-1, -1, -1]], [[1, 0, 0], [1, 1, 1], [0, 0, 0]])
示例 3
输入: [a.shape for a in pad_batch([])]
输出: [(0, 0), (0, 0)]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
Find the longest sequence first: it sets the width of both output arrays.
提示 2
Compute each length, create an np.full((n, max_len), pad_id) int array, copy each sequence into the start of its row, then build the mask from the lengths.
提示 3
The mask is np.arange(max_len)[None, :] < lens[:, None] cast to int, and remember the empty input case must return two (0, 0) arrays before you call max.
常见错误
- 有 Bug 的版本将 token 右对齐了,这破坏了 mask 所描述的左对齐布局。
理解思路
Batch 中的 token 序列长度不同,但模型需要一个矩形数组。因此,较短的序列会在末尾使用 pad id 进行填充,并使用 mask 记录哪些位置是真实的 (1),哪些是 padding (0)。后续层会利用 mask 在 attention 和 loss 中忽略 padding。
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]].
max_len = 最长序列的长度;ids 初始化为填充了 pad_id 且 shape 为 (batch, max_len) 的数组,然后将每个序列从左侧开始复制;当 j < len(seqs[i]) 时,mask[i, j] = 1,你可以通过将 0 到 max_len - 1 的位置行与长度列进行比较来构建;两个数组均为 int 类型。空列表返回两个 (0, 0) 数组。注意 pad_id 可以是任何值,因此永远不要通过检查 ids != pad_id 来构建 mask:真实的 token 可能会等于 pad id。在 transformer data loader 中,带 mask 的右填充是训练 batch 的标准布局。