Fine-tune a classifier on the last real token's hidden state

Why it matters Sequence classification and reward models built on decoder LLMs read the last non-padding token exactly like this.

Decoder-only LLMs can be turned into classifiers: take the hidden state of the last real token (which has seen the whole input under causal attention) and put a linear head on it.

Write last_token_cls(hidden, attn_mask, W, b, labels). hidden is (B, T, d), attn_mask is (B, T) with right padding (1s then 0s, at least one 1 per row), W is (d, C), b is (C,), labels has length B. Pick feats[i] = hidden[i, last_i] where last_i = (number of 1s in row i) - 1. logits = feats @ W + b; loss = mean cross-entropy over the batch (stable). Return (logits, loss, dW, db), the gradients of the loss with respect to W and b.

Signaturedef last_token_cls(hidden, attn_mask, W, b, labels)

Example

hidden = [[[1], [2]], [[3], [0]]], attn_mask = [[1, 1], [1, 0]], W = [[1, -1]], b = [0, 0], labels = [0, 1] gives logits [[2, -2], [3, -3]], loss 3.0103, dW [[1.4783, -1.4783]] and db [0.4898, -0.4898].

Understand the idea

With causal attention, token t only sees tokens 0..t. So the only position that has read the whole input is the last real token. To classify a sentence with a GPT-style model, you read the hidden state there, like asking the last person in a line who has heard everyone before them.

Example: row 0 has 2 real tokens, so read position 1, hidden [2]. Row 1 has 1 real token plus padding, so read position 0, hidden [3], not the padded position. With W = [[1, -1]], logits are [2, -2] and [3, -3]. Row 0's label 0 is likely (loss 0.018), row 1's label 1 is badly wrong (loss 6.002), mean 3.010.

Rule: last_i = sum(mask_i) - 1; logits = hidden[i, last_i] W + b; dW = feats^T (p - onehot) / B.

Hugging Face style sequence-classification heads on decoder models and most LLM reward models use this last-token pooling, so padding side matters.

Shapes and data flow

hidden (B, T, d) -> feats (B, d) -> logits (B, C); dW (d, C), db (C,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplelast_token_cls([[[1.0], [2.0]], [[3.0], [0.0]]], [[1, 1], [1, 0]], [[1.0, -1.0]], [0.0, 0.0], [0, 1])
  • Sample 2: randomlast_token_cls(H, M, Wc, bc, [2, 0, 1])