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
sft_labels([5, 6, 7, 8, 0], 2, 0) is [-100, -100, 7, 8, -100].
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. Worked example: 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]. Rule: 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.