smollm2_135m_from_smollm2_360m-alpaca-on_policy_kd
HuggingFaceTB/SmolLM2-135M-Instruct trained on Stanford Alpaca by on-policy knowledge distillation (KD) from the Alpaca-tuned SmolLM2-360M teacher smollm2_360m-alpaca-it, with torchdistill.
Both models are scored on sequences the student generated itself, so the student learns from the teacher on its own outputs rather than only on the reference completions. The training budget, optimizer and schedule match the teacher-free baseline smollm2_135m-alpaca-it, so the two are directly comparable. Its counterpart trained off-policy from the same teacher is smollm2_135m_from_smollm2_360m-alpaca-off_policy_kd.
Model details
| Student (base model) | HuggingFaceTB/SmolLM2-135M-Instruct (135M parameters, Llama architecture) |
| Teacher | smollm2_360m-alpaca-it (SmolLM2-360M-Instruct fine-tuned on the same Alpaca split; frozen) |
| Training | Full-parameter on-policy KD: 0.5 x cross-entropy on reference responses + 0.5 x forward KL to the teacher |
| Training data | tatsu-lab/alpaca, 90% of the train split (46,801 examples) |
| Language | English |
| Context used in training | 512 tokens (prompt up to 256) |
| Weights | model.safetensors, float32 |
| License | CC BY-NC 4.0 (see License) |
Usage
The model was trained with the system prompt "You are a helpful assistant.". The bundled chat template falls back
to SmolLM's default system prompt when none is given, so pass the training one explicitly:
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id = 'yoshitomo-matsubara/smollm2_135m_from_smollm2_360m-alpaca-on_policy_kd'
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, dtype='bfloat16', device_map='auto')
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': 'Give three tips for staying healthy.'},
]
inputs = tokenizer.apply_chat_template(
messages, add_generation_prompt=True, return_tensors='pt', return_dict=True
).to(model.device)
outputs = model.generate(**inputs, max_new_tokens=256)
print(tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True))
The tokenizer pads on the right (the default). That is fine for a single prompt, but for batched generation set left padding, so that every prompt ends at the last position and generation continues from the prompt rather than from pad tokens:
tokenizer.padding_side = 'left'
batch = [
[{'role': 'system', 'content': 'You are a helpful assistant.'}, {'role': 'user', 'content': instruction}]
for instruction in ['Give three tips for staying healthy.', 'What is the capital of France?']
]
inputs = tokenizer.apply_chat_template(
batch, add_generation_prompt=True, padding=True, return_tensors='pt', return_dict=True
).to(model.device)
outputs = model.generate(**inputs, max_new_tokens=256)
print(tokenizer.batch_decode(outputs[:, inputs['input_ids'].shape[1]:], skip_special_tokens=True))
Training data and split
tatsu-lab/alpaca ships only a train split (52,002 examples), so it was split 90/5/5 into train, validation and
test at run time with torchdistill's split_dataset (lengths: [90, 5, 5], generator_seed: 42). The equivalent
in plain PyTorch:
import torch
from datasets import load_dataset
from torch.utils.data import random_split
dataset = load_dataset('tatsu-lab/alpaca', split='train', revision='dce01c9b08f87459cf36a430d809084718273017')
subsets = random_split(dataset, [46801, 2600, 2601], generator=torch.Generator().manual_seed(42))
train, validation, test = (dataset.select(subset.indices) for subset in subsets)
# train: 46,801 examples, validation: 2,600 examples, test: 2,601 examples
The training run did not pin revision; the commit above is the one it resolved to. The same seed reproduces the
same split only for the same dataset revision (and a PyTorch version that keeps the randperm stream unchanged).
The SmolLM2 Alpaca models (the 135M baseline, the 360M and 1.7B teachers and the distilled 135M students) all use
this split, so the teacher never saw this student's validation or test examples either.
Each example is formatted with SmolLM2's chat template: the system prompt above, the instruction field as the
user turn (prompt_key: 'instruction') and the output field as the assistant turn (response_key: 'output').
Prompt tokens are masked out of the task loss.
Training procedure
The loss is
L_total = 0.5 * L_task + 0.5 * L_KD
where L_task is the cross-entropy on the reference response tokens (the baseline's only loss) and L_KD is the
on-policy KL term below. SmolLM2 models share one tokenizer and vocabulary (49,152 entries), which is what lets
the token-level KL compare the teacher's and the student's logits position by position.
Before each training step, the current student samples a continuation of up to 32 tokens for every
prompt in the batch. The frozen teacher and the student then score those sequences, and the KL term is computed on
the generated tokens. A second student forward pass over the reference completions provides the cross-entropy task
loss. The sequential decoding dominates the run time; it scales roughly linearly with max_new_tokens, which is
why it is capped at 32. Data split, chat template, teacher, budget, optimizer, schedule, loss weights and
kl_type are identical to the off-policy counterpart.
| Hyperparameter | Value |
|---|---|
| KD term | Forward KL divergence KL(p_teacher || p_student), averaged per token over the student's generated tokens |
| Rollouts | Sampled from the current student before each forward pass: up to 32 new tokens, temperature 1.0, top-p 0.9 |
| Loss weights | 0.5 task (cross-entropy) / 0.5 KD |
| Epochs | 3 (checkpoint kept from epoch 3, see Evaluation) |
| Optimizer | AdamW, lr 5e-5, weight decay 0.0 |
| Schedule | Linear decay with 100 warmup steps |
| Batch size | 8 per device x 1 device(s) x gradient accumulation 4 = 32 |
| Gradient clipping | max norm 1.0 |
| Precision | fp32 master weights (student and teacher), bf16 autocast |
| Hardware | 1 GPU, bf16 mixed precision (accelerate launch), peak memory ~10.5 GB |
| Time per epoch | ~52 min |
| Seed | 42 |
The full torchdistill config, CLI arguments, training log and per-step metrics are in logs/:
config.yaml, args.json, train.log, metrics.json and trackio/summary.csv. To reproduce the run with
torchdistill, use the command in the header of logs/config.yaml.
Evaluation
Perplexity over the response tokens. The 2,600-example validation split was measured after each epoch and used to pick the checkpoint:
| Epoch | Validation perplexity |
|---|---|
| 1 | 5.2994 |
| 2 | 5.2465 |
| 3 (released) | 5.2410 |
The checkpoint with the lowest validation perplexity (epoch 3) is the one released here. Evaluated once on the 2,601-example test split, its perplexity is 5.2820 (teacher: 4.4717).
Comparison with the other SmolLM2-135M Alpaca models
All rows share the data split, the 3-epoch budget at an effective batch size of 32, the optimizer, learning rate and schedule; each test score is from the checkpoint with the best validation perplexity.
| Model | Teacher | Test perplexity | vs. baseline | Time per epoch |
|---|---|---|---|---|
| smollm2_135m-alpaca-it (instruction tuning) | - | 5.3968 | - | ~7 min |
| smollm2_135m_from_smollm2_1_7b-alpaca-off_policy_kd | 1.7B | 5.2805 | -0.1163 (-2.2%) | ~18 min |
| smollm2_135m_from_smollm2_1_7b-alpaca-on_policy_kd | 1.7B | 5.2623 | -0.1345 (-2.5%) | ~1 h 37 min |
| smollm2_135m_from_smollm2_360m-alpaca-off_policy_kd | 360M | 5.2849 | -0.1119 (-2.1%) | ~11 min |
| smollm2_135m_from_smollm2_360m-alpaca-on_policy_kd (this model) | 360M | 5.2820 | -0.1148 (-2.1%) | ~52 min |
The two distillation methods are close: the on-/off-policy gap (0.018 with the 1.7B teacher, 0.003 with the 360M teacher) is far smaller than the gain over the baseline, from a single seed each. Unlike the baseline, whose validation perplexity rises after epoch 1, every distilled student keeps improving or plateaus through epoch 3.
The test split is disjoint from the training data and the checkpoint selection, so these are held-out scores; they
are still in-distribution (Alpaca-style instructions and text-davinci-003 references). Perplexity on the reference
completions measures what the off-policy objective trains on directly, and does not capture the generation quality
that on-policy distillation targets. No downstream benchmarks (e.g. AlpacaEval, MT-Bench) have been run.
Limitations
- Alpaca's responses were generated by OpenAI's
text-davinci-003and inherit its factual errors, biases and short, generic style. The teacher was fine-tuned on the same data, so distillation does not remove them. The model may produce incorrect, harmful or biased text. - No safety tuning was performed beyond what the base SmolLM2-Instruct model already has.
- English only; trained on sequences of at most 512 tokens.
- On-policy rollouts are capped at 32 new tokens, so the KL term only covers the beginning of each response.
- Results are from a single seed.
- Intended for research, in particular as a reference point for knowledge-distillation experiments. Not intended for production or commercial use.
License
The weights are released under CC BY-NC 4.0 (LICENSE),
because the training data, tatsu-lab/alpaca, is licensed under CC BY-NC 4.0 and its outputs were generated with
OpenAI's text-davinci-003, whose terms restrict use for developing competing models. The teacher,
smollm2_360m-alpaca-it, is released under the same license.
This model is a modification of HuggingFaceTB/SmolLM2-135M-Instruct by Hugging Face, which is licensed under the
Apache License 2.0; a copy is included in LICENSE.SmolLM2. The modification is full-parameter
knowledge distillation on the data described above.
Citation
If you use this model, please cite torchdistill, as well as SmolLM2 and Alpaca:
@inproceedings{matsubara2021torchdistill,
title={torchdistill: A Modular, Configuration-Driven Framework for Knowledge Distillation},
author={Matsubara, Yoshitomo},
booktitle={International Workshop on Reproducible Research in Pattern Recognition},
pages={24--44},
year={2021},
organization={Springer}
}
@inproceedings{matsubara2023torchdistill,
title={{torchdistill Meets Hugging Face Libraries for Reproducible, Coding-Free Deep Learning Studies: A Case Study on NLP}},
author={Matsubara, Yoshitomo},
booktitle={Proceedings of the 3rd Workshop for Natural Language Processing Open Source Software (NLP-OSS 2023)},
publisher={Empirical Methods in Natural Language Processing},
pages={153--164},
year={2023}
}
@misc{allal2025smollm2,
title={SmolLM2: When Smol Goes Big -- Data-Centric Training of a Small Language Model},
author={Loubna Ben Allal and Anton Lozhkov and Elie Bakouch and Gabriel Mart\'in Bl\'azquez and Guilherme Penedo and Lewis Tunstall and Andr\'es Marafioti and Hynek Kydl\'i\v{c}ek and Agust\'in Piqueres Lajar\'in and Vaibhav Srivastav and Joshua Lochner and Caleb Fahlgren and Xuan-Son Nguyen and Cl\'ementine Fourrier and Ben Burtenshaw and Hugo Larcher and Haojun Zhao and Cyril Zakka and Mathieu Morlon and Colin Raffel and Leandro von Werra and Thomas Wolf},
year={2025},
eprint={2502.02737},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
@misc{alpaca,
author={Rohan Taori and Ishaan Gulrajani and Tianyi Zhang and Yann Dubois and Xuechen Li and Carlos Guestrin and Percy Liang and Tatsunori B. Hashimoto},
title={Stanford Alpaca: An Instruction-following LLaMA model},
year={2023},
publisher={GitHub},
journal={GitHub repository},
howpublished={\url{https://github.com/tatsu-lab/stanford_alpaca}}
}