/ Модель

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

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

smollm2_135m_from_smollm2_360m-alpaca-off_policy_kd

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

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

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

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

SmolLM2-135M — компактная языковая модель семейства Llama, разработанная HuggingFaceTB и дообученная автором репозитория на инструкциях Stanford Alpaca методом off-policy knowledge distillation. В роли ученика использована HuggingFaceTB/SmolLM2-135M-Instruct, а учителем — Alpaca-версия SmolLM2-360M. Обучение полного набора параметров сочетало кросс-энтропию по эталонным ответам и forward KL к распределению учителя.

Модель предназначена для генерации ответов на инструкции и коротких диалогов на английском языке. Она содержит 134,5 млн параметров, использует архитектуру Llama и поддерживает контекст до 8192 токенов. В README сообщается, что обучение ограничивалось последовательностями до 512 токенов; на отложенном Alpaca-разбиении perplexity составила 5,2849, но качество генерации и производственные сценарии отдельно не оценивались.

Модель подходит для экспериментов с дистилляцией и компактной генерацией текста. Ответы могут наследовать фактические ошибки и смещения Alpaca и учителя; отдельной настройки безопасности не проводилось. Лицензия CC-BY-NC-4.0 ограничивает коммерческое использование.

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

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

Ограничения

Обучение и оценка опирались на англоязычные примеры Alpaca; модель может воспроизводить их ошибки и смещения, а отдельные тесты качества генерации и безопасности не проводились. Коммерческое использование ограничено лицензией CC-BY-NC-4.0.

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

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

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

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

Источники: 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_360m-alpaca-off_policy_kd

HuggingFaceTB/SmolLM2-135M-Instruct trained on Stanford Alpaca by off-policy knowledge distillation (KD) from the Alpaca-tuned SmolLM2-360M teacher smollm2_360m-alpaca-it, with torchdistill.

Both models are scored on the reference (dataset) completions, so the student generates nothing during training (word-level KD). The training budget, optimizer and schedule match the teacher-free baseline smollm2_135m-alpaca-it, so the two are directly comparable. Its counterpart trained on-policy from the same teacher is smollm2_135m_from_smollm2_360m-alpaca-on_policy_kd.

Model details

Student (base model)HuggingFaceTB/SmolLM2-135M-Instruct (135M parameters, Llama architecture)
Teachersmollm2_360m-alpaca-it (SmolLM2-360M-Instruct fine-tuned on the same Alpaca split; frozen)
TrainingFull-parameter off-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_360m-alpaca-off_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 off-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.

Each training step runs one forward pass of the frozen teacher and one of the student over the same reference completions. That single student pass yields both the logits for the KL term and the cross-entropy task loss. The only difference from the on-policy counterpart is the source of the sequences the KL term is computed on; data split, chat template, teacher, budget, optimizer, schedule, loss weights and kl_type are identical.

HyperparameterValue
KD termForward KL divergence KL(p_teacher || p_student), averaged per token over the reference completion tokens
RolloutsNone: the student and the teacher are scored on the reference completions
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 size8 per device x 1 device(s) x gradient accumulation 4 = 32
Gradient clippingmax norm 1.0
Precisionfp32 master weights (student and teacher), bf16 autocast
Hardware1 GPU, bf16 mixed precision (accelerate launch), peak memory ~11.1 GB
Time per epoch~11 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.2967
25.2575
3 (released)5.2533

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.2849 (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.

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_kd1.7B5.2623-0.1345 (-2.5%)~1 h 37 min
smollm2_135m_from_smollm2_360m-alpaca-off_policy_kd (this model)360M5.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.
  • 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}}
}

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

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

GPU в ailist

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

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

Подбираем GPU…

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

0 моделей