QuiddityML

By · 25 November 2026 · 7 min read

Instruction tuning and supervised fine-tuning (SFT) explained

What an SFT training example looks like, why the loss skips the prompt tokens, where instruction data comes from, and what SFT cannot teach, with the loss written in PyTorch.

Supervised fine-tuning (SFT), also called instruction tuning, trains a pretrained language model on pairs of an instruction and a good response. It is usually the first step that turns a base model, which only continues text, into an assistant that answers requests. Chat assistants usually go through this step before any training on human preferences.

Language models read and write text as tokens, which are whole words or pieces of words. A base model is the model you have after pretraining, the stage where it learns to predict the next token over a huge amount of general text.

Why it is called supervised fine-tuning

Both halves of the name are ordinary machine learning terms. Fine-tuning means training starts from existing model weights instead of random ones. Supervised means every training example comes with a target, here a written response. The base model already writes fluent text, so the examples steer how it uses that ability.

One training example has two parts, the request and the response:

One instruction-tuning example: the user asks "Rewrite this in a calmer tone: This is completely wrong and you ignored the instructions." The assistant replies "This does not match the instructions yet. Could you revise it so it follows the requested format?"

The model learns no new fact from this example. It learns the shape of the behavior: read what the user wants, keep the task, and answer in the requested style.

What changes after tuning

The same message gets very different treatment before and after SFT. Ask a base model to "List three reasons a model might hallucinate" and it may continue the page with another prompt or a fragment of an article. A tuned model is more likely to answer the question directly.

For "List three reasons a model might hallucinate", the base model continues the page and may drift, while the instruction-tuned model answers with three numbered reasons.

The training set mixes many kinds of requests on purpose, such as summaries, translations, questions and code fixes. No single kind is meant to dominate, so what the model picks up is a general habit of producing the response a request asks for.

A training mixture of summarize, translate, answer, fix code and rewrite requests. What survives the mixture is the habit of producing the response a request asks for.

One way to check for that general habit is to hold out a whole family of tasks. Train on question answering, summarization and natural language inference, and keep translation out of the training data. If the tuned model then handles translation requests better than the base model did, some instruction following carried over to a task it never trained on.

Question answering, summarization and natural language inference are trained on, while translation is held out for testing.

Chat templates turn messages into tokens

Training examples are not fed in as one bare string. They are wrapped in a chat template with role markers, so the model can tell who is speaking. The system turn holds standing instructions for the whole conversation, such as a tone. The user turn is the request, and the assistant turn is the text the model learns to generate.

In code, an example is often stored as a list of messages:

1messages = [
2    {"role": "system", "content": "You are concise."},
3    {"role": "user", "content": "Define a token."},
4    {"role": "assistant", "content": "A token is one chunk of text from the tokenizer."},
5]

The template then renders these messages into one text sequence with a marker before each role. After tokenization, the role markers are ordinary tokens in the sequence. The model never sees a special conversation object, only tokens.

Structured messages go through a chat template and become one token sequence: the system, user and assistant markers each come before their text, and the assistant turn continues in the same sequence.

Because the template is part of the training data, the model expects to see the same template again when it is used.

The SFT loss

SFT does not need a new objective. It keeps the next-token loss from pretraining and changes the data, from raw web text to instruction and response pairs.

Name the pieces before the formula. $x$ is the prompt. The response is a list of tokens $y_1$ to $y_n$, and $y_{<t}$ means every response token before position $t$. $p_\theta(y_t \mid y_{<t}, x)$ is the probability the model, with weights $\theta$, gives to the correct token $y_t$ after seeing the prompt and the response so far. The loss $L$ adds up minus the log of that probability over the response tokens:

$$L = -\sum_{t \in \text{response}} \log p_\theta(y_t \mid y_{<t}, x)$$

This is cross-entropy over the response. For example, take a two-token response where the model gives the first correct token probability 0.5 and the second 0.25. Then $-\log 0.5 = 0.693$ and $-\log 0.25 = 1.386$, so $L = 2.079$. A model that put more probability on the correct tokens would get a smaller loss.

Pretraining uses raw web text and SFT uses instruction and response pairs, but both train with next-token cross-entropy. What differs is that SFT computes the loss over the response tokens only, with the prompt as context.

Why the loss skips the prompt

The prompt is context the model reads, not text it is graded on writing. So in many SFT setups the loss covers the response tokens only, and the prompt tokens are masked out.

In PyTorch, the usual way is to copy the token ids into a labels tensor and set every prompt position to $-100$. That is the default ignore_index of cross_entropy, so those positions add nothing to the loss. The function below also shifts the labels by one, so the prediction at each position is scored against the next token.

1import torch
2import torch.nn.functional as F
3 
4def sft_loss(logits, labels):
5    shift_logits = logits[:, :-1, :].reshape(-1, logits.size(-1))
6    shift_labels = labels[:, 1:].reshape(-1)
7    return F.cross_entropy(shift_logits, shift_labels, ignore_index=-100)
8 
9torch.manual_seed(0)
10vocab_size, seq_len, prompt_len = 100, 10, 6
11input_ids = torch.randint(0, vocab_size, (1, seq_len))
12logits = torch.randn(1, seq_len, vocab_size)  # stands in for model(input_ids)
13 
14labels = input_ids.clone()
15labels[:, :prompt_len] = -100
16print(labels)
17print("loss on the response only:", round(sft_loss(logits, labels).item(), 3))
18print("loss on every token:", round(sft_loss(logits, input_ids).item(), 3))
1tensor([[-100, -100, -100, -100, -100, -100,   27,    3,   97,   83]])
2loss on the response only: 4.008
3loss on every token: 4.16

logits[:, :-1, :] drops the last position and labels[:, 1:] drops the first, so position $t$ is compared with the token at $t + 1$. The two reshape calls flatten the batch and position axes into one list of rows, the shape cross_entropy expects. PyTorch's cross_entropy also averages over the scored tokens instead of summing them, which only rescales the loss from the formula above.

The prompt tokens from the user marker through the assistant marker get labels set to -100 and no loss, and the loss is computed only on the response tokens "Artificial intelligence transforms industries."

If the mask is left out, the model is also trained to reproduce the user's prompt, which is not the behavior SFT is after.

Why SFT is cheap next to pretraining

Pretraining may use trillions of tokens and a large cluster of GPUs. SFT can use a much smaller curated dataset and a short training run. It reuses what pretraining already built and mostly teaches the model how to respond, which is why it is often the practical entry point to post-training.

Pretraining uses trillions of tokens and a large GPU cluster, while SFT uses a small curated dataset and a short training run.

Where instruction data comes from

There are three common sources of instruction and response pairs:

Where the data comes from: human-written pairs by annotators, templated labeled data phrased as instructions, and synthetic pairs generated by a strong model. Many instruction datasets mix these three sources.

These sources trade off cost against quality per example. A small, carefully curated set can beat a much larger noisy one. The model already knows how to write, so SFT mostly teaches behavior, and clean demonstrations can count for more than many of them.

Human-written data costs the most per example and has the highest quality, templated sits in the middle and synthetic costs least. A small carefully curated set often trains a better assistant than a very large noisy set.

Instruction data can also teach safety. Safety examples show the model refusing harmful requests and handling sensitive topics with care. A small number of refusal demonstrations can carry over to harmful prompts the model never saw in tuning, so refusing becomes part of the behavior the model is taught.

A small set of refusal demonstrations can generalize to new harmful prompts not seen during tuning, so safety data is taught behavior and not only a filter after training.

What SFT cannot teach

SFT has four limits, and they point at the next step of post-training.

  1. Cost. Every instruction needs a demonstration response, and technical or sensitive domains need skilled people to write and review them.
  2. One answer per prompt. Many prompts have many good answers. "Write an encouraging note to a coworker" has many, and the annotator writes one. The model learns to imitate that one choice and nothing about how it compares with the others.
  3. The imitation ceiling. SFT trains the model to match its demonstrations, so its behavior is shaped by their quality and coverage. Matching a written answer says nothing about which of several answers people would like more.
  4. Only positive examples. SFT shows the model what to write, but rarely a bad answer labeled as bad. The contrast between a strong answer and a weak one is missing.

Five good notes to a coworker are all acceptable, but the model imitates the one the annotator wrote, and the other four get no label at all.

SFT output sits at or below the quality of its demonstrations, because nothing in the training signal points above the answers the model was shown.

For "Explain what a learning rate does", the SFT data holds correct answers, while wrong answers never appear with a label saying they are worse.

All four limits point at a different kind of signal: judging outputs instead of demonstrating them. That is what training on human preferences adds after SFT.

Common mistakes

SFT is the first step of post-training, and the full path from base model to assistant is in pretraining vs post-training. The failures SFT does not remove, such as hallucination, are covered in why LLMs hallucinate. SFT is one kind of fine-tuning, and the general idea is in fine-tuning vs transfer learning.

QuiddityML teaches supervised fine-tuning as its own concept in the Intro to NLP track, where the exercises go from picking the code that computes the response-only loss to tracing its tensor shapes and writing sft_loss from scratch.