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

4. 使用 argsort 的逆排列撤销长度排序

EasyNumPy foundations

重要性 按长度排序的 batching 在训练和推理服务中非常常用,每个排序后的 batch 在结果返回给用户之前都必须进行反排序。

推理服务器通常按长度对 batch 进行排序以减少 padding,运行模型后,必须将输出按请求进入的原始顺序放回。实现这一目标的工具是逆排列 (inverse permutation)。

编写 restore_order(x_sorted, order)。order 是对原始 batch 执行 np.argsort 返回的 int 数组(因此排序后的 batch 为 original[order])。x_sorted 的 shape 为 (B,) 或 (B, ...) 且按排序顺序持有输出。返回原始顺序的输出,保持相同的 shape,使得 result[order[i]] == x_sorted[i]。

函数def restore_order(x_sorted, order)

示例 1

输入: restore_order([10, 20, 30], [2, 0, 1])

输出: [20, 30, 10]

示例 2

输入: x_sorted = np.arange(8).reshape(4, 2), order = [1, 3, 0, 2]

输出: [[4, 5], [0, 1], [6, 7], [2, 3]]

示例 3

输入: x_sorted = [5, 6], order = [0, 1]

输出: [5, 6]

约束条件

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 4 tests to be accepted.
提示 1

np.argsort(order) 是逆排列;使用它对 x_sorted 进行索引。

提示 2

使用 order 进行索引是排序;你需要的是能将其逆转的操作。

提示 3

result[order] = x_sorted 是其中一种有效方法。

提示 4

np.argsort(order) 直接给出了逆排列。

常见错误
  • 再次使用 order 进行索引。
  • 按数值对输出进行排序,这会丢失与请求之间的关联。
理解思路

排列 (permutation) 是一种重新排序。如果 order = argsort(lengths),那么 lengths[order] 是有序的:排序后 batch 的位置 i 来自原始 batch 的位置 order[i]。要返回原始顺序,你需要逆排列 inv,它指明了每个原始项被移动到了哪里。

Worked example

order = [2, 0, 1]。排序后的第 0 项来自原始的 2,第 1 项来自原始的 0,第 2 项来自原始的 1。若 x_sorted = [10, 20, 30],则原始位置 2 得到 10,位置 0 得到 20,位置 1 得到 30,因此结果是 [20, 30, 10]。argsort([2, 0, 1]) = [1, 2, 0],且 x_sorted[[1, 2, 0]] = [20, 30, 10]。

inv = argsort(order), original = x_sorted[inv]。等价于 result[order] = x_sorted。

LLM 服务器中的动态 batching 和分桶训练加载器 (bucketed training loaders) 都利用这一点来按请求顺序返回结果。

Shape 与数据流
order (B,), x_sorted (B, ...) -> result (B, ...)
主题
NumPy foundations
相似题目
  • 不使用 Python 循环计算所有成对距离Easy
  • 使用 fancy indexing 进行类别标签的 one-hot 编码Easy
  • 对排行榜分数进行排名,使并列分数共享名次Easy
  • 使用 np.unique 将稀疏 token ids 映射到紧凑的词表Easy
所有 NumPy foundations 道题目
反馈
4 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def restore_order(x_sorted, order):
# your code here
pass
​

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

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