By Sagi Shaier · 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:

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.

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.

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.

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.

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.

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.16logits[:, :-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.

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.

Where instruction data comes from
There are three common sources of instruction and response pairs:
- Human-written: paid annotators write prompts and responses by hand. This can give the strongest examples, but it is slow and expensive.
- Templated: an existing labeled dataset is rephrased as instructions. A review labeled positive becomes "Is this review positive?" plus the review text, with the label as the answer.
- Synthetic: a strong LLM writes new instructions and responses, an approach called self-instruct. This is cheap and fast, but the data inherits the strengths and weaknesses of the model that wrote it.

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.

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.

What SFT cannot teach
SFT has four limits, and they point at the next step of post-training.
- Cost. Every instruction needs a demonstration response, and technical or sensitive domains need skilled people to write and review them.
- 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.
- 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.
- 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.



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
- Training on the whole sequence without masking the prompt. The model then also learns to write user messages.
- Using a different chat template at inference than in training. The role markers are tokens the model learned, so text in another format is not what it was tuned on.
- Scaling up noisy synthetic data in place of cleaning a smaller set.
Related concepts
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.