Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← Fine-tuningAI guideIntermediate#fine-tuning#sft#trl#training
Frame · ai-engineering / fine-tuning / 03-supervised-fine-tuning.mdGuide 074 / 103

Supervised fine-tuning (SFT)

Supervised fine-tuning is the workhorse of post-training: you show the model input and output pairs and nudge its weights so it produces outputs like yours. Almost every other technique in this track, from DPO to RL, assumes you start from a model that has already been through some SFT. If you only learn one training method well, make it this one.

Why it matters

SFT is how base models become chat models, and how chat models become specialists. It is the right tool when you can write down what a good answer looks like: a house style, a strict output schema, a domain-specific classification, or a tool-calling pattern. It is also the first stage of most reasoning pipelines, where the model is shown worked solutions before RL sharpens it.

It is also the method most likely to go wrong quietly. A model can reach low training loss while forgetting general skills, overfitting to phrasing, or learning to imitate the mistakes in your data.

How it works

Mechanically, SFT is next-token prediction on your examples. The loss is token-level cross-entropy, and the trick is choosing which tokens count. You almost always want loss only on the assistant's response, not on the system prompt or the user's message, otherwise the model spends capacity learning to predict your prompts.

Rendering diagram…

Three details matter more than the rest:

  1. Chat template. The model must see exactly the same special tokens and role markers at training time as at inference time. Use the tokenizer's template and let the trainer apply it; hand-rolled templates are a common source of "the model never stops generating" bugs, usually because the end-of-turn token does not match.
  2. Loss masking. In TRL, prompt-completion datasets get completion-only loss by default. For messages datasets, set assistant_only_loss=True, which relies on generation markers in the chat template (TRL patches known families such as Qwen3 automatically).
  3. Packing. Packing several short examples into one sequence improves GPU utilisation. TRL supports packing=True with a best-fit strategy; make sure attention does not leak across packed examples (padding-free packing with FlashAttention handles this).

Hyperparameters that usually matter: learning rate (TRL's SFT default is 2e-5 for full fine-tuning; for LoRA the docs suggest something closer to 1e-4), number of epochs (1 to 3 is typical; more invites memorisation), and maximum sequence length.

Reference architecture

A sensible SFT pipeline treats training as one step in a loop with data versioning and evaluation on both sides.

Rendering diagram…

The regression suite is what catches catastrophic forgetting: a few hundred general prompts (instruction following, safety refusals, reasoning) scored before and after training. If your specialist model gets worse at saying "I don't know", you want to find out here, not from a customer.

Start from an instruct model rather than a base model unless you are deliberately teaching a new chat format. Instruct models need less data and already know how to follow the chat template.

Code

This uses TRL's SFTTrainer with a LoRA adapter, assistant-only loss and packing. It matches the API in the current TRL docs (v1.x).

from datasets import load_from_disk
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer

ds = load_from_disk("triage_sft")  # prompt / completion conversational rows

args = SFTConfig(
    output_dir="qwen3-triage-sft",
    num_train_epochs=2,
    learning_rate=1e-4,          # higher LR because we train a LoRA adapter
    per_device_train_batch_size=4,
    gradient_accumulation_steps=4,
    max_length=2048,
    packing=True,
    eval_strategy="steps",
    eval_steps=200,
    logging_steps=10,
    report_to="none",
)

trainer = SFTTrainer(
    model="Qwen/Qwen3-4B",
    args=args,
    train_dataset=ds["train"],
    eval_dataset=ds["test"],
    peft_config=LoraConfig(r=16, lora_alpha=32, target_modules="all-linear"),
)
trainer.train()
trainer.save_model()

Watch both training and eval loss. If eval loss starts rising while training loss keeps falling, you are memorising; stop earlier or add data.

Trade-offs and pitfalls

  • SFT teaches imitation, not judgement. The model learns to produce outputs that look like yours, including your errors. It does not learn why an answer is right. That is where preference tuning and RL come in.
  • Catastrophic forgetting. Aggressive full fine-tuning on a narrow dataset degrades general skills. LoRA, lower learning rates, fewer epochs and mixing in some general instruction data all help.
  • Knowledge injection is unreliable. SFT on facts tends to teach the style of knowing them more than the facts themselves, which can increase confident hallucination. Use retrieval for knowledge.
  • Thinking models need care. If your base model emits reasoning traces, decide whether your training targets include them. Mixing examples with and without reasoning confuses the model.
  • Template mismatch. Train with one template, serve with another, and quality falls off a cliff. Pin the tokenizer and template version with the checkpoint.
  • Eval on training distribution only. Always include out-of-distribution and general prompts in your eval.

Checklist

  • Start from an instruct checkpoint and its official chat template.
  • Use completion-only or assistant-only loss.
  • Hold out a validation split and watch eval loss, not just training loss.
  • Keep epochs low (1 to 3) and stop on validation plateau.
  • Run a general regression suite before and after training.
  • Pin model, tokenizer, template and dataset versions together.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.