⚗️ Offline Distillation Explained
📖 Background
Knowledge distillation trains a student model with the output distribution of a teacher model as the supervision signal. It was proposed by Hinton et al. in Distilling the Knowledge in a Neural Network: the teacher distribution carries more information than a one-hot label. It indicates the correct answer and also indicates how close each wrong answer is to the correct one. Kim and Rush applied the method to sequence generation in Sequence-Level Knowledge Distillation, training the student on teacher-generated sequences in place of reference translations and obtaining lower error on machine translation tasks.
In 2025, the R1 reasoning data (800k samples) open-sourced by DeepSeek extended the method to reasoning tasks: fine-tuning the Qwen and Llama series from 7B to 70B on reasoning chains generated by R1 raised the scores on AIME and MATH significantly. In form, that process is sequence-level distillation, and the training stage involves only SFT.
The cost of offline distillation is concentrated in data: the coverage of the prompt set decides the capability ceiling, teacher generation and filtering decide the data quality, and student training and evaluation decide whether the effect can be verified. This page goes through the engineering constraints of each stage in pipeline order and presents a set of measured training regression curves.
⚗️ The relation between SFT and distillation
For a single annotated sequence, the cross-entropy loss of SFT is
L_SFT = -Σ_t log P_S(y*_t | x, y*_<t)which is equivalent to minimizing the KL divergence between the one-hot distribution δ_{y*} and the student distribution P_S at every position. Distillation replaces the one-hot distribution with the teacher distribution P_T and minimizes KL(P_T || P_S). By two dimensions, where the training sequence comes from and how dense the signal is, post-training methods fall into four classes:
| Method | Training sequence source | Signal per token | Teacher distribution |
|---|---|---|---|
| SFT | Fixed annotations (off-policy) | Yes, one-hot | None |
| Offline distillation | Fixed after teacher generation (off-policy) | Yes | Soft distribution or text only |
| RL | Student sampling (on-policy) | None, one reward per sequence | None |
| Online distillation | Student sampling (on-policy) | Yes, teacher scores every token | Soft distribution |
Offline distillation has fixed data, dense signals, and stable training. Its limitation is that the student only sees states on teacher trajectories during training. Once the student makes a mistake early in inference that the teacher would not make, all later positions are outside the training distribution. This problem is called exposure bias and needs online distillation to handle.
⚗️ Output distillation and logits distillation
By information content, logits distillation is better than output distillation that uses only text. In practice output distillation is more common, for three reasons:
- Teachers are usually served as an API that returns only text or top-k logprobs. The probability mass outside the top-k is truncated, and computing KL after re-normalizing on that subset is an approximation.
- A single long chain-of-thought trajectory can reach 8000 tokens. Storing the full distribution at every position is infeasible, while the trajectory text itself already contains sufficient supervision signal.
- Most positions on a reasoning chain are unambiguous connectives or arithmetic steps, and the teacher distribution is close to one-hot. The gain of soft labels over one-hot is limited.
The DeepSeek-V4 technical report points out that using only the log-ratio on student-sampled tokens as the advantage gives a gradient estimate of high variance, and its full-vocabulary online distillation uses the full logits. With teacher weights available and enough GPU memory, logits distillation has a higher ceiling. When only text is available, output distillation is still an effective baseline.
📚 Data pipeline
💬 Prompt set
The prompt set is decided before the teacher is chosen. Data from a single source pulls the student's capability in one direction: data generated only on GSM8K is effective on GSM8K and may fall below the original model on MMLU.
In practice, first decide the capability matrix (the proportions and difficulty distributions of math, code, instruction following, multi-turn dialogue, and domain knowledge), then organize prompts by the matrix. The difficulty distribution decides the teacher's accuracy. With only easy problems the teacher is always right and the student learns only smooth reasoning paths. With only hard problems the teacher's error rate is high and wrong data enters the training set. In measured runs the teacher accuracy is kept between 60% and 85%, and a verifier then filters out wrong samples.
⚗️ Teacher generation
The controllable variables are temperature, the number of samples per prompt, the system prompt, and the maximum output length. Reasoning tasks use temperature 0.7 to 1.0 with 4 to 8 samples per prompt, kept after verifier filtering, which is equivalent to rejection sampling. For open-ended dialogue tasks, keeping a single reply per prompt is usually enough.
The system prompt and chat template must be consistent between teacher generation and student inference. If the teacher is asked to write the answer into \boxed{}, and all student training data are replies with \boxed{}, but the system prompt at inference time does not contain that requirement, the training and inference distributions are inconsistent. The special tokens of the chat template need to be consistent as well.
🧹 Filtering and verification
Filtering has two layers. Format and completeness: a reply whose length reaches the limit is most likely truncated, and a reply without \boxed{} most likely did not reach a conclusion. Both kinds are dropped directly. Correctness: tasks with a reference answer are compared by a verifier. Math tasks use math-verify (more tolerant of equivalent forms than string matching), code tasks run unit tests, and tasks without a reference answer are scored by teacher self-assessment or a reward model.
The verifier needs a timeout guard. In one regression, sympy fell into an unbounded loop while simplifying an expression, and the verification process was found only 24 minutes later. The original implementation used signal.alarm to set a timeout, but the verification function ran in a Ray worker, signal can only be used in the main thread, and the timeout did not take effect. The fix was to run verification in a persistent subprocess with a hard wall-clock timeout. After a timeout the reward is recorded as 0 and a log is written. This problem did not show up on a few hundred samples and only triggered once the data reached hundreds of thousands, while a single hung sample blocks the whole rollout batch.
After filtering, bucket by the original difficulty of the prompt and count the retention rate before and after filtering. An abnormally low retention rate in one difficulty bucket means the teacher's accuracy is insufficient at that difficulty. Replace the teacher or lower the difficulty.
📚 Data format and loss mask
Offline distillation data is usually stored as messages-format JSONL, where the last assistant message is the teacher output. The solution column of the dataset is provided only to the verifier and does not appear in the student-visible input. Data whose prompt contains the reference answer at the end makes the student depend on a hint that does not exist at inference time. In multi-turn tool-call trajectories, the observations returned by tools are not generated by the model, so the label at those positions should be -100.
🧑🎓 Student training
Training arguments are the same as SFT. The distillation-related arguments are as follows:
- LoRA vs full-parameter: to distill a 7B model into learning math reasoning with LoRA, rank 8 to 32 is usually enough. Full-parameter fine-tuning is more stable when transferring a markedly different kind of behavior (for example, from a chat model to a code model). The capacity of LoRA matches the quality ceiling of the teacher data and does not easily overwrite the student's general capability.
- Learning rate and epochs: LoRA commonly uses 1e-4, and full-parameter fine-tuning is on the order of 1e-5. After 2 to 3 epochs on distillation data the student starts to memorize the teacher's wording and the held-out score stops rising.
max_length: must cover the teacher's longest output. A long chain of thought can reach 8000 tokens. When truncated at 4096, exactly the concluding part at the end is cut off, and the student learns to stop in the middle of reasoning. Raisemax_lengthor filter out overly long samples.
📏 Evaluation
The training loss only reflects how well the student fits the teacher data. Evaluation includes at least: held-out task scores, a comparison with the original student under the same sampling settings, and the average output length (inference cost). The third item is often ignored: when the teacher's replies average 8000 tokens, the student learns replies of similar length and the inference cost rises accordingly.
📈 Training curve analysis
The following data comes from the SFT path of a recent training regression. It applies equally to judging the effect of distillation.
Loss deviation between implementations. On the same data, with the same seed and the same LoRA initialization, 30 steps were trained on each of two training implementations: the first-step loss differed by 0.056%, the per-step difference was below 0.62% for the first 8 steps, from step 9 the difference grew to 1% to 4%, and the end point differed by 3.9%. Both the 4B and the 35B-A3B models showed this shape, and the deviation was not monotonic. A difference of this magnitude comes from a different reduction order in bf16, amplified over 30 steps of training. Re-running the same implementation with the same configuration once gave identical loss values at all 30 steps, which rules out nondeterminism inside an implementation.
What this means for distillation evaluation: loss is not used to compare the effect of two distillation runs. A 3% end-point loss difference may make no difference on the evaluation set, while two runs that differ by 2 points on evaluation may share the same loss curve. Evaluate with held-out task scores.
35B-A3B LoRA, 30 steps: loss dropped from 2.82 to 0.96, grad_norm dropped from 5.6 to 1.8, all finite throughout. The descent was fastest in the first 10 steps and then converged slowly, which is the typical shape of a healthy distillation dataset on this model.
A rising loss needs an explanation before it is judged. In the seq_cls task, loss rose from 0.95 to 3.17 in 4 steps. In the pretrain task, it rose from 2.68 to 3.81. The former is a learning rate that is too high plus a randomly initialized classification head. The latter does not constitute a trend on 4 steps with a small sample. Explain a loss anomaly first, and treat it as a defect only if the explanation fails.
The decision model converged from 1.1 to below 1e-4 (30 steps, effective batch 16). The data is small, and the task goal is for the model to memorize a scoring head, so this shape is the expected result.
⚗️ Online distillation methods
The ceiling of offline distillation is decided by two things: the teacher's capability on the data distribution, and the student's ability to recover on its own outside teacher trajectories. The second cannot be provided by offline methods. When the student enters a state at inference time that never appeared in the teacher data, the way to proceed from there is not covered by offline data. When such errors are critical to the task, use online distillation:
- GKD (Agarwal et al., 2023): the student samples on its own with probability
lmbda, the teacher gives a per-token soft distribution on the sampled sequence, and they are aligned with the generalized JSD.lmbda=0degenerates into offline distillation, andlmbda=1is purely online. - MiniLLM: replaces forward KL with reverse KL. The student focuses on the high-probability region of the teacher and is less prone to over-smoothing on small models.
- On-Policy Distillation (Thinking Machines, 2025): uses the teacher's log-ratio as the per-token advantage and optimizes with policy gradient. It only needs the teacher's logp on the student-sampled tokens, so the teacher can be an API. The signal density is higher than RL, and the distribution is closer to the student's own than in offline distillation.
- OPSD (On-Policy Self-Distillation): self-distillation with a single model. The teacher-side input contains privileged information (such as the reference solution), the student side takes only the question as input, and the two are aligned on the distribution over the student-sampled sequence.
The engineering cost of online methods is higher than offline: an online sampling engine is needed, the teacher keeps participating in the training loop, and sampling and training run on separate GPUs or share GPUs. When choosing, compare three things: whether the data quality meets the requirements of offline training, whether the student's own errors are critical enough to need on-policy, and the share of teacher generation versus student training in the total budget.
🧩 Component-level implementation
The following code comes from examples/v5/train/lora/train.py and examples/v5/rl/gkd/gkd.py, trimmed to the arguments of this page. The training loop is written in the script: components are built from Config objects and then driven directly. This corresponds to the student training and online distillation methods sections above.
📚 Data
Messages-format JSONL, one sample per line. The solution column is read by the verifier during filtering, and only messages takes part in encoding during training:
{"messages": [{"role": "user", "content": "计算 17×23,把最终答案放在 \\boxed{} 中。"}, {"role": "assistant", "content": "17×23 = 17×20 + 17×3 = 340 + 51 = \\boxed{391}"}], "solution": "391"}🧑🎓 Student SFT
import math
from swift.dev.builder.optimizer import resolve_max_grad_norm
from swift.dev.config import (
CheckpointConfig, DatasetConfig, DistributedConfig, LoggingConfig, ModelConfig, QuantizeConfig,
TemplateConfig, TrainConfig, TunerConfig,
)
from swift.dev.loss import configure_loss
from swift.dev.recipe.configs import RecipeConfigs
from swift.dev.recipe.distill.signal import teacher_signal
from swift.dev.recipe.offline import build_offline_objects
from swift.dev.recipe.batching import grouped_training_batches
from swift.dev.recipe.utils import (
StepState, build_save_knobs, save_final_checkpoint, save_training_step,
)
def build_configs() -> dict:
return {
# attn_impl is fixed to flash_attention_2: bf16 training on the transformers backend produced NaN in the cuDNN SDPA backward
'model_config': ModelConfig(model='Qwen/Qwen3.5-4B', task_type='causal_lm',
torch_dtype='bfloat16', attn_impl='flash_attention_2'),
# max_length covers the teacher's longest output; truncating at 4096 cuts off the conclusion at the end
'template_config': TemplateConfig(max_length=8192),
'dataset_config': DatasetConfig(dataset=['distill_math.jsonl']),
'train_config': TrainConfig(num_train_epochs=2, per_device_train_batch_size=1,
gradient_accumulation_steps=8, learning_rate=1e-4,
lr_scheduler='cosine', warmup_ratio=0.05),
# mode='ray': the model runs on Ray workers and this process only schedules; nproc_per_node is the number of training GPUs
'distributed_config': DistributedConfig(mode='ray', nproc_per_node=8),
'checkpoint_config': CheckpointConfig(output_dir='output/distill-4b', save_steps=100, save_total_limit=2),
'logging_config': LoggingConfig(report_to=['tensorboard'], logging_steps=5),
'tuner_config': TunerConfig(tuner='lora', lora_rank=16, lora_alpha=32, target_modules=['all-linear']),
'quantize_config': QuantizeConfig(),
}
def main() -> None:
cfg = build_configs()
train, ckpt = cfg['train_config'], cfg['checkpoint_config']
ga = train.gradient_accumulation_steps
def sft_loss(model):
# Cross-entropy is equivalent to KL with a one-hot teacher, and is the entire training-side objective of offline distillation
configure_loss(model, loss_type='cross_entropy')
# The assembly order is fixed: twinkle initialize -> model -> tuner -> loss -> optimizer -> dataset/dataloader
cluster = build_offline_objects(
RecipeConfigs(
model=cfg['model_config'], template=cfg['template_config'], dataset=cfg['dataset_config'],
train=train, distributed=cfg['distributed_config'], checkpoint=ckpt,
tuner=cfg['tuner_config'], logging=cfg['logging_config'], quantize=cfg['quantize_config'],
),
recipe='run_sft', configure_loss=sft_loss, output_dir=ckpt.output_dir)
model, dataloader = cluster.model, cluster.dataloader
state = StepState(model, train, gradient_accumulation_steps=ga, max_steps=cluster.total_opt_steps,
max_grad_norm=resolve_max_grad_norm(train), logging_config=cfg['logging_config'],
output_dir=ckpt.output_dir, save_steps=ckpt.save_steps)
save_knobs = build_save_knobs(ckpt, cfg['dataset_config'], cfg['distributed_config'], cfg['tuner_config'],
output_dir=ckpt.output_dir)
def save(name: str, is_final: bool = False) -> str:
state.publish_state()
return save_training_step(model, state.handler, name, save_knobs,
consumed_train_samples=0, component_states={}, is_final=is_final)
state.handler.on_train_begin()
for epoch in range(math.ceil(train.num_train_epochs)):
dataloader.set_epoch(epoch) # reshuffle every epoch
# One group = gradient_accumulation_steps dataloader batches = one full update
for group, batch_count in grouped_training_batches(dataloader, ga):
state.micro_step += batch_count
state.handler.on_step_begin()
# The whole group is submitted as one call; the backend splits it into micro-batches of per_device_train_batch_size and accumulates gradients
model.forward_backward(inputs=group, task=cluster.forward_task,
gradient_accumulation_steps=1,
micro_batch_size=train.per_device_train_batch_size)
state.handler.on_pre_optimizer_step()
model.clip_grad_and_step(max_grad_norm=state.max_grad_norm, gradient_accumulation_steps=1)
state.handler.on_optimizer_step()
state.record() # reads model.calculate_metric: loss / grad_norm / lr
state.step_tail(save=save)
if state.reached_max() or state.should_stop():
break
if state.reached_max() or state.should_stop():
break
state.handler.on_train_end()
ckpt_dir = save_final_checkpoint(model, save, enabled=True)Several places in the loop correspond to the training experience above: attn_impl='flash_attention_2' is the workaround for the NaN in the cuDNN SDPA backward. TemplateConfig(max_length=8192) covers the teacher's longest output. lr_scheduler='cosine' together with warmup_ratio=0.05 and 2 epochs corresponds to the stopping point before the student starts to memorize the teacher's wording. Inside forward_backward, loss is computed only at positions whose label is not -100, which excludes the observation positions in tool-call trajectories from the gradient. When logits distillation is needed, this loop is not changed. Go through GKD below with lmbda=0 instead, where the teacher distribution replaces one-hot as the target.
⚗️ Online distillation
GKD adds a teacher on the same set of components. The teacher is an independent frozen Ray actor that exclusively occupies a group of DeviceGroup and shares the tokenizer with the student. Every trajectory of the student is re-scored by the teacher with forward_only(return_logits=True). This forward is initiated by the driver through teacher_signal, and the returned full-vocabulary logits are passed as references to the training ranks with the training kwargs. The driver does not hold teacher tensors:
'rl_config': RLConfig(
rl_type='gkd',
teacher_model=['Qwen/Qwen3.5-9B'], # An independent teacher needs an extra set of GPUs; the same as --model means self-distillation with the adapter disabled
lmbda=0.5, # Each turn uses the student's own samples with this probability, otherwise the completion from the dataset
beta=0.5, # 0 is forward KL, 1 is reverse KL, 0.5 is symmetric JSD
num_generations=1, sampling_temperature=1.0, max_completion_length=2048),
'reward_config': RewardConfig(), # Distillation does not use the reward channelThe teacher signal in the training loop (on-policy turn):
for trajs, batch_facts in driver:
for lo, hi in optimizer_batch_slices(len(trajs), train_batch_size, ga):
update, balance_metrics = balance_update(state, trajs[lo:hi], lengths[lo:hi],
micro_batch_kwargs={'micro_batch_size': micro_batch_size})
# use_student=True: the teacher scores the response tokens sampled by the student itself, with no SFT term attached
signal = teacher_signal(cluster, update, use_student=True)
cluster.model.forward_backward(inputs=copy_inputs(update), gradient_accumulation_steps=1,
micro_batch_size=micro_batch_size, **signal)
cluster.model.clip_grad_and_step(max_grad_norm=state.max_grad_norm, gradient_accumulation_steps=1)OPSD reuses the same loop and teacher_signal. The differences are on the teacher-side input and the loss: the dataset gains a teacher_prompt column. After distill_dataset_rows reads that column, it is encoded into the teacher-side input through attach_user_data, and the student-side input is unchanged. With rl_type='opsd', the teacher returns only the logp of the response tokens and does not pass full-vocabulary logits, and the loss is the k3 form on the sampled tokens.
'rl_config': RLConfig(
rl_type='opsd',
teacher_model=['Qwen/Qwen3.5-4B'], # Frozen teacher, 4B like --model; holds its own set of GPUs
lmbda=1.0, # Purely on-policy: every turn uses the student's own samples
opsd_reverse=True, # reverse-KL direction
num_generations=1, sampling_temperature=1.0, max_completion_length=2048),
'train_config': TrainConfig(learning_rate=2e-5, ...), # The k3 form tolerates a narrower range of lr than JSDThis path has no reward channel. The loss itself is the disagreement between teacher and student, and a falling loss is the convergence signal. The surrogate gradient of the k3 form is exp(teacher_logp - student_logp) - 1. When the teacher and the student disagree strongly on individual tokens, the exponential term amplifies the gradient: with lr 1e-4 the step-2 grad_norm was 13323, which is why the example script uses 2e-5.
🔗 References
For example scripts and data format see examples/v5 and Custom datasets. For the engineering structure of the online path see Online RL.
📊 Performance and Stability
Efficient GRPO, multi-node 122B MoE LoRA training, and numerical consistency in ms-swift v5.
🎯 Online Reinforcement Learning Explained
The GRPO objective and its known biases, what variants such as DAPO / GSPO / CISPO change, importance-sampling correction for training-inference mismatch and MoE routing replay, plus training regression curves, engineering constraints, and hyperparameter experience.