SFT learns a conditional distribution
In one lineDemonstrations teach behavior: if every example answers at once, the model may learn never to ask. Unseen tasks show how far it generalizes.
Give a model support conversations that demonstrate citing a return policy and asking for an order number, and it can learn similar behavior. If every example answers immediately and none asks for missing information, it may learn that habit too.
Training on these demonstrations is supervised fine-tuning (SFT). When preparing the data, consider both how many examples it contains and what behavior they teach. The model may apply what it learns to new situations and acquire new knowledge. Testing on unseen tasks tells us how far those improvements extend.
For a closer look at the data, What data teaches the model follows one demonstration through filtering, sampling, and labeling to show how each choice changes the learning signal.
First follow one conversation through training, then consider what the data can teach. If you already run experiments, jump to checking loss masks or deciding whether to try RL.
What it does
In one lineSFT raises the likelihood of demonstrated answers without sampling new ones: imitation learning. Task tests decide whether it is enough.
Given demonstrations of an input and its target response, training increases the likelihood of that response conditioned on the input. Let $x$ be the input, $y_t$ the target token at position $t$, and $y_{<t}$ the target text before it. The token-level cross-entropy is:
$$\mathcal{L}_{\text{SFT}} = -\sum_{t} \log \pi_\theta(y_t \mid x, y_{<t})$$
Ordinary offline SFT updates use demonstrations selected in advance, without generating and scoring a fresh batch of answers before each update. This is imitation learning. The demonstrations themselves may still have been generated by a model and filtered: using existing targets during the update does not mean data preparation involved no sampling.
SFT is commonly used to learn task formats, follow instructions, imitate expert behavior, or prepare a starting point for reinforcement learning (RL). Task-level tests still determine whether it is sufficient.
How one conversation sample actually enters SFT
In one lineSame next-token loss as pretraining, but a mask usually scores only the assistant answer. Score the end token too, matching the stop setting.
1. Pre-training and SFT: similar equations, different supervision
Pre-training text supplies its own next-token targets. Given $x_1,\ldots,x_T$:
$$ \begin{aligned} \mathcal L_{\text{pretrain}}&=\sum_{t=2}^{T}\ell_t,\\ \ell_t&=-\log p_\theta(x_t\mid x_{<t}). \end{aligned} $$
The text supplies its own targets without separate token-by-token annotation: this is self-supervised learning. An SFT demonstration specifies how the assistant should respond to the system and user messages. People may write those demonstrations, models may generate them for later filtering, or the dataset may combine several sources. “Supervised” means we select the behavior to learn; it does not require every word to be written by a person.
Both can use cross-entropy to train next-token prediction. Pre-training usually learns patterns from a large text collection; SFT uses selected demonstrations to adjust task behavior. How examples are structured, which data sources are mixed, and which positions contribute loss all affect what the model learns.
2. Next-token prediction does not require scoring every token
The chat template and tokenizer turn the messages into a sequence $z_1,\ldots,z_T$. Inputs and labels are shifted by one position: the model uses $z_{<t}$ to predict $z_t$. To train only on assistant responses, an assistant-only loss uses a loss mask to select the scored positions:
$$ \begin{aligned} \mathcal L_{\text{SFT}}&=\sum_{t=2}^{T}m_t\ell_t,\\ \ell_t&=-\log p_\theta(z_t\mid z_{<t}). \end{aligned} $$
Here $m_t\in\{0,1\}$ selects supervised targets. This simplified template is an example; role-marker supervision depends on the actual template.
system / user / assistant role marker → m_t = 0
assistant answer / end-of-message → m_t = 1
System and user messages remain available as context for later predictions, but the model is not trained to reproduce them. Training code commonly sets ignored labels to -100 so cross-entropy skips those targets.
Multi-turn training may score every assistant answer or only the final one; some setups score the full sequence. Whichever policy you choose, check that template boundaries and masks agree. Otherwise, user text or padding that you meant to ignore can accidentally become training targets.
3. The end token is behavioral supervision too
If the target contains only “I am fine.” without an end-of-message or end-of-sequence (EOS) token, this example does not explicitly teach where to stop. The model may have learned stopping in earlier training, but this demonstration supplies no target for it. A common choice is to include the end marker in the loss, with $m_t=1$:
I → am fine → . → <|im_end|>
The inference system places the corresponding token in its stop set and ends the message when it appears. Three pieces must agree: the ending marker used as a training target, its special-token ID in the tokenizer, and the inference engine's stop configuration.
The system still needs a length limit to prevent unbounded generation. Reaching that limit forces a cutoff; learning to stop means assigning the ending token a high probability when the answer is complete.
Follow the mask and the shift
In one lineLabels shift by one: the previous position predicts each token. Masked user text is still context; decode labels to see what is really supervised.
The user asks “What is 2 + 3?” and the demonstration answers “5.” To make alignment easy to see, represent the whole sequence with six symbols:
position 0 1 2 3 4 5
input <BOS> question <assistant> 5 <EOS> <PAD>
label -100 -100 -100 5 <EOS> -100
A real tokenizer splits the question into several tokens; “question” is a diagram placeholder. Initially, labels line up with input positions. The causal loss then shifts the targets by one:
| Output position | Predicts | Scored here? |
|---|---|---|
After <BOS> |
Question | No |
| After the question | <assistant> |
Not in this example |
After <assistant> |
5 |
Yes |
After 5 |
<EOS> |
Yes |
After <EOS> |
<PAD> |
No |
The label for 5 sits at position 3, but uses logits from position 2. Using position 3 to predict that same 5 would expose the current target in its own input.
No model is needed to check this. Construct logits where the two supervised targets receive probabilities 0.8 and 0.6. Their mean loss should be $(-\log0.8-\log0.6)/2\approx0.3670$.
The code assigns token ID 4 to the answer text 5, and ID 5 to <EOS>. Text and vocabulary IDs are different things. This tiny invented vocabulary is not a real tokenizer's mapping.
import math
import torch
import torch.nn.functional as functional
probabilities = torch.full((1, 6, 6), 1 / 6, dtype=torch.float64)
probabilities[0, 2] = torch.tensor([.04, .04, .04, .04, .8, .04], dtype=torch.float64)
probabilities[0, 3] = torch.tensor([.08, .08, .08, .08, .08, .6], dtype=torch.float64)
logits = probabilities.log().requires_grad_()
labels = torch.tensor([[-100, -100, -100, 4, 5, -100]])
loss = functional.cross_entropy(
logits[:, :-1].reshape(-1, 6),
labels[:, 1:].reshape(-1),
ignore_index=-100,
)
assert math.isclose(loss.item(), -(math.log(.8) + math.log(.6)) / 2, abs_tol=1e-7)
loss.backward()
active_positions = (logits.grad.abs().sum(-1) > 0).nonzero().tolist()
assert active_positions == [[0, 2], [0, 3]]
We shift manually because this code calls cross-entropy directly. The Transformers causal LM loss already handles shifting (checked against ForCausalLMLoss in v5.20.0, 2026-10); do not pre-shift labels again when passing them to a model that does this internally.
Why test generation if both token predictions look good?
When predicting <EOS> above, the model sees the demonstration's 5, not a token it just sampled. This is teacher forcing: each position learns the next step from the correct preceding tokens.
The 0.6 probability therefore means “emit <EOS> given that the preceding token is 5.” Sampling step by step from these probabilities produces the complete 5 → <EOS> sequence with probability $0.8\times0.6=0.48$, or $\exp(-2\times\text{mean loss})$. This is the probability of that two-token sequence, not overall task success; other answers could also be correct.
If the first sampled token is different, the next prediction sees a different prefix. This demonstration's loss does not directly check that situation. Shared parameters may generalize, but generation tests are still needed: inspect complete answers, behavior after a wrong prefix, and stopping.
If user targets are masked, how does the model learn to use the question?
A loss mask selects predictions to score, not text to read. Predicting 5 still depends on the preceding 2 + 3. Gradients can pass through attention and shared parameters into computations that process context. Not scoring reconstruction of the question does not remove its influence on learning.
An attention mask has a different job: controlling visibility, such as hiding future tokens or padding. Hiding the user message there would remove information needed to answer.
What about multiple turns and tool calls?
| Conversation content | Common assistant-only treatment | What to verify |
|---|---|---|
| System / user | Context, not prediction targets | A training choice, not a rule for every task |
| Assistant tool call | Can supervise the name and arguments | The template must identify the call correctly |
| Tool result | Usually context for the next answer | Do not mistake tool output for an assistant response |
| Assistant answer | Supervise content and ending marker | Every assistant turn, or only the last? |
| Padding | Exclude from loss | Distinguish by position if PAD and EOS share an ID |
The TRL v1.16.0 guide (checked 2026-10) exposes assistant-only and completion-only options separately. Their names alone do not establish equivalent behavior.
Assistant-only loss needs {% generation %} and {% endgeneration %} markers in the chat template. The docs say TRL patches them in automatically for known model families such as Qwen3 when assistant_only_loss=True; for other models, check the template yourself. Inspect masks returned by the actual template and decode final labels for a few examples to see which text actually supplies supervision.
Check truncation too: does the example retain an answer, or only its prompt? Was the ending marker cut off? All--100 labels provide no supervision and need handling during data checks. Packing additionally needs sample-boundary and attention checks; a loss mask alone does not isolate conversations.
Test cases the demonstrations did not cover
In one lineA falling training loss does not show the model can handle cases the demonstrations missed. Hold out new phrasings, combinations and exceptions.
Training covers routine returns, but evaluation includes cross-border orders and opened products. The model may generalize using prior knowledge and related examples, or apply the wrong rule. Missing coverage does not guarantee failure, but a lower training loss does not establish success.
Hold out different phrasings, combinations, and exceptions. These tests help distinguish learning a task rule from relying on familiar answers.
Lower loss, better answers?
In one line“Refund allowed” and “not allowed” differ by one word. In the example, getting it wrong moves the mean loss by about 0.011, so test the decision.
“Refund allowed” and “refund not allowed” differ by one word but have opposite consequences. Cross-entropy does penalize the wrong token, potentially strongly. Ordinary token weighting just does not know which position matters most to the task.
If the target-token probability falls from 0.9 to 0.1, its negative log-likelihood rises from about 0.105 to 2.303. Averaged over 200 tokens with other terms unchanged, the reported loss rises by only about 0.011. Check the refund decision as well as average loss.
More targeted demonstrations, sample or token weighting, and task-level checks can help. RL is one option, not the only remedy.
Did the examples show when to ask a question?
In one lineIf every example answers confidently, the model rarely learns to ask or abstain. SFT can teach both; generic refusals can make it dodge answerable questions.
If every demonstration answers confidently, the model gets little practice asking questions, abstaining, or admitting uncertainty. SFT can teach those behaviors: include examples such as “Please provide the order number” or “There is not enough evidence to tell.”
The challenge is matching behavior to available information. Answer when evidence is sufficient; ask when something essential is missing. Adding generic refusal templates can instead make the model avoid answerable questions.
Preference training or RL can compare the costs of different choices, but still depends on suitable rewards. No training method, by itself, guarantees honesty.
How do you check whether knowledge was learned?
In one lineSFT can store facts, but not reliably from one occurrence or under new phrasings. When rules change often, retrieval is easier to update.
SFT can store new facts in model parameters, but does not guarantee reliable learning from one occurrence or successful recall under a different question. Fluent expert wording is not a substitute for fact checking.
Suppose a return window changes from 30 days to 14. Fine-tuning is one option; if policies change often, retrieving the current document may be easier to update and audit. Both approaches need tests for stale rules, correct citations, and fabrication when evidence is missing.
Choosing SFT, continued pretraining, or retrieval depends on knowledge volume, update frequency, and task structure—not a rule that SFT cannot learn facts.
In a 2024 closed-book QA study, Gekhman and colleagues found that new facts were fitted more slowly than familiar knowledge, with increased hallucination in their setup. This motivates testing new-fact learning separately from regressions on familiar questions. It does not establish that SFT cannot learn facts, or that every model, dataset, and training method behaves the same way.
So when is SFT enough
In one lineIf format and task quality pass, or the issue is using a skill the model already has, SFT may be enough.
If these checks already pass, a more elaborate training pipeline may not be necessary:
- Both format and task quality meet requirements. For extraction, check field correctness and missing information, not just parsable JSON.
- You want a reliable behavioral starting point. Demonstrations can establish tool protocols and response habits. Their value before RL depends on the base model and task.
- The main problem is eliciting an existing capability. Try a small set of useful demonstrations, then check whether improvements transfer to unseen inputs before reaching for a heavier method.
The division of labor between SFT and RL
In one lineGood demonstrations: start with SFT. A process hard to write but outcomes you can judge: RL may fit. The two can alternate.
Start with the reliable signal you can obtain. If you can provide useful demonstrations, try SFT. If the desired process is hard to write down but attempted outcomes can be evaluated, RL may be useful. A workflow can also alternate the two.
| Question | SFT | RL |
|---|---|---|
| Direct signal | Selected target outputs | Rewards for sampled actions or outcomes |
| Typical update granularity | Token-level cross-entropy, with masks and weights | Rewards assigned to actions through returns, advantages, and related estimators |
| Can teach clarification or abstention? | Yes, with context-appropriate examples | Yes, if rewards distinguish useful questions from unnecessary avoidance |
| Requires judging current-policy attempts? | Ordinary offline SFT does not | Usually needs rollouts, or recorded trajectories with appropriate estimators |
| Main checks | Coverage, templates, masks, generalization | Reward validity, sampling distribution, update stability |
Compare under the same task and evaluation budget. More elaborate training does not automatically produce a better result.
When is it worth trying RL?
In one lineNo loss threshold says “start RL”. Check that the reward tells good from bad, attempts on one task score differently, and RL beats a cheaper baseline.
There is no universal “start below loss 0.5” rule. Tokenizers, response lengths, masks, and reductions all change that number. A more useful check is to generate answers from several checkpoints on the same held-out tasks and inspect their failures.
Consider a support assistant that uses an order tool. These are illustrative numbers, not measured results or deployment thresholds:
| Check | Checkpoint A | Checkpoint B | Interpretation |
|---|---|---|---|
| Parsable arguments in 100 calls | 72 | 96 | A still struggles with the protocol; templates and demonstrations may be the direct fix |
| Completed tasks out of 100 | 42 | 61 | B has better formatting, but task success still lags |
| Useful clarifications on 20 incomplete requests | 3 | 12 | Overall success must not hide this failure category |
B's numbers do not automatically justify RL. Ask three more questions:
- Can the reward distinguish good attempts from bad ones? Rewarding valid JSON alone can accept irrelevant answers. Check the reward or verifier against a small human-reviewed slice.
- Do different attempts on the same task provide a learning signal? With within-group relative advantages, equal scores give no contrast from that term (for how common such groups are, see DAPO's dynamic sampling). If every attempt fails, inspect difficulty, sampling, and reward design; more SFT is not the only possible response.
- What does RL solve beyond a simpler, equal-budget alternative? Start from the same checkpoint and compare continued SFT, generation-and-filtering followed by training, and a short RL run. Track quality, length, cost, and regressions—not just training reward.
Choose metrics and stopping conditions before the pilot. If reward rises while success stays flat and answers get longer, inspect the reward before simply adding steps.
SFT followed by RL is common, not mandatory. DeepSeek-R1-Zero investigated RL without a preliminary SFT stage; that did not mean starting from random weights. Whether this stage helps depends on the model and task.
A closer look: DFT changes token weights, not the gate for starting RL
DFT (2025) weights CE by the current target-token probability, with the weight detached:
$$ \ell_{\text{DFT}}=-\operatorname{sg}(p_y)\log p_y. $$
This is one term; a batch still needs a mask and reduction. It adds no environment reward and specifies no probability threshold for switching to RL. As of October 2026, the TRL v1.16.0 SFTTrainer ships this loss: set loss_type="dft" in SFTConfig. Before using the built-in option, confirm that its mask and reduction match your setup.
Forgetting detach() changes the update. With binary target probability $p=0.01$, the positive logit's CE gradient is −0.99; detached weighting gives −0.0099. Fully differentiating $-p\log p$ instead gives about +0.0357, so gradient descent would lower this already unlikely target's score.
That is a chain-rule difference, not a precision issue. The tests check both directions. Probability weighting can also weaken learning from difficult but important examples. Compare on your held-out tasks rather than treating a paper's gains as universal.
What to check when designing SFT data
In one lineFive questions: coverage, whether key tokens are tested, clarification and refusal examples, what the base knows, and whether RL is needed.
- Which situations do my demonstrations cover? For the ones they don't, how does the model behave — have I tested it?
- Is the correctness I care about "does it look right overall" or "are these few pivotal tokens right"? For the latter, test the decision separately from mean loss.
- Does my SFT set contain context-appropriate abstention or clarification? Test what happens when essential evidence is missing.
- Does the base model already know the facts I want to teach? Can it give correct facts and supporting evidence under different phrasings, rather than just sound confident?
- Does this task really need RL? When useful demonstrations are available, start with an SFT baseline and compare equal-budget task quality. A fixed output format alone does not decide which method is more cost-effective.
Quick learning: what does SFT teach?
In one lineInterview answer: SFT raises demonstration-token likelihood, often on assistant tokens only; that loss does not measure task success.
Assistant-only CE, behavior cloning, and the capability ceiling
Remember: SFT optimizes demonstration-token likelihood given the preceding context; conversational setups often score only assistant tokens. That objective does not guarantee that every demonstration becomes more likely after every update, or that unseen tasks are solved.
Reference answer
In a common assistant-only setup, SFT serializes the conversation and uses the system and user messages as context to learn the assistant answer and its end token. Demonstrations can teach format, tone, tool calls, and solutions. Their coverage and quality matter; teacher-forced token loss does not directly measure task success, so complete generated answers still need checking.
Deep dive: why does low token CE not imply a better complete answer?
CE penalizes errors at individual target tokens, but a mean over a long response can obscure the few decisions that determine success. Inspect those decisions separately. Task checks, targeted examples, weighting, and preference or reward signals offer different ways to emphasize them.