TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Supervised Fine-Tuning (SFT) and Loss Masking

Supervised Fine-Tuning (SFT) and Loss Masking

A pretrained language model continues text; it does not answer. Asked "What is the capital of France?", a base model may well continue with "What is the capital of Spain?", because lists of questions are common on the web. Supervised fine-tuning (SFT) turns it into a model that responds: it keeps training with the same next-token loss, but on (prompt, response) pairs, and usually scores only the response. Training: Pretraining, Fine-tuning, RLHF placed SFT in the pipeline; this lesson is about the mechanics that decide whether an SFT run works: the data format, which tokens carry a loss, the end-of-sequence token and packing.

There is no pretrained generative LLM in this course's offline environment, so the recorded example trains a tiny decoder from scratch on an SFT data set. The mechanics are exactly those of fine-tuning a 7B model, but there is no pretraining underneath: the tiny model learns its task from the SFT data alone.

The data format

An SFT example is a prompt and the desired response. Real data sets store them as fields ({"prompt": ..., "completion": ...}) or as a list of chat messages, which a chat template renders into one string. Either way, training sees one token sequence:

x=(p1,…,pm⏟prompt,r1,…,rn,⟨eos⟩⏟response)\mathbf{x} = (\underbrace{p_1, \dots, p_m}_{\text{prompt}}, \underbrace{r_1, \dots, r_n, \langle \text{eos} \rangle}_{\text{response}})

and the loss is the usual causal language-modelling loss, restricted to the response:

L=−1n+1∑t=1n+1log⁡pθ(rt∣p1..m,r<t),rn+1=⟨eos⟩L = -\frac{1}{n + 1} \sum_{t=1}^{n+1} \log p_\theta(r_t \mid p_{1..m}, r_{<t}), \qquad r_{n+1} = \langle \text{eos} \rangle

In code that restriction is a label mask: the labels are the input shifted by one, and every position whose target belongs to the prompt gets −100-100, the ignore_index of PyTorch's cross-entropy. Those positions still go through the model (the response needs to attend to the prompt), they just add nothing to the loss or the gradient.

input label position a -100 0 b -100 1 c -100 2 > c 3 c b 4 b a 5 a . 6 . -100 7 prompt: a b c > response: c b a, then EOS "." label at t = input at t + 1; red = ignored, green = scored

The task in the figure is "reverse the word": the prompt is a word followed by >, the response is the reversed word followed by ., which plays the role of the end-of-sequence token. Position 3 (>) is the first scored one: having read the whole prompt, the model must produce the first letter of the answer.

From scratch: labels, masked loss and packing

The code builds the labels of the figure, computes the masked loss from a made-up logits matrix, and then packs two examples into one row. Packing fills each training row with several short examples instead of padding them, which saves the compute that padding wastes. Done carefully, each example still sees only itself: the attention mask becomes block-diagonal and the position ids restart.

python · try it yourself
import numpy as np
VOCAB = "_abcdefghijklmnopqrstuvwxyz>."
stoi = {c: i for i, c in enumerate(VOCAB)}

def sft_example(prompt, response):
    """Token ids and next-token labels; prompt positions get -100 so only the response is scored."""
    ids = [stoi[c] for c in prompt + response]
    labels = ids[1:] + [-100]                      # position t predicts token t + 1
    labels[: len(prompt) - 1] = [-100] * (len(prompt) - 1)
    return ids, labels

ids, labels = sft_example("abc>", "cba.")
print("tokens:", list("abc>cba."))
print("ids:   ", ids)
print("labels:", labels)

def masked_ce(logits, labels):
    labels = np.array(labels)
    keep = labels != -100
    z = logits[keep] - logits[keep].max(1, keepdims=True)
    logp = z - np.log(np.exp(z).sum(1, keepdims=True))
    return float(-logp[np.arange(keep.sum()), labels[keep]].mean()), int(keep.sum())

rng = np.random.default_rng(0)
logits = rng.normal(size=(len(ids), len(VOCAB)))   # an untrained model's scores
print("masked loss over %d response targets: %.3f | uniform guess: ln %d = %.3f" % (*masked_ce(logits, labels)[::-1], len(VOCAB), np.log(len(VOCAB))))

# packing: two examples in one row, separated by EOS, with a block-diagonal causal mask
a, b = sft_example("ab>", "ba."), sft_example("xyz>", "zyx.")
packed_ids, packed_labels = a[0] + b[0], a[1] + b[1]
doc = np.array([0] * len(a[0]) + [1] * len(b[0]))
pos = np.concatenate([np.arange(len(a[0])), np.arange(len(b[0]))])   # positions restart for each example
T = len(packed_ids)
mask = (np.tril(np.ones((T, T), dtype=int)) * (doc[:, None] == doc[None, :])).astype(int)
print("packed:", "".join(VOCAB[i] for i in packed_ids), "| labels:", packed_labels)
print("position ids:", pos.tolist())
print("attention mask (row = query):")
for c, row in zip(packed_ids, mask):
    print(" ", VOCAB[c], "".join(map(str, row)))
print("scored targets:", sum(l != -100 for l in packed_labels), "of", T, "positions")
tokens: ['a', 'b', 'c', '>', 'c', 'b', 'a', '.']
ids:    [1, 2, 3, 27, 3, 2, 1, 28]
labels: [-100, -100, -100, 3, 2, 1, 28, -100]
masked loss over 4 response targets: 4.448 | uniform guess: ln 29 = 3.367
packed: ab>ba.xyz>zyx. | labels: [-100, -100, 2, 1, 28, -100, -100, -100, -100, 26, 25, 24, 28, -100]
position ids: [0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 7]
attention mask (row = query):
  a 10000000000000
  b 11000000000000
  > 11100000000000
  b 11110000000000
  a 11111000000000
  . 11111100000000
  x 00000010000000
  y 00000011000000
  z 00000011100000
  > 00000011110000
  z 00000011111000
  y 00000011111100
  x 00000011111110
  . 00000011111111
scored targets: 7 of 14 positions

Of the 8 positions only 4 are scored: the three that would predict prompt letters, and the last one (after the EOS there is nothing to predict). The random logits give a loss of 4.448, worse than the 3.367 of a uniform guess over 29 symbols, as is typical for random but confident scores. In the packed row, the label after the first example's . is −100-100, so the model is never trained to predict "x" from "ab>ba.", and the mask's two triangles keep "xyz>" from attending to the first example at all. Simple packing implementations skip that mask and just concatenate with EOS between examples (cross-example attention leaks, but the EOS teaches the model that what follows is unrelated); Transformers supports the exact version through position_ids with FlashAttention (DataCollatorWithFlattening).

The end-of-sequence token

The model only learns to stop if the response ends with an EOS token and that token is a scored target. Two common bugs remove it: the tokenizer does not append EOS (GPT-2's tokenizer adds no special tokens), or the pad token is set to the EOS token and the collator masks all pad ids with −100-100, which masks the real EOS too. Either way the fine-tuned model rambles on until max_new_tokens.

The recorded run: masked vs unmasked, with and without EOS

A tiny decoder-only transformer, 2 pre-norm blocks of width 64 with 4 heads and a causal mask (built from PyTorch's nn.TransformerEncoderLayer, which is only an encoder by name: with a causal mask it is a GPT block, see A Tiny Transformer Language Model), learns to reverse words of 3 to 7 random letters. There are 3,000 training words, and 200 test words that never occur in training. AdamW at 3⋅10−33 \cdot 10^{-3}, batches of 64 random training words, padding at the end (with a causal mask, end padding never influences real tokens), greedy decoding until EOS or 10 new tokens. Five settings:

  • the loss on every token (prompt and response) or with the prompt masked, after 150 and after 400 steps;
  • prompt masked but no EOS at the end of the responses.

The "logged train loss" is what the training loop would print; the "test loss (response)" is the loss on the response tokens of the test words, the number that is comparable across settings.

python · try it yourself
import random
import torch, torch.nn as nn, torch.nn.functional as F
VOCAB = "_abcdefghijklmnopqrstuvwxyz>."          # _ = padding, > ends the prompt, . = end of sequence (EOS)
stoi = {c: i for i, c in enumerate(VOCAB)}
PAD, EOS = stoi["_"], stoi["."]

class TinyGPT(nn.Module):
    def __init__(self, V=len(VOCAB), d=64, heads=4, layers=2, T=32):
        super().__init__()
        self.tok, self.pos = nn.Embedding(V, d), nn.Embedding(T, d)
        self.blocks = nn.ModuleList(nn.TransformerEncoderLayer(d, heads, 4 * d, dropout=0.0, batch_first=True, norm_first=True)
                                    for _ in range(layers))
        self.norm, self.head = nn.LayerNorm(d), nn.Linear(d, V)
    def forward(self, x):
        T = x.shape[1]
        mask = torch.triu(torch.full((T, T), float("-inf")), 1)      # causal mask
        h = self.tok(x) + self.pos(torch.arange(T))
        for b in self.blocks:
            h = b(h, src_mask=mask)
        return self.head(self.norm(h))

rng = random.Random(0)
def word(): return "".join(rng.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(rng.randint(3, 7)))
train_words = [word() for _ in range(3000)]
test_words = [w for w in (word() for _ in range(300)) if w not in set(train_words)][:200]

def example(w, mask_prompt, eos=True):
    prompt, response = w + ">", w[::-1] + ("." if eos else "")
    ids = [stoi[c] for c in prompt + response]
    labels = ids[1:] + [-100]                                         # next-token targets
    if mask_prompt:
        labels = [-100] * (len(prompt) - 1) + labels[len(prompt) - 1:]   # only response tokens are scored
    return ids, labels

def batch(words, mask_prompt, eos=True):
    ex = [example(w, mask_prompt, eos) for w in words]
    T = max(len(i) for i, _ in ex)
    x = torch.tensor([i + [PAD] * (T - len(i)) for i, _ in ex])
    y = torch.tensor([l + [-100] * (T - len(l)) for _, l in ex])
    return x, y

def generate(model, w, max_new=10):
    ids = [stoi[c] for c in w + ">"]
    for _ in range(max_new):
        nxt = model(torch.tensor([ids]))[0, -1].argmax().item()
        ids.append(nxt)
        if nxt == EOS: break
    return "".join(VOCAB[i] for i in ids)

def run(mask_prompt, eos, steps):
    torch.manual_seed(0)
    model = TinyGPT()
    opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
    g = random.Random(1)
    for step in range(steps):
        x, y = batch(g.sample(train_words, 64), mask_prompt, eos)
        loss = F.cross_entropy(model(x).flatten(0, 1), y.flatten(), ignore_index=-100)
        opt.zero_grad(); loss.backward(); opt.step()
    model.eval()
    with torch.no_grad():
        x, y = batch(test_words, True, eos)                  # the comparable number: loss on response tokens only
        test_loss = F.cross_entropy(model(x).flatten(0, 1), y.flatten(), ignore_index=-100).item()
        outs = [generate(model, w) for w in test_words]
    correct = sum(o.split(">")[1].startswith(w[::-1]) for o, w in zip(outs, test_words)) / len(test_words)
    stops = sum(o.endswith(".") for o in outs) / len(test_words)
    return loss.item(), test_loss, correct, stops, outs[0]

print("TinyGPT parameters:", f"{sum(p.numel() for p in TinyGPT().parameters()):,}")
print("setting                  steps | logged train loss | test loss (response) | reversed | stopped | first test word")
for label, mask_prompt, eos, steps in [("loss on every token", False, True, 150), ("prompt masked (-100)", True, True, 150),
                                       ("loss on every token", False, True, 400), ("prompt masked (-100)", True, True, 400),
                                       ("prompt masked, no EOS", True, False, 400)]:
    tl, vl, c, st, out = run(mask_prompt, eos, steps)
    print(f"{label:22s} {steps:7d} | {tl:17.3f} | {vl:20.3f} | {c:8.3f} | {st:7.3f} | {out}")
TinyGPT parameters: 105,885
setting                  steps | logged train loss | test loss (response) | reversed | stopped | first test word
loss on every token        150 |             1.360 |                0.018 |    1.000 |   1.000 | ussg>gssu.
prompt masked (-100)       150 |             0.094 |                0.117 |    0.795 |   1.000 | ussg>gssu.
loss on every token        400 |             1.361 |                0.018 |    0.990 |   0.990 | ussg>gssu.
prompt masked (-100)       400 |             0.001 |                0.002 |    1.000 |   1.000 | ussg>gssu.
prompt masked, no EOS      400 |             0.047 |                0.242 |    0.765 |   0.000 | ussg>gssugssusu

Three findings, each with a practical consequence (200 test words, one seed):

  1. The logged loss of an unmasked run is mostly prompt. It sits at 1.36 after 150 and after 400 steps, because random prompt letters cannot be predicted (about ln⁡26≈3.26\ln 26 \approx 3.26 per letter). Meanwhile the same model's loss on the response is 0.018. If you compare runs, or decide when to stop, by the logged loss, the masked and unmasked numbers are not on the same scale.
  2. Masking is not automatically faster. After 150 steps the unmasked model reverses all 200 test words and the masked one only 0.795 of them; after 400 steps the masked one is perfect and the unmasked one makes 2 errors. Here, predicting the prompt letters is extra practice in reading letters, which helps early on. Whether loss on the prompt helps or hurts accuracy depends on the task and the data: the published results go both ways, so the default (masking, the behaviour of TRL's SFTTrainer for prompt-completion data) is a choice to verify, not a law. The reasons that do not depend on the task are behavioural: an unmasked model also learns to write prompts, including user turns of chats, repeated system prompts and whatever junk the prompts contain, and with long prompts (documents, retrieved passages) the prompt tokens dominate the loss.
  3. Without EOS the model never stops. The no-EOS model wrote the right reversal and kept going ("gssu" then "gssusu"); in this run its reversals were also less accurate (0.765 of the test words, response loss 0.242), though with one seed that part may be chance. In a chat model this is the answer that continues with an invented next user turn.

Pitfalls

  • Masking with the wrong offset. Labels are shifted by one: the last prompt position is scored (it predicts the first response token). Check with a printed example like the one above; Transformers models shift internally when you pass labels=input_ids, so pass unshifted labels to them.
  • Pad token equals EOS, and all pads masked. Then the real EOS is masked too. Mask by position (from the lengths) rather than by token id, or use a separate pad token.
  • Truncating from the right. A long prompt plus response cut at max_length loses the response, the only part with a loss. Truncate the prompt (or drop the example) and keep the response.
  • Packing without boundaries. At minimum separate examples with EOS; better, reset positions and block cross-example attention.
  • Comparing logged losses across settings. Different masks, packing or templates change what the average is over. Compare on a fixed held-out set of responses, and on generations.
  • Too many epochs on a small SFT set. A few thousand examples are memorised quickly; watch held-out loss and sample outputs, and see catastrophic forgetting for what full fine-tuning can erase.

Practice

  1. Prompt "hi>" and response "ih." in the lesson's vocabulary. Write the label list with prompt masking.
  2. Why must the last prompt position not be masked?
  3. A batch packs three examples of lengths 10, 6 and 8 into one row of 24. How many attention-mask entries are 1 with the block-diagonal causal mask, and how many with a plain causal mask?
  4. Your SFT model answers correctly but then writes "User: ..." and invents a new question. Name two likely causes.
Answers
  1. Tokens h, i, >, i, h, . with ids 8, 9, 27, 9, 8, 28. Labels: [−100,−100,9,8,28,−100][-100, -100, 9, 8, 28, -100]: position 2 (">") predicts "i", position 3 predicts "h", position 4 predicts ".", and the last position has no target.
  2. Its target is the first response token. Masking it would leave the model never trained to start the answer.
  3. Block-diagonal: 10⋅112+6⋅72+8⋅92=55+21+36=112\frac{10 \cdot 11}{2} + \frac{6 \cdot 7}{2} + \frac{8 \cdot 9}{2} = 55 + 21 + 36 = 112. Plain causal: 24⋅252=300\frac{24 \cdot 25}{2} = 300.
  4. The EOS (or end-of-turn) token is missing from the training responses or masked out, and/or the user turns were not masked, so the model learned to write them. A chat template mismatch between training and inference is a third.

Test yourself

In SFT, what does the label −100-100 at a position mean?

  1. The token is padding and is removed from the input
  2. The position is processed by the model but adds nothing to the loss
  3. The model must predict token id 100
  4. The attention to this position is blocked

In the recorded run, the unmasked model's logged loss stayed at 1.36 while its response loss on test words was 0.018. Why?

  1. The model overfitted
  2. The logged average includes the random prompt letters, which cannot be predicted (about ln⁡26\ln 26 each)
  3. The test set is easier
  4. Masking changes the model architecture

The model trained without EOS in its responses produced ussg>gssugssusu. What fixes this?

  1. A lower learning rate
  2. End every training response with an EOS token and keep it as a scored target
  3. Masking the prompt
  4. Packing

Why do packed SFT rows usually restart position ids and use a block-diagonal attention mask?

  1. To make rows shorter
  2. So each packed example behaves as if it were alone: no attention to, and no prediction of, the neighbouring examples
  3. To mask the prompt
  4. Because EOS tokens are not allowed in packed rows