When fine-tuning a decoder-only language model for sequence classification, a common technique is to attach a classification head and read out the logits at the position of the last non-padding token in each sequence. This is more flexible than always reading from the final position (which would be a pad token for shorter sequences in a right-padded batch) and is more efficient than running with batch size 1.
Implement a function gather_last_token_logits(logits, input_ids, pad_token_id) that, for each sequence in the batch, gathers the logit vector at the index of the last non-padding token.
Inputs:
logits: a NumPy array of shape (B, T, V) containing the per-position logits from the model.input_ids: a NumPy array of shape (B, T) of integer token ids.pad_token_id: an integer specifying which token id represents padding.Output:
(B, V) where row b equals logits[b, last_b, :] and last_b is the largest index t such that input_ids[b, t] != pad_token_id.Edge cases:
input_ids is entirely padding, use index 0 for that row.