Supervised fine-tuning starts with the training examples

← Back to Blog & Articles

What changes is which positions contribute to the loss.

the companion book defined the pretraining objective as maximum-likelihood minimization of cross-entropy over a corpus of unlabeled text, restated here for a single sequence x=(x1,…,xn)x = (x_1,\ldots,x_n):

ℒ(θ)=−𝔼x∼𝒟[∑t=1nlogpθ(xt∣x<t)]. \mathcal{L}(\theta) = -\mathbb{E}_{x\sim\mathcal D}\left[\sum_{t=1}^n \log p_\theta(x_t \mid x_{<t})\right].

Supervised fine-tuning uses exactly this objective — no new loss function, no new architecture — applied to a different kind of sequence and, critically, summed over a different set of positions. An SFT example is not raw web text; it is a curated pair (xprompt,xresponse)(x_{\text{prompt}}, x_{\text{response}}) consisting of an instruction (and, in the multi-turn case, some conversation history) followed by a demonstrated response that a human annotator judged to be a good reply. The two halves are concatenated into a single token sequence x=(x1,…,xm,xm+1,…,xn)x = (x_1,\ldots,x_m,x_{m+1},\ldots,x_n), where the first mm tokens are the prompt and the remaining n−mn-m tokens are the response, and the sequence is fed through the decoder-only Transformer exactly as in pretraining — the model still just predicts the next token at every position, autoregressively, with a causal mask (the companion book).

What changes is which positions contribute to the loss. Rather than summing the per-token negative log-likelihood over the entire sequence, SFT restricts the sum to the response tokens:

ℒSFT(θ)=−𝔼(x,m)∼𝒟[∑t=m+1nlogpθ(xt∣x<t)].\begin{equation} \mathcal{L}_{\text{SFT}}(\theta) = -\mathbb{E}_{(x,m)\sim\mathcal D}\left[\sum_{t=m+1}^{n} \log p_\theta(x_t \mid x_{<t})\right]. \end{equation}

Equivalently, define a per-token binary mask wt∈{0,1}w_t \in \{0,1\} that is 11 for response tokens and 00 for prompt tokens, and write the loss as a masked average over the full sequence,

ℒSFT(θ)=−𝔼x∼𝒟[1∑t=1nwt∑t=1nwtlogpθ(xt∣x<t)], \mathcal{L}_{\text{SFT}}(\theta) = -\mathbb{E}_{x\sim\mathcal D}\left[\frac{1}{\sum_{t=1}^n w_t}\sum_{t=1}^n w_t \,\log p_\theta(x_t \mid x_{<t})\right],

which is the more useful form in practice because it generalizes immediately to multi-turn conversations: wt=1w_t=1 for every token that belongs to an assistant turn, and wt=0w_t=0 for every token belonging to a system or user turn, regardless of how many turns precede the one currently being trained on. The two formulations agree exactly for a single-turn (prompt, response) pair; the masked-sum form is simply the general statement that lets a single conversation contain several loss-bearing spans separated by non-loss-bearing ones.

The masking is not a minor implementation detail — it follows directly from what the objective is supposed to teach. Recall from the companion book that the gradient of the per-token cross-entropy loss with respect to the model’s logits at position tt is 𝐲̂t−𝐲t\hat{\mathbf{y}}_t - \mathbf{y}_t, the difference between the predicted distribution and the one-hot target. If prompt tokens were included in the loss, every prompt position would contribute a nonzero term to this gradient, pushing the model’s parameters to better predict the instruction itself — text that, at inference time, is never generated by the model; it is supplied externally by the user. Training the model to predict its own input serves no purpose the model needs: the instruction is conditioning information, not a target to imitate, and the model’s job is to produce a good response given that conditioning, not to reconstruct the conditioning from a blank slate. Unmasked training would spend gradient signal, and more importantly parameter capacity, learning the statistics of instruction phrasing — a task with far lower entropy than open-ended response generation and therefore, after a few thousand examples, contributing an almost-zero, uninformative gradient that dilutes the informative gradient coming from the response tokens. The dilution is worst exactly when it matters most: prompts that are long relative to their responses (a document to summarize, a long system message, a multi-turn history) would dominate the unmasked loss’s token count, shrinking the effective learning signal applied to the comparatively few response tokens that actually need to change. Masking removes both problems at once: it is the formal statement that the model is being fine-tuned to be a good conditional generator pθ(response∣prompt)p_\theta(\text{response}\mid\text{prompt}), not a good unconditional generator of the concatenation of the two, and the mechanism achieving it is exactly the gradient-zeroing implied by wt=0w_t=0 on prompt positions.

Chat-format data structure. In practice, prompts and responses are not concatenated as raw text; they are wrapped in a structured template with special delimiter tokens marking turn boundaries and roles, so that a single serialized sequence can encode an arbitrary number of system, user, and assistant turns unambiguously, and so that the trained model, at inference time, knows when it is being asked to speak versus when it is reading context. A widely used format (ChatML, adopted with variations across most current open and commercial chat models) looks like this for a single-turn example:

Here <|im_start|> and <|im_end|> are special tokens added to the tokenizer’s vocabulary (the companion book) specifically for this purpose — they do not occur in ordinary text, so the model can learn to treat them as unambiguous structural markers rather than content. Multi-turn conversations are formed by repeating the <|im_start|>role ... <|im_end|> block for each turn in order, with earlier turns (including earlier assistant turns from the same conversation, when training on multi-turn history) typically included in the input but masked out of the loss just like the current turn’s user message — only the most recent assistant turn, or in some recipes every assistant turn in the conversation, contributes to ℒSFT\mathcal{L}_{\text{SFT}}. Whether the role tag itself (<|im_start|>assistant) is included in the loss mask is a design choice that varies across training recipes: including it teaches the model to also predict when it is its turn to speak, which is occasionally useful for multi-agent or tool-calling setups, while excluding it (masking through to the first token of the actual response content) keeps the loss purely on generated content. Other conventions in current use follow the same structural idea with different literal tokens — Llama-2-style chat formatting uses [INST]...[/INST] wrapping user turns with a <<SYS>>...<</SYS>> block for the system prompt, for example — but the underlying principle is identical across all of them: delimiter tokens make turn and role boundaries explicit and machine-parseable, and the loss mask derived above is computed from those boundaries.

It is worth noting that this text-to-text framing — cast every task as “read some conditioning text, generate some target text” and apply one loss — did not originate with chat-format instruction tuning; T5 (Raffel et al., 2020) established the same idea a few years earlier for supervised NLP tasks generally, recasting classification, translation, and summarization alike as text generation conditioned on a task-describing prefix, trained with one unified maximum-likelihood objective rather than task-specific heads and losses. Instruction tuning is that same idea applied to natural-language instructions instead of fixed task prefixes, letting a single model generalize to instructions unseen during training rather than being restricted to a fixed task inventory. The SFT stage described here is also the first of the two post-pretraining stages in the InstructGPT recipe (Ouyang et al., 2022): human labelers write demonstration responses to sampled prompts, the base model is fine-tuned on those demonstrations with the masked cross-entropy objective derived above, and the resulting SFT model is then used as the starting policy for the preference-based alignment stage covered in the next chapter (the companion book, Alignment: RLHF, Reward Models, and DPO) — SFT establishes instruction-following behavior and response format; RLHF and DPO refine which of several instruction-following responses is preferred, a distinction this article does not revisit further.

The following listing implements the masking mechanism directly: given a full token sequence and the length of its prompt portion, it produces a labels tensor in which prompt positions are set to -100, the sentinel value PyTorch’s F.cross_entropy treats as ignore_index by default, dropping those positions from both the loss and its gradient with no additional bookkeeping required at the loss call site.

The two printed sums make the masking concrete: the gradient with respect to the logits at the six prompt positions is exactly zero, while the gradient at the four response positions is not — precisely the selective supervision the loss ℒSFT\mathcal{L}_{\text{SFT}} was defined to produce.

Continue with the book

Explore the full treatment, worked examples, and exercises in LLMs Derived.


Companion article for LLMs Derived, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.

Scroll to Top