10. 选取每个位置正确 token 的 log-probability
语言模型损失函数在每个位置需要一个数值:即模型为实际出现的下一个 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) 对使用的索引都不同。
一个长度为 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。