Supervised fine-tuning (SFT)

In one sentence

Keep training a pretrained model on (prompt, ideal response) pairs so it imitates them. It teaches format, style and task behavior; a few thousand curated examples usually beat a million noisy ones.

Analogy: An apprentice studying a binder of the master's finished work: they learn to produce the same kind of output, including the master's mistakes if the binder contains them.

Same loss as pretraining, applied only to the answer. When eval regresses, fix the data before touching hyperparameters.

How it works

  • Same next-token loss as pretraining, usually computed only on response tokens; the prompt is masked.
  • Render every example in the model's exact chat template; training and serving with different templates silently drops quality.
  • Typical runs use ~1k–100k examples and 1–3 epochs; more epochs on small data means memorization.
  • If eval loss rises while training loss keeps falling, stop and ship the earlier checkpoint.
  • Run the same eval before and after, on the target task and on general ability.

Check yourself

Answer to mark it learned; your answers aren't scored.

After SFT, your model's answers are correct, but it doesn't stop: it keeps generating, sometimes inventing a new user turn. Training and eval loss looked healthy. Most likely cause?

Go deeper

Full explanation

Supervised fine-tuning keeps training a model with the same next-token loss as pretraining, but on curated (prompt, ideal response) pairs. The model learns to imitate those responses: their format, tone and the task's decision rules. It is how a base model becomes an assistant, and how you specialize one for your task.

How it works:

  • Chat template. Each example is rendered in the model's exact template (role markers, special tokens such as <|im_start|>, the end-of-turn token). Train and serve with the same template, or quality drops silently.
  • Loss masking. The loss is usually computed only on response tokens; prompt tokens are masked, so every gradient goes to answering, not to predicting the question.
  • Data. Quality beats quantity: LIMA aligned a 65B model with ~1,000 hand-curated examples. Task SFT typically uses ~1k–100k.
  • Hyperparameters. 1–3 epochs; learning rate ~1e-5–2e-5 for full fine-tuning, ~1e-4–2e-4 with LoRA & QLoRA. More epochs on small data means memorization.

Where to run it: managed APIs (Vertex AI, Bedrock) take a JSONL of chat examples and handle the GPUs (OpenAI's fine-tuning closed to new users in 2026 and is winding down); for open weights, Hugging Face TRL's SFTTrainer, Axolotl or Unsloth. Either way, run the same eval before and after, on the target task and on general ability (Catastrophic forgetting).

Code SFT with Hugging Face TRL (LoRA on one GPU)
pythonSFT with Hugging Face TRL (LoRA on one GPU)
from datasets import load_dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer

MODEL = "Qwen/Qwen2.5-7B-Instruct"  # any HF chat model

# Rows: {"prompt": [{"role": "user", ...}], "completion": [{"role": "assistant", ...}]}
data = load_dataset("json", data_files={"train": "train.jsonl", "eval": "eval.jsonl"})

config = SFTConfig(
    output_dir="sft-claims-v1",
    num_train_epochs=2,             # 1-3; more on small data = memorizing
    learning_rate=2e-4,             # LoRA range; ~2e-5 for full fine-tuning
    per_device_train_batch_size=4,
    gradient_accumulation_steps=8,  # effective batch of 32
    completion_only_loss=True,      # loss on response tokens only
    eval_strategy="steps",
    eval_steps=50,                  # watch eval loss for overfitting
    bf16=True,
)
trainer = SFTTrainer(
    model=MODEL,                    # chat template comes from the tokenizer
    args=config,
    train_dataset=data["train"],
    eval_dataset=data["eval"],
    # LoRA fits one GPU; full fine-tuning needs ~16 bytes/param (weights+grads+Adam)
    peft_config=LoraConfig(r=16, lora_alpha=32, target_modules="all-linear"),
)
trainer.train()
trainer.save_model()
Real example

A bank needs dispute summaries in a fixed 5-field format with compliance-approved wording. A prompted frontier model fills the fields correctly 85% of the time on a 200-case eval set, but the wording drifts. Analysts write 2,000 gold summaries; SFT of an 8B open model with LoRA (2 epochs, a few GPU-hours) reaches 96% field accuracy with the approved phrasing, at a fraction of the per-call cost. A third epoch kept lowering training loss but raised eval loss, so they shipped the epoch-2 checkpoint.

Trade-offs +4 · −4

+ You gain

  • The most reliable way to lock in a format, tone or task behavior that prompting only approximates.
  • Shorter prompts at inference: the instructions live in the weights.
  • Lets a small model match a big one on a narrow task, the basis of cost-cutting distillation.
  • Simple, stable training: a plain supervised loss and mature tooling (TRL, Axolotl, managed APIs).

− You pay

  • Only as good as the examples: it faithfully imitates their errors and biases.
  • Can erode general skills and the base model's safety behavior.
  • Teaches imitation, not preference: it can't learn "A is better than B" and can't exceed its demonstrations.
  • You now own a model version tied to a base model that will be deprecated.

Use it when

A stable, narrow task with a clear ideal output where prompting plateaus on format, style or consistency, or when a small model should replace a large one.

Avoid it when

To teach facts that change (use RAG), with fewer than ~50–100 good examples, or before an eval set shows prompting is really the bottleneck.

Numbers to know 5
  • LIMA: ~1,000 curated examples aligned LLaMA-65B competitively (Zhou et al., 2023).
  • InstructGPT's SFT set was only ~13k prompts with labeler-written answers.
  • OpenAI's SFT guide: minimum 10 examples; gains typically from 50–100 (platform closed to new users, 2026).
  • Rule of thumb: 1–3 epochs; LR ~1e-5–2e-5 full, ~1e-4–2e-4 LoRA.
  • Qi et al. (2023): 10 adversarial examples (<$0.20) undid GPT-3.5 Turbo's safety tuning.
Common pitfalls 4
  • Template mismatch: training with one chat template and serving with another, or dropping the EOS token, so the model rambles or never stops.
  • Overfitting small data: train loss falls while eval worsens after epoch 2–3. Hold out a set and keep the best checkpoint.
  • Training on raw production logs without curation: SFT copies the bad answers too.
  • Measuring only the target task: also check general ability and safety refusals didn't regress.
Interview questions 3

Answer out loud first, then reveal.

You have 500 examples and a 7B model. How do you approach SFT?Show answer

First I check the data is worth imitating: I read 100 examples and dedupe, because SFT copies whatever is there. I hold out ~15% as eval, plus a small general-ability set. Then LoRA, 2–3 epochs, LR around 1e-4 to 2e-4, loss only on responses, the model's own chat template. With 500 examples overfitting is the main risk, so I check the task metric per epoch and keep the best checkpoint. If results fall short, I invest in more and better examples before tuning hyperparameters.

Why mask the prompt tokens in the loss?Show answer

Because I want the model to learn to produce answers, not to model the distribution of prompts. With the prompt in the loss, gradient is spent predicting questions, often long, repeated system prompts, which dilutes the signal from the responses and can teach the model to write like a user. With masking, every gradient comes from the behavior I'm paying for. It's the standard default, not a law; in continued pretraining every token counts.

SFT or preference tuning: how do you choose?Show answer

It depends on what I can write down. If I can produce the ideal answer (an extraction, a format, a house style), SFT is simpler and more direct. If I can only judge which of two answers is better (helpfulness, tone, when to push back), I need preference pairs and DPO or RLHF. In practice they stack: SFT first for format and a sensible starting policy, then DPO to sharpen it. SFT alone has a ceiling: it imitates its demonstrations, so it can't beat them.