3.6Post-training I: SFT & instruction tuning
How a raw text predictor becomes an assistant. Chat templates, special tokens, loss masking, and why a small instruction-tuned model can beat a giant base model.
The model that answers questions with more questions
After pretrainingPretrainingThe first and largest training phase: next-token prediction on trillions of tokens of general text., you have a base modelBase modelA language model after pretraining only: it continues text rather than following instructions. Chat models are base models with further post-training.: a superb predictor of what text comes next on the internet. That is not the same as being helpful. Type a question into a base model and it does whatever a web page containing that question would do next. Here is the kind of thing you see (an illustrative example, but very typical):
Prompt:
What is the capital of Australia?Base model:
What is the capital of Canada? What is the capital of Brazil? Test your geography with these 20 quiz questions...Instruct model:
The capital of Australia is Canberra. (Sydney is the largest city, which is why people often guess it.)
The base model is not broken. On the web, a line like “What is the capital of Australia?” is often followed by another quiz question, so continuing the list is a perfectly good prediction. The knowledge that Canberra is the capital is in there; the base model just has no reason to use it the way you want.
Post-training is the set of steps that turns this text predictor into an assistant. This lesson covers the first and simplest step, supervised fine-tuningSupervised fine-tuning (SFT)Training a pretrained model on curated (prompt, ideal response) examples to teach it to follow instructions. (SFT), often called instruction tuning. The next two lessons cover what comes after: learning from preferences (RLHF & reward models) and the policy-optimization algorithms behind it (PPO vs DPO vs GRPO).
Imagine hiring an intern who has read every book in the library but has never worked in an office. Ask them a question and they might recite related passages, quote a quiz, or ramble. They know a lot; they just don’t know the job. So you hand them a binder of a few thousand example exchanges: “When a customer writes this, a good reply looks like that.” After studying it, they answer in the house style.
The library reading is pretraining. The binder of examples is the SFT dataset. The fixed layout of each example (“Customer:” … “Reply:” …) is the chat template. And the fact that the intern studies only the replies, not the customer messages, is loss masking. The intern learns no new facts from the binder; they learn a format and a behavior.
Same loss, different data
The surprising thing about SFT is how little changes mechanically. The loss is the same cross-entropyCross-entropy lossThe negative log-probability the model assigned to the correct answer. It is low when the model is confidently right. on next-token predictionNext-token predictionThe training objective of LLMs: given the text so far, output a probability distribution over the next token. you met in Part 2. The optimizer is the same. What changes is the data: instead of random web documents, the model sees (prompt, ideal response) pairs, written or curated to show the behavior you want.
Where do those pairs come from?
- Human-written demonstrations. OpenAI’s InstructGPT work paid a team of contractors to write ideal responses to prompts, many of them drawn from real API usage. The SFT set had roughly 13,000 training prompts.
- Reformatted NLP datasets. Google’s FLAN (2021) rephrased dozens of existing tasks (translation, sentiment, question answering) as natural-language instructions and showed that tuning on them improves zero-shot performance on unseen tasks.
- Synthetic data from a stronger model. Stanford’s Alpaca (2023) fine-tuned a 7B LLaMA on 52,000 instruction-following examples generated with an OpenAI model. Today most open SFT sets are largely model-generated and then filtered, an idea we’ll return to in Distillation.
Quality beats quantity here. The LIMA paper (2023) fine-tuned a 65B LLaMA on just 1,000 carefully curated examples and got a surprisingly capable assistant. Its authors proposed the superficial alignment hypothesis: almost all knowledge comes from pretraining, and SFT mostly teaches the model which “sub-distribution” of its abilities to use, in what style. That’s a hypothesis, not a law, and modern pipelines do use millions of SFT examples (for coding, math, tool use and multiple languages), but it captures why a small, clean dataset goes such a long way.
Chat templates: a conversation is still one long string
A transformer has no built-in notion of “turns” or “speakers”. It sees one sequence of tokens. So a conversation, which is naturally a list of messages, has to be flattened into a single string with markers saying who said what. That flattening rule is the chat templateChat templateThe exact text format, with role markers and special tokens, that turns a list of conversation messages into the single token sequence a chat model is trained and run on..
A common family of templates, often called ChatML after the format OpenAI introduced, wraps every message like this:
<|im_start|>system
You are a concise math tutor.<|im_end|>
<|im_start|>user
What is 12 squared?<|im_end|>
<|im_start|>assistant
12 squared is 144.<|im_end|>
The strings <|im_start|> and <|im_end|> are special tokensSpecial tokenA reserved vocabulary entry, such as a turn delimiter or end-of-sequence marker, that ordinary text never produces and that the model learns to treat as structure.: reserved entries in the vocabularyVocabularyThe fixed set of tokens a model knows, typically 32k–260k entries for modern LLMs., each a single token, that ordinary text never produces. Other model families use different markers (header tokens around the role name, an [INST] wrapper, or a plain end-of-sequence token), but they all do the same three jobs:
- Separate turns so the model knows where one message ends and the next begins.
- Label roles (system, user, assistant, and often tool) so the model can treat the system promptSystem promptInstructions placed before the conversation that set the model's role, rules and context. as instructions and the user turn as the request.
- Mark the end of a reply. At inference time the serving code stops generating when the model emits the end-of-turn token. If the model never learned to emit it, it would ramble on and start writing the user’s next message itself.
At inference, the app renders the conversation so far with the template and then appends an open assistant header (<|im_start|>assistant followed by a newline), the “generation prompt”. The model’s job is simply to continue from there.
Loss masking: learn the replies, not the questions
If you trained on the rendered string with an ordinary language-modeling loss, the model would learn to predict every token, including the system prompt and the user’s messages. That wastes capacity and, worse, teaches the model to imitate users. So SFT usually applies loss maskingLoss maskingExcluding some tokens (typically the system and user turns) from the training loss, so the model learns to produce assistant replies without being trained to imitate the user.: the loss is computed only on the tokens the assistant should produce, which are the reply text plus its end-of-turn token. Every other token is still in the input (the model needs it as context), but its prediction target is ignored. In PyTorch code this is done by setting those labels to -100, the default ignore_index of the cross-entropy loss.
Play with it below. Edit the conversation, switch template styles, and watch which tokens are trained on.
Toy word-level tokenizer and generic templates for illustration; real models use BPE and their own exact special tokens. Note that each assistant turn's end token is trained: that is how the model learns to stop.
Things to try:
- Count the overhead. In the ChatML-style view, every turn costs a few structural tokens. With short messages, scaffolding can be a sizeable fraction of the sequence.
- Look at what’s highlighted in an assistant turn. The role header is not trained (the template always supplies it), but the closing end token is. That’s how the model learns to stop.
- Switch to “Everything”. Now the model would also learn to write user questions and system prompts. Some recipes do this deliberately for a little extra signal, but most mask.
- Switch to “Last assistant turn”. Some pipelines only train on the final reply of each conversation. That throws away the signal in earlier replies, which is why “all assistant turns” is the more common default for multi-turn data.
Multi-turn conversations
Real assistants hold conversations, so SFT data includes multi-turn dialogues. Rendered with the template, a five-turn chat is just a longer sequence, and with assistant-only masking, every assistant reply contributes to the loss in one forward pass, each conditioned on everything before it. That’s efficient: a single 2,000-token conversation trains several replies at once.
Two practical details matter at scale:
- Packing. Training batches are fixed-length (say 8,192 tokens), but conversations vary. Pipelines pack several short conversations into one row, with attention masks or position resets so they don’t see each other.
- Loss normalization. Do you average the loss over all trained tokens in the batch, or first per conversation? Per-token averaging gives long replies more weight; per-sequence averaging treats each example equally. Neither is “right”, but the choice measurably changes behavior, such as how verbose the model becomes.
MATH CORNER · optionalThe masked SFT loss, with a worked example
Let a rendered conversation be tokens and let be the mask: if token belongs to an assistant reply (including its end token). The SFT loss is the average negative log-likelihood over trained tokens only:
Compare plain pretraining, which is the same formula with every . Note that the masked tokens still appear inside the conditioning context ; masking removes them as targets, not as inputs.
Worked example. A tiny sequence of 6 tokens: three prompt tokens and three reply tokens (the last is the end token). Suppose the model assigns these probabilities to the correct next token:
| position | token | role | |||
|---|---|---|---|---|---|
| 1 | user | scaffold | 0 | 0.90 | 0.105 |
| 2 | Hi | user | 0 | 0.05 | 3.000 |
| 3 | assistant | scaffold | 0 | 0.95 | 0.051 |
| 4 | Hello | assistant | 1 | 0.40 | 0.916 |
| 5 | ! | assistant | 1 | 0.60 | 0.511 |
| 6 | <end> | assistant | 1 | 0.80 | 0.223 |
Masked loss: . Unmasked loss: . The big term, for failing to predict that the user would say “Hi”, dominates the unmasked loss. Without masking, a large share of the gradient would go into guessing what users type, which is not the skill you want.
In code
A minimal SFT step with Hugging Face-style tokenization and assistant-only labels:
import torch, torch.nn.functional as F
def build_example(tokenizer, messages):
ids, labels = [], []
for m in messages: # render each turn with the template
prefix = tokenizer.encode(f"<|im_start|>{m['role']}\n", add_special_tokens=False)
body = tokenizer.encode(m["content"] + "<|im_end|>", add_special_tokens=False)
ids += prefix + body
if m["role"] == "assistant":
labels += [-100] * len(prefix) + body # train on reply + end token
else:
labels += [-100] * (len(prefix) + len(body))
return torch.tensor(ids), torch.tensor(labels)
ids, labels = build_example(tok, conversation)
logits = model(ids[None]).logits[0] # (T, vocab)
loss = F.cross_entropy(logits[:-1], labels[1:], ignore_index=-100) # shift by one
loss.backward(); optimizer.step()
In practice you would call tokenizer.apply_chat_template(...), which renders the model’s official template for you, and many training libraries offer an “assistant-only loss” option. The shift by one is the usual next-token alignment: the logits at position predict token .
- “SFT teaches the model new knowledge.” Mostly it teaches format and behavior. Facts come overwhelmingly from pretraining. Fine-tuning on facts the model never saw is possible but inefficient, and some studies link it to more hallucination.
- “Special tokens are just strings like any other.” They are single reserved vocabulary entries. If you type the characters
<|im_end|>into a well-configured app, the tokenizer should split them into ordinary text pieces, not the real control token. Confusing the two is a classic source of prompt-injection bugs. - “Masking means the model never sees the user’s message.” It sees every token as input. Masking only removes the user tokens as prediction targets in the loss.
- “Bigger SFT datasets are always better.” Noisy or inconsistent demonstrations teach noise. Small, high-quality sets (LIMA used 1,000 examples) can beat much larger sloppy ones.
Check your understanding
Q1.A base model answers 'What is the capital of Australia?' by listing more quiz questions. What is the best explanation?
Q2.In assistant-only loss masking, which tokens of an assistant turn are usually included in the loss?
Q3.You serve a model with a chat template that differs slightly from the one used in training (different end token). What is the most likely symptom?
Q4.What did the InstructGPT paper find when comparing a 1.3B InstructGPT model with the 175B GPT-3 base model?
Q5.What is the main difference between pretraining and SFT, mechanically?
Further reading
- paperTraining language models to follow instructions with human feedback (InstructGPT) — Ouyang et al., 2022. The SFT → reward model → PPO recipe and the 1.3B vs 175B result.
- paperFinetuned Language Models Are Zero-Shot Learners (FLAN) — Wei et al., 2021. Instruction tuning on many tasks generalizes to unseen tasks.
- paperLIMA: Less Is More for Alignment — Zhou et al., 2023. 1,000 curated examples and the superficial alignment hypothesis.
- docsChat templates (Hugging Face Transformers docs) — How templates are stored with tokenizers and applied in practice.
- blogAlpaca: A Strong, Replicable Instruction-Following Model — Stanford CRFM, 2023. SFT on 52K model-generated instructions.