Sub topic 12
From Base Model to Assistant: Instruction Tuning and Preference Tuning
This chapter assumes you know the pretraining objective (next-token cross-entropy), how a decoder-only transformer produces logits, and how sampling works. It covers what happens after pretraining. A pretrained model is a strong text continuer, but it is not yet an assistant.
Why a base model is not an assistant
A base model is trained to continue text that looks like its training corpus. It does not know that a question is something to answer.
Given the prompt What is the capital of France?, a base model may continue with:
- Another quiz question, such as
What is the capital of Germany?, because lists of questions are common on the web. - A multiple-choice list.
- A plausible answer followed by unrelated text, because nothing taught it where to stop.
The knowledge is usually there. What is missing is the behavior: reading a request, answering it, and ending the turn. Post-training adds that behavior. It is a short phase compared with pretraining. It also uses far less data, typically thousands to millions of curated examples instead of trillions of tokens.
The usual pipeline has three stages:
- Pretraining on a large text corpus, which gives a base model.
- Supervised fine-tuning (SFT), also called instruction tuning, which teaches the format and style of following instructions.
- Preference tuning, which pushes the model toward responses people judge as better.
Instruction tuning (supervised fine-tuning)
The data
Instruction tuning uses pairs of a prompt and a desired response. Human annotators write them, or existing models generate them and people review them. A single example looks like this:
- Prompt:
Summarize this paragraph in one sentence: ... - Response:
The paragraph argues that ...
Good datasets cover many task types, such as summarization, question answering, code, extraction, and refusing unsafe requests. They also vary in length and tone. The model learns from the spread of examples, so narrow data gives narrow behavior.
The chat template
Conversations are flattened into a single token sequence using special tokens that mark who is speaking. The exact tokens differ between model families. A generic version looks like this:
<|system|>You are a helpful assistant.<|end|>
<|user|>What is the capital of France?<|end|>
<|assistant|>The capital of France is Paris.<|end|>The model sees the same kind of sequence at training and at inference. The end-of-turn token matters: it is how the model learns to stop. If you format a prompt with the wrong template at inference time, quality drops, because the model is seeing a layout it was not tuned on.
The loss is still next-token cross-entropy
Instruction tuning uses the same loss as pretraining. The difference is which tokens count. The loss is usually computed only on the assistant's response tokens. Tokens in the prompt are still fed to the model as context, but they are masked out of the loss. The model should learn to produce answers, not to predict user questions.
The code below shows the masking. It reuses the cross-entropy calculation from pretraining and adds a boolean mask.
import numpy as np
def masked_next_token_loss(logits, targets, loss_mask):
# logits: (seq_len, vocab_size), targets: (seq_len,) of token IDs
# loss_mask: (seq_len,) of bools, True where the token is part of the response
shifted = logits - logits.max(axis=-1, keepdims=True)
log_probs = shifted - np.log(np.exp(shifted).sum(axis=-1, keepdims=True))
token_losses = -log_probs[np.arange(len(targets)), targets]
return token_losses[loss_mask].mean()
logits = np.array([[2.0, 0.5, 0.1],
[0.2, 1.5, 0.3],
[0.1, 0.2, 2.5]])
targets = np.array([0, 1, 2])
loss_mask = np.array([False, True, True]) # first token is prompt, ignored
print(masked_next_token_loss(logits, targets, loss_mask))Only the second and third positions contribute to the average. Gradients therefore flow only from the response tokens, though they still pass through the representations of the prompt.
What SFT does and does not do
SFT mostly changes style, format, and willingness to follow instructions. It is not a good way to add large amounts of new knowledge. Training on a few thousand examples cannot replace what pretraining learned from trillions of tokens.
SFT has a known limitation. It only shows the model good answers. It never shows what a bad answer looks like or how two answers compare. The model imitates the demonstrations, including their flaws, and it can learn to imitate confident-sounding answers even about things it does not know. Preference tuning addresses part of this.
Preference tuning
For many qualities, such as helpfulness, tone, and honesty, it is hard to write the ideal response but easy to compare two of them. Preference tuning uses that fact.
Comparison data
For a prompt, the model produces two or more candidate responses. A human, or a model following written guidelines, marks which one is better. Each record becomes a triple: a prompt, a preferred (chosen) response, and a rejected response.
Reinforcement learning from human feedback (RLHF)
RLHF is the classic approach and has two parts.
- Train a reward model. This is a transformer, often initialized from the SFT model, with a head that outputs one scalar score for a prompt and response. It is trained so the chosen response scores higher than the rejected one. A common loss for a pair is
-log(sigmoid(r_chosen - r_rejected)), whereris the reward score. - Optimize the assistant against the reward model. The assistant generates responses, the reward model scores them, and a reinforcement learning algorithm, often PPO (proximal policy optimization), updates the assistant to raise the expected score.
The optimization includes a penalty on how far the tuned model drifts from the SFT model. This is usually a KL divergence term, which measures how different two probability distributions are. Without it, the model finds outputs that fool the reward model, such as odd phrasing the reward model happens to like, instead of outputs people actually prefer. This failure is called reward hacking.
Direct preference optimization (DPO)
DPO reaches a similar goal without a separate reward model and without a reinforcement learning loop. It trains directly on the comparison triples. For each triple it increases the probability of the chosen response relative to the rejected one, measured against a frozen copy of the SFT model, called the reference model. A coefficient beta controls how strongly the model is held close to the reference.
The pair loss can be sketched like this:
import numpy as np
def dpo_pair_loss(logp_chosen, logp_rejected, ref_logp_chosen, ref_logp_rejected, beta=0.1):
# Each argument is the summed log-probability of a full response.
margin = beta * ((logp_chosen - ref_logp_chosen) - (logp_rejected - ref_logp_rejected))
return float(np.log1p(np.exp(-margin))) # equals -log(sigmoid(margin))
# The tuned model has shifted probability toward the chosen response.
print(dpo_pair_loss(-12.0, -20.0, -15.0, -18.0))
# No shift from the reference: loss is log(2), about 0.693.
print(dpo_pair_loss(-15.0, -18.0, -15.0, -18.0))The loss is low when the tuned model has moved toward the chosen response and away from the rejected one, more than the reference model has. When the tuned model equals the reference, the margin is zero and the loss is log 2.
Comparing the approaches
| Aspect | SFT | RLHF | DPO |
|---|---|---|---|
| Training data | Prompt and ideal response | Comparisons, plus prompts for sampling | Comparisons |
| Extra models needed | None | Reward model, and a reference model for the KL penalty | Frozen reference model |
| Samples from the model during training | No | Yes | No (uses stored responses) |
| Main risk | Imitating flaws in demonstrations | Reward hacking, unstable training | Sensitivity to data quality and `beta` |
| Relative complexity | Low | High | Medium |
Other variants exist, including methods that use written principles to generate AI feedback and methods that use automatically checkable rewards, such as unit tests passing for code. They follow the same idea: define a signal of quality, then move the model toward it.
Effects you can observe
Post-training changes how the model behaves at the decoding stage:
- Output distribution: Tuned models are often more peaked. They put more probability on a few good responses and less on diverse ones. At the same temperature, a tuned model can feel less varied than its base model.
- Calibration: Preference tuning can make a model's stated confidence less reliable. Raters tend to favor fluent, assertive answers, so the model may sound sure when it should not.
- Length and style bias: If raters prefer longer or more polished answers, the model drifts that way, even when the extra length adds nothing.
- Sycophancy: Models can learn to agree with the user because agreement often gets rated well.
- Refusals: Safety-focused data teaches the model to decline some requests. Too much of it causes over-refusal of harmless requests.
Common mistakes
- Using the wrong chat template. Each tuned model expects its own special tokens. A mismatched template is a frequent cause of rambling or ignored instructions.
- Treating SFT as a way to teach facts. Fine-tuning on a small document set tends to teach style, not reliable recall. For facts that change, supply them in the prompt.
- Computing loss on the prompt. This wastes capacity and can teach the model to generate user turns.
- Overfitting to a small dataset. Many epochs on a few thousand examples can make outputs repetitive and hurt general ability.
- Noisy preference labels. Inconsistent raters give the reward model or DPO an unclear target. Quality of comparisons matters more than quantity.
- Setting
betaor the KL penalty too low. The model drifts far from the reference, and fluency or general capability can degrade.
Exercise
A team fine-tunes a base model on 5,000 prompt-and-response pairs. They compute the cross-entropy loss over every token in the sequence, including the user's prompt. Name one problem this can cause and state the fix. Then explain why they might add preference tuning after this step.
Show answer
Including prompt tokens in the loss makes the model learn to predict user text as well as answers, which spends training signal on the wrong target and can lead it to generate user turns. The fix is a loss mask that keeps only the assistant response tokens, while still feeding the prompt as context. Preference tuning helps because SFT only shows good answers to imitate. Comparison data shows which of two answers is better, so the model can be pushed toward qualities such as helpfulness and honesty that are hard to write as a single ideal response.
Exercise
In the dpo_pair_loss function, what is the loss when the tuned model's log-probabilities equal the reference model's for both responses, and why?
Show answer
The loss is log 2, about 0.693. When the tuned and reference log-probabilities match, both differences are zero, so the margin is zero. The loss is -log(sigmoid(0)) = -log(0.5) = log 2. Training lowers the loss by raising the chosen response's probability and lowering the rejected one's, relative to the reference.