What happens mechanically
SFT uses the same cross-entropy objective as pretraining. The difference is the data and the mask. Each example is rendered through a chat template into a single token sequence containing role markers, the user's instruction and the assistant's response. The model predicts the next token at every position, but the loss is computed only over the response tokens: the instruction and the role markers are labelled as ignored. This is the whole trick. The model is not rewarded for being able to reproduce your question, only for producing the answer that follows it.
Training is teacher-forced, meaning the model sees the true previous token at each step rather than its own last prediction. That makes optimisation stable and parallel, but it also creates a gap between training and inference that shows up as exposure bias: at generation time the model consumes its own output, and a small early error can compound. This is one reason SFT alone does not make a model robust to its own mistakes, and why preference optimisation or on-policy methods are used afterwards.
The objective is narrow by design. SFT teaches the conditional distribution of responses given instructions. It does not teach the model to search, to verify, to prefer one correct answer over another, or to know when it does not know. Those require different data or different objectives. Expecting a pure SFT run to fix hallucination is a category error; the training signal never mentions truth.
Read the loss number carefully. It is average cross-entropy per response token, so 2.0 nats corresponds to a perplexity near 7.4 choices per token, and 1.0 corresponds to about 2.7. Those numbers are only comparable between runs that share a tokenizer, a template and a masking scheme; changing any of the three moves the baseline without changing quality. A fine-tune that drops loss from 1.4 to 1.1 has probably learned your formatting conventions rather than anything deeper, which is fine if formatting was the goal and misleading if it was not.
The data is the product
An SFT dataset is a set of demonstrations, and its quality, diversity and internal consistency matter far more than its size. The LIMA result, that a thousand carefully curated examples can produce a usable assistant, is often quoted and often misread: the point was not that a thousand is enough for every task, but that curated demonstrations outperform large noisy collections. A few thousand excellent examples routinely beat a hundred thousand scraped ones, because the noisy set teaches inconsistency.
Every example should be self-contained: a reader with no context should be able to follow the instruction and judge the response. It should reflect the behaviour you want in production, not an idealised version of it. If your product answers in three sentences with a citation, the training data should answer in three sentences with a citation. If it declines certain requests, the dataset needs examples of those refusals phrased the way you want them, or the model will invent its own wording under pressure.
Diversity is what makes the behaviour generalise. A dataset of two thousand customer-support questions about refunds teaches refunds; it does not teach the model to be a support agent. Cover the intents, lengths, difficulty levels, languages and edge cases you expect, and deliberately include the prompts that currently fail. Deduplicate near-identical examples, because a repeated template gets weighted as if it were many independent observations and drags the model toward that exact phrasing.
Chat templates and special tokens
A chat template is the serialisation format that turns a list of messages into a token sequence. ChatML wraps each message in role tags and an end-of-turn token; Llama 3 uses header tokens with a different separator; Mistral uses instruction markers. The model learns the template during SFT, so the template used at training time must match the one used at inference exactly. This is the single most common cause of a fine-tune that looks broken.
The symptoms are recognisable. The model continues the user's question instead of answering it, emits role markers in its output, stops mid-sentence, or rambles past the end of its answer. Each points at a specific mismatch: missing end-of-turn token in the targets, a different system-prompt format, or an inference server that silently applies its own default template on top of yours. Print the exact token sequence for one training example and one inference request, and diff them. That five-minute check saves days.
Two related details: train with the system prompt present if production uses one, including some empty or varied system prompts, or the model will behave oddly when the field is populated. And make sure the end-of-sequence token is in the targets, otherwise the model never learns to stop and generation runs to the token limit.
Masking, packing and truncation
Loss masking sounds trivial and is where silent bugs live. If prompt tokens are not masked, the model spends most of its capacity learning to generate instructions, which is not the task. If the mask is offset by one position relative to the labels, the model learns to predict the token it just saw, loss drops to near zero and the resulting model is useless while the training curves look excellent. Assert that the number of supervised tokens is roughly the length of the responses in the batch, and print one decoded example end to end before launching.
Packing several short examples into one long sequence improves throughput substantially but requires care. Without block-diagonal attention or per-example position resets, tokens from one conversation attend to another, and the model learns spurious cross-talk. If your framework does not support that, either pad to a fixed length with a proper attention mask or accept the waste. Truncation is the other trap: cutting a long example at the context limit can remove the end of the response, teaching the model to stop mid-sentence.
Hyperparameters and how much data
SFT is forgiving on hyperparameters and unforgiving on data. One to three epochs is standard. Full fine-tuning usually runs at 1e-5 to 2e-5 with a cosine schedule and a warmup of a few percent of steps; LoRA runs an order of magnitude higher, around 1e-4 to 2e-4. Batch size should be as large as memory permits, with gradient accumulation to reach an effective batch of thirty-two to one hundred twenty-eight examples. Weight decay and dropout are minor compared with the effect of learning rate and data quality.
Data volume depends on the task. Format and tone changes can land with five hundred to two thousand examples. A new classification scheme or extraction schema needs a few thousand, with balanced coverage of labels. A genuinely new capability, such as a domain-specific reasoning style, needs tens of thousands, and if the base model does not have the underlying capability, no volume will substitute. A rough diagnostic: if held-out loss plateaus early and quality is still poor, you need better data; if held-out loss rises while training loss falls, you have too little diversity or too many epochs.
What SFT can and cannot do
- Can teach response format, length, tone, structure and house style with a few hundred examples.
- Can teach tool-call syntax and when to call a tool, provided the base already understands the tools' semantics.
- Can improve instruction following and reduce preamble when the base model has the capability but applies it inconsistently.
- Cannot reliably add factual knowledge; facts learned by SFT are shallow and degrade under paraphrase.
- Cannot fix a weak base model, and cannot make a model truthful by training it on true statements alone.
- Cannot teach a model to know when it is uncertain unless the data contains genuine abstentions.
Where SFT sits in the pipeline
SFT is the first post-training stage, not the only one. Pretraining produces a text continuator; SFT produces something that responds to instructions; preference optimisation then shifts the distribution toward the responses people prefer. The order matters because preference methods assume the model can already produce valid candidates in the right format. Running DPO on a model that has never seen a chat template mostly teaches it the template, which is a waste of a more expensive objective.
The distinction between the stages is about the signal, not the algorithm. SFT says: here is a good response, imitate it. Preference optimisation says: here are two responses, prefer this one. The second can express things that are awkward to demonstrate, such as being slightly less verbose or slightly more cautious, but it needs a model that can already generate both options. Rejection sampling, where you generate several candidates, keep the ones a reward model scores highest and then SFT on them, sits between the two and is often the cheapest way to get most of the benefit.
In practice, many teams ship a well-tuned SFT model and skip preference optimisation entirely, because the marginal gain is small relative to the engineering cost. That is a defensible choice. What is not defensible is skipping evaluation, which is the stage that actually determines whether any of this worked.
Multi-turn and tool-use data
Single-turn instruction-response pairs are the easy case. Real products are multi-turn, and multi-turn data has to be constructed as full conversations with consistent roles, including the assistant's earlier turns. If you flatten a conversation into one instruction and one answer, the model never learns to use context, to refer back, or to stay consistent with something it said three turns ago.
Tool use adds another layer. A tool-calling example needs the schema available in the prompt, a correctly formatted call with valid JSON arguments, and a tool result followed by a final answer that actually uses that result. The most common defect is a model that calls the tool correctly and then ignores the output, which happens when training examples contain final answers that were written independently of the tool result. Generate the final answer after the tool returns, or the data teaches the model to perform the ritual without consuming the information.
Keep a share of examples where no tool is needed, and a share where the correct behaviour is to ask a clarifying question. Without them, a model trained on tool-use data calls a tool for everything, which is worse than not having the capability at all.
Evaluation that means something
Hold out prompts, not just examples. If your dataset has five paraphrases of the same request and you split randomly, the held-out set leaks the training distribution and your score is fiction. Split by template, by customer, or by topic so that the evaluation measures generalisation rather than memorisation.
Score on a rubric rather than a single number: correctness, format compliance, completeness, refusal behaviour and length. Pairwise comparison against the base model on the same prompts is more reliable than absolute scoring, and it is what you will actually care about in production. If you use a model as a judge, be aware of its biases: it prefers longer answers, it prefers the first option in a pair, and it prefers text that resembles its own output. Randomise option order, cap length, and calibrate the judge against a few hundred human labels before trusting it.
Keep a frozen regression suite of prompts that must keep working, separate from the prompts you use to iterate. Every new adapter runs the suite. Without it, fixing one behaviour quietly breaks three others, and nobody notices until a customer does.
A sane workflow
Start from the strongest base you can afford, ideally one that has already been instruction-tuned, because SFT on a raw base model needs far more data to reach the same point. Build two hundred examples by hand and write the evaluation set first. Run a LoRA fine-tune at rank 16 and evaluate. Inspect twenty failures individually and classify them: format, knowledge, reasoning or refusal. Only format and refusal failures are SFT's job; the other two need retrieval, a stronger base, or a different objective.
Scale the dataset only after the small run shows a real gain, and scale in the direction the failures point. Keep the base model as a permanent baseline, version every dataset, and record the exact template. When the adapter beats the baseline on the held-out set and the regression suite, merge it, quantise it, and evaluate once more in the serving configuration, because quantisation can change behaviour in ways the training run never showed.