Supervised Fine-Tuning (SFT), Instruction Datasets, Assistant-Only Loss Masking & Distillation
- β Golden Rule of LLM Engineering: Use RAG for dynamic or private factual knowledge; use Fine-Tuning (SFT/LoRA) to teach behavioral form, domain syntax, strict JSON/tool-call reliability, or to distill a large expensive model ($10/1M) into a fast 8B specialist ($0.05/1M).
- β In Supervised Fine-Tuning (SFT), never compute cross-entropy loss on system prompts or user questionsβapply Assistant-Only Loss Masking by setting labels[t] = -100 on all non-assistant tokens so gradients only train the modelβs responses.
- β Wait-free Sequence Packing (Multipack + FlashAttention varlen cu_seqlens) concatenates short training examples into full 8,192-token buffers while isolating cross-example attention masks, accelerating SFT throughput by 3β5x.
- β LIMA ("Less Is More for Alignment") Principle: 5,000 deduplicated, execution-verified, high-complexity SFT trajectories consistently beat 200,000 noisy unverified scraped conversations.
01. Architectural Decision Matrix: Prompt Engineering vs. RAG vs. Fine-Tuning (SFT / LoRA)
| Dimension | Prompting + Context Caching | Agentic RAG + Tool Calling | Fine-Tuning (SFT / LoRA / DPO) |
|---|---|---|---|
| Primary Goal | Rapid task specification via instructions & 3β5 few-shot examples | Grounding responses in live, cited, ACL-protected external facts | Baking in domain behavior, DSL syntax, tone, or distilling 400B β 8B |
| Data Freshness | Instant (edit system prompt) | Real-time (sub-second DB/index updates) | Static snapshot per training cycle (hours/days) |
| Per-Request Token Cost | High if long few-shot prefix isn't KV-cached | Medium (retrieved chunks added to prompt) | Lowest (zero-shot prompt on a compact 8B model!) |
| Hallucination Control | Moderate | High (inline chunk IDs & grounding verifiers) | Can increase hallucination if trained on unverified facts |
02.
Assistant-Only Completion Loss Masking (IGNORE_INDEX = -100)
In PyTorch nn.CrossEntropyLoss(ignore_index=-100), any token position whose target label is set to -100 contributes zero loss and zero gradient. During multi-turn SFT, we mask all system, user, and tool_result tokens to -100 and only supervise assistant completions (and end-of-turn <|im_end|> stop tokens):
INPUT TOKENS: [ <|im_start|>, user,
, Write, SQL, <|im_end|>, <|im_start|>, assistant,
, SELECT, *, <|im_end|> ]
TARGET LABELS: [ -100, -100, -100, -100, -100, -100, -100, -100, -100, SELECT, *, <|im_end|> ]
ββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββ ββββββββββββ¬βββββββββββ
MASKED (0 Loss / 0 Gradient Backprop) SUPERVISED (Active Loss!)
π» Hands-On WebAssembly LLM Engineering Labs (Module 5)
Click Run & Edit Live (Wasm) on any lab below to execute and modify the algorithm in our browser Pyodide runtime.
Lab 5.1: Building a Multi-Turn ChatML SFT Collator with Assistant-Only Loss Masking (-100)
Run this live Python script to tokenize a multi-turn conversation (System + User + Assistant Tool Call + Tool Output + Final Assistant Answer) and verify exact -100 loss masking.
IGNORE_INDEX = -100
def build_sft_training_example(messages: list[dict[str, str]]) -> dict[str, list]:
input_tokens: list[str] = []
label_tokens: list[str | int] = []
for msg in messages:
role = msg["role"]
content_toks = msg["content"].split()
header = [f"<|im_start|>{role}"]
footer = ["<|im_end|>"]
turn_tokens = header + content_toks + footer
input_tokens.extend(turn_tokens)
if role == "assistant":
# Mask the '<|im_start|>assistant' header, supervise content + '<|im_end|>' stop token!
label_tokens.extend([IGNORE_INDEX] + content_toks + footer)
else:
# Mask 100% of system, user, and tool_observation turns
label_tokens.extend([IGNORE_INDEX] * len(turn_tokens))
return {"input_tokens": input_tokens, "labels": label_tokens}
conversation = [
{"role": "system", "content": "You are a SQL specialist."},
{"role": "user", "content": "Count active users"},
{"role": "assistant", "content": "SELECT COUNT(*) FROM users WHERE active = 1;"},
]
ex = build_sft_training_example(conversation)
supervised_count = sum(1 for x in ex["labels"] if x != IGNORE_INDEX)
print(f"Total Sequence Length: {len(ex['input_tokens'])} tokens | Active Supervised Tokens: {supervised_count}")
print("-" * 72)
for idx, (inp, lbl) in enumerate(zip(ex["input_tokens"], ex["labels"])):
status = "SUPERVISED (Grad ON)" if lbl != IGNORE_INDEX else "MASKED (-100)"
print(f" Pos {idx:<2} | input={inp:<22} | label={str(lbl):<22} | {status}")
Lab 5.2: Teacher-Student SFT Trajectory Distillation with Execution-Verified Rejection Sampling
Filter synthetic teacher trajectories by running deterministic schema and AST sandbox checks before admitting examples into your SFT dataset.
import ast
import json
raw_teacher_rollouts = [
{"id": "traj_1", "tool_json": '{"tool": "run_sql", "sql": "SELECT id FROM orders LIMIT 5"}', "code": "def add(a, b): return a + b"},
{"id": "traj_2", "tool_json": '{bad_json: true}', "code": "def add(a, b): return a + b"},
{"id": "traj_3", "tool_json": '{"tool": "run_sql", "sql": "DROP TABLE orders"}', "code": "def broken(: pass"},
]
def verify_and_filter_rollout(item: dict) -> tuple[bool, str]:
# Gate 1: Strict JSON Schema validation
try:
payload = json.loads(item["tool_json"])
except json.JSONDecodeError as e:
return False, f"REJECTED (Invalid JSON: {e.msg})"
# Gate 2: Policy guardrail verification
sql = str(payload.get("sql", "")).upper()
if any(forbidden in sql for forbidden in ("DROP ", "DELETE ", "TRUNCATE ")):
return False, "REJECTED (Destructive SQL in trajectory)"
# Gate 3: Python AST Compilation verification
try:
ast.parse(item["code"])
except SyntaxError as e:
return False, f"REJECTED (SyntaxError in code: {e.msg})"
return True, "ADMITTED to Golden SFT Dataset"
print("EXECUTION-VERIFIED REJECTION SAMPLING PIPELINE:")
print("-" * 68)
for r in raw_teacher_rollouts:
ok, reason = verify_and_filter_rollout(r)
print(f" {r['id']} -> {reason}")
Frequently Asked Staff LLM Interview Questions (Module 5)
Should I fine-tune an LLM to teach it our companyβs latest product documentation or database records? βΈ
No! Fine-tuning is the wrong mechanism for volatile factual lookup: parametric weights cannot enforce per-user access control (ACLs), cannot cite real-time row updates, and hallucinate when facts change. Always use Retrieval-Augmented Generation (RAG) + tool calling for dynamic knowledge, and reserve fine-tuning for style, domain reasoning patterns, schema adherence, and latency/cost distillation.
What happens if you forget Assistant-Only Loss Masking (labels = -100 on user prompts) during SFT? βΈ
If loss is computed on user prompt tokens as well as assistant tokens, gradient updates reward the model for predicting user questions and noisy user typosβdegrading response accuracy on short answers and causing the model to hallucinate follow-up "User:" turns during generation.
How does Teacher-Student Knowledge Distillation work for agent tool calling? βΈ
You run a frontier teacher model (e.g., Claude Opus 5.5 or GPT-6 Astra) over 10,000 realistic multi-step tool-calling tasks, execute every generated tool call against a deterministic sandbox/schema verifier (Rejection Sampling), keep only the trajectories that pass 100% of unit tests, and fine-tune a compact 7B/8B open-weight model (Llama 4 / Qwen 3) on those verified trajectories.