Best on a larger screen — the animation and controls have more room to breathe.
Inputs

Supervised Fine-Tuning (SFT)

Supervised Fine-Tuning (SFT) adapts a pretrained causal language model into an instruction-following assistant by training on (prompt, response) demonstrations with the exact same next-token cross-entropy objective, while masking prompt tokens out of the loss (mask = 0) so direct prediction loss comes strictly from assistant tokens and <eos> (while prompt tokens remain readable in causal attention).

A pretrained base model is not blank; it already knows world facts and grammar. Its problem is role confusion: show it a user question, and it often continues the pattern by inventing another question, because pretraining scraped documents where questions followed questions. SFT does not replace the Transformer or teach facts from scratch; it steers existing representations toward answering and stopping on cue, provided two hazards do not derail the run: unmasked prompt loss and excessive weight drift.

Loss Masking Without Blinding Causal Attention

SFT wraps each demonstration into one causal sequence with explicit turn boundaries (here [BOS, USR, Q, ?, AST, ANS, EOS]) and runs standard teacher-forced autoregressive scoring (Causal Masking & Autoregressive Training). All six shifted input-target pairs pass through causal attention so assistant positions can read the user's question.

The change happens only when computing the loss. In PyTorch and Hugging Face trainers, prompt label positions are set to ignore_index = -100 (mask = 0), leaving mask = 1 strictly on the assistant reply and <eos>:

# Prompt stays in causal attention; only prompt target loss is masked
logits = model(input_ids)
loss = cross_entropy(
    logits.view(-1, vocab_size),
    labels.view(-1),       # [-100, -100, -100, -100, ANS, EOS]
    ignore_index=-100,
)

Masking prompt targets to 0 keeps 100% of direct target supervision focused on predicting ANS after AST and EOS after ANS (while assistant loss can still backpropagate through causal prompt representations in full Transformer training). Leave those prompt targets unmasked (full-sequence), and every prompt token enters the loss average alongside the response, diluting the response gradient divisor while pushing shared weights back toward predicting user tokens (Q, ?, AST).

Because the hidden representation dimension (D = 5) is smaller than the vocabulary (|V| = 10), different tasks share bottleneck features and output biases. Moderate updates nudge assistant predictions upward without disturbing unrelated factual circuits; overly aggressive updates pull the shared parameters far from W_0, raising KL divergence until held-out base knowledge breaks.

Supervised Fine-Tuning Step by Step

The default trace runs response-only masking (mask = [0, 0, 0, 0, 1, 1]) with balanced SGD step size (η = 0.70) for 6 updates starting from pretrained weights W_0:

StageL_resp (nats/tok)L_base (nats/tok)KL DriftInstruction RolloutBase Probe [BOS, SKY, IS]
Base (W_0, step 0)5.8000.3890.000Q → ? → ?BLUE (0.678)
Step 1 (η = 0.70)4.2770.4720.012—BLUE (0.62)
Step 2 (η = 0.70)2.8580.5590.049—BLUE (0.57)
Steps 3–5 (η = 0.70)1.678 → 0.5690.665 → 0.9000.120 → 0.327—BLUE (0.51 → 0.41)
Step 6 (W_6, final)0.3900.9930.416ANS → EOSBLUE (0.370)
  1. Pretrained baseline (W_0). Before any fine-tuning, W_0 scores the held-out fact probe [BOS, SKY, IS] cleanly (BLUE at p = 0.678, L_base = 0.389). On the instruction prompt [BOS, USR, Q, ?, AST], however, W_0 falls back on raw web Q&A priors and generates Q (0.501) → ? (0.421) → ? (0.332) with P(ANS | AST) = 0.004.
  2. Shifted alignment and causal forward pass. Formatting [BOS, USR, Q, ?, AST, ANS, EOS] produces six input-target pairs: four prompt pairs (BOS→USR, USR→Q, Q→?, ?→AST) and two assistant pairs (AST→ANS at loss 5.500, ANS→EOS at loss 6.100, giving L_resp = 5.800). Causal attention at AST reads all prompt tokens [BOS..AST] normally.
  3. Loss mask gate and gradient split. Setting m = 0 on positions 0..3 eliminates all four prompt losses from the objective (M = 2 active terms, L_SFT = 5.800) and zeroes out prompt gradients (0% prompt / 100% assistant response).
  4. Six balanced SGD updates (η = 0.70). Across steps 1 through 6, response loss drops monotonically (5.800 → 4.277 → 2.858 → 1.678 → 0.933 → 0.569 → 0.390), lifting P(ANS | AST) to 0.610 and P(EOS | ANS) to 0.750 while L_base rises modestly to 0.993 (KL = 0.416).
  5. Post-SFT dual evaluation. On [BOS, USR, Q, ?, AST], W_6 switches to ANS → EOS and stops. On [BOS, SKY, IS], BLUE (0.370) remains top-1 ahead of IS (0.201) and EOS (0.154), confirming alignment without catastrophic forgetting.

In the canvas, masked prompt targets fade behind dashed gray m=0 badges (eliminated) while active assistant targets stay green (added); backward gradient flow turns orange (network.gradient), and the optimization chart plots L_resp (solid teal) against held-out L_base (dashed red) so forgetting appears the moment EOS overtakes BLUE.

Alignment Gains vs. Catastrophic Forgetting

Evaluating SFT solely by training loss misses two failure regimes. All four runs below start from the exact same pretrained W_0 for 6 updates:

RegimeLoss MaskStep Size ηL_respL_base (KL)Instruction RolloutBase Probe
Base (W_0)pretrain—5.8000.389 (0.00)Q → ? → ?BLUE (0.68)
Balanced SFTresponse-only (2/6)0.700.3900.993 (0.42)ANS → EOSBLUE (0.37)
Unmasked Prompt Lossfull-sequence (6/6)0.702.9290.605 (0.06)Q → ? → ASTBLUE (0.55)
Over-SFT (high)response-only (2/6)1.900.0751.647 (1.04)ANS → EOSEOS (FLIP)
Under-trained (low)response-only (2/6)0.252.7020.560 (0.05)Q → ? → ?BLUE (0.57)

Compare Unmasked and Over-SFT. Unmasked training starts step 0 with a deceptively low mixed objective (L_obj = 2.814 across all 6 tokens vs. true L_resp = 5.800), then stalls at L_resp = 2.929 by step 6 because 66.7% (4/6) of its loss terms pull toward prompt tokens, keeping generation stuck on Q → ? → AST. Meanwhile, Over-SFT drives L_resp down to 0.075 (looking "best" on the training metric) yet pushes KL to 1.041, flipping [BOS, SKY, IS] by step 4 and leaving step 6 at EOS (0.324) over BLUE (0.193).

Edge Cases

  • Unmasked prompt loss looks lower on step 0 (L_obj = 2.814 vs. L_resp = 5.800). Because W_0 already predicts prompt tokens with low surprise (0.78–2.28 nats), averaging over all 6 positions drops L_obj immediately before any learning happens. Real context lengths amplify this: a 2,000-token system prompt paired with a 20-token reply wastes ~99% of gradient terms rather than 66.7%.
  • Off-by-one chat-template delimiter masking. Setting labels = -100 one token too late leaves turn headers (such as <|assistant|>\n) inside m = 1, while stopping one token early masks out <eos> so the reply never ends.
  • Over-SFT collapse on held-out probes. With η = 1.90, P(ANS | AST) reaches 0.918 and P(EOS | ANS) reaches 0.938, while shared weights and bias b shift so heavily toward EOS that unrelated prompts terminate instead of completing facts.
  • Under-trained SFT (η = 0.25). Zero capability is forgotten (KL = 0.053, BLUE = 0.571), but six small updates only cut L_resp to 2.702, leaving Q → ? → ? stronger than ANS.
  • Missing <eos> supervision (m_5 = 0). Masking prompt tokens properly while omitting EOS from m = 1 teaches the model to start answering (AST → ANS) without ever learning to stop.

Common Mistakes

  • Confusing loss masking with causal attention masking. Setting labels[i] = -100 (m_i = 0) never hides position i from attention. Blocking prompt tokens in the attention mask would blind the assistant to the user's question.
  • Evaluating convergence using unmasked sequence loss. Tracking L_obj across both prompt and response hides stagnant response adaptation behind easy prompt tokens; always evaluate L_resp on assistant tokens alone.
  • Dropping <eos> or turn delimiters during dataset tokenization. Stripping AST or masking EOS strips the exact tokens that mark turn boundaries and termination.
  • Optimizing SFT loss to near zero without monitoring KL or base benchmarks. SFT works by re-weighting behavior inside shared representations; training too aggressively without held-out evaluation or KL/replay regularization erases pretrained capabilities.

A Note on Simplification

This lesson runs exact causal arithmetic in pure TypeScript over a symbolic 10-token vocabulary, a fixed D = 5 bottleneck embedding and single-head self-attention block (W_Q, W_K, W_V frozen), pretraining W_0 via 140 batch-SGD updates on three short documents and fine-tuning only the linear output head (W, b) on one (prompt, response) demonstration. Using a large step size η = 1.90 over 6 updates magnifies total weight drift (η · T) to illustrate the forgetting threshold quickly; in production LLM post-training, the same drift typically comes from excessive training epochs or narrow datasets without early stopping. Full pipelines update multi-layer Transformer blocks or low-rank adapters (LoRA) across thousands of diverse multi-turn dialogues (masking every user turn while supervising every assistant turn, with assistant loss still backpropagating through causal prompt keys/values), often mix in pretraining replay or KL regularization, and pair SFT with preference optimization such as DPO or RLHF (Policy Gradient).