timm documentation
The timm Model API
The timm Model API
Every timm model is a torch.nn.Module that shares a common interface on top of forward(). The interface splits
the model into a feature extractor and a classifier head, exposes intermediate features, and provides hooks for
training (gradient checkpointing, parameter grouping) and for changing the input resolution. Code written against it
works across architectures, which is how timmβs training script, feature extraction wrappers and optimizer factory
handle every model the same way.
This page describes the interface of a constructed model: which parts every model provides, which most provide, and
which are specific to some families. How models are created (create_model arguments, pretrained tags, the
pretrained config) is covered in the models reference.
Feature extractor and head
A modelβs forward pass is forward_head(forward_features(x)).
forward_features(x)returns the unpooled output of the last stage, after the final norm layer if the model has one: aNCHWfeature map for convolutional models,NLCtokens (including any class / register prefix tokens) for ViT style models.forward_head(x, pre_logits=False)applies the global pooling (or token selection), any pre-logits layers and the classifier. Withpre_logits=Trueit stops before the classifier and returns the pooled features.
Three attributes describe the sizes involved:
| Attribute | Description |
|---|---|
num_classes | Classifier output size, 0 if the classifier was removed |
num_features | Channels (or embedding dim) of the forward_features output |
head_hidden_size | Size of the pre_logits=True output, the classifier input. Equal to num_features unless the head has a hidden layer (e.g. ConvNeXt w/ head_hidden_size set) |
import torch
import timm
model = timm.create_model('convnext_atto').eval()
x = torch.randn(2, 3, 224, 224)
features = model.forward_features(x) # (2, 320, 7, 7), num_features = 320
pooled = model.forward_head(features, pre_logits=True) # (2, 320), head_hidden_size = 320
logits = model.forward_head(features) # (2, 1000), same as model(x)A few models deviate from the single tensor in, single tensor out form: multi-branch models (CrossViT,
EfficientViM) return a list from forward_features, and the NaFlex / Gemma4 ViTs accept extra patch coordinate and
validity inputs for variable resolution.
Classifier
get_classifier()returns the classifier module.reset_classifier(num_classes, global_pool=None)replaces the classifier with a new, randomly initialized one.num_classes=0replaces it with an identity, somodel(x)returns the pooled features.global_poolchanges the pooling at the same time,''disables it somodel(x)returns unpooled features. In most modelsglobal_pool=Nonekeeps the current pooling, but a few default to'avg', pass it explicitly if it matters.
Creating a model with num_classes / global_pool set has the same effect as resetting the classifier afterwards,
without allocating the original classifier. Encoder-only vision towers (the DeepSeek, Gemma4, MobileNetV5 and Qwen3
encoders) have no classifier and donβt implement these methods.
Intermediate features
forward_intermediates(x, indices=None, norm=False, stop_early=False, output_fmt='NCHW', intermediates_only=False)runs the model and returns the final features plus a list of intermediate features, or only the intermediates withintermediates_only=True.indicesselects them:Nonefor all, anintnfor the lastn, or a list of indices (negative values count from the end).stop_early=Trueskips the blocks after the last selected index (withintermediates_only=True),norm=Trueapplies the final norm layer to each intermediate.feature_infodescribes the available intermediate features, one entry per index with the number of channels (num_chs), the stride relative to the input (reduction) and the module name (module).prune_intermediate_layers(indices=1, prune_norm=False, prune_head=True)removes the blocks after the last index that will be used (and optionally the final norm and the head) and returns the absolute indices to take. Use it when the model will only be used to extract intermediates, as a backbone for a detection or segmentation head.
model = timm.create_model('resnet18').eval()
print([(f['num_chs'], f['reduction']) for f in model.feature_info])
# [(64, 2), (64, 4), (128, 8), (256, 16), (512, 32)]
final, intermediates = model.forward_intermediates(x) # all 5 feature levels
last_two = model.forward_intermediates(x, indices=2, intermediates_only=True) # (2, 256, 14, 14), (2, 512, 7, 7)
take_indices = model.prune_intermediate_layers(indices=2, prune_head=True) # [3, 4], no classifier leftAll features are returned as NCHW maps by default, including those of ViT style models, whose spatial tokens are
reshaped to a grid with the prefix tokens dropped. The other output_fmt options are family specific (NLC for
ViT style models, NHWC for some), as are extra arguments such as return_prefix_tokens (ViT family). Creating a
model with features_only=True wraps it as a backbone that returns the feature maps from model(x), see feature extraction for both approaches in detail.
Input size
Models fall into three groups by how they handle the input resolution:
- Any input size. Most convolutional models, and convolutional hybrids without fixed size position embeddings or window partitions, work at any input size larger than their total stride, without changes.
- Fixed input size, resizable. Models with position embeddings, attention window partitions or relative position
tables are built for one size, set by the
img_sizeargument at creation (default: the pretrained cfginput_size). In the families that implement it (ViT, DeiT, BEiT, EVA, Swin, MaxViT and others, see the table below),set_input_size(img_size=...)changes it afterwards, resampling the position embeddings and relative position tables and updating the windows. Several accept further arguments, e.g.patch_sizefor ViT,window_size/window_ratiofor Swin. Calling it at the current size leaves the model unchanged. The others must be created with theimg_sizethey will be used at. - Dynamic input size. ViT and EVA family models created with
dynamic_img_size=Trueresample their position embedding to the input size on every forward pass, at some cost in speed. Swin, SwinV2 and SwinV2-CR models created withdynamic_img_size=True(or the equivalentstrict_img_size=False) compute their attention masks for the input size on each forward pass instead. NaFlex ViTs handle variable resolution natively.
model = timm.create_model('vit_tiny_patch16_224')
model.set_input_size(img_size=(384, 384))
model(torch.randn(1, 3, 384, 384))Training hooks
set_grad_checkpointing(enable=True)enables activation (gradient) checkpointing, recomputing the forward activations of each block in the backward pass to save memory (--grad-checkpointingintrain.py). Most models support it, some older architectures (VGG, DPN, Inception, β¦) raise an error.group_matcher(coarse=False)returns regular expressions that assign each parameter to a stem or block group. The optimizer factory uses it to scale learning rates per layer for layer-wise learning rate decay (layer_decay, see the optimizers reference).no_weight_decay(), where implemented, returns the names of parameters that should not be weight decayed (position embeddings, class tokens, β¦). The optimizer factory excludes these and all 1D parameters (biases, norm scales) from weight decay.
Pretrained config
model.pretrained_cfg (and its older alias model.default_cfg) is a dict describing the source checkpoint: input
size, interpolation, crop, normalization, classifier and first conv module names, license and source. It is used to
adapt the classifier and input conv when pretrained weights are loaded, and as the preprocessing defaults. See the models reference for the fields.
The pretrained cfg isnβt changed when a model is created or modified to differ from its checkpoint (in_chans, img_size, set_input_size()). The modelβs current input is tracked separately, timm.models.get_model_input_config(model) returns its channels, size and fixed size constraint, and timm.data.resolve_input_data_config(model) resolves a data config for the transforms against it. timm.models.get_model_args(model) returns the arguments to rebuild the model as it is now, and save_for_hf writes
them to the exported config, so a resized or adapted model can be reloaded. See adapt and export models.
Support by family
The table below lists which optional parts of the interface each model family supports. It is generated by hfdocs/generate_model_docs.py, which builds and runs a small model of each model class in each family. Support can
vary between the architectures of a family, see the family pages for details.
| Family | Classes | features_only | forward_intermediates | prune_intermediate_layers | Any input size | set_input_size | dynamic_img_size | Grad checkpointing | Layer decay | reset_classifier |
|---|---|---|---|---|---|---|---|---|---|---|
| Aligned Xception | XceptionAligned | β | β | β | β | β | β | β | β | β |
| BEiT | Beit | β | β | β | β | β | β | β | β | β |
| BYOANet (BoTNet, HaloNet, LambdaNet) | ByobNet | β | β | β | β | β | β | β | β | β |
| BYOBNet (GENet, RepVGG, MobileOne, β¦) | ByobNet | β | β | β | β | β | β | β | β | β |
| CaiT | Cait | β | β | β | β | β | β | β | β | β |
| CoaT | CoaT | β | β | β | β | β | β | β | β | β |
| ConViT | ConVit | β | β | β | β | β | β | β | β | β |
| ConvMixer | ConvMixer | β | β | β | β | β | β | β | β | β |
| ConvNeXt | ConvNeXt | β | β | β | β | β | β | β | β | β |
| CPUBone | CPUBone | β | β | β | β | β | β | β | β | β |
| CrossViT | CrossVit | β | β | β | β | β | β | β | β | β |
| CSATv2 | CSATv2 | β | β | β | β | β | β | β | β | β |
| CSPNet (CSPResNet, CSPDarkNet, DarkNet) | CspNet | β | β | β | β | β | β | β | β | β |
| CSPNeXt | CspNext | β | β | β | β | β | β | β | β | β |
| DaViT | DaVit | β | β | β | β | β | β | β | β | β |
| DeepSeek ViT | DeepseekVitClassifier | β | β | β | β | β | β | β | β | β |
DeepseekVitEncoder | β | β | β | β | β | β | β | β | β | |
| DeiT | VisionTransformer, VisionTransformerDistilled | β | β | β | β | β | β | β | β | β |
| DenseNet | DenseNet | β | β | β | β | β | β | β | β | β |
| DLA | DLA | β | β | β | β | β | β | β | β | β |
| DPN | DPN | β | β | β | β | β | β | β | β | β |
| EdgeNeXt | EdgeNeXt | β | β | β | β | β | β | β | β | β |
| EfficientFormer | EfficientFormer | β | β | β | β | β | β | β | β | β |
| EfficientFormer-V2 | EfficientFormerV2 | β | β | β | β | β | β | β | β | β |
| EfficientNet | EfficientNet | β | β | β | β | β | β | β | β | β |
| EfficientViM | EfficientViM, EfficientViMDistilled | β | β | β | β | β | β | β | β | β |
| EfficientViT (MIT) | EfficientVit, EfficientVitLarge | β | β | β | β | β | β | β | β | β |
| EfficientViT (MSRA) | EfficientVitMsra | β | β | β | β | β | β | β | β | β |
| EVA | Eva | β | β | β | β | β | β | β | β | β |
| FasterNet | FasterNet | β | β | β | β | β | β | β | β | β |
| FastViT | FastVit | β | β | β | β | β | β | β | β | β |
| FocalNet | FocalNet | β | β | β | β | β | β | β | β | β |
| GCViT | GlobalContextVit | β | β | β | β | β | β | β | β | β |
| Gemma 4 ViT | Gemma4VitClassifier | β | β | β | β | β | β | β | β | β |
Gemma4VitEncoder | β | β | β | β | β | β | β | β | β | |
| GhostNet | GhostNet | β | β | β | β | β | β | β | β | β |
| HardCoRe-NAS | MobileNetV3 | β | β | β | β | β | β | β | β | β |
| Hiera | Hiera | β | β | β | β | β | β | β | β | β |
| HieraDet (SAM 2) | HieraDet | β | β | β | β | β | β | β | β | β |
| HRNet | HighResolutionNet | β | β | β | β | β | β | β | β | β |
| Hybrid Vision Transformer | VisionTransformer | β | β | β | β | β | β | β | β | β |
| iFormer | IFormer | β | β | β | β | β | β | β | β | β |
| Inception-ResNet-v2 | InceptionResnetV2 | β | β | β | β | β | β | β | β | β |
| Inception-v3 | InceptionV3 | β | β | β | β | β | β | β | β | β |
| Inception-v4 | InceptionV4 | β | β | β | β | β | β | β | β | β |
| InceptionNeXt | MetaNeXt | β | β | β | β | β | β | β | β | β |
| LeViT | Levit, LevitDistilled | β | β | β | β | β | β | β | β | β |
| LowFormer | LowFormer | β | β | β | β | β | β | β | β | β |
| MambaOut | MambaOut | β | β | β | β | β | β | β | β | β |
| MaxViT and CoAtNet | MaxxVit | β | β | β | β | β | β | β | β | β |
| MetaFormer (PoolFormer, ConvFormer, CAFormer) | MetaFormer | β | β | β | β | β | β | β | β | β |
| MLP-Mixer, ResMLP and gMLP | MlpMixer | β | β | β | β | β | β | β | β | β |
| MobileNet-V3 | MobileNetV3 | β | β | β | β | β | β | β | β | β |
| MobileNet-V5 | MobileNetV5 | β | β | β | β | β | β | β | β | β |
MobileNetV5Encoder | β | β | β | β | β | β | β | β | β | |
| MobileViT | ByobNet | β | β | β | β | β | β | β | β | β |
| MViTv2 | MultiScaleVit | β | β | β | β | β | β | β | β | β |
| NaFlex ViT | NaFlexVit | β | β | β | β | β | β | β | β | β |
| NASNet | NASNetALarge | β | β | β | β | β | β | β | β | β |
| NesT | Nest | β | β | β | β | β | β | β | β | β |
| Next-ViT | NextViT | β | β | β | β | β | β | β | β | β |
| NFNet | NormFreeNet | β | β | β | β | β | β | β | β | β |
| PiT | PoolingVisionTransformer | β | β | β | β | β | β | β | β | β |
| PNASNet | PNASNet5Large | β | β | β | β | β | β | β | β | β |
| PP-HGNet | HighPerfGpuNet | β | β | β | β | β | β | β | β | β |
| PP-LCNetV2 | LCNetV2 | β | β | β | β | β | β | β | β | β |
| PVTv2 | PyramidVisionTransformerV2 | β | β | β | β | β | β | β | β | β |
| Qwen3 ViT | Qwen3VitClassifier | β | β | β | β | β | β | β | β | β |
Qwen3VitEncoder | β | β | β | β | β | β | β | β | β | |
| RDNet | RDNet | β | β | β | β | β | β | β | β | β |
| RegNet | RegNet | β | β | β | β | β | β | β | β | β |
| RepGhost | RepGhostNet | β | β | β | β | β | β | β | β | β |
| RepViT | RepVit | β | β | β | β | β | β | β | β | β |
| Res2Net | ResNet | β | β | β | β | β | β | β | β | β |
| ResNeSt | ResNet | β | β | β | β | β | β | β | β | β |
| ResNet | ResNet | β | β | β | β | β | β | β | β | β |
| ResNetV2 (BiT) | ResNetV2 | β | β | β | β | β | β | β | β | β |
| ReXNet | RexNet | β | β | β | β | β | β | β | β | β |
| Segment Anything ViT | VisionTransformerSAM | β | β | β | β | β | β | β | β | β |
| SelecSLS | SelecSls | β | β | β | β | β | β | β | β | β |
| SENet (legacy) | SENet | β | β | β | β | β | β | β | β | β |
| Sequencer | Sequencer2d | β | β | β | β | β | β | β | β | β |
| SHViT | SHViT | β | β | β | β | β | β | β | β | β |
| SKNet | ResNet | β | β | β | β | β | β | β | β | β |
| StarNet | StarNet | β | β | β | β | β | β | β | β | β |
| SwiftFormer | SwiftFormer | β | β | β | β | β | β | β | β | β |
| Swin Transformer | SwinTransformer | β | β | β | β | β | β | β | β | β |
| Swin Transformer V2 | SwinTransformerV2 | β | β | β | β | β | β | β | β | β |
| Swin Transformer V2 (CR) | SwinTransformerV2Cr | β | β | β | β | β | β | β | β | β |
| TinyViT | TinyVit | β | β | β | β | β | β | β | β | β |
| TNT | TNT | β | β | β | β | β | β | β | β | β |
| TResNet | TResNet | β | β | β | β | β | β | β | β | β |
| Twins | Twins | β | β | β | β | β | β | β | β | β |
| VGG | VGG | β | β | β | β | β | β | β | β | β |
| Visformer | Visformer | β | β | β | β | β | β | β | β | β |
| Vision Transformer (relative position) | VisionTransformerRelPos | β | β | β | β | β | β | β | β | β |
| Vision Transformer (ViT) | VisionTransformer | β | β | β | β | β | β | β | β | β |
| ViTamin | VisionTransformer | β | β | β | β | β | β | β | β | β |
| VOLO | VOLO | β | β | β | β | β | β | β | β | β |
| VoVNet | VovNet | β | β | β | β | β | β | β | β | β |
| Xception (legacy) | Xception | β | β | β | β | β | β | β | β | β |
| XCiT | Xcit | β | β | β | β | β | β | β | β | β |
β supported, β (square) works for square sizes only, β not supported, β not needed (the model already accepts any input size). Each model class of a family is checked by running every feature on a randomly initialized model of its smallest (non-test) architecture in the family. Classes with the same results share a row, the family page lists the architecture used for each.
Implementing a model
A new model should implement the interface so it works with the training script, feature extraction and the optimizer factory without special cases:
forward_features,forward_head(x, pre_logits=False)andforwardas their composition, withnum_classes,num_featuresandhead_hidden_sizeset.get_classifierandreset_classifier(num_classes, global_pool=None).forward_intermediates,prune_intermediate_layersand afeature_infolist.set_grad_checkpointing,group_matcher, andno_weight_decayfor any parameter that shouldnβt be decayed.set_input_sizeif the model is built for a fixed input size.- The standard constructor arguments:
num_classes,in_chans,global_pool,drop_rate,drop_path_rate, anddevice/dtypefor parameter creation.
tests/test_models.py checks the forward, backward, features, intermediates, classifier reset and pretrained cfg
parts of the interface for the registered models (the largest are excluded from some tests to keep CI time down).