Supervised Fine-Tuning (SFT): ChatML Formatting & Assistant Loss Masking
How Supervised Fine-Tuning transforms a raw Base LLM document completer into a helpful Chat Assistant: ChatML serialization, Assistant-only loss masking (ignore_index = −100), packing, and why 1,000 curated examples beat 100,000 noisy ones.
Supervised Fine-Tuning (SFT) teaches a pretrained base LLM to follow chat instructions by training on curated (Prompt, Assistant Response) pairs while masking prompt tokens with ignore_index = -100.
A raw pretrained LLM only predicts the next web text—it will keep asking more questions instead of answering! Loss masking focuses gradients strictly on assistant replies.
SFT is Stage 1 of every modern post-training recipe — teaching a Base model that already knows the whole internet how to listen, answer, and stop talking!
A single off-by-one bug in SFT label masking (accidentally masking <|im_end|> to −100) produces a fine-tuned model that literally never stops generating until max_tokens!
Knowing when to use SFT (style, domain tone, JSON format, strict workflows) vs. RAG (dynamic/new factual knowledge) saves months of wasted fine-tuning runs.
Favorite fine-tuning interview question: 'Why do we set labels = -100 on prompt tokens during Chat SFT, and what breaks if you also mask the EOS token?'
During Chat SFT in PyTorch, what happens if your data collator accidentally sets label = -100 on the Assistant's closing <|im_end|> (EOS) token?
- Contrast a Base Pretrained LLM (next-token web completer) with an SFT Instruction-Tuned Assistant
- Implement Assistant-only loss masking in PyTorch by setting labels = −100 on System and User prompt tokens while keeping <|im_end|> UNMASKED
- Explain why data diversity and quality outweigh raw dataset size in SFT (Superficial Alignment Hypothesis)
- Avoid catastrophic forgetting and sample-packing cross-contamination during SFT
F.cross_entropy so prompt tokens contribute zero loss and zero gradientPre-training fills an LLM's brain with 99% of its world knowledge, like a scholar who memorized every book in a library — but has never held a conversation. SFT is a short etiquette & formatting bootcamp: by masking out the user's question (−100) and computing loss ONLY on clean Assistant replies, we teach the scholar how to answer clearly and stop cleanly at <|im_end|>!
1. Base Model vs. SFT Assistant Behavior
Base models predict what document continues the text (like an exam sheet of questions); SFT models predict the Assistant's reply.
The Exact SFT Loss Objective
SFT uses the exact same Next-Token Cross-Entropy Loss as pre-training — just restricted to Assistant token positions :
2. Assistant-Only Loss Masking (`ignore_index = −100`)
Toggle Mask Prompt (−100) ON vs. OFF in the mini-lab below to see which tokens generate gradients!
Why Masking Prompt Tokens Matters
If you compute loss on long 2,000-token RAG prompts + 50-token answers without masking, 97.5% of your gradient is wasted teaching the LLM to memorize random user questions instead of mastering the 50-token answer! Masking prompts to -100 focuses 100% of gradient capacity on the Assistant's output + <|im_end|>.
SFT Token Loss-Mask Switcher (−100 on Prompt)
3. Data Quality > Quantity & Sequence Packing
In SFT, 1,000 spotless, diverse examples beat 100,000 noisy scraped examples every single time.
SFT Production Checklist
- Filter aggressively: Deduplicate, verify code/JSON outputs, and strip refusal/boilerplate noise.
- Keep LR small: Use 10×–30× smaller learning rate than pre-training (e.g.
1e-5to2e-5for full SFT) and 1–3 epochs max to avoid Catastrophic Forgetting. - Pack with Block-Diagonal Masks: When packing multiple chats into one 8K training window, reset RoPE position IDs and block cross-chat attention so Chat B never attends to Chat A!
Worked Example: Building SFT Labels in 4 Lines of Python
Tokenized chat: input_ids = [10, 20, 30, 40, 50, 2] where tokens 0..2 are User prompt and 3..5 are Assistant + EOS (2).
labels = input_ids.copy() → [10, 20, 30, 40, 50, 2].
In PyTorch Chat SFT, which token MUST NOT be masked to −100?
Should you use SFT or RAG to teach an LLM your company's daily changing product pricing?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Mostly SFT elicits and formats knowledge learned during pre-training — though distilling high-quality Chain-of-Thought traces (e.g., from DeepSeek-R1) via SFT can dramatically boost small-model reasoning!
Token-Level SFT Assistant Loss Masking Animator
Watch the training cursor scan across a ChatML sequence: prompt tokens get ignore_index = −100, while Assistant + <|im_end|> tokens backpropagate gradients.
−100) on prompt tokens and active ONLY on Assistant tokens + <|im_end|>.Domain-Specific Tone & Format Alignment
Fine-tunes compact 8B models to output exact SQL dialects, clinical notes, or brand-voice replies with zero few-shot prompt bloat.
import torch
import torch.nn.functional as F
# SFT Assistant-Only Loss Masking: ignore prompt tokens with ignore_index = -100
prompt_ids = [101, 205, 309, 412] # user prompt tokens (DO NOT compute loss)
answer_ids = [518, 622, 701, 2] # assistant reply tokens (COMPUTE loss)
input_ids = torch.tensor(prompt_ids + answer_ids)
labels = input_ids.clone()
labels[:len(prompt_ids)] = -100 # mask out user prompt
# Shift logits/labels by 1 for next-token causal LM prediction
vocab_size = 1000
logits = torch.randn(1, len(input_ids), vocab_size)
loss = F.cross_entropy(logits[:, :-1, :].reshape(-1, vocab_size), labels[1:], ignore_index=-100)
print(f"Masked SFT loss (computed on {int((labels[1:] != -100).sum())} assistant tokens): {loss.item():.3f}")
labels = -100 on System and User prompt tokens during Chat SFT?