从源码安装(pip3 install -e .)官方标注为不推荐,优先用 pip;复现实验需额外下载 README 提到的预训练模型、训练日志和配置;用 ForwardHookManager 时需按模块名注册 hook,并调用 pop_io_dict 取出结果。
torchdistill
yoshitomo-matsubaraMIT活跃维护基于 PyTorch 的知识蒸馏框架,无需写代码即可复现和对比 28 种顶会蒸馏方法,附带训练模型、日志和配置,方便做可复现的深度学习研究。
A coding-free framework built on PyTorch for reproducible deep learning studies. PyTorch Ecosystem. 🏆28 knowledge distillation methods presented at TPAMI, CVPR, ICLR, ECCV, NeurIPS, ICCV, AAAI, etc are implemented so far. 🎁 Trained models, training logs and configurations are available for ensuring the reproducibiliy and benchmark.
pip3 install torchdistillREADME 未说明显存或 GPU 型号要求;示例代码用 torch.device('cpu') 在 CPU 上运行,实际训练所需硬件取决于所选模型与数据集。
基于 PyTorch 的配置驱动知识蒸馏框架,用 YAML 定义实验,无需写 Python 代码
基于 PyTorch 的知识蒸馏框架,无需写代码即可复现和对比 28 种顶会蒸馏方法,附带训练模型、日志和配置,方便做可复现的深度学习研究。
核心能力
- 用声明式 PyYAML 配置定义模型、数据集、优化器和损失
- 内置 28 种发表于 TPAMI、CVPR、ICLR 等会议的知识蒸馏方法
- 用 ForwardHookManager 提取中间层表示,无需改动 forward 接口
- 提供训练好的模型、训练日志和配置,便于复现与基准对比
- 去掉配置中的 teacher 条目即可做普通深度学习训练
容易踩的坑
- v1.1.5A new KD method, FSDP/FSDP2 support, and experiment tracking最新正式版2026-08-05 · 2026-08-05 05:40 UTC
New method
- Add SKD method (PRs #538, #541)
New features
- Extend data parallel support for FSDP/FSDP2 (PR #537)
- Support trackio and wandb (PR #543)
- Add accumulation mode with stack option (PR #536)
Improvements
- Use a more robust eval for DDP (PR #532)
- Remove teacher I/O caching (PR #539)
- Extend example log_analyzer.py (PR #544)
- Add yaml examples (PR #542)
- Refactor (PR #526)
Tests and CI
- Add loss test cases with fixtures (PR #535)
- Replace setup.py with pyproject.toml (PR #534)
- Add a Copilot instruction file and update GitHub Actions (PRs #528, #530, #531, #533)
Documentation
- Update README's (PR #540)
- Update acknowledgments (PRs #527, #529)
- Update year (PR #523)
Misc
- Update version and notebooks (PRs #522, #545)
- Update dependencies (PR #539)
- v1.1.4A new KD method, bug fixes, and end of Python 3.9 support2025-12-24 · 2025-12-24 05:41 UTC
查看更新说明
New method
- Add DIST+ method (PR #513)
Bug fixes
- Address weights_only related issues (PR #520)
- Fix a bug (PR #519)
Documentation
- Update projects.rst (PR #516)
- Update the benchmark doc (PR #515)
Misc
- Update references (PRs #514, #518)
- Update package and Python versions (PRs #512, #521)
- v1.1.3Add a new text classification example, Interface & YAML util updates2025-05-11 · 2025-05-11 23:21 UTC
查看更新说明
Examples
- Fix typos (PRs #500, #501)
- Rename text_classification.py (PR #508)
- Move GLUE-specific code to general_language_understanding.py (PR #509)
- Upgrade the text classification script, supporting multiple evaluation metrics with GoEmotions example (PR #510)
Interfaces
- Add a new forward proc (PR #502)
- Fix potential bugs (PR #507)
YAML util
- Support call_method (PR #506)
Documentation
- Update projects (PR #498)
Misc
- Add repo_or_dir (PR #493)
- Update README (PRs #494, #496, #497, #499)
- Simplify example (PR #495)
- Update versions (PRs #492, #511)
- v1.1.2PyTorch 2.5 support, model migrations, end of Python 3.8 support2024-12-15 · 2024-12-15 22:17 UTC
查看更新说明
Python version
- Update Python versions due to Python 3.8 EOL (PR #486)
Models
- Migrate all bottleneck-injected models to sc2bench (PR #490)
- Update with PyTorch Hub links (PR #489)
- Update yaml example (PR #487)
Misc
- Force-use pytorch hub when repo_or_dir is given (PR #488)
- Explicitly add evaluate to dependency (PR #483)
- Update versions (PRs #480, #491)
- v1.1.1A new KD method, new benchmark results, and updated YAML constructors2024-08-13 · 2024-08-13 05:07 UTC
查看更新说明
New method
- Add KD with logits standardization (PR #460)
YAML configs
- Fix the official config for SRD (Issue #471, PR #473)
- Fix SRD config (Issue #471, PR #472)
- Add os.path YAML constructors (PR #454)
Logs
- Disable an auto-configuration for def_logger (Issue #465, PR #469)
- Use warning (PR #468)
Documentation
- Add a new benchmark (PR #464)
- Update Projects page (PRs #456, #475)
Misc
- Update README (PRs #461, #470)
- Update a URL (PR #459)
- Update GH Action vers (PRs #457, #458)
- Update CITATION (PR #455)
- Add a new DOI badge (PR #453)
- Update version (PRs #452, #479)
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。

torchdistill: A Modular, Configuration-Driven Framework for Knowledge Distillation
torchdistill (formerly kdkit) offers various state-of-the-art knowledge distillation methods and enables you to design (new) experiments simply by editing a declarative yaml config file instead of Python code. Even when you need to extract intermediate representations in teacher/student models, you will NOT need to reimplement the models, that often change the interface of the forward, but instead specify the module path(s) in the yaml file. Refer to these papers for more details.
In addition to knowledge distillation, this framework helps you design and perform general deep learning experiments (WITHOUT coding) for reproducible deep learning studies. i.e., it enables you to train models without teachers simply by excluding teacher entries from a declarative yaml config file. You can find such examples below and in configs/sample/.
In December 2023, torchdistill officially joined PyTorch Ecosystem.
When you refer to torchdistill in your paper, please cite these papers
instead of this GitHub repository.
If you use torchdistill as part of your work, your citation is appreciated and motivates me to maintain and upgrade this framework!
Documentation
You can find the API documentation and research projects that leverage torchdistill at https://yoshitomo-matsubara.net/torchdistill/
Forward hook manager
Using ForwardHookManager, you can extract intermediate representations in model without modifying the interface of its forward function.
This example notebook
will give you a better idea of the usage such as knowledge distillation and analysis of intermediate representations.
E.g., extract intermediate representations (feature map) of ResNet-18 for a random input batch
import torch
from torchvision import models
from torchdistill.core.forward_hook import ForwardHookManager
# Define a model and choose torch device
model = models.resnet18(pretrained=False)
device = torch.device('cpu')
# Register forward hooks for modules of your interest
forward_hook_manager = ForwardHookManager(device)
forward_hook_manager.add_hook(model, 'conv1', requires_input=True, requires_output=False)
forward_hook_manager.add_hook(model, 'layer1.0.bn2', requires_input=True, requires_output=True)
forward_hook_manager.add_hook(model, 'fc', requires_input=False, requires_output=True)
# Define a random input batch and run the model
x = torch.rand(32, 3, 224, 224)
y = model(x)
# Extract input and/or output of the modules
io_dict = forward_hook_manager.pop_io_dict()
conv1_input = io_dict['conv1']['input']
layer1_0_bn2_input = io_dict['layer1.0.bn2']['input']
layer1_0_bn2_output = io_dict['layer1.0.bn2']['output']
fc_output = io_dict['fc']['output']
1 experiment → 1 declarative PyYAML config file
In torchdistill, many components and PyTorch modules are abstracted e.g., models, datasets, optimizers, losses, and more! You can define them in a declarative PyYAML config file so that can be seen as a summary of your experiment, and in many cases, you will NOT need to write Python code at all. Take a look at some configurations available in configs/. You'll see what modules are abstracted and how they are defined in a declarative PyYAML config file to design an experiment.
E.g., instantiate CIFAR-10 datasets with a declarative PyYAML config file
from torchdistill.common import yaml_util
config = yaml_util.load_yaml_file('./test.yaml')
train_dataset = config['datasets']['cifar10/train']
test_dataset = config['datasets']['cifar10/test']
test.yaml
datasets:
cifar10/train: !import_call
key: 'torchvision.datasets.CIFAR10'
init:
kwargs:
root: &root_dir '~/datasets/cifar10'
train: True
download: True
transform: !import_call
key: 'torchvision.transforms.Compose'
init:
kwargs:
transforms:
- !import_call
key: 'torchvision.transforms.RandomCrop'
init:
kwargs:
size: 32
padding: 4
- !import_call
key: 'torchvision.transforms.RandomHorizontalFlip'
init:
kwargs:
p: 0.5
- !import_call
key: 'torchvision.transforms.ToTensor'
init:
- !import_call
key: 'torchvision.transforms.Normalize'
init:
kwargs: &normalize_kwargs
mean: [0.49139968, 0.48215841, 0.44653091]
std: [0.24703223, 0.24348513, 0.26158784]
cifar10/test: !import_call
key: 'torchvision.datasets.CIFAR10'
init:
kwargs:
root: *root_dir
train: False
download: True
transform: !import_call
key: 'torchvision.transforms.Compose'
init:
kwargs:
transforms:
- !import_call
key: 'torchvision.transforms.ToTensor'
init:
- !import_call
key: 'torchvision.transforms.Normalize'
init:
kwargs: *normalize_kwargs
If you want to use your own modules (models, loss functions, datasets, etc) with this framework,
you can do so without editing code in the local package torchdistill/.
See the official documentation and Discussions for more details.
Benchmarks
Top-1 validation accuracy for ILSVRC 2012 (ImageNet)
Examples
Executable code can be found in examples/ such as
- Image classification: ImageNet (ILSVRC 2012), CIFAR-10, CIFAR-100, etc
- Object detection: COCO 2017, etc
- Semantic segmentation: COCO 2017, PASCAL VOC, etc
- Text classification: GoEmotions, etc
- GLUE: CoLA, SST-2, MRPC, STS-B, QQP, MNLI, QNLI, RTE, WNLI, AX
- Causal language modeling / Instruction tuning: Alpaca
For CIFAR-10 and CIFAR-100, some models are reimplemented and available as pretrained models in torchdistill. More details can be found here.
Some Transformer models fine-tuned by torchdistill for GLUE tasks are available at Hugging Face Model Hub. Sample GLUE benchmark results and details can be found here.
Google Colab Examples
The following examples are available in demo/. Note that these examples are for Google Colab users and compatible with Amazon SageMaker Studio Lab. Usually, examples/ would be a better reference if you have your own GPU(s).
CIFAR-10 and CIFAR-100
GLUE
These examples write out test prediction files for you to see the test performance at the GLUE leaderboard system.
PyTorch Hub
If you find models on PyTorch Hub or GitHub repositories supporting PyTorch Hub, you can import them as teacher/student models simply by editing a declarative yaml config file.
e.g., If you use a pretrained ResNeSt-50 available in huggingface/pytorch-image-models (aka timm) as a teacher model for ImageNet dataset, you can import the model via PyTorch Hub with the following entry in your declarative yaml config file.
models:
teacher_model:
key: 'resnest50d'
repo_or_dir: 'huggingface/pytorch-image-models'
kwargs:
num_classes: 1000
pretrained: True
How to setup
- Python >= 3.9
- pipenv (optional)
Install by pip/pipenv
pip3 install torchdistill
# or use pipenv
pipenv install torchdistill
Install from this repository (not recommended)
git clone https://github.com/yoshitomo-matsubara/torchdistill.git
cd torchdistill/
pip3 install -e .
# or use pipenv
pipenv install "-e ."
Issues / Questions / Requests / Pull Requests
Feel free to create an issue if you find a bug.
If you have either a question or feature request, start a new discussion here.
Please search through Issues and Discussions and make sure your issue/question/request has not been addressed yet.
Pull requests are welcome. Please start with an issue and discuss solutions with me rather than start with a pull request.
Citation
If you use torchdistill in your research, please cite the following papers:
[Paper] [Preprint]
@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}
}
[Paper] [OpenReview] [Preprint]
@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}
}
Acknowledgments
This project has been supported by Travis CI's OSS credits since November 2021. JetBrain's Free License Programs (Open Source) has supported the project since June 2022.
References
- :mag: pytorch/vision/references/classification/
- :mag: pytorch/vision/references/detection/
- :mag: pytorch/vision/references/segmentation/
- :mag: huggingface/transformers/examples/pytorch/text-classification
- :mag: Geoffrey Hinton, Oriol Vinyals, Jeff Dean. "Distilling the Knowledge in a Neural Network" @ Deep Learning and Representation Learning Workshop: NIPS 2014
- :mag: Adriana Romero, Nicolas Ballas, Samira Ebrahimi Kahou, Antoine Chassang, Carlo Gatta, Yoshua Bengio. "FitNets: Hints for Thin Deep Nets" @ ICLR 2015
- :mag: Junho Yim, Donggyu Joo, Jihoon Bae, Junmo Kim. "A Gift From Knowledge Distillation: Fast Optimization, Network Minimization and Transfer Learning" @ CVPR 2017
- :mag: Sergey Zagoruyko, Nikos Komodakis. "Paying More Attention to Attention: Improving the Performance of Convolutional Neural Networks via Attention Transfer" @ ICLR 2017
- :mag: Nikolaos Passalis, Anastasios Tefas. "Learning Deep Representations with Probabilistic Knowledge Transfer" @ ECCV 2018
- :mag: Jangho Kim, Seonguk Park, Nojun Kwak. "Paraphrasing Complex Network: Network Compression via Factor Transfer" @ NeurIPS 2018
- :mag: Byeongho Heo, Minsik Lee, Sangdoo Yun, Jin Young Choi. "Knowledge Transfer via Distillation of Activation Boundaries Formed by Hidden Neurons" @ AAAI 2019
- :mag: Tong He, Chunhua Shen, Zhi Tian, Dong Gong, Changming Sun, Youliang Yan. "Knowledge Adaptation for Efficient Semantic Segmentation" @ CVPR 2019
- :mag: Wonpyo Park, Dongju Kim, Yan Lu, Minsu Cho. "Relational Knowledge Distillation" @ CVPR 2019
- :mag: Sungsoo Ahn, Shell Xu Hu, Andreas Damianou, Neil D. Lawrence, Zhenwen Dai. "Variational Information Distillation for Knowledge Transfer" @ CVPR 2019
- :mag: Yoshitomo Matsubara, Sabur Baidya, Davide Callegaro, Marco Levorato, Sameer Singh. "Distilled Split Deep Neural Networks for Edge-Assisted Real-Time Systems" @ Workshop on Hot Topics in Video Analytics and Intelligent Edges: MobiCom 2019
- :mag: Baoyun Peng, Xiao Jin, Jiaheng Liu, Dongsheng Li, Yichao Wu, Yu Liu, Shunfeng Zhou, Zhaoning Zhang. "Correlation Congruence for Knowledge Distillation" @ ICCV 2019
- :mag: Frederick Tung, Greg Mori. "Similarity-Preserving Knowledge Distillation" @ ICCV 2019
- :mag: Yonglong Tian, Dilip Krishnan, Phillip Isola. "Contrastive Representation Distillation" @ ICLR 2020
- :mag: Yoshitomo Matsubara, Marco Levorato. "Neural Compression and Filtering for Edge-assisted Real-time Object Detection in Challenged Networks" @ ICPR 2020
- :mag: Li Yuan, Francis E.H.Tay, Guilin Li, Tao Wang, Jiashi Feng. "Revisiting Knowledge Distillation via Label Smoothing Regularization" @ CVPR 2020
- :mag: Guodong Xu, Ziwei Liu, Xiaoxiao Li, Chen Change Loy. "Knowledge Distillation Meets Self-Supervision" @ ECCV 2020
- :mag: Youcai Zhang, Zhonghao Lan, Yuchen Dai, Fangao Zeng, Yan Bai, Jie Chang, Yichen Wei. "Prime-Aware Adaptive Distillation" @ ECCV 2020
- :mag: Pengguang Chen, Shu Liu, Hengshuang Zhao, Jiaya Jia. "Distilling Knowledge via Knowledge Review" @ CVPR 2021
- :mag: Li Liu, Qingle Huang, Sihao Lin, Hongwei Xie, Bing Wang, Xiaojun Chang, Xiaodan Liang. "Exploring Inter-Channel Correlation for Diversity-Preserved Knowledge Distillation" @ ICCV 2021
- :mag: Tao Huang, Shan You, Fei Wang, Chen Qian, Chang Xu. "Knowledge Distillation from A Stronger Teacher" @ NeurIPS 2022
- :mag: Roy Miles, Krystian Mikolajczyk. "Understanding the Role of the Projector in Knowledge Distillation" @ AAAI 2024
- :mag: Rishabh Agarwal, Nino Vieillard, Yongchao Zhou, Piotr Stanczyk, Sabela Ramos Garea, Matthieu Geist, Olivier Bachem. "On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes" @ ICLR 2024
- :mag: Shangquan Sun, Wenqi Ren, Jingzhi Li, Rui Wang, Xiaochun Cao. "Logit Standardization in Knowledge Distillation" @ CVPR 2024
- :mag: Tao Huang, Shan You, Fei Wang, Chen Qian, Chang Xu. "DIST+: Knowledge Distillation From a Stronger Adaptive Teacher" @ TPAMI (2025)
- :mag: Hyeon-Jin Jeong, Han-Jin Lee, Seok-Hwan Choi. "Streamlined Knowledge Distillation" @ CVPR 2026