# Instruction Tuning: Understanding the First Step of Post-Training

> Instruction Tuning, also known as Supervised Fine-Tuning (SFT), is the crucial first stage of post-training for large language models. It uses instruction-response pairs to teach models to follow human instructions and generate helpful answers instead of simply continuing text, achieving strong generalization with only a small amount of high-quality data.

- Source: https://www.waytoagi.com/en/kb/learning-path/instruction-tuning-explained
- Original (Feishu, Chinese): https://waytoagi.feishu.cn/wiki/AxtTwpYjUiX4QckVGjhc20Wcn4c
- Updated: 2026-10-23

---

> 🔗 Original link: [https://x.com/dongxi_nlp/status/21133943...](https://x.com/dongxi_nlp/status/2113394315967795538)

> Dongxi NLP · X · @dongxi_nlp · 2026-10-23 06:17

> 📌 This article is reprinted. Copyright belongs to the original author. The full text is subject to the original link.

![](https://www.waytoagi.com/api/kb-media/H4InbsKDbo2DHbxyHydclL95nIg)

Second article in the Post-Training series: Instruction Tuning.

In March 2023, a Stanford team used Meta’s LLaMA 7B to train a model called Alpaca that could answer questions according to instructions. The original LLaMA 7B had only undergone pre-training and could merely predict the next token.

The team made no changes to the model architecture and used only 52,000 examples, each consisting of one instruction and one response. Yet this was enough for LLaMA 7B to learn how to respond according to instructions.

The data was automatically generated by OpenAI’s text-davinci-003 at a cost of less than $500. Training took 3 hours on 8 GPUs and cost less than $100.

Alpaca still produces incorrect answers. When asked for the capital of Tanzania, it replies “Dar es Salaam”; the correct answer is Dodoma.

> The examples taught the model *how* to answer, but did not teach it which facts are correct.

Why can a small number of examples dramatically change a model’s behavior, yet fail to correct its factual errors? Starting from this question, this article introduces the first post-training technique: **instruction tuning**, also known as **supervised fine-tuning (SFT)**. This is the second article in the post-training series.


## Same Loss, Different Tasks

Instruction tuning reuses the training objective of pre-training: predicting the next token at each position. It measures the gap between the prediction and the correct token using **cross-entropy loss** and improves the probability of the correct token through training.

The difference lies in the data and the task. Pre-training uses raw text with the task of continuation; instruction tuning uses paired data, where each pair contains an instruction and a response, and the task is to generate the answer according to the instruction.

> The loss function is the same, but the data and task are different: pre-training learns to continue text, while instruction tuning learns to answer instructions.

It is called supervised fine-tuning because each input has a designated target output, regardless of who wrote the data. Pre-training text is also written by humans; all of Alpaca’s examples were generated by a model, yet they still count as supervised data.


## What Instruction Tuning Actually Learns

Base models have already acquired vast amounts of knowledge during pre-training—including facts, grammar, code, and various writing styles. However, their default behavior is to continue the input text. When given a question, the model may simply generate more questions.

What instruction tuning changes is the model’s *behavior*:

- It produces an answer in response to a request instead of continuing the input.
- It outputs in the format requested by the instruction (e.g., lists, single words, or translations).
- It distinguishes between user and assistant turns in multi-turn conversations.
- It stops generation after completing the answer.
- It refuses certain requests when the examples contain refusals.

Two studies, LIMA and FLAN, illustrate the nature of this change.

**LIMA (2023)** fine-tuned a 65B LLaMA using only 1,000 carefully selected examples, without any reinforcement learning. In human evaluations, 43% of its responses were considered equal to or better than GPT-4. The authors concluded that a model’s knowledge comes almost entirely from pre-training, and a small amount of instruction data mainly determines *how* it answers.

**FLAN (2021)** rewrote more than 60 NLP tasks as natural language instructions and used them to fine-tune a 137B model. On tasks that never appeared during training, it outperformed zero-shot 175B GPT-3 on 20 out of 25 evaluation benchmarks.

This shows that instruction tuning teaches a general ability to follow instructions that can generalize to unseen tasks. Therefore, instruction tuning is the first step of post-training: first make the model capable of answering according to instructions, then use preference alignment and reinforcement learning to further improve response quality.


## Training Process

Instruction tuning consists of five steps:

1. **Collection**: Prepare data pairs consisting of instructions and responses.
2. **Formatting**: Use the model’s **chat template** to convert each data pair into a token sequence in conversation format.
3. **Masking**: Use a **loss mask** to mark which tokens should contribute to the loss, computing loss only on the response portion.
4. **Training**: Use next-token prediction loss with a small learning rate. Training usually runs for only a few epochs. One can update all parameters (**full fine-tuning**) or freeze the original parameters and train only a small number of newly added parameters (**LoRA**), which will be the topic of the next article.
5. **Evaluation**: Assess performance on tasks not seen during training.

Steps 2 and 3 involve many details and are explained separately below.

**Three Forms of a Single Example**

**Storage Form**: A conversation consisting of multiple messages, each labeled with a role (system, user, or assistant).

**Input Form**: A conversation template concatenates all messages into a single token sequence and inserts special tokens. In Qwen’s template, each turn begins with `<|im_start|>` followed by the role name, and ends with `<|im_end|>`.

**Training Form**: A loss mask indicates which tokens in the sequence participate in loss calculation. The model reads the entire sequence, but only the marked tokens contribute to the loss.

The diagram below shows all three forms side by side for comparison:

![](https://www.waytoagi.com/api/kb-media/ZNznbM1Qmo4FyTxrSOOciahKnae)

## Which Tokens Are Used for Loss Calculation

There is only one criterion:

> Compute loss only on the tokens that the model is expected to generate during actual use.

Applying this rule item by item:

- **User messages: not computed.** The model needs to read them but does not need to generate them. Computing loss on them would cause the model to learn to generate user questions.

- **Assistant start marker `<|im_start|>assistant`: not computed.** In real usage, this marker is written into the prompt by the application.

- **Assistant response: computed.**

- **End marker `<|im_end|>`: computed.** The model learns from it when to stop generation. Without this, the model may continue generating after the answer, or even produce the next user message.

- **Newline after `<|im_end|>`: not computed.** Generation has already finished at this point.

Written as a formula, where \( m_t = 1 \) means the token at position \( t \) contributes to the loss, otherwise 0:

$$
\text{loss} = -\frac{1}{\text{number of tokens used for loss}} \sum_t m_t \cdot \log p(\text{correct next token at position } t)
$$

Positions where loss is not computed contribute zero, and the average is taken only over the tokens used for loss.

## Masked Tokens Are Still Trained

The loss mask only determines which positions’ predictions are included in the loss; it does not affect which tokens the **attention** mechanism can read. Since the answer depends on reading the prompt, the gradients from the answer’s loss propagate back to the prompt tokens through attention and update the parameters that process those tokens.

In other words, masked tokens do not contribute to the loss, but they still participate in training.

## Shifted by One Position

The model’s output at position \( t \) is a prediction for the token at position \( t+1 \). Therefore, when computing loss, the predictions must be aligned with the next token. In PyTorch this is written as:

> `cross_entropy(logits[:-1], labels[1:], ignore_index=-100)`

Here, `-100` indicates positions where loss is not computed.

If this shift is omitted, the shapes still match and the code will run, but each prediction will be aligned with the token at the current position. The model would then learn to copy the current token.

Before training, it is strongly recommended to decode the tokens used for loss and inspect them: the result should contain only the assistant answers and their corresponding `<|im_end|>` tokens.

## Where Does the Data Come From

Instruction data mainly comes from three sources:

- **Human-written**: Instructions and answers written by volunteers or annotators. High quality, but also high cost.

- **Rewriting existing datasets**: Converting translation, question-answering, sentiment analysis, and similar datasets into instruction format using simple templates. For example: “Does this reviewer like the movie?”

- **Model-generated**: Instructions and answers generated by language models, usually followed by filtering or review. This is currently the most common source.

Data quality has a significant impact. One study showed that adding just 500 safety examples to a large instruction dataset substantially reduced the rate at which the model produced harmful responses.

When combining datasets, attention must also be paid to length. Since loss is averaged over the tokens used for loss, longer answers receive proportionally higher weight: a 500-token answer carries roughly 250 times the weight of a 2-token answer. Therefore, when mixing instruction data, balance should be based on token count rather than merely the number of examples.

## Capabilities and Limitations of Instruction Tuning

**What it can do**: At relatively low cost, it enables the model to follow instructions, adhere to specific formats, distinguish between dialogue roles, stop at appropriate times, refuse certain requests, and generalize to new tasks.

**What it cannot do**:

- **Reliably supplement knowledge.** The example of Alpaca incorrectly stating a capital city shows that the model primarily learns the *form* of the answer, without genuinely increasing its underlying knowledge. It may also learn to give confident answers even to questions it is uncertain about.

- **Go beyond the training data.** The model imitates the examples, including any errors present in them.

- **Compare the quality of different answers or determine whether an answer is correct.** Each example provides only one reference answer, so the model cannot learn which of two plausible answers is better, nor can it judge whether a long, multi-step solution is ultimately correct.

The last limitation is addressed by two subsequent techniques: **preference alignment**, which learns from comparisons between answers, and **RLVR (Reinforcement Learning with Verifiable Rewards)**, which learns based on whether the answer is correct.

The training of reasoning models follows the same sequence: first, instruction tuning is performed using well-written step-by-step solutions to teach the model the format of chain-of-thought reasoning, followed by reinforcement learning to improve the accuracy of its reasoning.

## Summary

- Instruction tuning uses the same loss function as pre-training and continues training on data pairs consisting of instructions and responses.

- It is called supervised fine-tuning because each input has a designated target output, regardless of who wrote the data.

- It primarily changes the model’s behavior patterns and adds very little knowledge. It can produce noticeable effects with only a small amount of data and generalizes well to new tasks.

- Loss is computed only on the tokens the model is expected to generate: the answer itself and the ending `<|im_end|>` token. Masked tokens still participate in training.

- It can only imitate the reference answers and cannot compare quality or verify correctness. These capabilities are provided by subsequent stages of preference alignment and reinforcement learning.

Next: LoRA and QLoRA, and how to fine-tune large models on a single GPU.
