Unit 3 of 10 · about 6 hours · implement

Assistant-only loss masks and packed SFT boundaries

The LLM Foundations unit on packing and loss masks established the two-mask distinction. Now prove it on a real instruction pipeline, where role headers, assistant endings and library label shifting can silently change the objective.

You'll be able to

  • Implement assistant-only targets with an explicit shift convention and valid-target denominator.
  • Check real chat-template spans against an independently marked token table, including multiple assistant turns and truncation.
  • Prove packed examples are attention-isolated and label-isolated under the declared packing policy.

Covers

Assistant-only loss masks and token-level denominator checksPacked SFT boundaries, attention masks and cross-example leakage
1

Read

In this order, only the parts listed

0 of 3 done

  1. CS336 Spring 2026 Assignment 5 Supplement, Version 26.0.0CS336 Assignment 5 Supplement - SFT

    Section 4.2.1, Data Loader, Problem data_loading, pp. 9 to 10; get_packed_sft_dataset and run_iterate_batches

    Implement its concatenated-stream contract separately from your isolated assistant-only path. The assignment's token fixtures do not prove assistant masks or attention isolation. Do not publish assignment solutions.

  2. TRL 1.15.0: SFT masking and packingHugging Face LLM Course Chapter 11 and smol-course Unit 1

    Train on assistant messages only; Train on completion only; SFTConfig entries for packing, packing_strategy, padding_free, completion_only_loss and assistant_only_loss

  3. RLHF Book code: final-turn-only labelsRLHF Book Code - Instruction Tuning and Distillation

    _encode_batch, compute_loss and _collate

    Trace one multi-turn record. This is final-assistant-turn-only supervision, not all-assistant-turn supervision; do not reuse prefix lengths without checking prefix ID equality.

2

Focus on

  • For logits indexed by source position, supervise the next token only if it belongs to an eligible assistant span in the same example. Decide whether assistant endings are targets; include the stop token in this route. Mask padding and cross-example transitions.
  • Compute summed negative log likelihood divided by the number of valid shifted targets, not padded length. Reject or explicitly skip zero-target batches. Accumulated microbatches need one combined valid-token denominator.
  • With conversational language-modeling records, TRL 1.15.0 defaults to full-sequence loss. Prompt-completion records default to completion-only loss. assistant_only_loss=True is separate; the template must expose generation spans. TRL can substitute a bundled Qwen3 training template, so inspect the effective template and token IDs too.
  • EOS does not isolate attention. For isolated packing allow only causal, same-example visibility and reset positions as in separate forwards. On CPU use a small decoder with an explicit dense mask, or train unpacked; TRL's default bfd packing enables padding-free execution with a FlashAttention backend requirement.
Common mistakes · 3
  • Passing already shifted TensorTonic labels into a causal-LM loss that shifts labels internally. Choose source-aligned or token-aligned labels, then shift exactly once.
  • Treating a public packing test as a leakage oracle. Matching token and label fixtures says nothing about which examples attend to one another.
  • Masking every token equal to the padding ID when padding and EOS share an ID. Use position validity so real assistant stop tokens remain supervised.
3

Try it yourself

Closed-book, before checking anything

Closed-book, recover TensorTonic's first public case: input_ids=[[10,11,20,21,2]], role_ids=[[-1,0,-1,1,-1]], all positions attended and assistant_role=1 give source-aligned labels [[-100,-100,21,-100,-100]]. Then pack two conversations from the preceding unit with the real tokenizer. Independently mark target owners and the block-causal attention matrix. On a tiny PyTorch 2.14.1 decoder in evaluation mode, compare packed logits with separate forwards using the same position IDs and a declared tolerance; changing the first example must not change the second example's logits.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Can a masked user token still influence an assistant prediction?Answer

    Yes. Loss masking removes its prediction from the objective, not its use as context. Attention permissions govern influence.

  2. 2.Why can averaging two microbatch mean losses misweight SFT?Answer

    Different valid-target counts give each token a different weight. Sum the token losses and divide by the total valid-target count across the accumulation window.

  3. 3.What must match between packed and separate forwards besides the labels?Answer

    Token IDs, causal and example visibility, position IDs and model state. Disable dropout and compare with a stated numeric tolerance. Labels alone cannot make logits equivalent.

  4. 4.Why inspect the effective TRL template after enabling assistant-only loss?Answer

    The trainer can replace a template lacking generation markers. That may change serialized tokens as well as mask ownership, so rerun the train-serve and stop-token fixtures.

5

Practice

  • TensorTonic: Build an Assistant-Only SFT Loss Mask

    Implement assistant_only_sft_mask(input_ids, role_ids, attention_mask, assistant_role)

    The three public cases cover one, no and two assistant targets. They consume role IDs, not text, and do not check gradients or packing. The section mini-project supplies real-template, truncation, denominator and packed-attention oracles.

  • CS336 Assignment 5 Supplement: data_loading

    test_packed_sft_dataset and test_iterate_batches

    CPU tests compare packed input and label IDs, exercise shuffling, and check batch count, shapes and integer dtypes. Keep the stream baseline distinct from the isolated SFT implementation.

You're done when

The public cases pass, your real-tokenizer label oracle catches a seeded one-token shift, and the packed-versus-separate and cross-example perturbation tests pass within your declared tolerance.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 16 more in the section
  • CS336 Assignment 5 Supplement - SFTStanford University · required

    Do supplement Sections 3 and 4: zero-shot baselines, look_at_sft, get_packed_sft_dataset and the SFT script, with the data tests passing on CPU. The handout fine-tunes Llama 3.1 8B on B200s and judges with a 70B model; use a small open model that fits your GPU and rule-based scoring on fixed MMLU and GSM8K subsets, and keep the evaluation identical before and after.

  • Hugging Face LLM Course Chapter 11 and smol-course Unit 1Hugging Face · support

    Work through 11.2 (chat templates), 11.3 (SFT with TRL) and 11.4 (LoRA with PEFT) on SmolLM2-135M, then smol-course Unit 1 for an SFT, LoRA and evaluation loop. TRL 1.15.0 trains on the whole sequence unless you set assistant_only_loss=True, and the template must expose assistant spans for that to work.

  • RLHF Book Code - Instruction Tuning and DistillationNathan Lambert · support

    Read instruction_tuning/train.py and utils.py (it masks all but the final assistant turn) and distillation/loss.py. The default configs use 1B to 1.7B models and long contexts; cut the model, context and sample count to fit your GPU, hold the data and evaluator fixed, sweep one variable and compare with a no-distillation baseline.

Also in this section

  • RLHF Book - Training Overview, Instruction Tuning and Synthetic DataNathan Lambert · primary

    Read Chapter 3 (training overview and canonical recipes; no exercises), Chapter 4 (instruction tuning, 04-instruction-tuning.html) and Chapter 12 (synthetic data and distillation, 12-synthetic-data.html). Do the Suggested Experiments in Chapters 4 and 12 at a scale that fits your GPU. Use the recipe maps to separate continued pretraining, SFT, rejection sampling and distillation before selecting an intervention.

  • LoRA: Low-Rank Adaptation of Large Language ModelsMicrosoft Research · required

    Read Section 4 and Figure 1 (Section 3 explains why adapters add latency): derive the low-rank update, the alpha over r scale, the zero initialization of B and the parameter count, then implement LoRA for selected decoder linear layers and test that the merged weights reproduce the adapter output. The paper adapts attention only; later work finds the MLP layers matter.

  • LoRA Learns Less and Forgets Less (Biderman et al., 2024)Columbia University and Databricks · required

    Read Section 3 and Sections 4.1 to 4.7 with Figures 2 to 4: on code and math, full fine-tuning learns more of the target and forgets more of the source, and LoRA rank controls the trade-off. Slice forgetting on your own evaluations.

  • LoRA Without RegretThinking Machines Lab · support

    Read "What matters", the rank, batch-size and layer results, and "Setting LoRA hyperparameters": all-layer LoRA at high rank matches full fine-tuning loss, the best LoRA learning rate is about ten times higher, and large batches hurt LoRA more. The curves are log loss, not sampled evaluations.

  • QLoRA: Efficient Finetuning of Quantized LLMsUniversity of Washington · reference

    Read the method and memory-analysis sections only after plain LoRA passes. Use it to explain quantized-base adaptation and its numerical assumptions, not as a mandatory large training run.

  • Distilling the Knowledge in a Neural Network (Hinton et al., 2015)Google · reference

    Read Sections 1 and 2 for the temperature-softened softmax and the mix of soft and hard targets that later distillation methods reuse.

  • MiniLLM: Knowledge Distillation of Large Language Models (Gu et al., 2024)Tsinghua and Microsoft Research · support

    Read Section 2.1 (reverse KL from student to teacher, and why it is mode-seeking) and Section 2.2 (the on-policy gradient and its stabilizers). It needs white-box teacher log probabilities.

  • On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes (Agarwal et al., 2024)Google DeepMind · support

    Read Sections 3 and 4 with Algorithm 1: the student-data fraction lambda mixes fixed data with student samples, and the divergence is a choice. Budget the extra student rollouts and teacher scoring per step.

  • On-Policy DistillationThinking Machines Lab · support

    Read the loss (per-token reverse KL on student samples), the pseudocode and the reasoning and personalization results. Teacher and student share a tokenizer and lineage there; the FLOP ratios are estimates.

  • Tulu 3, Sections 3 and 4 (data and supervised fine-tuning)Allen Institute for AI · support

    Read Section 3 (prompt curation and decontamination) and Section 4 (the SFT mix, data experiments and recipe) as an auditable data contract to imitate at small scale, not a scale to reproduce.

  • Don't Stop Pretraining: Adapt Language Models to Domains and Tasks (Gururangan et al., 2020)Allen Institute for AI · support

    Read Sections 3 and 4: domain-adaptive and task-adaptive continued pretraining before fine-tuning. Compare continued pretraining with SFT at matched tokens and a fixed evaluator.

  • Build a Large Language Model (From Scratch), Chapter 7 and Appendix ESebastian Raschka / Manning · support

    Use Chapter 7 (SFT, pp. 204-249) and Appendix E (LoRA, pp. 322-336) for the smallest full SFT and LoRA run. The chapter trains on instructions too by default; Exercise 7.2 (p. 223) is the masked variant, and there is no packing.

  • Build a Reasoning Model (From Scratch), Chapter 8Sebastian Raschka / Manning · support

    Use Chapter 8 (pp. 267-304: generating and filtering a distillation set, losses, training loop and evaluation) as a runnable 0.6B sequence-distillation baseline with provenance.

  • Modern LLM Notebook - LoRA, Distillation and OPDWalking Labs · support

    Use notebooks-en/part2-training/16-lora.ipynb, 17-distillation.ipynb and notebooks-en/part4-frontiers/31-opd.ipynb for compact implementations. Derive the objectives from MiniLLM and GKD rather than the notebooks, and scale the 7B distillation example down.

  • TensorTonic - Assistant-Only SFT Loss MaskTensorTonic · support

    Solve Build an Assistant-Only SFT Loss Mask (cs336-l15-assistant-only-sft-mask). It takes role ids, so add your own tests for chat-template parsing, multi-turn roles, truncation, packed examples and special-token boundaries. Public test cases check the listed edge cases, not gradients or the hidden grader, so keep your own tests beside each solution.

  • PEFT conceptual guide: Soft promptsHugging Face · reference

    Read Prompt tuning and Prefix tuning only (page read 2026-10-16). These supply the optional soft-prompt mechanisms missing from the section pool; no extra training run is required.