/ Модель

Характеристики

Контекст
8 192 токена
Параметры
134 млн
Лицензия
CC BY-NC 4.0
Архитектура
llama · dense
Базовая модель
SmolLM2-135M-Instruct
Библиотека
transformers
Опубликована
27 окт 2026

smollm2_135m_from_smollm2_1_7b-alpaca-on_policy_kd

Генерация текстаТекст → текст3 профессии
449скачиваний за 30 дней0лайковвеса обновлены27 окт 2026

Описание модели

Составлено на русском по карточке модели и метаданным Hugging Face

Компактная англоязычная модель SmolLM2-135M, дистиллированная на Alpaca для генерации ответов на инструкции и экспериментов с дистилляцией.

Это компактная англоязычная инструктивная языковая модель на 134,5 млн параметров, разработанная автором репозитория на основе HuggingFaceTB/SmolLM2-135M-Instruct. Модель дообучена на наборе Stanford Alpaca методом дистилляции знаний с учителем SmolLM2-1.7B, также настроенным на Alpaca. Во время обучения ученик генерировал собственные последовательности, на которых его ответы сравнивались с ответами учителя; функция потерь сочетала кросс-энтропию по эталонным ответам и прямую KL-дивергенцию. Архитектура — плотная Llama, формат весов — safetensors; контекст составляет 8192 токена.

Модель предназначена для генерации ответов на англоязычные инструкции и исследовательских экспериментов с дистилляцией компактных языковых моделей. На отложенной выборке Alpaca достигнута perplexity 5,2623, однако оценка выполнена только на одном запуске и не заменяет проверку качества генерации на прикладных задачах. Обучающие данные унаследовали фактические ошибки, смещения и краткий стиль ответов text-davinci-003; дополнительная настройка безопасности не проводилась. Обучение использовало последовательности длиной до 512 токенов, а часть дистилляции по собственным ответам охватывала не более 32 новых токенов. Лицензия CC-BY-NC-4.0 запрещает коммерческое использование; автор позиционирует модель как исследовательский ориентир.

Сценарии применения

  • генерация ответов на англоязычные инструкции
  • сравнение методов on-policy и off-policy дистилляции
  • исследование дистилляции компактных языковых моделей
  • воспроизведение экспериментов обучения на Alpaca

Ограничения

Обучающие ответы Alpaca могут содержать ошибки и смещения; дополнительной настройки безопасности не проводилось. Оценка проведена на одном запуске, ответы при обучении ограничивались 512 токенами, а KL-дистилляция — первыми 32 новыми токенами; лицензия запрещает коммерческое использование.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus, LLM Stats

Бенчмарки пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь рядом с другими моделями теста

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Текст» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы по шкале 0–100.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

smollm2_135m_from_smollm2_1_7b-alpaca-on_policy_kd

HuggingFaceTB/SmolLM2-135M-Instruct trained on Stanford Alpaca by on-policy knowledge distillation (KD) from the Alpaca-tuned SmolLM2-1.7B teacher smollm2_1_7b-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_1_7b-alpaca-off_policy_kd.

Model details

Student (base model)HuggingFaceTB/SmolLM2-135M-Instruct (135M parameters, Llama architecture)
Teachersmollm2_1_7b-alpaca-it (SmolLM2-1.7B-Instruct fine-tuned on the same Alpaca split; frozen)
TrainingFull-parameter on-policy KD: 0.5 x cross-entropy on reference responses + 0.5 x forward KL to the teacher
Training datatatsu-lab/alpaca, 90% of the train split (46,801 examples)
LanguageEnglish
Context used in training512 tokens (prompt up to 256)
Weightsmodel.safetensors, float32
LicenseCC 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_1_7b-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.

HyperparameterValue
KD termForward KL divergence KL(p_teacher || p_student), averaged per token over the student's generated tokens
RolloutsSampled from the current student before each forward pass: up to 32 new tokens, temperature 1.0, top-p 0.9
Loss weights0.5 task (cross-entropy) / 0.5 KD
Epochs3 (checkpoint kept from epoch 3, see Evaluation)
OptimizerAdamW, lr 5e-5, weight decay 0.0
ScheduleLinear decay with 100 warmup steps
Batch size4 per device x 1 device(s) x gradient accumulation 8 = 32
Gradient clippingmax norm 1.0
Precisionfp32 master weights (student and teacher), bf16 autocast
Hardware1 GPU, bf16 mixed precision (accelerate launch), peak memory ~9.4 GB
Time per epoch~1 h 37 min
Seed42

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:

EpochValidation perplexity
15.2918
25.2226
3 (released)5.2167

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.2623 (teacher: 3.8093).

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.

ModelTeacherTest perplexityvs. baselineTime per epoch
smollm2_135m-alpaca-it (instruction tuning)-5.3968-~7 min
smollm2_135m_from_smollm2_1_7b-alpaca-off_policy_kd1.7B5.2805-0.1163 (-2.2%)~18 min
smollm2_135m_from_smollm2_1_7b-alpaca-on_policy_kd (this model)1.7B5.2623-0.1345 (-2.5%)~1 h 37 min
smollm2_135m_from_smollm2_360m-alpaca-off_policy_kd360M5.2849-0.1119 (-2.1%)~11 min
smollm2_135m_from_smollm2_360m-alpaca-on_policy_kd360M5.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-003 and 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_1_7b-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}}
}

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · transformers

Можно запустить

Подбираем GPU…

Класс архитектуры
LlamaForCausalLM
Ревизия весов
7d10c25

0 моделей