From teacher traces to a reasoning model: hard distillation
Follow Raschka’s Chapter 8 from teacher traces and token masks to checkpoint selection, MATH-500 results and an offline loss lab.
Sources & version details
In this article
Follow one teacher response into a student checkpoint
A team serves a small model for math exercises. Each task has a verified numeric answer, but the model needs to learn intermediate steps as well as the final format. Start with a stronger teacher that can produce responses, a student that already predicts the next token, and a reference-answer checker. The data pipeline freezes prompts, teacher responses, provenance and verification outcomes. Tokenization converts approved responses into supervised examples. Training updates the student on these fixed sequences. Serving loads only the student checkpoint. Start with a teacher the team is authorized to use and a task where the verifier's mistakes can be audited.
This tutorial follows Sebastian Raschka's Chapter 8 through four decisions: what supervision to store, which sequences to train on, exactly which tokens contribute gradient, and how to decide whether to deploy the student. Prerequisites are causal language modeling, cross-entropy, and the distinction between validation and test sets. A prefix is the tokens available before a prediction. A logit is an unnormalized score. A teacher rollout is a sampled completion. A verifier compares an extracted answer with a reference under explicit equivalence rules.
Choose the target and the source of prefixes independently
| Choice | Training signal | What you need |
|---|---|---|
| Hard distillation | The teacher's sampled output token at each position | Authorized response text. Re-tokenize it with the student tokenizer. |
| Soft distillation | A distribution over next tokens at a specified prefix | Teacher logits or sufficiently faithful scores with compatible token semantics; temperature and divergence choices. |
| Offline prefix sampling | Fixed teacher or prepared sequences | Precompute data and reuse it. Errors produced by the student at serving time may be absent. |
| On-policy prefix sampling | Sequences produced by the current student | Generate new rollouts and obtain teacher feedback on them. Recompute as the student changes. |
| RL with verifiable rewards | Outcome feedback on student rollouts | A checker and a learning algorithm that handles exploration and credit assignment. |
Hard and soft describe the target. Offline or on-policy describes where prefixes come from. A classic soft choice is forward KL at a shared prefix. With both distributions formed at temperature tau, minimizing it gives the student gradients that respect the teacher's relative preferences across classes. Conventional token-level KL needs a meaningful mapping of the output symbols. Top-k log probabilities leave unobserved mass; padding missing entries with zeros changes the objective. At scale, caching dense logits is often prohibitive. As an upper-bound illustration, storing an fp16 score for every one of 151,936 tokens at 2,048 positions for 12,000 sequences would take about 6.79 TiB before metadata. It is a hypothetical budget, separate from the notebook run. The chapter implements offline hard distillation; Hinton et al., Agarwal et al. (GKD), and DeepSeek-R1 provide context for alternative routes.
Build an auditable data pipeline
Keep a stable problem ID, original source and revision, teacher name and generation configuration, reasoning text, final completion, reference answer, verifier outcome and reason for rejection. Remove evaluation problems before sending prompts to the teacher, and group near-duplicates or variants before splitting. A base or teacher may still have seen the benchmark during pretraining. Treat an exact-match audit as one check, and use new problem families when claiming transfer. Keep train, development and final evaluation partitions distinct.
The notebook's released MATH data pairs problem with the reference gtruth_answer, the teacher's message_thinking and final message_content. It formats a reasoning section and a final section with an EOS token. Markup such as <think> is a format convention; the student learns its token behavior and the evaluator needs matching parsing. A verified final answer can accompany flawed reasoning. Decide whether to require verifier passes, review a trace sample, collect alternative paths, or keep borderline records for separate analysis. Record that policy and its effect by topic, length and difficulty.
Chapter 8 pre-tokenizes and rejects examples whose combined length exceeds 2,048 tokens. Dropping a whole example preserves the final answer and EOS for examples kept; it can change the question mix. Truncating blindly can train the student to emit an incomplete proof or lose the answer. Measure retention by cohort, compare verified shorter traces at matched task coverage, and retain fingerprints of the split, tokenizer, template and label policy. Related engineering detail is covered in the site's storage guide through immutable manifests and checkpoint recovery.
Align logits and labels before training
For a sequence of length L with P prompt tokens (including the assistant header), feed tokens 0 through L−2 and shift the labels one position. The logit row at index i predicts the token at index i+1. The first supervised row is P−1. A prompt token can still be used as context and influence gradients through attention, even though its own label is masked. Include the target EOS when present; mask padding and any other excluded tokens separately. Use [B,L−1,V] logits with [B,L−1] shifted labels and select valid rows before averaging. Reject examples with no supervised tokens to avoid dividing by zero. When using a library that shifts internally, supply unshifted labels with the intended mask and verify its convention.
Minimize negative mean log probability of the teacher's answer tokens. For a short example, if the student assigns 0.5, 0.25 and 0.8 to the two answer tokens and EOS, the loss is about 0.7675 nats per supervised token. A reduction averaged across sequence losses weights each example equally. A total loss divided by total supervised tokens weights longer examples more. The notebook's validation helper averages per-example means. Document the reduction before comparing runs, especially with packing, gradient accumulation or multi-device training.
Train, resume, and decide whether improved quality pays
The teaching loop shuffles at each epoch, forwards teacher-forced examples, backpropagates answer cross-entropy, applies optional gradient clipping, and steps AdamW. For a full resume, keep optimizer and scheduler state where applicable, sampler position, RNG states and the versioned data contract. The notebook saves model weights at epoch boundaries; its files can be evaluated, while exact continuation needs the additional training state. Validate without gradients and keep the serving template, stopping conditions and answer extractor versioned.
Compare student vs base and plausible alternatives under matched generation settings. Report final accuracy, parse failures, truncation rate, output tokens and latency on the target hardware. Measure teacher-label quality separately from student performance. Model size alone cannot predict serving speed when a model writes longer traces. To compare teachers, hold problem set, tokenizer, filters, train and output budgets and seeds constant. A lower validation cross-entropy can coexist with worse free-decoding accuracy. Select checkpoints on development metrics, then evaluate once on an untouched test set.
Practice and verification
Use the interactive toy below to change only the loss mask while keeping the same normalized probabilities. Under answer-only supervision the three target positions are scored. With all shifted labels the two easy prompt targets dilute the loss. The off-by-one fixture drops the first answer token. Inspect the effects on both the token count and the mean. This deterministic exercise needs no model download and does not train Qwen.
Raschka's notebook outputs show 12,000 DeepSeek-R1 completions, 10,871 correct under its answer verifier (90.6%), 6,695 records kept after the combined-length cap, then 6,670 training and 25 validation examples. The recorded MATH-500 results are 15.2% for base, 48.2% for the existing reasoning variant, and 30.6%, 32.4%, 33.6% across the three R1-distilled checkpoints. The Qwen3-235B-A22B teacher run is listed at 45.0%, 43.8%, 44.2%; its validation loss falls from 0.4043 to 0.3948. The latter pair shows why loss alone can pick a worse checkpoint in this run. These are the author's reported outputs, not a reproduction or a controlled teacher ranking. The example evaluation uses a 4,096-new-token cap. The referenced training script's author-reported DGX Spark run was about 3 h 5 min using 15.02 GB GPU memory. Treat this as a reference configuration, not a hardware requirement.
For a fair offline exercise, freeze prompts and verifier, compare final-answer-only and trace-plus-answer targets, and report retained examples, trained target tokens, spent compute and held-out performance. If matching the token budget changes how many examples are seen, report a second comparison at matched examples. Test a bad EOS, accidental benchmark overlap and parser ambiguity before any full run.
node --input-type=module -e "import {masks,scoreFixture} from './distillation-lab.mjs'; for (const m of masks) console.log(m, scoreFixture(m))"
Show reference code
export const masks = ['answer', 'all', 'late', 'without-eos'];
export function scoreFixture(mask) {
if (!masks.includes(mask)) throw new RangeError('Unknown mask');
const promptLength = 3;
// These probabilities stand in for the target column after log-softmax.
const shiftedTargets = [0.95, 0.90, 0.50, 0.25, 0.80];
const firstRow = mask === 'all' ? 0 : promptLength - 1 + Number(mask === 'late');
const exclusiveEnd = shiftedTargets.length - Number(mask === 'without-eos');
const selected = shiftedTargets.slice(firstRow, exclusiveEnd);
return {count: selected.length, loss: -selected.reduce((sum, p) => sum + Math.log(p), 0) / selected.length};
}
for (const lab of globalThis.document?.querySelectorAll('[data-distillation-lab]') ?? []) {
const select = lab.querySelector('select');
const output = lab.querySelector('output');
const [tokens, mean] = JSON.parse(lab.dataset.distillationLab);
const update = () => {
const {count, loss} = scoreFixture(select.value);
output.textContent = tokens + ' ' + count + ' · ' + mean + ' ' + loss.toFixed(4);
};
select.addEventListener('change', update);
update();
}
Original mock interview questions
Why does supervision start at P−1?
Hint 1
Trace a single logit row.
Hint 2
The final prompt token predicts the first answer token.
Answer and reasoning
Row P−1 predicts token P. Mask the label columns, leave the prompt available as context, and verify EOS and padding separately.
Can a teacher with only text support soft distillation?
Hint 1
Identify what a sampled token reveals.
Hint 2
Canonical token-level KL needs aligned distributions.
Answer and reasoning
Use supervised hard distillation with the student tokenizer on authorized text. A full soft distribution requires more information. Top-k scores require a specified treatment of the residual mass.
Does a lower validation loss select the better deployed checkpoint?
Hint 1
Think about teacher forcing.
Hint 2
Compare free generation on unseen tasks.
Answer and reasoning
Freeze an extractor and a generation budget, choose with development accuracy and cost, then evaluate once on a reserved set. Report parse failures and output lengths.
How do you compare short traces against long ones fairly?
Hint 1
Start with identical problems.
Hint 2
Matching examples may change training tokens.
Answer and reasoning
Run paired analyses at matched examples and at matched supervised tokens. Report filtering by cohort, verification and total training cost.
Scoring from 1 to 5
1 identifies the component. 2 explains its contract. 3 calculates the worked case. 4 handles a failure. 5 designs a fair, reproducible comparison.
Notebook, data, and papers
- Sebastian Raschka · Chapter 8 · revision 2026-03-12 · Notebookhttps://github.com/rasbt/reasoning-from-scratch/blob/f1e1c67e4fb91128356656a501b6aa9dd55053cc/ch08/01_main-chapter-code/ch08_main.ipynb · distill.pyhttps://github.com/rasbt/reasoning-from-scratch/blob/f1e1c67e4fb91128356656a501b6aa9dd55053cc/ch08/04_train_with_distillation/distill.py · MATH distillation datasethttps://huggingface.co/datasets/rasbt/math_distill · MATH minus MATH-500https://github.com/rasbt/math_full_minus_math500
- Hinton, Vinyals & Dean · Distilling the Knowledge in a Neural Network · workshop/arXiv · arXivhttps://arxiv.org/abs/1503.02531 · PDFhttps://arxiv.org/pdf/1503.02531
- Agarwal et al. · Generalized Knowledge Distillation · ICLR 2024 · Google DeepMindhttps://deepmind.google/research/publications/48050/ · arXiv v3https://arxiv.org/abs/2306.13649v3 · PDFhttps://arxiv.org/pdf/2306.13649v3
- DeepSeek-R1 · 2025 technical report · arXivhttps://arxiv.org/abs/2501.12948 · PDFhttps://arxiv.org/pdf/2501.12948 · Official code and checkpointshttps://github.com/deepseek-ai/DeepSeek-R1
- Qwen3-0.6B Base · Model cardhttps://huggingface.co/Qwen/Qwen3-0.6B-Base