Write an SFT collate function that shifts, pads and masks labels

MediumFine-tuningPro

Why it matters Every SFT pipeline has a collate step like this, and off-by-one masking bugs here are common and hard to spot.

A supervised fine-tuning batch needs inputs, next-token labels and an attention mask, with the prompt and padding excluded from the loss.

Write collate(pairs, pad_id, eos_id, ignore=-100). pairs is a list of (prompt_ids, response_ids). For each pair, seq = prompt + response + [eos_id]; inputs = seq[:-1] and labels = seq[1:]. Label position j predicts seq[j + 1]; set it to ignore when seq[j + 1] is still part of the prompt, that is j < len(prompt) - 1. Right-pad inputs with pad_id and labels with ignore to the longest inputs length in the batch. Return (input_ids, labels, attn_mask) as int arrays, where attn_mask is 1 on real input tokens and 0 on padding.

Signaturedef collate(pairs, pad_id, eos_id, ignore=-100)

Example

collate([([5, 6], [7]), ([4], [3])], 0, 2) gives input_ids [[5, 6, 7], [4, 3, 0]], labels [[-100, 7, 2], [3, 2, -100]] and attn_mask [[1, 1, 1], [1, 1, 0]].

Understand the idea

In supervised fine-tuning the model reads the prompt and the answer, but it is graded only on the answer, like an exam where the question is printed but only your answers get marks.

Take prompt [5, 6], response [7], EOS 2. The full sequence is 5 6 7 2. Inputs drop the last token: 5 6 7. Labels drop the first: 6 7 2. Label 0 (target 6) is a prompt token, so it becomes -100. Label 1 (target 7) is the first answer token, predicted while reading the last prompt token, so it stays. Label 2 (EOS) stays too.

Rule: labels[j] = seq[j + 1], masked when j < len(prompt) - 1; pad inputs with pad_id, labels with -100, attention mask 1 on real inputs.

Cross-entropy implementations skip label -100, so prompt and padding contribute nothing. Getting the boundary one position off either leaks prompt tokens into the loss or hides the first answer token.

Shapes and data flow

pairs -> per row seq (n_i,) -> inputs, labels (n_i - 1,) -> padded (B, L) each, plus attn_mask (B, L)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplecollate([([5, 6], [7]), ([4], [3])], 0, 2)
  • Sample 2: long promptcollate([([1, 2, 3, 4], [9, 9]), ([8], [7, 6, 5])], 0, 2)