1. Project Overview & Quickstart (huggingface/pytorch-image-models)
File: README.md
PyTorch Image Models
- What's New
- Introduction
- Models
- Features
- Results
- Getting Started (Documentation)
- Train, Validation, Inference Scripts
- Awesome PyTorch Resources
- Licenses
- Citing
What's New
August 11, 2026
- Add model defs and pretrained weights for
- CPUBone, an efficient vision backbone for devices with low parallelization capabilities.
- PP-LCNetV2.
- LingBot-Vision.
- Add per-batch image and batch size scheduling for non-NaFlex training, including progressive small-to-large resolution schedules.
- Improve NaFlexViT with key-only attention masks, compile-friendly and memory-efficient position sampling, and cached variable-patch interpolation.
- Improve model factory path and checkpoint handling; fix equal-token positional embedding resampling.
July 10, 2026
- Improve optimizer
torch.compileand tensor learning-rate support. - Extend NaFlexViT patch-layout (for NaFlex-CLAP), and
forward_intermediates(NaFlex dict input) support. - Harden pickle loading and improve custom-label inference.
- Release 1.0.28
May 27, 2026
- Add model defs and pretrained weights for EUPE ViT (DINOv3-style) and ConvNeXt models. See the Efficient Universal Perception Encoder paper.
- Add TIPSv2 model defs and pretrained weights for (DINOv2-style) ViTs. See the TIPSv2 paper.
May 8, 2026
- Release 1.0.27
April 23, 2026
- Add Gemma4 ViT encoders w/ NaFlex pipeline support (variable aspect/size per image). Thanks Yonghye Kwon
- Support DINOv3 weights in NaFlexVit. Thanks Yonghye Kwon
- Some improvements to Muon fallback (AdamW/NadamW) lr behavior
March 23, 2026
- Improve pickle checkpoint handling security. Default all loading to
weights_only=True, add safe_global for ArgParse. - Improve attention mask handling for core ViT/EVA models & layers. Resolve bool masks, pass
is_causalthrough for SSL tasks. - Fix class & register token uses with ViT and no pos embed enabled.
- Add Patch Representation Refinement (PRR) as a pooling option in ViT. Thanks Sina (https://github.com/sinahmr).
- Improve consistency of output projection / MLP dimensions for attention pooling layers.
- Hiera model F.SDPA optimization to allow Flash Attention kernel use.
- Caution added to SGDP optimizer.
- Release 1.0.26. First maintenance release since my departure from Hugging Face.
Feb 23, 2026
- Add token distillation training support to distillation task wrappers
- Remove some torch.jit usage in prep for official deprecation
- Caution added to AdamP optimizer
- Call reset_parameters() even if meta-device init so that buffers get init w/ hacks like init_empty_weights
- Tweak Muon optimizer to work with DTensor/FSDP2 (clamp_ instead of clamp_min_, alternate NS branch for DTensor)
- Release 1.0.25
Jan 21, 2026
- Compat Break: Fix oversight w/ QKV vs MLP bias in
ParallelScalingBlock(&DiffParallelScalingBlock)- Does not impact any trained
timmmodels but could impact downstream use.
- Does not impact any trained
Jan 5 & 6, 2026
- Release 1.0.24
- Add new benchmark result csv files for inference timing on all models w/ RTX Pro 6000, 5090, and 4090 cards w/ PyTorch 2.9.1
- Fix moved module error in deprecated timm.models.layers import path that impacts legacy imports
- Release 1.0.23
Dec 30, 2025
- Add better NAdaMuon trained
dpwee,dwee,dlittle(differential) ViTs with a small boost over previous runs - Add a ~21M param
timmvariant of the CSATv2 model at 512x512 & 640x640- https://huggingface.co/timm/csatv2_21m.sw_r640_in1k (83.13% top-1)
- https://huggingface.co/timm/csatv2_21m.sw_r512_in1k (82.58% top-1)
- Factor non-persistent param init out of
__init__into a common method that can be externally called viainit_non_persistent_buffers()after meta-device init.
Dec 12, 2025
- Add CSATV2 model (thanks https://github.com/gusdlf93) -- a lightweight but high res model with DCT stem & spatial attention. https://huggingface.co/Hyunil/CSATv2
- Add AdaMuon and NAdaMuon optimizer support to existing
timmMuon impl. Appears more competitive vs AdamW with familiar hparams for image tasks. - End of year PR cleanup, merge aspects of several long open PR
- Merge differential attention (
DiffAttention), add correspondingDiffParallelScalingBlock(for ViT), train some wee vits - Add a few pooling modules,
LsePlusandSimPool - Cleanup, optimize
DropBlock2d(also add support to ByobNet based models)
- Merge differential attention (
- Bump unit tests to PyTorch 2.9.1 + Python 3.13 on upper end, lower still PyTorch 1.13 + Python 3.10
Dec 1, 2025
- Add lightweight task abstraction, add logits and feature distillation support to train script via new tasks.
- Remove old APEX AMP support
Nov 4, 2025
- Fix LayerScale / LayerScale2d init bug (init values ignored), introduced in 1.0.21. Thanks https://github.com/Ilya-Fradlin
- Release 1.0.22
Oct 31, 2025 ๐
- Update imagenet & OOD variant result csv files to include a few new models and verify correctness over several torch & timm versions
- EfficientNet-X and EfficientNet-H B5 model weights added as part of a hparam search for AdamW vs Muon (still iterating on Muon runs)
Oct 16-20, 2025
- Add an impl of the Muon optimizer (based on https://github.com/KellerJordan/Muon) with customizations
- extra flexibility and improved handling for conv weights and fallbacks for weight shapes not suited for orthogonalization
- small speedup for NS iterations by reducing allocs and using fused (b)add(b)mm ops
- by default uses AdamW (or NAdamW if
nesterov=True) updates if muon not suitable for parameter shape (or excluded via param group flag) - like torch impl, select from several LR scale adjustment fns via
adjust_lr_fn - select from several NS coefficient presets or specify your own via
ns_coefficients
- First 2 steps of 'meta' device model initialization supported
- Fix several ops that were breaking creation under 'meta' device context
- Add device & dtype factory kwarg support to all models and modules (anything inherting from nn.Module) in
timm
- License fields added to pretrained cfgs in code
- Release 1.0.21
Sept 21, 2025
- Remap DINOv3 ViT weight tags from
lvd_1689m->lvd1689mto match (same forsat_493m->sat493m) - Release 1.0.20
Sept 17, 2025
- DINOv3 (https://arxiv.org/abs/2508.10104) ConvNeXt and ViT models added. ConvNeXt models were mapped to existing
timmmodel. ViT support done via the EVA base model w/ a newRotaryEmbeddingDinoV3to match the DINOv3 specific RoPE impl - MobileCLIP-2 (https://arxiv.org/abs/2508.20691) vision encoders. New MCI3/MCI4 FastViT variants added and weights mapped to existing FastViT and B, L/14 ViTs.
- MetaCLIP-2 Worldwide (https://arxiv.org/abs/2507.22062) ViT encoder weights added.
- SigLIP-2 (https://arxiv.org/abs/2502.14786) NaFlex ViT encoder weights added via timm NaFlexViT model.
- Misc fixes and contributions
July 23, 2025
- Add
set_input_size()method to EVA models, used by OpenCLIP 3.0.0 to allow resizing for timm based encoder models. - Release 1.0.18, needed for PE-Core S & T models in OpenCLIP 3.0.0
- Fix small typing issue that broke Python 3.9 compat. 1.0.19 patch release.
July 21, 2025
- ROPE support added to NaFlexViT. All models covered by the EVA base (
eva.py) including EVA, EVA02, Meta PE ViT,timmSBB ViT w/ ROPE, and Naver ROPE-ViT can be now loaded in NaFlexViT whenuse_naflex=Truepassed at model creation time - More Meta PE ViT encoders added, including small/tiny variants, lang variants w/ tiling, and more spatial variants.
- PatchDropout fixed with NaFlexViT and also w/ EVA models (regression after adding Naver ROPE-ViT)
- Fix XY order with grid_indexing='xy', impacted non-square image use in 'xy' mode (only ROPE-ViT and PE impacted).
July 7, 2025
- MobileNet-v5 backbone tweaks for improved Google Gemma 3n behaviour (to pair with updated official weights)
- Add stem bias (zero'd in updated weights, compat break with old weights)
- GELU -> GELU (tanh approx). A minor change to be closer to JAX
- Add two arguments to layer-decay support, a min scale clamp and 'no optimization' scale threshold
- Add 'Fp32' LayerNorm, RMSNorm, SimpleNorm variants that can be enabled to force computation of norm in float32
- Some typing, argument cleanup for norm, norm+act layers done with above
- Support Naver ROPE-ViT (https://github.com/naver-ai/rope-vit) in
eva.py, add RotaryEmbeddingMixed module for mixed mode, weights on HuggingFace Hub
| model | img_size | top1 | top5 | param_count |
|---|---|---|---|---|
| vit_large_patch16_rope_mixed_ape_224.naver_in1k | 224 | 84.84 | 97.122 | 304.4 |
| vit_large_patch16_rope_mixed_224.naver_in1k | 224 | 84.828 | 97.116 | 304.2 |
| vit_large_patch16_rope_ape_224.naver_in1k | 224 | 84.65 | 97.154 | 304.37 |
| vit_large_patch16_rope_224.naver_in1k | 224 | 84.648 | 97.122 | 304.17 |
| vit_base_patch16_rope_mixed_ape_224.naver_in1k | 224 | 83.894 | 96.754 | 86.59 |
| vit_base_patch16_rope_mixed_224.naver_in1k | 224 | 83.804 | 96.712 | 86.44 |
| vit_base_patch16_rope_ape_224.naver_in1k | 224 | 83.782 | 96.61 | 86.59 |
| vit_base_patch16_rope_224.naver_in1k | 224 | 83.718 | 96.672 | 86.43 |
| vit_small_patch16_rope_224.naver_in1k | 224 | 81.23 | 95.022 | 21.98 |
| vit_small_patch16_rope_mixed_224.naver_in1k | 224 | 81.216 | 95.022 | 21.99 |
| vit_small_patch16_rope_ape_224.naver_in1k | 224 | 81.004 | 95.016 | 22.06 |
| vit_small_patch16_rope_mixed_ape_224.naver_in1k | 224 | 80.986 | 94.976 | 22.06 |
- Some cleanup of ROPE modules, helpers, and FX tracing leaf registration
- Preparing version 1.0.17 release
June 26, 2025
- MobileNetV5 backbone (w/ encoder only variant) for Gemma 3n image encoder
- Version 1.0.16 released
June 23, 2025
- Add F.grid_sample based 2D and factorized pos embed resize to NaFlexViT. Faster when lots of different sizes (based on example by https://github.com/stas-sl).
- Further speed up patch embed resample by replacing vmap with matmul (based on snippet by https://github.com/stas-sl).
- Add 3 initial native aspect NaFlexViT checkpoints created while testing, ImageNet-1k and 3 different pos embed configs w/ same hparams.
| Model | Top-1 Acc | Top-5 Acc | Params (M) | Eval Seq Len |
|---|---|---|---|---|
| naflexvit_base_patch16_par_gap.e300_s576_in1k | 83.67 | 96.45 | 86.63 | 576 |
| naflexvit_base_patch16_parfac_gap.e300_s576_in1k | 83.63 | 96.41 | 86.46 | 576 |
| naflexvit_base_patch16_gap.e300_s576_in1k | 83.50 | 96.46 | 86.63 | 576 |
- Support gradient checkpointing for
forward_intermediatesand fix some checkpointing bugs. Thanks https://github.com/brianhou0208 - Add 'corrected weight decay' (https://arxiv.org/abs/2506.02285) as option to AdamW (legacy), Adopt, Kron, Adafactor (BV), Lamb, LaProp, Lion, NadamW, RmsPropTF, SGDW optimizers
- Switch PE (perception encoder) ViT models to use native timm weights instead of remapping on the fly
- Fix cuda stream bug in prefetch loader
June 5, 2025
- Initial NaFlexVit model code. NaFlexVit is a Vision Transformer with:
- Encapsulated embedding and position encoding in a single module
- Support for nn.Linear patch embedding on pre-patchified (dictionary) inputs
- Support for NaFlex variable aspect, variable resolution (SigLip-2: https://arxiv.org/abs/2502.14786)
- Support for FlexiViT variable patch size (https://arxiv.org/abs/2212.08013)
- Support for NaViT fractional/factorized position embedding (https://arxiv.org/abs/2307.06304)
- Existing vit models in
vision_transformer.pycan be loaded into the NaFlexVit model by adding theuse_naflex=Trueflag tocreate_model- Some native weights coming soon
- A full NaFlex data pipeline is available that allows training / fine-tuning / evaluating with variable aspect / size images
- To enable in
train.pyandvalidate.pyadd the--naflex-loaderarg, must be used with a NaFlexVit
- To enable in
- To evaluate an existing (classic) ViT loaded in NaFlexVit model w/ NaFlex data pipe:
python validate.py /imagenet --amp -j 8 --model vit_base_patch16_224 --model-kwargs use_naflex=True --naflex-loader --naflex-max-seq-len 256
- The training has some extra args features worth noting
- The
--naflex-train-seq-lens'argument specifies which sequence lengths to randomly pick from per batch during training - The
--naflex-max-seq-lenargument sets the target sequence length for validation - Adding
--model-kwargs enable_patch_interpolator=True --naflex-patch-sizes 12 16 24will enable random patch size selection per-batch w/ interpolation - The
--naflex-loss-scalearg changes loss scaling mode per batch relative to the batch size,timmNaFlex loading changes the batch size for each seq len
- The
May 28, 2025
- Add a number of small/fast models thanks to https://github.com/brianhou0208
- SwiftFormer - (ICCV2023) SwiftFormer: Efficient Additive Attention for Transformer-based Real-time Mobile Vision Applications
- FasterNet - (CVPR2023) Run, Donโt Walk: Chasing Higher FLOPS for Faster Neural Networks
- SHViT - (CVPR2024) SHViT: Single-Head Vision Transformer with Memory Efficient
- StarNet - (CVPR2024) Rewrite the Stars
- GhostNet-V3 GhostNetV3: Exploring the Training Strategies for Compact Models
- Update EVA ViT (closest match) to support Perception Encoder models (https://arxiv.org/abs/2504.13181) from Meta, loading Hub weights but I still need to push dedicated
timmweights- Add some flexibility to ROPE impl
- Big increase in number of models supporting
forward_intermediates()and some additional fixes thanks to https://github.com/brianhou0208- DaViT, EdgeNeXt, EfficientFormerV2, EfficientViT(MIT), EfficientViT(MSRA), FocalNet, GCViT, HGNet /V2, InceptionNeXt, Inception-V4, MambaOut, MetaFormer, NesT, Next-ViT, PiT, PVT V2, RepGhostNet, RepViT, ResNetV2, ReXNet, TinyViT, TResNet, VoV
- TNT model updated w/ new weights
forward_intermediates()thanks to https://github.com/brianhou0208 - Add
local-dir:pretrained schema, can uselocal-dir:/path/to/model/folderfor model name to source model / pretrained cfg & weights Hugging Face Hub models (config.json + weights file) from a local folder. - Fixes, improvements for onnx export
Feb 21, 2025
- SigLIP 2 ViT image encoders added (https://huggingface.co/collections/timm/siglip-2-67b8e72ba08b09dd97aecaf9)
- Variable resolution / aspect NaFlex versions are a WIP
- Add 'SO150M2' ViT weights trained with SBB recipes, great results, better for ImageNet than previous attempt w/ less training.
vit_so150m2_patch16_reg1_gap_448.sbb_e200_in12k_ft_in1k- 88.1% top-1vit_so150m2_patch16_reg1_gap_384.sbb_e200_in12k_ft_in1k- 87.9% top-1vit_so150m2_patch16_reg1_gap_256.sbb_e200_in12k_ft_in1k- 87.3% top-1vit_so150m2_patch16_reg4_gap_256.sbb_e200_in12k
- Updated InternViT-300M '2.5' weights
- Release 1.0.15
Feb 1, 2025
- FYI PyTorch 2.6 & Python 3.13 are tested and working w/ current main and released version of
timm
Jan 27, 2025
- Add Kron Optimizer (PSGD w/ Kronecker-factored preconditioner)
Jan 19, 2025
- Fix loading of LeViT safetensor weights, remove conversion code which should have been deactivated
- Add 'SO150M' ViT weights trained with SBB recipes, decent results, but not optimal shape for ImageNet-12k/1k pretrain/ft
vit_so150m_patch16_reg4_gap_256.sbb_e250_in12k_ft_in1k- 86.7% top-1vit_so150m_patch16_reg4_gap_384.sbb_e250_in12k_ft_in1k- 87.4% top-1vit_so150m_patch16_reg4_gap_256.sbb_e250_in12k
- Misc typing, typo, etc. cleanup
- 1.0.14 release to get above LeViT fix out
Jan 9, 2025
- Add support to train and validate in pure
bfloat16orfloat16 wandbproject name arg added by https://github.com/caojiaolong, use arg.experiment for name- Fix old issue w/ checkpoint saving not working on filesystem w/o hard-link support (e.g. FUSE fs mounts)
- 1.0.13 release
Jan 6, 2025
- Add
torch.utils.checkpoint.checkpoint()wrapper intimm.modelsthat defaultsuse_reentrant=False, unlessTIMM_REENTRANT_CKPT=1is set in env.
Dec 31, 2024
convnext_nano384x384 ImageNet-12k pretrain & fine-tune. https://huggingface.co/models?search=convnext_nano%20r384- Add AIM-v2 encoders from https://github.com/apple/ml-aim, see on Hub: https://huggingface.co/models?search=timm%20aimv2
- Add PaliGemma2 encoders from https://github.com/google-research/big_vision to existing PaliGemma, see on Hub: https://huggingface.co/models?search=timm%20pali2
- Add missing L/14 DFN2B 39B CLIP ViT,
vit_large_patch14_clip_224.dfn2b_s39b - Fix existing
RmsNormlayer & fn to match standard formulation, use PT 2.5 impl when possible. Move old impl toSimpleNormlayer, it's LN w/o centering or bias. There were only twotimmmodels using it, and they have been updated. - Allow override of
cache_dirarg for model creation - Pass through
trust_remote_codefor HF datasets wrapper inception_next_attomodel added by creator- Adan optimizer caution, and Lamb decoupled weight decay options
- Some feature_info metadata fixed by https://github.com/brianhou0208
- All OpenCLIP and JAX (CLIP, SigLIP, Pali, etc) model weights that used load time remapping were given their own HF Hub instances so that they work with
hf-hub:based loading, and thus will work with new TransformersTimmWrapperModel
Introduction
PyTorch Image Models (timm) is a collection of image models, layers, utilities, optimizers, schedulers, data-loaders / augmentations, and reference training / validation scripts that aim to pull together a wide variety of SOTA models with ability to reproduce ImageNet training results.
The work of many others is present here. I've tried to make sure all source material is acknowledged via links to github, arxiv papers, etc in the README, documentation, and code docstrings. Please let me know if I missed anything.
Features
Models
All model architecture families include variants with pretrained weights. There are specific model variants without any weights, it is NOT a bug. Help training new or better weights is always appreciated.
- Aggregating Nested Transformers - https://arxiv.org/abs/2105.12723
- BEiT - https://arxiv.org/abs/2106.08254
- BEiT-V2 - https://arxiv.org/abs/2208.06366
- Big Transfer ResNetV2 (BiT) - https://arxiv.org/abs/1912.11370
- Bottleneck Transformers - https://arxiv.org/abs/2101.11605
- CaiT (Class-Attention in Image Transformers) - https://arxiv.org/abs/2103.17239
- CoaT (Co-Scale Conv-Attentional Image Transformers) - https://arxiv.org/abs/2104.06399
- CoAtNet (Convolution and Attention) - https://arxiv.org/abs/2106.04803
- ConvNeXt - https://arxiv.org/abs/2201.03545
- ConvNeXt-V2 - http://arxiv.org/abs/2301.00808
- ConViT (Soft Convolutional Inductive Biases Vision Transformers)- https://arxiv.org/abs/2103.10697
- ConvMixer - https://arxiv.org/abs/2201.09792
- CPUBone - https://arxiv.org/abs/2603.26425
- CrossViT - https://arxiv.org/abs/2103.14899
- CSATv2 - https://huggingface.co/Hyunil/CSATv2
- CspNet (Cross-Stage Partial Networks) - https://arxiv.org/abs/1911.11929
- DaViT (Dual Attention Vision Transformer) - https://arxiv.org/abs/2204.03645
- DeiT - https://arxiv.org/abs/2012.12877
- DeiT-III - https://arxiv.org/pdf/2204.07118.pdf
- DenseNet - https://arxiv.org/abs/1608.06993
- DLA - https://arxiv.org/abs/1707.06484
- DPN (Dual-Path Network) - https://arxiv.org/abs/1707.01629
- EdgeNeXt - https://arxiv.org/abs/2206.10589
- EfficientFormer - https://arxiv.org/abs/2206.01191
- EfficientFormer-V2 - https://arxiv.org/abs/2212.08059
- EfficientNet (MBConvNet Family)
- EfficientNet NoisyStudent (B0-B7, L2) - https://arxiv.org/abs/1911.04252
- EfficientNet AdvProp (B0-B8) - https://arxiv.org/abs/1911.09665
- EfficientNet (B0-B7) - https://arxiv.org/abs/1905.11946
- EfficientNet-EdgeTPU (S, M, L) - https://ai.googleblog.com/2019/08/efficientnet-edgetpu-creating.html
- EfficientNet V2 - https://arxiv.org/abs/2104.00298
- FBNet-C - https://arxiv.org/abs/1812.03443
- MixNet - https://arxiv.org/abs/1907.09595
- MNASNet B1, A1 (Squeeze-Excite), and Small - https://arxiv.org/abs/1807.11626
- MobileNet-V2 - https://arxiv.org/abs/1801.04381
- Single-Path NAS - https://arxiv.org/abs/1904.02877
- TinyNet - https://arxiv.org/abs/2010.14819
- EfficientViT (MIT) - https://arxiv.org/abs/2205.14756
- EfficientViT (MSRA) - https://arxiv.org/abs/2305.07027
- EVA (RoPE ViT family)
- EVA - https://arxiv.org/abs/2211.07636
- EVA-02 - https://arxiv.org/abs/2303.11331
- EVA-CLIP - https://arxiv.org/abs/2303.15389
- DINOv3 - https://arxiv.org/abs/2508.10104
- Efficient Universal Perception Encoder (EUPE) - https://arxiv.org/abs/2603.22387
- LingBot-Vision - https://arxiv.org/abs/2607.05247
- Perception Encoder (PE) - https://arxiv.org/abs/2504.13181
- RoPE-ViT - https://arxiv.org/abs/2403.13298
- FasterNet - https://arxiv.org/abs/2303.03667
- FastViT - https://arxiv.org/abs/2303.14189
- FocalNet (Focal Modulation Networks) - https://arxiv.org/abs/2203.11926
- GCViT (Global Context Vision Transformer) - https://arxiv.org/abs/2206.09959
- Gemma4 ViT encoder - https://arxiv.org/abs/2607.02770
- GhostNet - https://arxiv.org/abs/1911.11907
- GhostNet-V2 - https://arxiv.org/abs/2211.12905
- GhostNet-V3 - https://arxiv.org/abs/2404.11202
- gMLP - https://arxiv.org/abs/2105.08050
- GPU-Efficient Networks - https://arxiv.org/abs/2006.14090
- Halo Nets - https://arxiv.org/abs/2103.12731
- HGNet / HGNet-V2 - TBD
- Hiera (family)
- Hiera - https://arxiv.org/abs/2306.00989
- SAM 2 / 2.1 Hiera image encoders - https://arxiv.org/abs/2408.00714
- HRNet - https://arxiv.org/abs/1908.07919
- InceptionNeXt - https://arxiv.org/abs/2303.16900
- Inception-V3 - https://arxiv.org/abs/1512.00567
- Inception-ResNet-V2 and Inception-V4 - https://arxiv.org/abs/1602.07261
- Lambda Networks - https://arxiv.org/abs/2102.08602
- LCNet-V2 - TBD
- LeViT (Vision Transformer in ConvNet's Clothing) - https://arxiv.org/abs/2104.01136
- MambaOut - https://arxiv.org/abs/2405.07992
- MaxViT (Multi-Axis Vision Transformer) - https://arxiv.org/abs/2204.01697
- MetaFormer (PoolFormer-v2, ConvFormer, CAFormer) - https://arxiv.org/abs/2210.13452
- MLP-Mixer - https://arxiv.org/abs/2105.01601
- MobileCLIP - https://arxiv.org/abs/2311.17049
- MobileNet-V3 (MBConvNet w/ Efficient Head) - https://arxiv.org/abs/1905.02244
- FBNet-V3 - https://arxiv.org/abs/2006.02049
- HardCoRe-NAS - https://arxiv.org/abs/2102.11646
- LCNet - https://arxiv.org/abs/2109.15099
- MobileNetV4 - https://arxiv.org/abs/2404.10518
- MobileNetV5 (Gemma 3n vision encoder) - https://ai.google.dev/gemma/docs/gemma-3n
- MobileOne - https://arxiv.org/abs/2206.04040
- MobileViT - https://arxiv.org/abs/2110.02178
- MobileViT-V2 - https://arxiv.org/abs/2206.02680
- MViT-V2 (Improved Multiscale Vision Transformer) - https://arxiv.org/abs/2112.01526
- NaFlexViT (NaViT / FlexiViT family)
- NaViT - https://arxiv.org/abs/2307.06304
- FlexiViT - https://arxiv.org/abs/2212.08013
- SigLIP 2 NaFlex image encoders - https://arxiv.org/abs/2502.14786
- NASNet-A - https://arxiv.org/abs/1707.07012
- NesT - https://arxiv.org/abs/2105.12723
- Next-ViT - https://arxiv.org/abs/2207.05501
- NFNet-F - https://arxiv.org/abs/2102.06171
- NF-RegNet / NF-ResNet - https://arxiv.org/abs/2101.08692
- PNasNet - https://arxiv.org/abs/1712.00559
- PoolFormer (MetaFormer) - https://arxiv.org/abs/2111.11418
- Pooling-based Vision Transformer (PiT) - https://arxiv.org/abs/2103.16302
- PVT-V2 (Improved Pyramid Vision Transformer) - https://arxiv.org/abs/2106.13797
- RDNet (DenseNets Reloaded) - https://arxiv.org/abs/2403.19588
- RegNet - https://arxiv.org/abs/2003.13678
- RegNetZ - https://arxiv.org/abs/2103.06877
- RepVGG - https://arxiv.org/abs/2101.03697
- RepGhostNet - https://arxiv.org/abs/2211.06088
- RepViT - https://arxiv.org/abs/2307.09283
- ResMLP - https://arxiv.org/abs/2105.03404
- ResNet/ResNeXt
- ResNet (v1b/v1.5) - https://arxiv.org/abs/1512.03385
- ResNeXt - https://arxiv.org/abs/1611.05431
- 'Bag of Tricks' / Gluon C, D, E, S variations - https://arxiv.org/abs/1812.01187
- Weakly-supervised (WSL) Instagram pretrained / ImageNet tuned ResNeXt101 - https://arxiv.org/abs/1805.00932
- Semi-supervised (SSL) / Semi-weakly Supervised (SWSL) ResNet/ResNeXts - https://arxiv.org/abs/1905.00546
- ECA-Net (ECAResNet) - https://arxiv.org/abs/1910.03151v4
- Squeeze-and-Excitation Networks (SEResNet) - https://arxiv.org/abs/1709.01507
- ResNet-RS - https://arxiv.org/abs/2103.07579
- Res2Net - https://arxiv.org/abs/1904.01169
- ResNeSt - https://arxiv.org/abs/2004.08955
- ReXNet - https://arxiv.org/abs/2007.00992
- SelecSLS - https://arxiv.org/abs/1907.00837
- Selective Kernel Networks - https://arxiv.org/abs/1903.06586
- Sequencer2D - https://arxiv.org/abs/2205.01972
- SHViT - https://arxiv.org/abs/2401.16456
- StarNet - https://arxiv.org/abs/2403.19967
- SwiftFormer - https://arxiv.org/pdf/2303.15446
- Swin S3 (AutoFormerV2) - https://arxiv.org/abs/2111.14725
- Swin Transformer - https://arxiv.org/abs/2103.14030
- Swin Transformer V2 - https://arxiv.org/abs/2111.09883
- TinyViT - https://arxiv.org/abs/2207.10666
- Transformer-iN-Transformer (TNT) - https://arxiv.org/abs/2103.00112
- TResNet - https://arxiv.org/abs/2003.13630
- Twins (Spatial Attention in Vision Transformers) - https://arxiv.org/pdf/2104.13840.pdf
- VGG - https://arxiv.org/abs/1409.1556
- Visformer - https://arxiv.org/abs/2104.12533
- Vision Transformer (family)
- Vision Transformer (ViT) - https://arxiv.org/abs/2010.11929
- AIMv2 - https://arxiv.org/abs/2411.14402
- AugReg (How to train your ViT?) - https://arxiv.org/abs/2106.10270
- BEiT3 - https://arxiv.org/abs/2208.10442
- CLIP image encoders - https://arxiv.org/abs/2103.00020
- DINO - https://arxiv.org/abs/2104.14294
- DINOv2 / Vision Transformers Need Registers - https://arxiv.org/abs/2304.07193, https://arxiv.org/abs/2309.16588
- FlexiViT - https://arxiv.org/abs/2212.08013
- I-JEPA - https://arxiv.org/abs/2301.08243
- InternViT (InternVL vision encoder) - https://arxiv.org/abs/2312.14238
- MAE - https://arxiv.org/abs/2111.06377
- Sharpness-Aware Minimization (SAM) ViT weights - https://arxiv.org/abs/2106.01548
- Scaling Vision Transformers - https://arxiv.org/abs/2106.04560
- SigLIP image encoders - https://arxiv.org/abs/2303.15343
- SigLIP 2 image encoders - https://arxiv.org/abs/2502.14786
- TIPSv2 - https://arxiv.org/abs/2604.12012
- ViTamin - https://arxiv.org/abs/2404.02132
- Segment Anything (SAM) ViT image encoders - https://arxiv.org/abs/2304.02643
- VOLO (Vision Outlooker) - https://arxiv.org/abs/2106.13112
- VovNet V2 and V1 - https://arxiv.org/abs/1911.06667
- Xception - https://arxiv.org/abs/1610.02357
- Xception (Modified Aligned, Gluon) - https://arxiv.org/abs/1802.02611
- Xception (Modified Aligned, TF) - https://arxiv.org/abs/1802.02611
- XCiT (Cross-Covariance Image Transformers) - https://arxiv.org/abs/2106.09681
Optimizers
To see full list of optimizers w/ descriptions: timm.optim.list_optimizers(with_description=True)
Included optimizers available via timm.optim.create_optimizer_v2 factory method:
adabeliefan implementation of AdaBelief adapted from https://github.com/juntang-zhuang/Adabelief-Optimizer - https://arxiv.org/abs/2010.07468adafactoradapted from FAIRSeq impl - https://arxiv.org/abs/1804.04235adafactorbvadapted from Big Vision - https://arxiv.org/abs/2106.04560adahessianby David Samuel - https://arxiv.org/abs/2006.00719adampandsgdpby Naver ClovAI - https://arxiv.org/abs/2006.08217adamuonandnadamuonas per https://github.com/Chongjie-Si/AdaMuon - https://arxiv.org/abs/2507.11005adanan implementation of Adan adapted from https://github.com/sail-sg/Adan - https://arxiv.org/abs/2208.06677adoptADOPT adapted from https://github.com/iShohei220/adopt - https://arxiv.org/abs/2411.02853kronPSGD w/ Kronecker-factored preconditioner from https://github.com/evanatyourservice/kron_torch - https://sites.google.com/site/lixilinx/home/psgdlamban implementation of Lamb and LambC (w/ trust-clipping) cleaned up and modified to support use with XLA - https://arxiv.org/abs/1904.00962lapropoptimizer from https://github.com/Z-T-WANG/LaProp-Optimizer - https://arxiv.org/abs/2002.04839larsan implementation of LARS and LARC (w/ trust-clipping) - https://arxiv.org/abs/1708.03888lionand implementation of Lion adapted from https://github.com/google/automl/tree/master/lion - https://arxiv.org/abs/2302.06675lookaheadadapted from impl by Liam - https://arxiv.org/abs/1907.08610madgradan implementation of MADGRAD adapted from https://github.com/facebookresearch/madgrad - https://arxiv.org/abs/2101.11075marsMARS optimizer from https://github.com/AGI-Arena/MARS - https://arxiv.org/abs/2411.10438muonMUON optimizer from https://github.com/KellerJordan/Muon with numerous additions and improved non-transformer behaviournadaman implementation of Adam w/ Nesterov momentumnadamwan implementation of AdamW (Adam w/ decoupled weight-decay) w/ Nesterov momentum. A simplified impl based on https://github.com/mlcommons/algorithmic-efficiencynovogradby Masashi Kimura - https://arxiv.org/abs/1905.11286radamby Liyuan Liu - https://arxiv.org/abs/1908.03265rmsprop_tfadapted from PyTorch RMSProp by myself. Reproduces much improved Tensorflow RMSProp behavioursgdwand implementation of SGD w/ decoupled weight-decayfused<name>optimizers by name with NVIDIA Apex installedbnb<name>optimizers by name with BitsAndBytes installedcadamw,clion, and more 'Cautious' optimizers from https://github.com/kyleliang919/C-Optim - https://arxiv.org/abs/2411.16085adam,adamw,rmsprop,adadelta,adagrad, andsgdpass through totorch.optimimplementationscsuffix (egadamc,nadamcto implement 'corrected weight decay' in https://arxiv.org/abs/2506.02285)
Augmentations
- Random Erasing from Zhun Zhong - https://arxiv.org/abs/1708.04896)
- Mixup - https://arxiv.org/abs/1710.09412
- CutMix - https://arxiv.org/abs/1905.04899
- AutoAugment (https://arxiv.org/abs/1805.09501) and RandAugment (https://arxiv.org/abs/1909.13719) ImageNet configurations modeled after impl for EfficientNet training (https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py)
- AugMix w/ JSD loss, JSD w/ clean + augmented mixing support works with AutoAugment and RandAugment as well - https://arxiv.org/abs/1912.02781
- SplitBachNorm - allows splitting batch norm layers between clean and augmented (auxiliary batch norm) data
Regularization
- DropPath aka "Stochastic Depth" - https://arxiv.org/abs/1603.09382
- DropBlock - https://arxiv.org/abs/1810.12890
- Blur Pooling - https://arxiv.org/abs/1904.11486
Other
Several (less common) features that I often utilize in my projects are included. Many of their additions are the reason why I maintain my own set of models, instead of using others' via PIP:
- All models have a common default configuration interface and API for
- accessing/changing the classifier -
get_classifierandreset_classifier - doing a forward pass on just the features -
forward_features(see documentation) - these makes it easy to write consistent network wrappers that work with any of the models
- accessing/changing the classifier -
- All models support multi-scale feature map extraction (feature pyramids) via create_model (see documentation)
create_model(name, features_only=True, out_indices=..., output_stride=...)out_indicescreation arg specifies which feature maps to return, these indices are 0 based and generally correspond to theC(i + 1)feature level.output_stridecreation arg controls output stride of the network by using dilated convolutions. Most networks are stride 32 by default. Not all networks support this.- feature map channel counts, reduction level (stride) can be queried AFTER model creation via the
.feature_infomember
- All models have a consistent pretrained weight loader that adapts last linear if necessary, and from 3 to 1 channel input if desired
- High performance reference training, validation, and inference scripts that work in several process/GPU modes:
- NVIDIA DDP w/ a single GPU per process, multiple processes with APEX present (AMP mixed-precision optional)
- PyTorch DistributedDataParallel w/ multi-gpu, single process (AMP disabled as it crashes when enabled)
- PyTorch w/ single GPU single process (AMP optional)
- A dynamic global pool implementation that allows selecting from average pooling, max pooling, average + max, or concat([average, max]) at model creation. All global pooling is adaptive average by default and compatible with pretrained weights.
- A 'Test Time Pool' wrapper that can wrap any of the included models and usually provides improved performance doing inference with input images larger than the training size. Idea adapted from original DPN implementation when I ported (https://github.com/cypw/DPNs)
- Learning rate schedulers
- Ideas adopted from
- AllenNLP schedulers
- FAIRseq lr_scheduler
- SGDR: Stochastic Gradient Descent with Warm Restarts (https://arxiv.org/abs/1608.03983)
- Schedulers include
step,cosinew/ restarts,tanhw/ restarts,plateau
- Ideas adopted from
- Space-to-Depth by mrT23 (https://arxiv.org/abs/1801.04590)
- Adaptive Gradient Clipping (https://arxiv.org/abs/2102.06171, https://github.com/deepmind/deepmind-research/tree/master/nfnets)
- An extensive selection of channel and/or spatial attention modules:
- Bottleneck Transformer - https://arxiv.org/abs/2101.11605
- CBAM - https://arxiv.org/abs/1807.06521
- Effective Squeeze-Excitation (ESE) - https://arxiv.org/abs/1911.06667
- Efficient Channel Attention (ECA) - https://arxiv.org/abs/1910.03151
- Gather-Excite (GE) - https://arxiv.org/abs/1810.12348
- Global Context (GC) - https://arxiv.org/abs/1904.11492
- Halo - https://arxiv.org/abs/2103.12731
- Involution - https://arxiv.org/abs/2103.06255
- Lambda Layer - https://arxiv.org/abs/2102.08602
- Non-Local (NL) - https://arxiv.org/abs/1711.07971
- Squeeze-and-Excitation (SE) - https://arxiv.org/abs/1709.01507
- Selective Kernel (SK) - (https://arxiv.org/abs/1903.06586
- Split (SPLAT) - https://arxiv.org/abs/2004.08955
- Shifted Window (SWIN) - https://arxiv.org/abs/2103.14030
Results
Model validation results can be found in the results tables
Getting Started (Documentation)
The official documentation can be found at https://huggingface.co/docs/hub/timm. Documentation contributions are welcome.
Getting Started with PyTorch Image Models (timm): A Practitionerโs Guide by Chris Hughes is an extensive blog post covering many aspects of timm in detail.
timmdocs is an alternate set of documentation for timm. A big thanks to Aman Arora for his efforts creating timmdocs.
paperswithcode is a good resource for browsing the models within timm.
Train, Validation, Inference Scripts
The root folder of the repository contains reference train, validation, and inference scripts that work with the included models and other features of this repository. They are adaptable for other datasets and use cases with a little hacking. See documentation.
Awesome PyTorch Resources
One of the greatest assets of PyTorch is the community and their contributions. A few of my favourite resources that pair well with the models and components here are listed below.
Object Detection, Instance and Semantic Segmentation
- Detectron2 - https://github.com/facebookresearch/detectron2
- Segmentation Models (Semantic) - https://github.com/qubvel/segmentation_models.pytorch
- EfficientDet (Obj Det, Semantic soon) - https://github.com/rwightman/efficientdet-pytorch
Computer Vision / Image Augmentation
- Albumentations - https://github.com/albumentations-team/albumentations
- Kornia - https://github.com/kornia/kornia
Knowledge Distillation
- RepDistiller - https://github.com/HobbitLong/RepDistiller
- torchdistill - https://github.com/yoshitomo-matsubara/torchdistill
Metric Learning
- PyTorch Metric Learning - https://github.com/KevinMusgrave/pytorch-metric-learning
Training / Frameworks
- fastai - https://github.com/fastai/fastai
- lightly_train - https://github.com/lightly-ai/lightly-train
Deployment
- timmx (Export timm models to ONNX, CoreML, LiteRT, TensorRT, and more) - https://github.com/Boulaouaney/timmx
Licenses
Code
The code here is licensed Apache 2.0. I've taken care to make sure any third party code included or adapted has compatible (permissive) licenses such as MIT, BSD, etc. I've made an effort to avoid any GPL / LGPL conflicts. That said, it is your responsibility to ensure you comply with licenses here and conditions of any dependent licenses. Where applicable, I've linked the sources/references for various components in docstrings. If you think I've missed anything please create an issue.
Pretrained Weights
So far all of the pretrained weights available here are pretrained on ImageNet with a select few that have some additional pretraining (see extra note below). ImageNet was released for non-commercial research purposes only (https://image-net.org/download). It's not clear what the implications of that are for the use of pretrained weights from that dataset. Any models I have trained with ImageNet are done for research purposes and one should assume that the original dataset license applies to the weights. It's best to seek legal advice if you intend to use the pretrained weights in a commercial product.
Pretrained on more than ImageNet
Several weights included or references here were pretrained with proprietary datasets that I do not have access to. These include the Facebook WSL, SSL, SWSL ResNe(Xt) and the Google Noisy Student EfficientNet models. The Facebook models have an explicit non-commercial license (CC-BY-NC 4.0, https://github.com/facebookresearch/semi-supervised-ImageNet1K-models, https://github.com/facebookresearch/WSL-Images). The Google models do not appear to have any restriction beyond the Apache 2.0 license (and ImageNet concerns). In either case, you should contact Facebook or Google with any questions.
Citing
BibTeX
@misc{rw2019timm,
author = {Ross Wightman},
title = {PyTorch Image Models},
year = {2019},
publisher = {GitHub},
journal = {GitHub repository},
doi = {10.5281/zenodo.4414861},
howpublished = {\url{https://github.com/rwightman/pytorch-image-models}}
}Latest DOI
File: hfdocs/README.md
Hugging Face Timm Docs
Getting Started
pip install git+https://github.com/huggingface/doc-builder.git@main#egg=hf-doc-builder
pip install watchdog blackPreview the Docs Locally
doc-builder preview timm hfdocs/sourceFile: results/README.md
Validation and Benchmark Results
This folder contains validation and benchmark results for the models in this collection. Validation scores are currently only run for models with pretrained weights and ImageNet-1k heads, benchmark numbers are run for all.
Datasets
There are currently results for the ImageNet validation set and 5 additional test / label sets.
The test set results include rank and top-1/top-5 differences from clean validation. For the "Real Labels", ImageNetV2, and Sketch test sets, the differences were calculated against the full 1000 class ImageNet-1k validation set. For both the Adversarial and Rendition sets, the differences were calculated against 'clean' runs on the ImageNet-1k validation set with the same 200 classes used in each test set respectively.
ImageNet Validation - [`results-imagenet.csv`](results-imagenet.csv)
The standard 50,000 image ImageNet-1k validation set. Model selection during training utilizes this validation set, so it is not a true test set. Question: Does anyone have the official ImageNet-1k test set classification labels now that challenges are done?
- Source: http://image-net.org/challenges/LSVRC/2012/index
- Paper: "ImageNet Large Scale Visual Recognition Challenge" - https://arxiv.org/abs/1409.0575
ImageNet-"Real Labels" - [`results-imagenet-real.csv`](results-imagenet-real.csv)
The usual ImageNet-1k validation set with a fresh new set of labels intended to improve on mistakes in the original annotation process.
- Source: https://github.com/google-research/reassessed-imagenet
- Paper: "Are we done with ImageNet?" - https://arxiv.org/abs/2006.07159
ImageNetV2 Matched Frequency - [`results-imagenetv2-matched-frequency.csv`](results-imagenetv2-matched-frequency.csv)
An ImageNet test set of 10,000 images sampled from new images roughly 10 years after the original. Care was taken to replicate the original ImageNet curation/sampling process.
- Source: https://github.com/modestyachts/ImageNetV2
- Paper: "Do ImageNet Classifiers Generalize to ImageNet?" - https://arxiv.org/abs/1902.10811
ImageNet-Sketch - [`results-sketch.csv`](results-sketch.csv)
50,000 non photographic (or photos of such) images (sketches, doodles, mostly monochromatic) covering all 1000 ImageNet classes.
- Source: https://github.com/HaohanWang/ImageNet-Sketch
- Paper: "Learning Robust Global Representations by Penalizing Local Predictive Power" - https://arxiv.org/abs/1905.13549
ImageNet-Adversarial - [`results-imagenet-a.csv`](results-imagenet-a.csv)
A collection of 7500 images covering 200 of the 1000 ImageNet classes. Images are naturally occurring adversarial examples that confuse typical ImageNet classifiers. This is a challenging dataset, your typical ResNet-50 will score 0% top-1.
For clean validation with same 200 classes, see results-imagenet-a-clean.csv
- Source: https://github.com/hendrycks/natural-adv-examples
- Paper: "Natural Adversarial Examples" - https://arxiv.org/abs/1907.07174
ImageNet-Rendition - [`results-imagenet-r.csv`](results-imagenet-r.csv)
Renditions of 200 ImageNet classes resulting in 30,000 images for testing robustness.
For clean validation with same 200 classes, see results-imagenet-r-clean.csv
- Source: https://github.com/hendrycks/imagenet-r
- Paper: "The Many Faces of Robustness" - https://arxiv.org/abs/2006.16241
TODO
- Explore adding a reduced version of ImageNet-C (Corruptions) and ImageNet-P (Perturbations) from https://github.com/hendrycks/robustness. The originals are huge and image size specific.
Benchmark
CSV files with a model_benchmark prefix include benchmark numbers for models on various accelerators with different precision. Currently only run on RTX 3090 w/ AMP for inference, I intend to add more in the future.
Metadata
CSV files with model_metadata prefix contain extra information about the source training, currently the pretraining dataset and technique (ie distillation, SSL, WSL, etc). Eventually I'd like to have metadata about augmentation, regularization, etc. but that will be a challenge to source consistently.
2. Official Technical Reference & Guides (huggingface/doc-builder)
doc-builder
This is the package we use to build the documentation of our Hugging Face repos.
Table of Contents
- doc-builder
Installation
You can install from PyPi with
pip install hf-doc-builderTo install from source, clone this repository then
cd doc-builder
pip install -e .Previewing
To preview the docs, use the following command:
doc-builder preview {package_name} {path_to_docs}For example:
doc-builder preview datasets ~/Desktop/datasets/docs/source/**preview command only works with existing doc files. When you add a completely new file, you need to update _toctree.yml & restart preview command (ctrl-c to stop it & call doc-builder preview ... again).
Doc building
To build the documentation of a given package, use the following command:
#Add --not_python_module if not building doc for a python lib
doc-builder build {package_name} {path_to_docs} --build_dir {build_dir}For instance, here is how you can build the Datasets documentation (requires pip install datasets[dev]) if you have cloned the repo in ~/git/datasets:
doc-builder build datasets ~/git/datasets/docs/source --build_dir ~/tmp/test-buildThis will generate MDX files that you can preview like any Markdown file in your favorite editor. To have a look at the documentation in HTML, you need to install node version 14 or higher. Then you can run (still with the example on Datasets)
doc-builder build datasets ~/git/datasets/docs/source --build_dir ~/tmp/test-build --htmlwhich will build HTML files in ~/tmp/test-build. You can then inspect those files in your browser.
Specifying a version
By default, doc-builder automatically determines the version:
- For Python modules: uses the package's
__version__attribute (ormainfor dev versions) - For non-Python modules (with
--not_python_module): uses the default branch name (typicallymain)
You can override this behavior with the --version flag:
# Build documentation for a specific semantic version (must start with "v")
doc-builder build transformers ~/git/transformers/docs/source --build_dir ~/tmp/test-build --version v4.30.0
# Build documentation for the default branch (non-Python modules)
doc-builder build hub ~/git/hub-docs/docs/source --build_dir ~/tmp/test-build --not_python_module --version mainImportant: When specifying a semantic version with --version, it must start with the letter "v" (e.g., v1.0.0, v2.3.1). For branch names like main, master, or other default branches, the "v" prefix is not required.
Page-level HTML build cache
Building the HTML docs of a large library (e.g. transformers) prerenders hundreds of pages, even when a commit only changed one of them. --html_page_cache enables a page-level cache so that only pages whose generated content changed are prerendered again:
# cache in a Hugging Face storage bucket (https://huggingface.co/docs/hub/storage-buckets) ...
doc-builder build datasets ~/git/datasets/docs/source --build_dir ~/tmp/test-build --html \
--html_page_cache hf://buckets/hf-doc-build/doc-build-cache
# ... or in a local directory
doc-builder build datasets ~/git/datasets/docs/source --build_dir ~/tmp/test-build --html \
--html_page_cache ~/tmp/doc-page-cache --html_page_cache_writeA page is reused when its generated MDX (post autodoc and internal-link resolution โ so docstring changes invalidate exactly the affected pages), the kit folder, and the doc-builder version are unchanged. Keys are version-normalized: pages that only differ by the built version (e.g. main vs pr_123 in resolved internal links) share a cache entry, and on a cross-version reuse the page URLs are rewritten to the target version while asset URLs stay pinned to the source version, whose content-hashed assets remain hosted.
--html_page_cache_write also stores freshly built pages. Only enable it on trusted builds (the shared GitHub workflows enable it on main-branch builds and keep PR builds read-only), so that untrusted code cannot poison the cache. Cache failures are never fatal: any error degrades to building the affected pages.
Building without installing heavy dependencies
doc-builder imports the documented library to read docstrings with inspect โ necessary because libraries like transformers construct docstrings dynamically. Historically that meant installing the library's full dependency tree (torch, GPU wheels, custom containers) just to build documentation.
doc-builder mocks heavy dependencies instead, so only the documented library itself (and its light dependencies) needs to be installed. Each library's registry file src/doc_builder/mock_deps/<library>.txt records both sides of that split:
- bare lines name the heavy dependencies to mock at build time (applied automatically by
doc-builder build/preview); real:lines name the light dependencies a doc build must install for real (things the library imports unguarded, version-pinned requirements, packages used throughisinstancechecks, ...);nodeps:lines are also installed for real but with--no-deps, because their own dependency trees pull in heavy packages (e.g.accelerate, whose install requires torch).
doc-builder light-install <library> installs the real:/nodeps: dependencies (via uv), so a full light setup is:
uv pip install ./accelerate --no-deps
doc-builder light-install accelerate
doc-builder build accelerate ~/git/accelerate/docs/source --build_dir ~/tmp/test-build
# torch and deepspeed are mocked automatically (src/doc_builder/mock_deps/accelerate.txt)Install the library before running light-install: bare registry names are pinned to the library's own declared version ranges (e.g. transformers' tokenizers>=0.22,<=0.23), so registry files never have to chase upstream pins. light-install exits with code 3 when the library has no registry entry โ light-install <library> --check tests this without installing anything, which is how the shared GitHub workflows decide between the light path and a full [dev] install. For a library without a registry entry (or to experiment), --mock_deps torch,... adds extra mocks on top of the registry.
The registry key is the doc-builder library name as passed to doc-builder build โ for namespace subpackages that is the dotted module name (e.g. mock_deps/optimum.intel.txt), and libraries that build under a shared name share a file (optimum-onnx builds as optimum). A registered name may itself be a dotted submodule (e.g. optimum.onnxruntime), which mocks a missing sibling inside an installed namespace package.
The mocked packages are importable, pass the importlib.util.find_spec + importlib.metadata availability checks HF libraries use, are subclassable without affecting the real subclass's signature or docstring, behave as pass-through decorators, and render in signatures like the real objects (repr(torch.float32) == "torch.float32"). Packages that are actually installed are never mocked, and doc-builder preview supports the flag too.
Fidelity, verified on accelerate built without torch installed: 46/48 pages byte-identical to a real-torch build; the two remaining pages differ only in typing paths rendered from the public import path instead of the internal one (e.g. torch.nn.Module instead of torch.nn.modules.module.Module).
Notebook conversion
doc-builder can also automatically convert some of the documentation guides or tutorials into notebooks. This requires two steps:
- add
[[open-in-colab]]in the tutorial for which you want to build a notebook - add
--notebook_dir {path_to_notebook_folder}to the build command.
Runnable code blocks
doc-builder recognizes runnable Python fences tagged with runnable or runnable:<label>:
```py runnable:quickstart
from transformers import pipeline
pipe = pipeline("sentiment-analysis")
print(pipe("I love this!"))
```You can use either py or python fences:
```python runnable:my_example
print("hello")
```During conversion:
- the runnable annotation is removed from the fence in rendered docs
- the code content is preserved unless lines are hidden with
# doc-builder: hide # doc-builder: hidecan hide a single line or a full indented block from rendered docs
The label is used in warning messages (for example, runnable:quickstart) to identify the block.
doc-builder tags and transforms runnable blocks, but it does not execute them by itself.
Use the reusable helper from hf-doc-builder:
from pathlib import Path
from doc_builder.testing import DocIntegrationTest
class MyPageDocIntegrationTest(DocIntegrationTest):
doc_path = Path(__file__).resolve().parents[2] / "docs" / "source" / "en" / "my_page.md"DocIntegrationTest finds runnable py/python fences in the target markdown file, creates one test per block, and executes each block with contextual failure output.
Run locally with:
pytest -q tests/docs/test_my_page_docs.pyThis executes trusted documentation code with exec, so keep it limited to repo-controlled docs and CI.
For continuation blocks, # pytest-decorator, bare-assert warnings, and GitHub Actions wiring, see docs/runnable-code-blocks.md.
Writing in notebooks
You can write your docs in jupyter notebooks & use doc-builder to: turn jupyter notebooks into mdx files.
In some situations, such as course & tutorials, it makes more sense to write in jupyter notebooks (& use doc-builder converter) rather than writing in mdx files directly.
The process is:
- In your
build_main_documentation.yml&build_pr_documentation.ymlenable the flag convert_notebooks: true. - After this flag is enabled, doc-builder will convert all .ipynb files in path_to_docs to mdx files.
Moreover, you can locally convert .ipynb files into mdx files.
doc-builder notebook-to-mdx {path to notebook file or folder containing notebook files}Templates for GitHub Actions
doc-builder provides templates for GitHub Actions, so you can build your documentation with every pull request, push to some branch etc. To use them in your project, simply create the following three files in the .github/workflows/ directory:
build_main_documentation.yml: responsible for building the docs for themainbranch, releases etc.build_pr_documentation.yml: responsible for building the docs on each PR.upload_pr_documentation.yml: responsible for uploading the PR artifacts to the Hugging Face Hub.delete_doc_comment_trigger.yml: responsible for removing the comments from theHuggingFaceDocBuilderbot that provides a URL to the PR docs.
Within each workflow, the main thing to include is a pointer from the uses field to the corresponding workflow in doc-builder. For example, this is what the PR workflow looks like in the datasets library:
name: Build PR Documentation
on:
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
build:
uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@main # Runs this doc-builder workflow
with:
commit_sha: ${{ github.event.pull_request.head.sha }}
pr_number: ${{ github.event.number }}
package: datasets # Replace this with your package nameNote the use of special arguments like pr_number and package under the with field. You can find the various options by inspecting each of the doc-builder workflow files.
Enabling multilingual documentation
doc-builder can also convert documentation that's been translated from the English source into one or more languages. To enable the conversion, the documentation directories should be structured as follows:
doc_folder
โโโ en
โ โโโ _toctree.yml
โ โโโ _redirects.yml
โ ...
โโโ es
โโโ _toctree.yml
โโโ _redirects.yml
...Note that each language directory has its own table of contents file _toctree.yml and that all languages are arranged under a single doc_folder directory - see the course repo for an example. You can then build the individual language subsets as follows:
doc-builder build {package_name} {path_to_docs} --build_dir {build_dir} --language {lang_id}To automatically build the documentation for all languages via the GitHub Actions templates, simply provide the languages argument to your workflow, with a space-separated list of the languages you wish to build, e.g. languages: en es.
Redirects
You can optionally provide _redirects.yml for "old links". The yml file should look like:
how_to: getting_started
package_reference/classes: package_reference/main_classes
# old_local: new_localFixing and testing doc-builder
If you are working on a fix or an update of the doc-builder tool itself, you will eventually want to test it in the CI of another repository (transformers, diffusers, courses, etc.). To do so you should set the doc_builder_revision argument in your workflow file to point to your branch. Here is an example of what it would look like in the transformers.js project:
jobs:
build:
uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@my-test-branch
with:
repo_owner: xenova
commit_sha: ${{ github.sha }}
pr_number: ${{ github.event.number }}
package: transformers.js
path_to_docs: transformers.js/docs/source
pre_command: cd transformers.js && npm install && npm run docs-api
additional_args: --not_python_module
doc_builder_revision: my-test-branch # <- add this lineOnce the docs build is complete in your project, you can drop that change.
Development docs
To test doc-builder changes locally, use the dummy/ folder. It contains a minimal setup for manual testing. Don't commit your changes in dummy/ since it's only for local development.
Run a preview with:
doc-builder preview dummy dummy --not_python_moduleDocumentation page should be available at http://localhost:5173/index.
Development Commands
Since we've modernized the tooling to use ruff and uv, here are the commands for development:
Code Quality & Formatting
Check code quality (linting)
uv run ruff check .Fix auto-fixable linting issues
uv run ruff check --fix .Check code formatting
uv run ruff format --check .Apply code formatting
uv run ruff format .Run both linting and formatting checks (equivalent to old `make quality`)
uv run ruff check . && uv run ruff format --check .Apply both linting fixes and formatting (equivalent to old `make style`)
uv run ruff check --fix . && uv run ruff format .Check links
Check for broken links in the docs (includes line, link text and url)
uv run doc-builder check-links /path/to/docsCheck for broken links in the docs (more compact view)
uv run doc-builder check-links /path/to/docs --format linkTesting
Run all tests (equivalent to old `make test`)
uv run python -m pytest -n 1 --dist=loadfile -s -v ./tests/Run specific test file
uv run python -m pytest tests/test_utils.py -vRun tests with coverage
uv run python -m pytest --cov=src/doc_builder tests/Development Workflow
Install dependencies for development
uv sync --extra devInstall only testing dependencies
uv sync --extra testingInstall only quality/linting dependencies
uv sync --extra qualityRun the full quality check (for CI)
uv run ruff check .
uv run ruff format --check .Run the full test suite (for CI)
uv run python -m pytest -n 1 --dist=loadfile -s -v ./tests/Writing documentation for Hugging Face libraries
doc-builder expects Markdown so you should write any new documentation in ".mdx" files for tutorials, guides, API documentations. For docstrings, we follow the Google format with the main difference that you should use Markdown instead of restructured text (hopefully, that will be easier!)
Values that should be put in code should either be surrounded by backticks: `like so`. Note that argument names
and objects like True, None or any strings should usually be put in code.
Multi-line code blocks can be useful for displaying examples. They are done between two lines of three backticks as usual in Markdown:
```
# first line of code
# second line
# etc
```We follow the doctest syntax for the examples to automatically test
the results stay consistent with the library.
Internal link to object
Syntax:
[`XXXClass`] or [`~XXXClass`] // for class
[`XXXClass.method`] or [`~XXXClass.method`] // for methodExample: here & here (as used inside docstring).
When mentioning a class, function or method, it is recommended to use the following syntax for internal links so that our tool
automatically adds a link to its documentation: [`XXXClass`] or [`function`]. This requires the class or
function to be in the main package.
If you want to create a link to some internal class or function, you need to
provide its path. For instance, in the Transformers documentation [`file_utils.ModelOutput`] will create a link to the documentation of ModelOutput. This link will have file_utils.ModelOutput in the description. To get rid of the path and only keep the name of the object you are
linking to in the description, add a ~: [`~file_utils.ModelOutput`] will generate a link with ModelOutput in the description.
The same works for methods, so you can either use [`XXXClass.method`] or [`~XXXClass.method`].
External link to object
Syntax:
[`XXXLibrary.XXXClass`] or [`~XXXLibrary.XXXClass`] // for class
[`XXXLibrary.XXXClass.method`] or [`~XXXLibrary.XXXClass.method`] // for methodExample: here linking object from accelerate inside transformers.
Tip
To write a block that you'd like to see highlighted as a note or warning, use the blockquote syntax. This is the
preferred approach for new content.
Syntax:
> [!TIP]
> Here is a tip. Go to this url [website](www.tip.com)
>
> Second lineExample: here
Legacy docs may still use the <Tip> component, but we recommend migrating to blockquotes when updating files.
For warnings, change the introduction to:
Syntax:
> [!WARNING]Example: here
Framework Content
If your documentation has a block that is framework-dependent (PyTorch vs TensorFlow vs Flax), you can use the
following syntax:
Syntax:
<frameworkcontent>
PyTorch content goes here
<tf>
TensorFlow content goes here
</tf>
<flax>
Flax content goes here
</flax>
</frameworkcontent>Example: here
Note: all frameworks are optional (you can write a PyTorch-only block for instance) and the order does not matter.
Options
Show alternatives (let's say code blocks for different version of a library etc.) in a way where a user can select an option and see the selected option content:
Syntax:
<hfoptions id="some id">
<hfoption id="id for option 1">
{YOUR MARKDOWN}
</hfoption>
<hfoption id="id for option 2">
{YOUR MARKDOWN}
</hfoption>
... however many <hfoption> tags
</hfoptions>Example: here
Note: for multiple <hfoptions id="some id"> in a same page, you may consider using same id so that when a user selects one option it affects all other hfoptions blocks. If you don't want this behaviour, use different ids.
Anchor link
Anchor links for markdown headings are generated automatically (with the following rule: 1. lowercase, 2. replace space with dash -, 3. strip [^a-z0-9-]):
Syntax:
## My awesome section
// the anchor link is: `my-awesome-section`Example: here
Moreover, there is a way to customize the anchor link.
Syntax:
## My awesome section[[some-section]]
// the anchor link is: `some-section`Example: here
LaTeX
Latex display mode. $$...$$
Syntax:
$$Y = X * \textbf{dequantize}(W); \text{quantize}(W)$$Example: here
Latex inline mode. some prose \\( ... \\) more prose
Syntax:
A paragraph about \\( Y = X * \textbf{dequantize}(W); \text{quantize}(W) \\) the equation.Example: here
Code Blocks
Code blocks are written using a regular markdown syntax ```. However, there is a special flag you can put in your mdx files to change the wrapping style of the resulting html from overflow/scrollbar to wrap.
Syntax:
Example: here
Stretch Tables
By default, tables in the documentation are sized to fit their content. If you want tables to stretch to the full width of the content area, you can add a special flag at the top of your mdx file.
Syntax:
This will make all tables in that page expand to 100% width of the content container.
Inference Snippet
The InferenceSnippet component is used to render an interactive interface for AI model inference. It uses huggingface/huggingface.js under the hood to get the snippets.
Props
Below is a description of the props that can be passed to this component:
pipeline (string, required):
Specifies the type of pipeline to be used for inference. Common values include"text-generation","text-classification", etc.providersMapping (mapping of {modelId: string, providerModelId: string}, required):
A mapping which keys are provider names and values are objects withmodelIdandproviderModelId.
Example:{"fireworks-ai": {modelId: "deepseek-ai/DeepSeek-R1", providerModelId: "accounts/fireworks/models/deepseek-r1", novita: {modelId: "deepseek-ai/DeepSeek-V3-0324", providerModelId: "deepseek/deepseek-v3-0324"}}conversational (boolean, optional):
If set totrue, the component will enable conversational mode, allowing for multi-turn interactions fortext-generationmodels.
Example Usage
Adding new inference provider
Step 1: get latest huggingface/huggingface.js by running the command below:
cd kit
npm run update-inference-providersStep 2: add an icon for the new provider in kit/src/lib/InferenceSnippet/InferenceSnippet.svelte.
Writing API documentation (Python)
Autodoc
To show the full documentation of any object of the python library you are documenting, use the [[autodoc]] marker.
Syntax:
[[autodoc]] SomeObjectExample: here
If the object is a class, this will include every public method of it that is documented. If for some reason you wish for a method
not to be displayed in the documentation, you can do so by specifying which methods should be in the docs, here is an example:
Syntax:
[[autodoc]] XXXTokenizer
- build_inputs_with_special_tokens
- get_special_tokens_mask
- create_token_type_ids_from_sequences
- save_vocabularyExample: here
If you just want to add a method that is not documented (for instance magic method like __call__ are not documented
by default) you can put the list of methods to add in a list that contains all:
Syntax:
## XXXTokenizer
[[autodoc]] XXXTokenizer
- all
- __call__Example: here
Code Blocks from file references
You can create a code-block by referencing a file excerpt with <literalinclude> (sphinx-inspired) syntax.
There should be json between <literalinclude> open & close tags.
Syntax:
<literalinclude>
{"path": "./data/convert_literalinclude_dummy.txt", # relative path
"language": "python", # defaults to " (empty str)
"start-after": "START python_import", # defaults to start of file
"end-before": "END python_import", # defaults to end of file
"dedent": 7 # defaults to 0
}
</literalinclude>Writing source documentation
Description
For a class or function description string, use markdown with all the custom syntax of doc-builder.
Example: here
Arguments
Arguments of a function/class/method should be defined with the Args: (or Arguments: or Parameters:) prefix, followed by a line return and
an indentation. The argument should be followed by its type, with its shape if it is a tensor, a colon, and its
Syntax:
Args:
n_layers (`int`): The number of layers of the model.Example: here
If the description is too long to fit in one line, another indentation is necessary before writing the description
after the argument.
Syntax:
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`AlbertTokenizer`]. See [`~PreTrainedTokenizer.encode`] and
[`~PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)Example: here
You can check the full example it comes from here
Attributes
If a class is similar to that of a dataclass but the parameters do not align to the available attributes of the class, such as in the below example, Attributes instance should be rewritten as **Attributes** in order to have the documentation properly render these. Otherwise it will assume that Attributes is synonymous to Parameters.
Syntax:
class SomeClass:
"""
Docstring
- Attributes:
+ **Attributes**:
- **attr_a** (`type_a`) -- Doc a
- **attr_b** (`type_b`) -- Doc b
"""
def __init__(self, param_a, param_b):
...Parameter typing and default value
For optional arguments or arguments with defaults we follow the following syntax. Imagine we have a function with the
following signature:
def my_function(x: str = None, a: float = 1):then its documentation should look like this:
Syntax:
Args:
x (`str`, *optional*):
This argument controls ...
a (`float`, *optional*, defaults to 1):
This argument is used to ...Example: here
Note that we always omit the "defaults to `None`" when None is the default for any argument. Also note that even
if the first line describing your argument type and its default gets long, you can't break it on several lines. You can
however write as many lines as you want in the indented description (see the example above with input_ids).
If your argument has for type a class defined in the package, you can use the syntax we saw earlier to link to its
documentation:
Args:
config ([`BertConfig`]):
Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.Returns
The return block should be introduced with the Returns: prefix, followed by a line return and an indentation.
The first line should be the type of the return, followed by a line return. No need to indent further for the elements
building the return.
Here's an example for a single value return:
Syntax:
Returns:
`List[int]`: A list of integers in the range [0, 1] --- 1 for a special token, 0 for a sequence token.Example: here
Here's an example for tuple return, comprising several objects:
Syntax:
Returns:
`tuple(torch.FloatTensor)` comprising various elements depending on the configuration ([`BertConfig`]) and inputs:
- ** loss** (*optional*, returned when `masked_lm_labels` is provided) `torch.FloatTensor` of shape `(1,)` --
Total loss as the sum of the masked language modeling loss and the next sequence prediction (classification) loss.
- **prediction_scores** (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) --
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).Example: here
Yields
Similarly, Yields is also supported.
Syntax:
Yields:
`tuple[str, io.BufferedReader]`:
2-tuple (path_within_archive, file_object).
File object is opened in binary mode.Example: here
Raises
You can also document Raises.
Syntax:
Args:
config ([`BertConfig`]):
Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
Raises:
`pa.ArrowInvalidError`: if the arrow data casting fails
TypeError: if the target type is not supported according, e.g.
- point1
- point2
[`HTTPError`](https://2.python-requests.org/en/master/api/#requests.HTTPError) if credentials are invalid
[`HTTPError`](https://2.python-requests.org/en/master/api/#requests.HTTPError) if connection got lost
Returns:
`List[int]`: A list of integers in the range [0, 1] --- 1 for a special token, 0 for a sequence token.Example: here
Directives for Added, Changed, Deprecated
There are directives for Added, Changed, & Deprecated.
Syntax:
Args:
cache_dir (`str`, *optional*): Directory to cache data.
config_name (`str`, *optional*): Name of the dataset configuration.
It affects the data generated on disk: different configurations will have their own subdirectories and
versions.
If not provided, the default configuration is used (if it exists).
<Added version="2.3.0">
`name` was renamed to `config_name`.
</Added>
name (`str`): Configuration name for the dataset.
<Deprecated version="2.3.0">
Use `config_name` instead.
</Deprecated>Example: here
Developing svelte locally
We use svelte components for doc UI (Tip component, Docstring component, etc.).
Follow these steps to develop svelte locally:
- Create this file if it doesn't already exist:
doc-builder/kit/src/routes/_toctree.yml. Contents should be:
- sections:
- local: index
title: Index page
title: Index page- Create this file if it doesn't already exist:
doc-builder/kit/src/routes/index.mdx. Contents should be whatever you'd like to test. For example:
<script lang="ts">
import Tip from "$lib/Tip.svelte";
import Youtube from "$lib/Youtube.svelte";
import Docstring from "$lib/Docstring.svelte";
import CodeBlock from "$lib/CodeBlock.svelte";
import CodeBlockFw from "$lib/CodeBlockFw.svelte";
</script>
<Tip>
[Here](https://myurl.com)
</Tip>
## Some heading
And some text [Here](https://myurl.com)
Physics is the natural science that studies matter,[a] its fundamental constituents, its motion and behavior through space and time, and the related entities of energy and force.[2] Physics is one of the most fundamental scientific disciplines, with its main goal being to understand how the universe behaves.[b][3][4][5] A scientist who specializes in the field of physics is called a physicist.- Install dependencies & run dev mode
cd doc-builder/kit
npm ci
npm run dev -- --open- Start developing. See svelte files in
doc-builder/kit/src/libfor reference. The flow should be:- Create a svelte component in
doc-builder/kit/src/lib - Import it & test it in
doc-builder/kit/src/routes/index.mdx
- Create a svelte component in