Chapter 28 of 40 · ~20 min read & lab+75 XP
Chapter 28 · Generative AI

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.

What Is It?

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.

Why Is It Required?

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.

Everyday Analogy: Training a talented writer to answer customer tickets by grading ONLY their reply drafts, never grading them on copying the customer's question.
Why ML Engineers & Data Scientists Actually Need This

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!

ML / AI Engineer

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!

Data Scientist

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.

Interview & Debug Edge

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?'

Step 0 · Test Your Gut Before Any Math!

During Chat SFT in PyTorch, what happens if your data collator accidentally sets label = -100 on the Assistant's closing <|im_end|> (EOS) token?

What You Will Master in This Chapter
  • 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
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
ignore_index=−100\text{ignore\_index} = -100Say aloud:“PyTorch masked label sentinel”
Plain-English Meaning
Default label value ignored by F.cross_entropy so prompt tokens contribute zero loss and zero gradient
Everyday Example
labels[:prompt_len] = -100
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Pre-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

Everyday Story First (Zero Math Yet!)

Base models predict what document continues the text (like an exam sheet of questions); SFT models predict the Assistant's reply.

Base Pretrained LLM vs. SFT Instruction-Tuned AssistantBase Model (Document Completer)Prompt: "Explain gravity simply."Output: "Explain magnetism simply. Explain optics simply..."SFT Chat Model (Assistant)Prompt: "Explain gravity simply."Output: "Gravity is the invisible pull between masses.<|im_end|>" ✓
A Base LLM only continues web text (often answering a question with more questions!); Supervised Fine-Tuning (SFT) unlocks conversational instruction following and clean stop-token termination.

The Exact SFT Loss Objective

SFT uses the exact same Next-Token Cross-Entropy Loss as pre-training — just restricted to Assistant token positions A\mathcal{A}: LSFT(θ)=−1∣A∣∑t∈Aln⁡Pθ(xt∣x<t)\mathcal{L}_{\text{SFT}}(\theta) = -\frac{1}{|\mathcal{A}|} \sum_{t \in \mathcal{A}} \ln P_\theta(x_t \mid x_{<t})

2. Assistant-Only Loss Masking (`ignore_index = −100`)

Everyday Story First (Zero Math Yet!)

Toggle Mask Prompt (−100) ON vs. OFF in the mini-lab below to see which tokens generate gradients!

Assistant-Only Loss Masking: ignore_index = −100 on Prompt Tokens<|user|>−1002 + 2 =−100<|asst|>−100TheLOSS ✓answer: 4LOSS ✓<|im_end|>LOSS ✓Crucial: ALWAYS unmask <|im_end|> so the model learns WHEN to stop talking!
In Chat SFT, System and User prompt tokens are masked with label = −100 (ignored by PyTorch CrossEntropyLoss) so gradients update ONLY on Assistant response tokens + <|im_end|>!

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|>.

Animated Mini-Lab • 5.1

SFT Token Loss-Mask Switcher (−100 on Prompt)

<|user|>
label: −100
Reverse
label: −100
'cat'
label: −100
<|asst|>
label: −100
'tac'
GRADIENT ✓
<|im_end|>
GRADIENT ✓

3. Data Quality > Quantity & Sequence Packing

Everyday Story First (Zero Math Yet!)

In SFT, 1,000 spotless, diverse examples beat 100,000 noisy scraped examples every single time.

Quality > Quantity in SFT (Superficial Alignment Hypothesis)100K Noisy Scraped Pairs → 64% Win Rate1K Curated, Diverse, Verified Pairs → 88% Win Rate (Less Overfitting!)
The LIMA / Superficial Alignment Hypothesis: 1,000 curated, diverse, high-quality instruction pairs routinely beat 100,000 noisy scraped examples!

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-5 to 2e-5 for 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!
Walk Through With Me · Interactive Worked Example

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).

11. Clone input_ids into labelsStep 1 / 2

labels = input_ids.copy() → [10, 20, 30, 40, 50, 2].

Teacher's Note: Hugging Face models automatically shift logits/labels by 1 internally!
Pause & Check · Quick Intuition Pulse

In PyTorch Chat SFT, which token MUST NOT be masked to −100?

Try It YourselfStandard

Should you use SFT or RAG to teach an LLM your company's daily changing product pricing?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS SFT Loss Masking Animator scan across prompt (−100) and Assistant (backprop ✓) tokens.
Interactive Animation • 5.1 Deep Lab

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.

SKIP (−100)
<|user|>
−100
Capital
−100
of
−100
Japan?
−100
<|asst|>
−100
Tokyo
loss ✓
.
loss ✓
<|im_end|>
loss ✓
0%
Token 1/8: <|user|>
Intuition Takeaway: SFT turns a Base LLM into an instruction-following Assistant using standard next-token loss masked (−100) on prompt tokens and active ONLY on Assistant tokens + <|im_end|>.
Where This Powers Real ML, Deep Learning & Generative AI

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.

Production NumPy & PyTorch Code Patterns
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}")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Training SFT for 15 epochs on 2,000 examples until training loss hits 0.01.
Best Practice: Watch validation loss — 2–3 epochs is usually optimal; over-training SFT causes severe Catastrophic Forgetting of general reasoning!
Chapter Mastery Check (+75 XP)
Score: 0 / 1
1Why do we set labels = -100 on System and User prompt tokens during Chat SFT?

Apply What You Learned — Solve Matching Coding Problems