502. Mask prompt tokens out of the SFT loss
Why it matters Every chat SFT recipe (TRL, Axolotl) masks the prompt like this.
In supervised fine-tuning, the model should be graded only on the response, not on the prompt.
Write sft_labels(input_ids, prompt_len, pad_id, ignore_id=-100). Return a copy of input_ids where the first prompt_len positions and every pad_id position are set to ignore_id.
def sft_labels(input_ids, prompt_len, pad_id, ignore_id=-100)Example 1
Input: sft_labels([5, 6, 7, 8, 0], 2, 0)
Output: [-100, -100, 7, 8, -100]
Example 2
Input: input_ids = [1, 2, 3], prompt_len = 0, pad_id = 9
Output: [1, 2, 3]
Example 3
Input: input_ids = [4, 4, 4, 2, 2], prompt_len = 1, pad_id = 2
Output: [-100, 4, 4, -100, -100]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
Copy, then two masked assignments.
Hint 2
Copy the ids first.
Hint 3
Mask the prompt prefix and the pads.
Common mistakes
- Training on padding.
- Editing the input array in place.
Understand the idea
In supervised fine-tuning you want the model to learn to write good answers, not to memorise the question. So the labels copy the input ids, but every prompt position and every padding position is replaced by -100, a special value cross-entropy skips. The model still reads the prompt as input; it is just not graded on it.
input_ids [11, 12, 13, 14, 15, 0, 0], prompt_len 3, pad_id 0. The first 3 positions become -100, the response tokens 14 and 15 stay, and the two pads become -100. Labels: [-100, -100, -100, 14, 15, -100, -100].
labels = copy of input_ids; labels[:prompt_len] = ignore_id; labels[labels == pad_id] = ignore_id
Apply the pad check on the original ids, and never change input_ids in place. Forgetting the pads teaches the model to emit padding. Note that if the pad id is also used as a real token, such as EOS, you would need a separate attention mask; here every pad_id is treated as padding. Used in: chat and instruction tuning for LLMs.