Pick the last real hidden state of each sequence

Why it matters Sentence embeddings from decoder models often use the last real token, and padding bugs here are common.

With padded batches, the final hidden state you want is at each sequence's own last real step, not at the last column.

Write last_hidden(H, lengths). H is (batch, time, d), lengths is (batch,) with values >= 1. Return the (batch, d) array H[b, lengths[b] - 1].

Signaturedef last_hidden(H, lengths)

Example

H with lengths [1, 3] returns H[0, 0] and H[1, 2].

Understand the idea

When sequences of different lengths are batched, shorter ones are padded at the end. If you want the RNN or encoder state at the end of each sequence, you must pick each row's own last real time step, not the final column, which is padding for short rows. Worked example: H has shape (2, 4, d) and lengths = [2, 4]. For row 0 the last real step is index 2 - 1 = 1, so you take H[0, 1]. For row 1 it is index 3, so you take H[1, 3]. The result has shape (2, d). Taking H[:, -1] would wrongly give H[0, 3], a padding step, for row 0. Rule: out[b] = H[b, lengths[b] - 1] for every batch row b. In NumPy, do this in one shot with advanced indexing, pairing an array of batch indices 0 to B - 1 with the array lengths - 1. lengths are at least 1, so the index is never negative. Used in: sentence classification with RNNs, pooling the last token of a causal LLM to get a sequence embedding or a reward model score.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplelast_hidden(_H, [1, 3])
  • Sample 2: full lengthslast_hidden(_H, [3, 3])
  • Test 3: shapelist(last_hidden(np.zeros((4, 5, 2)), [1, 2, 3, 5]).shape)