Pick the log-probability of the correct token at every position
Language model losses need one number per position: the log-probability the model gave to the token that actually came next.
Write gather_logprobs(logprobs, targets). logprobs has shape (batch, seq, vocab), targets has shape (batch, seq) with integer token ids. Return a (batch, seq) float array where out[b, t] = logprobs[b, t, targets[b, t]]. No Python loops.
def gather_logprobs(logprobs, targets)Example
logprobs [[[-1, -2], [-3, -4]]] with targets [[1, 0]] gives [[-2, -3]].
Understand the idea
A language model outputs a log-probability for every vocabulary token at every position. The loss only needs one of them per position: the log-probability of the token that actually came next. That is a gather along the last axis, using a different index at each (batch, position) pair. Worked example: logprobs for one sequence of two positions: position 0 = [-0.1, -2.3], position 1 = [-1.2, -0.4]. targets = [[0, 1]]. Position 0 picks index 0, giving -0.1. Position 1 picks index 1, giving -0.4. Output [[-0.1, -0.4]]. Rule: out[b, t] = logprobs[b, t, targets[b, t]]. In NumPy, add a trailing axis to targets so it has shape (batch, seq, 1), gather along the last axis, then drop that axis again. Using one token id for every position reads the wrong probabilities. Negating and averaging this output gives the usual next-token cross-entropy loss used to train and evaluate every LLM, and it also gives per-token scores for perplexity.