InterviewsVector
Arc 6
Build labAdvanced125 min estimateOriginal publication

Supervised Fine-Tuning as Behavior Shaping

The training objective is the behavior encoded by your examples, boundaries, and loss mask—not the behavior you intended.

Authorship
InterviewsVector
Published / updated
2026-09-19 / 2026-09-19
Review status
Artifact tests passing · primary sources recorded

Original InterviewsVector teaching. Executable illustrative contracts are covered by focused tests and primary sources are recorded. No named human review or empirical model improvement is claimed.

The decision in one pass

Supervised fine-tuning shapes behavior by increasing the likelihood of demonstrated target tokens under a specified context. The dataset, conversation template, tokenizer, loss mask, split policy, and example weighting jointly define that behavior. For an assistant-only objective, user and system tokens supply context without becoming prediction targets, while assistant tokens receive loss. Preserve conversation and packed-sequence attention boundaries, split by causal source groups before leakage can occur, and evaluate on independently held-out tasks. Lower training loss or reproduction of familiar answers is not evidence of generalization. The executable artifact validates a narrow data contract and explicitly refuses to claim model improvement.

Why this matters

An incorrect mask can train on user text; a split conversation can leak its answer into evaluation; repeated or unlicensed data can dominate updates and create avoidable risk. These defects can survive a healthy-looking training curve because the optimizer is faithfully minimizing the wrong objective.

You will be able to

  • Derive assistant-only token loss and distinguish the loss mask from the attention mask.
  • Bind conversation boundaries, tokenizer identity, row contents, source groups, licenses, PII review, and evaluation provenance.
  • Explain how packing, truncation, length weighting, and duplicate rows change the effective training distribution.
  • Reject exact duplicates and cross-split source leakage before training.
  • Design independent behavior evaluations and refuse unqualified memorization-as-improvement claims.

Your Vector Loop for this lab

  1. 01

    Model

    Name the behavior target, conversation template, tokenizer, data source, split unit, rights, and evaluation protocol.

  2. 02

    Derive

    Derive the masked token objective and show how example length and packing affect the effective dataset.

  3. 03

    Build

    Create a frozen, content-addressed data contract with assistant-only masks and complete conversation boundaries.

  4. 04

    Stress

    Inject mask errors, duplicate rows, shared source groups, stale evaluation content, truncation, and unapproved data.

  5. 05

    Operate

    Track data versions, training and held-out curves, cohort regressions, contamination checks, and release rollback.

  6. 06

    Defend

    Separate contract validity, optimization success, memorization, and demonstrated generalization.

A demonstration is a behavior specification

A training row says which response should become more likely in a context. It also implicitly teaches tone, completeness, tool-use conventions, uncertainty handling, refusal behavior, and when to ask a question. If annotators reward a fluent unsupported answer, the model is trained toward fluent unsupported answers. Start with a behavior rubric and representative failure cases, then author demonstrations that expose the desired decision—not just a polished final sentence.

Separate stable behavior from volatile knowledge. A formatting or domain-language pattern can be demonstrated repeatedly; today's refund limit should generally remain attributable to an authorized current source. Include examples that use evidence, recognize missing evidence, refuse unauthorized requests, and recover from tool errors. Synthetic examples need the same review and provenance discipline as collected examples; a generation model's mistakes do not become truth because they are numerous.

The loss mask decides what receives gradient

L = −Σ_t m_t log pθ(x_t | x_<t) / Σ_t m_t, with m_t = 1 only for assistant targets

This token-normalized assistant-only objective requires at least one supervised token. The real implementation must align labels with the model's next-token shift and handle padding and boundary tokens according to a versioned template.

A loss mask answers whether a target token contributes to the objective. An attention mask answers which context positions a token may read. Setting user loss to zero does not remove user context; blocking attention does. Confusing these masks can train a model on the wrong targets or let packed examples read unrelated conversations. Test token IDs, rendered roles, shifted labels, loss masks, and attention visibility together on small hand-inspectable examples before scaling.

Packing and truncation are semantic operations

Keep whole conversations inside one split. A system message may introduce an instruction, followed by alternating user and assistant turns; a row should not end halfway through the target answer. Truncation can erase the evidence while preserving the answer, change a refusal into compliance, or delete an end-of-turn marker. The teaching contract rejects over-budget conversations instead of silently truncating them. A production pipeline needs an explicit truncation policy with before-and-after behavioral fixtures.

ChoicePotential defectRequired proof
Sequence packingOne conversation attends to anotherBlock-diagonal or equivalent attention boundaries
PaddingPadding tokens receive lossPadding labels are ignored and token count is correct
Length normalizationLong replies dominate updatesDeclare token versus example weighting and inspect cohort exposure
TruncationInstruction or assistant completion is cutPreserved task semantics and complete target boundary
Chat templateTraining and serving role markers differVersioned template/tokenizer parity fixtures

Batching changes which gradients are averaged together and how frequently examples are exposed. Repeated long examples may dominate even when row counts look balanced. Record supervised-token counts, sampling weights, length distributions, and repetition by source. This artifact audits row semantics only; it does not implement a packer or prove attention-mask correctness in a training framework.

Split the source of dependence before deduplicating claims

A random row split can place adjacent messages from the same conversation, rewritten answers from the same source document, or repeated customer incidents on both sides. Choose a causal grouping unit—conversation, source document, entity, organization, or time window—before building train and evaluation material. Preserve split provenance so an evaluator can explain why a held-out row is genuinely independent of the training path.

The contract rejects reused conversation IDs, repeated tokenized conversation contents, and source groups crossing train/eval. Those are precise checks, not a comprehensive contamination detector. Near duplicates, paraphrases, quoted answers, pretraining contamination, and temporal leakage require additional review and evidence. A content digest binds what was checked; it does not prove that every form of semantic overlap was detected.

Audit the data without claiming the model improved

The fixture has one synthetic training conversation and one independent synthetic evaluation conversation. Frozen rows contain defensively copied turns and integer token/mask tuples. The public audit reconstructs nested records to catch constructor bypass, binds exact evaluation row contents, and rejects malformed masks, unsupported roles, leakage, unlicensed rows, pending PII review, and unqualified claims. Its two supervised training tokens are accounting facts about this toy fixture, not a recommendation for dataset size.

sft_data_contract.py
1def main():
2 result = audit(example_contract())
3 print("example=illustrative_only")
4 print(f"rows=train:{result.train_rows},eval:{result.eval_rows}")
5 print(f"supervised_train_tokens={result.supervised_tokens}")
6 print("claim=" + result.claim)

Expected output

example=illustrative_only
rows=train:1,eval:1
supervised_train_tokens=2
claim=DATA_CONTRACT_ONLY_NO_GENERALIZATION_CLAIM

Verify: python3 -m unittest discover courses/ai-engineering/reference-impl/supervised_fine_tuning

A dataset version name is not enough: keep model, tokenizer, policy, source provenance, deduplication procedure, evaluation rubric, and row content in the identity. Recompute the evaluation digest after any authorized evaluation change; do not silently reuse old results. In a production release, bind the dataset identity to the actual training configuration, checkpoint, and evaluation outputs as the next layer of the contract.

Evaluate behavior outside the memorized neighborhood

Training loss establishes how well optimization fits supervised targets. Held-out token loss establishes predictive fit on the chosen holdout. Neither alone establishes the product outcome. Compare the adapted model with the untuned baseline on task completion, unsupported claims, format validity, abstention, security behavior, and regressions outside the tuned domain. Include new entities, phrasing, source combinations, and boundary cases chosen without inspecting training outputs.

Use an evaluation set for iteration and reserve an independently controlled final gate when repeated tuning would otherwise overfit the benchmark. Inspect cohort-level deltas and uncertainty, not just an aggregate. If training improves while held-out behavior degrades, investigate repeated data, label quality, task mismatch, too much optimization, and template drift. Do not label a memorized response as a learned capability without evidence of transfer.

Operate at three altitudes

Production lens

  • Snapshot source provenance, split grouping, exact row contents, tokenizer/template, masks, dedup policy, rights and PII attestations before training.
  • Test shifted labels and packing attention boundaries in the actual training stack; the row audit intentionally does not certify a framework packer.
  • Track supervised-token exposure, cohort failures, independent task success, and regressions; retain a baseline rollback path.

Staff lens

  • Treat dataset review as product specification and risk review, with accountable owners for rights, privacy, and label quality.
  • Maintain an evaluation governance boundary so repeated experiment selection does not consume every independent holdout.
  • Separate four claims in release documentation: valid data, successful optimization, held-out improvement, and acceptable production behavior.

Interview defense

Your instruction-tuned model has lower training loss but worse customer outcomes. What do you investigate?

I inspect the objective before changing hyperparameters: role/template parity, shifted labels, assistant-only loss, padding, and packed attention boundaries. Then I inspect source-group splits, duplicates, label quality, token exposure, rights and PII attestations. Lower training loss can reflect memorization or the wrong target. I compare against the base on independent task and safety cohorts, verify model/data/evaluator identities, and roll back the bound behavior package if release gates fail.

Expect the interviewer to press on

  • Why are loss and attention masks different?
  • How can row-random splitting leak conversations?
  • What does a valid data contract prove—and not prove?

Misconceptions to remove

Zero loss on user tokens means the assistant cannot read them.

Loss masking removes those prediction targets from the objective; attention masking controls visibility of context.

Deduplicating exact strings proves an uncontaminated holdout.

Paraphrase, entity, temporal, document, and pretraining overlap can remain. Exact deduplication is one bounded check.

A valid training dataset proves the model generalizes.

The contract establishes declared data invariants, not optimization results or transfer to independent product tasks.

Check your model

1. Why can an assistant-only objective still use user text?

User tokens remain in the causal context while their loss weights are zero; assistant target tokens receive the learning signal.

2. Why reject a conversation that exceeds the token budget?

Silent truncation can remove instructions, evidence, or completion boundaries. A safe alternative requires an explicit, separately tested semantic policy.

3. What changes when an evaluation row changes?

Its content digest and the enclosing dataset contract change; previous evaluation evidence must not be treated as a result for the new contents.

Prove the mechanism

Add synthetic multi-turn conversations and tests for truncated assistant endings, user-token supervision, source-group leakage, duplicate content, and pending PII review. Report supervised-token counts without asserting model improvement.

Add a production constraint

Design a real training-stack fixture that verifies label shifting, padding, packed attention isolation, and train/serve template parity. Then define independent behavioral cohorts and a release criterion that distinguishes memorization from transfer.

Artifact: Supervised fine-tuning data contract

courses/ai-engineering/reference-impl/supervised_fine_tuning/sft_data_contract.py

Download reference implementation

Primary references and next links

References

  1. 1. Finetuned Language Models Are Zero-Shot Learners

    Wei et al.. Primary instruction-tuning study; motivates task-based transfer evaluation.

  2. 2. Training language models to follow instructions with human feedback

    Ouyang et al.. Primary work with a supervised demonstration stage distinct from later preference optimization.

  3. 3. Deduplicating Training Data Makes Language Models Better

    Lee et al.. Primary investigation of training duplication and evaluation contamination.

Continue through the graph

Glossary: supervised fine-tuning · loss mask · attention mask · conversation boundary · sequence packing · data leakage · memorization · held-out evaluation