BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / NumPy foundations18 of 23 in topic

18. 使用 mask 将变长 token 列表填充为 batch

MediumNumPy foundations

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。

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]].

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 的标准布局。
主题
NumPy foundations
相似题目
  • 在填充的 batch 中仅对真实 token 求平均Medium
  • 将 token 序列切割为重叠的固定大小窗口Medium
  • 使用前缀和在常数时间内回答多个区间和查询Medium
  • 使用 searchsorted 和计数 padding 将序列分配到长度桶中Medium
所有 NumPy foundations 道题目
反馈
18 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def pad_batch(seqs, pad_id=0):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 3 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS