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

10. 选取每个位置正确 token 的 log-probability

EasyNumPy foundations

语言模型损失函数在每个位置需要一个数值:即模型为实际出现的下一个 token 所给出的 log-probability。

编写 gather_logprobs(logprobs, targets)。logprobs 的形状为 (batch, seq, vocab),targets 的形状为 (batch, seq),包含整数 token ids。返回一个 (batch, seq) 的 float 数组,其中 out[b, t] = logprobs[b, t, targets[b, t]]。禁止使用 Python 循环。

函数def gather_logprobs(logprobs, targets)

示例 1

输入: logprobs [[[-1, -2], [-3, -4]]] with targets [[1, 0]]

输出: [[-2, -3]]

约束条件

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

For each (b, t) you only need one entry along the vocab axis, picked by the target id, so this is a gather along the last axis.

提示 2

Give targets an extra trailing axis so it has the same number of dimensions as logprobs, then use np.take_along_axis along axis -1.

提示 3

np.take_along_axis(lp, t[..., None], axis=-1) returns shape (batch, seq, 1), so index with [..., 0] to drop that last axis and cast targets to int first.

常见错误
  • 错误的版本在每个位置都使用了同一个 token id,导致大部分行读取了错误的概率。
理解思路

语言模型在每个位置都会为词表中的每个 token 输出一个 log-probability。损失函数在每个位置只需要其中一个:即实际出现的下一个 token 的 log-probability。这本质上是在最后一个维度上进行 gather 操作,且每个 (batch, position) 对使用的索引都不同。

Worked example

一个长度为 2 的序列的 logprobs:position 0 = [-0.1, -2.3], position 1 = [-1.2, -0.4]。targets = [[0, 1]]。Position 0 选取 index 0,得到 -0.1。Position 1 选取 index 1,得到 -0.4。输出 [[-0.1, -0.4]]。

out[b, t] = logprobs[b, t, targets[b, t]]。在 NumPy 中,为 targets 添加一个末尾维度使其形状变为 (batch, seq, 1),沿最后一个维度进行 gather,然后再次去掉该维度。如果每个位置都使用同一个 token id,则会读取错误的概率。将此输出取负并求平均,即可得到用于训练和评估所有 LLM 的常规 next-token cross-entropy loss,同时也能得到用于计算 perplexity 的 per-token scores。
主题
NumPy foundations
相似题目
  • 不使用 Python 循环计算所有成对距离Easy
  • 使用 fancy indexing 进行类别标签的 one-hot 编码Easy
  • 对排行榜分数进行排名,使并列分数共享名次Easy
  • 使用 argsort 的逆排列撤销长度排序Easy
所有 NumPy foundations 道题目
反馈
10 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def gather_logprobs(logprobs, targets):
# your code here
pass
​

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

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