This page contains the API reference documentation for creating and discovering timm models, their pretrained
Models
This page contains the API reference documentation for creating and discovering timm models, their pretrained
configs and the checkpoint / Hub helpers, and an overview of the interface shared by timm models. The individual
architectures are covered in the model summaries and the per-model pages.
Usage
Models are created by name with create_model. The name selects an architecture registered in
timm, optionally w/ a pretrained tag after a . (resnet50.a1_in1k), or a model on the Hugging Face Hub or in a
local folder via a source prefix. Keyword arguments that create_model doesn't use itself pass through the model's
entrypoint function to the model class constructor, so any model specific argument can be set.
import torch
import timm
# Random init (pretrained=False is the default). The tag selects the pretrained cfg, and the weights loaded with
# pretrained=True. Without a tag the architecture's default tag is used.
model = timm.create_model('vit_tiny_patch16_224.augreg_in21k_ft_in1k')
print(model.pretrained_cfg['mean'], model.pretrained_cfg['crop_pct']) # (0.5, 0.5, 0.5) 0.9
# Model arguments pass through to the model class, a 10 class head, single channel input and regularization.
model = timm.create_model('resnet50', num_classes=10, in_chans=1, drop_rate=0.2, drop_path_rate=0.05)
# Discover models, filters are fnmatch wildcards.
timm.list_models('convnext*') # architecture names
timm.list_pretrained('resnet50.*') # architecture.tag names w/ pretrained weights
timm.list_models(module='vision_transformer', pretrained=True)
# Image preprocessing to match the model's pretrained cfg (input size, interpolation, crop, mean / std).
model = timm.create_model('vit_tiny_patch16_224.augreg_in21k_ft_in1k')
data_config = timm.data.resolve_model_data_config(model)
transform = timm.data.create_transform(**data_config, is_training=False)
x = torch.randn(2, 3, 224, 224)
features = model.forward_features(x) # unpooled features, (2, 197, 192)
pre_logits = model.forward_head(features, pre_logits=True) # pooled features, (2, 192)
logits = model.forward_head(features) # same as model(x), (2, 1000)
model.reset_classifier(5) # replace the classifier w/ a new 5 class one
model.set_input_size(img_size=(384, 384)) # resample the position embedding for a new resolution
logits = model(torch.randn(2, 3, 384, 384)) # (2, 5)
The training script (train.py) exposes the common arguments through these flags:
--modelselects the model.--pretrainedloads pretrained weights.--num-classessets the classifier size (num_classes).--in-chanssets the input channels (in_chans).--gpsets the global pooling type (global_pool).--dropsets classifier dropout (drop_rate).--drop-pathsets stochastic depth (drop_path_rate).--pretrained-pathloads pretrained weights from a local file with classifier / input conv adaptation (pretrained_cfg_overlay=dict(file=...)).--initial-checkpointloads a checkpoint after creating the model, without adaptation (checkpoint_path).--model-kwargs key=value ...passes any other model arguments.
See the quickstart for an introduction.
Model names
| Name | Source |
|---|---|
resnet50 |
Architecture in the timm registry, w/ its default pretrained cfg (here a1_in1k) |
resnet50.a1_in1k |
Architecture + pretrained tag, an unknown tag raises an error |
hf-hub:timm/resnet50.a1_in1k |
Hugging Face Hub repo, the architecture, pretrained cfg and model args come from its config.json, @revision selects a revision |
local-dir:/path/to/folder |
Local folder w/ a config.json and weights, as written by save_for_hf |
The Hub and local sources read the config even w/ pretrained=False, weights are only loaded w/ pretrained=True.
A name w/o a source prefix that contains /, \ or : raises a ValueError instead of falling back to a registry
model of the same name. hf_hub: is a deprecated alias of hf-hub:.
Common arguments
pretrainedloads the weights of the pretrained cfg, fromstate_dictorfileif set, otherwise from the Hub (hf_hub_id) whenhuggingface_hubis installed, or theurl. Classifier / input conv adaptation below lets a pretrained model be created for fine-tuning in one call.num_classessets the classifier size,0removes the classifier. The default comes from the pretrained cfg. When loading pretrained weights, a different class count discards the classifier weights (left at random init).global_poolsets the pooling type, the options are model specific (e.g.avg,max,avgmax,catavgmaxfor most convnets,token,avg,mapfor ViT),''disables pooling.in_chanssets the input channels. The default comes from the pretrained cfg. When loading pretrained weights, the first conv weights are adapted where supported if this differs from the source checkpoint's channel count (input_size[0]in the pretrained cfg).drop_ratesets classifier dropout, supported by most models.drop_path_ratesets stochastic depth, supported by most models.img_sizeis an argument of ViT style and other models w/ a fixed input size, they're built for the pretrained cfginput_sizeunless it's set.dynamic_img_size=Truein the ViT and EVA families resamples the position embedding to the input size on every forward pass.features_only(w/out_indices,output_stride,feature_cls) wraps the model as a feature backbone returning feature maps, see feature extraction.pretrained_cfgreplaces the pretrained cfg (a tag, dict orPretrainedCfg).pretrained_cfg_overlayoverrides some of its fields, e.g.pretrained_cfg_overlay=dict(file='weights.pth')loadspretrained=Trueweights from a local file, w/ the classifier / input conv adaptation above (as--pretrained-pathdoes intrain.py).checkpoint_pathloads a checkpoint w/load_checkpointafter the model is created. It's a strict load w/o adaptation, EMA weights are used if the checkpoint has them.cache_diroverrides the download cache for pretrained weights and Hub configs.deviceis passed to the model class, params are created on the device directly.device='meta'creates a model w/o allocating memory for its weights.dtypeis passed to the model class, params are created in the dtype directly.scriptablesets layer config flags for TorchScript scripting.exportablesets layer config flags for export / tracing.no_jitsets layer config flags to disable jit scripted layers.
Arguments set to None are dropped before reaching the model, so the model defaults apply. Arguments the model class
doesn't accept raise a TypeError in most models, a few ignore unknown arguments.
Pretrained config
Architectures have one or more pretrained cfgs, one per tag, registered w/ the model. A cfg describes the weights
(location, license, origin) and how the model was trained and should be evaluated w/ them. Models created by
create_model have their cfg as a dict in model.pretrained_cfg (model.default_cfg is an alias), the registry
versions are returned as PretrainedCfg instances by
get_pretrained_cfg.
| Field | Description |
|---|---|
architecture, tag |
Model architecture and pretrained tag |
hf_hub_id, url, file, state_dict |
Weight sources (see pretrained above) |
input_size, test_input_size, fixed_input_size |
Train (and default eval) input size, eval size used w/ use_test_size=True (if different), whether the model has a fixed input size (img_size argument) |
interpolation, crop_pct, test_crop_pct, crop_mode |
Eval resize interpolation, crop fraction (w/ the default center crop mode the image is resized to input_size / crop_pct, then center cropped) and crop mode |
mean, std |
Input normalization |
num_classes, label_names, label_descriptions |
Classifier size and labels (when known) |
classifier, first_conv |
Module names of the classifier and first conv, used to adapt the weights on load |
license, origin_url, paper_ids, paper_name, notes |
Weight meta-data |
The input fields are what resolve_data_config /
resolve_model_data_config resolve to a data config for the dataset
transforms and loader. The cfg describes the source checkpoint and isn't updated when the model is created or
modified differently (num_classes, in_chans, img_size, set_input_size()). The model's current input
channels, size and fixed size constraint are tracked separately:
get_model_input_config returns them, and
resolve_input_data_config resolves a data config against them (as the
training, validation and inference scripts do). get_model_args returns the arguments
to rebuild the model as it is now, which save_for_hf writes to the exported config. See
adapt and export models for details.
Model interface
timm models share a common interface beyond forward(): the forward_features() / forward_head() split,
classifier reset, intermediate features, input resizing and training hooks such as gradient checkpointing and
parameter grouping. It is described in the timm Model API, including which model families support
which parts.
Checkpoints and the Hub
load_checkpointloads a checkpoint file (PyTorch or.safetensors) into a model.load_state_dictreads a checkpoint file and returns its state dict.resume_checkpointrestores the model, optimizer and loss scaler state of atrain.pycheckpoint and returns the epoch to resume from.
load_checkpoint and load_state_dict pick the EMA weights of a train.py checkpoint by default (use_ema)
and remove module. (DDP) and _orig_mod. (torch.compile) key prefixes.
save_for_hfwrites the weights and aconfig.json(architecture, pretrained cfg,model_args,label_names) to a folder.push_to_hf_hubuploads the weights and config to a Hub repo w/ a generated model card if the repo has none.
The model is then created w/ hf-hub: or local-dir:, see
sharing and loading models.
import timm
from timm.models import save_for_hf
model = timm.create_model('resnet18', num_classes=4)
# ... fine-tune
save_for_hf(model, 'my_resnet18', model_config=dict(label_names=['a', 'b', 'c', 'd']), safe_serialization=True)
model = timm.create_model('local-dir:my_resnet18', pretrained=True) # 4 classes, weights and labels restored
print(model.pretrained_cfg['label_names'])
Custom models
A model entrypoint function decorated w/ register_model is added to the registry, so
it can be created w/ create_model and found w/ list_models. Entrypoints in timm build their model w/
build_model_with_cfg, which handles the pretrained cfg, pretrained weight
loading and features_only.
API
Model creation
[[autodoc]] timm.create_model
Model discovery
[[autodoc]] timm.list_models [[autodoc]] timm.list_pretrained [[autodoc]] timm.list_modules [[autodoc]] timm.is_model [[autodoc]] timm.is_model_pretrained [[autodoc]] timm.model_entrypoint
Pretrained config
[[autodoc]] timm.get_pretrained_cfg [[autodoc]] timm.get_pretrained_cfg_value [[autodoc]] timm.models.get_arch_pretrained_cfgs [[autodoc]] timm.models.PretrainedCfg
Current model input and export
[[autodoc]] timm.models.get_model_input_config [[autodoc]] timm.models.get_model_traits [[autodoc]] timm.models.get_model_args [[autodoc]] timm.models.resolve_model_input_args [[autodoc]] timm.models.adapt_input_conv
Checkpoints and Hub
[[autodoc]] timm.models.load_checkpoint [[autodoc]] timm.models.load_state_dict [[autodoc]] timm.models.resume_checkpoint [[autodoc]] timm.models.save_for_hf [[autodoc]] timm.models.push_to_hf_hub
Custom models
[[autodoc]] timm.models.register_model [[autodoc]] timm.models.build_model_with_cfg
Source and license
Source: timm documentation, adapted for this site. Licensing and attribution follow the terms of the upstream project.