timm documentation
Models
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 as --model, --pretrained, --num-classes, --in-chans, --gp, --drop, --drop-path, --pretrained-path, --initial-checkpoint and --model-kwargs key=value ... for any other model argument. 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. Ifnum_classesdiffers from the pretrained cfg, the classifier weights are discarded (left at random init). Ifin_chansdiffers from the source checkpoint’s channel count (input_size[0]in the pretrained cfg), the first conv weights are adapted where supported, so a pretrained model can be created for fine-tuning in one call.num_classessets the classifier size,0removes the classifier.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. Thenum_classesandin_chansdefaults come from the pretrained cfg.drop_rate(classifier dropout) anddrop_path_rate(stochastic depth) are 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. The ViT and EVA families also acceptdynamic_img_size=Trueto resample 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.deviceanddtypeare passed to the model class, params are created on the device and in the dtype directly.device='meta'creates a model w/o allocating memory for its weights.scriptable,exportableandno_jitset layer config flags for TorchScript scripting, export / tracing, and 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_checkpoint loads a checkpoint file (PyTorch or .safetensors) into a model, load_state_dict returns its state dict. Both pick the EMA weights of a train.py checkpoint by default (use_ema) and remove module. (DDP) and _orig_mod. (torch.compile) key prefixes. resume_checkpoint restores the model, optimizer and loss scaler state of a train.py checkpoint and returns the epoch to resume from.
save_for_hf writes the weights and a config.json (architecture, pretrained cfg, model_args, label_names) to a folder, push_to_hf_hub uploads them 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
timm.create_model
< source >( model_name: strpretrained: bool = Falsepretrained_cfg: typing.Union[str, typing.Dict[str, typing.Any], timm.models._pretrained.PretrainedCfg, NoneType] = Nonepretrained_cfg_overlay: typing.Optional[typing.Dict[str, typing.Any]] = Nonecheckpoint_path: typing.Union[str, pathlib.Path, NoneType] = Nonecache_dir: typing.Union[str, pathlib.Path, NoneType] = Nonescriptable: typing.Optional[bool] = Noneexportable: typing.Optional[bool] = Noneno_jit: typing.Optional[bool] = None**kwargs: typing.Any )
Parameters
- model_name — Name of model to instantiate.
- pretrained — If set to True, load pretrained ImageNet-1k weights.
- pretrained_cfg — Pass in an external pretrained_cfg for model.
- pretrained_cfg_overlay — Replace key-values in base pretrained_cfg with these.
- checkpoint_path — Path of checkpoint to load after the model is initialized.
- cache_dir — Override model cache dir for Hugging Face Hub and Torch checkpoints.
- scriptable — Set layer config so that model is jit scriptable (not working for all models yet).
- exportable — Set layer config so that model is traceable / ONNX exportable (not fully impl/obeyed yet).
- no_jit — Set layer config so that model doesn’t utilize jit scripted layers (so far activations only).
Create a model.
Lookup model’s entrypoint function and pass relevant args to create a new model.
Tip:
**kwargs will be passed through entrypoint fn to timm.models.build_model_with_cfg() and then the model class init(). kwargs values set to None are pruned before passing.
Keyword Args: drop_rate (float): Classifier dropout rate for training. drop_path_rate (float): Stochastic depth drop rate for training. global_pool (str): Classifier global pooling type.
Example:
>>> from timm import create_model
>>> # Create a MobileNetV3-Large model with no pretrained weights.
>>> model = create_model('mobilenetv3_large_100')
>>> # Create a MobileNetV3-Large model with pretrained weights.
>>> model = create_model('mobilenetv3_large_100', pretrained=True)
>>> model.num_classes
1000
>>> # Create a MobileNetV3-Large model with pretrained weights and a new head with 10 classes.
>>> model = create_model('mobilenetv3_large_100', pretrained=True, num_classes=10)
>>> model.num_classes
10
>>> # Create a Dinov2 small model with pretrained weights and save weights in a custom directory.
>>> model = create_model('vit_small_patch14_dinov2.lvd142m', pretrained=True, cache_dir="/data/my-models")
>>> # Data will be stored at */data/my-models/models--timm--vit_small_patch14_dinov2.lvd142m/*Model discovery
timm.list_models
< source >( filter: typing.Union[str, typing.Iterable[str]] = ''module: typing.Union[str, typing.Iterable[str]] = ''pretrained: bool = Falseexclude_filters: typing.Union[str, typing.Iterable[str]] = ''name_matches_cfg: bool = Falseinclude_tags: typing.Optional[bool] = None )
Parameters
- filter — Wildcard filter(s) that work with fnmatch.
- module — Limit model selection to specific submodule(s) (ie ‘vision_transformer’).
- pretrained — Include only models with valid pretrained weights if True.
- exclude_filters — Wildcard filter(s) to exclude models after including them with filter.
- name_matches_cfg — Include only models w/ model_name matching default_cfg name (excludes some aliases).
- include_tags — Include pretrained tags in model names (model.tag). If None, set to the value of pretrained.
Return list of available model names, sorted naturally.
Example: list_models(‘gluon_resnet’) — returns all models starting with ‘gluon_resnet’ list_models(’resnext*’, ‘resnet’) — returns all models with ‘resnext’ in ‘resnet’ module
timm.list_pretrained
< source >( filter: typing.Union[str, typing.Iterable[str]] = ''exclude_filters: typing.Union[str, typing.Iterable[str]] = '' )
Return list of pretrained model names (w/ tags), sorted naturally.
Return sorted list of module names that contain model entrypoints.
Check if a model architecture is registered, ignoring any pretrained tag.
Check if a model name (w/ or w/o tag) has pretrained weights registered.
timm.model_entrypoint
< source >( model_name: strmodule_filter: typing.Optional[str] = None )
Fetch the model entrypoint fn for a model name, ignoring any pretrained tag.
Pretrained config
timm.get_pretrained_cfg
< source >( model_name: strallow_unregistered: bool = True )
Get a copy of the pretrained cfg for a model name, the default tag is used if none specified.
timm.get_pretrained_cfg_value
< source >( model_name: strcfg_key: str )
Raises
RuntimeError
RuntimeError— If the model has no pretrained cfg registered or the tag is invalid.
Get a specific pretrained cfg value by key for a model name, None if the key doesn’t exist.
timm.models.get_arch_pretrained_cfgs
< source >( model_name: str )
Get copies of all pretrained cfgs for a model architecture.
class timm.models.PretrainedCfg
< source >( url: typing.Union[str, typing.Tuple[str, str], NoneType] = Nonefile: typing.Optional[str] = Nonestate_dict: typing.Optional[typing.Dict[str, typing.Any]] = Nonehf_hub_id: typing.Optional[str] = Nonehf_hub_filename: typing.Optional[str] = Nonesource: typing.Optional[str] = Nonearchitecture: typing.Optional[str] = Nonetag: typing.Optional[str] = Nonecustom_load: bool = Falseinput_size: typing.Tuple[int, int, int] = (3, 224, 224)test_input_size: typing.Optional[typing.Tuple[int, int, int]] = Nonemin_input_size: typing.Optional[typing.Tuple[int, int, int]] = Nonefixed_input_size: bool = Falseinterpolation: str = 'bicubic'crop_pct: float = 0.875test_crop_pct: typing.Optional[float] = Nonecrop_mode: str = 'center'mean: typing.Tuple[float, ...] = (0.485, 0.456, 0.406)std: typing.Tuple[float, ...] = (0.229, 0.224, 0.225)num_classes: int = 1000label_offset: typing.Optional[int] = Nonelabel_names: typing.Optional[typing.Tuple[str]] = Nonelabel_descriptions: typing.Optional[typing.Dict[str, str]] = Nonepool_size: typing.Optional[typing.Tuple[int, ...]] = Nonetest_pool_size: typing.Optional[typing.Tuple[int, ...]] = Nonefirst_conv: typing.Optional[str] = Noneclassifier: typing.Optional[str] = Nonelicense: typing.Optional[str] = Nonedescription: typing.Optional[str] = Noneorigin_url: typing.Optional[str] = Nonepaper_name: typing.Optional[str] = Nonepaper_ids: typing.Union[str, typing.Tuple[str], NoneType] = Nonenotes: typing.Optional[typing.Tuple[str]] = None )
Current model input and export
Return the current image channels, nominal size, and fixed-size constraint.
The nominal size is a recommendation for flexible models. Source checkpoint
metadata remains in model.pretrained_cfg and is never modified here.
Return a copy of the model’s traits, augmented with current channel and class counts.
Existing in_chans and num_classes attributes remain authoritative;
they are read here instead of being duplicated in the stored traits.
Attributes absent from a feature wrapper are omitted.
timm.models.get_model_args
< source >( model: Moduleoverrides: typing.Optional[typing.Dict[str, typing.Any]] = None )
Return reconstruction arguments, including supported changes made after construction.
Runtime arguments are excluded by the factory. Drop rates are omitted unless explicitly supplied in overrides. Non-serializable architecture arguments require an explicit serializable replacement when exporting.
timm.models.resolve_model_input_args
< source >( model_name: strargs: typing.Optional[typing.Dict[str, typing.Any]] = None**model_kwargs )
Resolve script input requests into arguments for create_model.
Saved model arguments are defaults. Explicit channel/size requests select the target without overwriting metadata describing the source checkpoint.
timm.models.adapt_input_conv
< source >( in_chans: intconv_weight: Tensorbase_chans: int = 3 )
Parameters
- in_chans — Number of input channels for the target model.
- conv_weight — Pretrained Conv2d weights in OIHW layout.
- base_chans — Number of physical input channels used for pretraining. This can differ from the weight’s input dimension for space-to-depth stems.
Raises
ValueError or NotImplementedError
ValueError— If either channel count is not positive.NotImplementedError— If the weight format cannot be adapted.
Adapt pretrained input convolution weights to a different channel count.
Checkpoints and Hub
timm.models.load_checkpoint
< source >( model: Modulecheckpoint_path: struse_ema: bool = Truedevice: typing.Union[str, torch.device] = 'cpu'strict: bool = Trueremap: bool = Falsefilter_fn: typing.Optional[typing.Callable] = Noneweights_only: bool = True )
Parameters
- model — Model to load checkpoint into.
- checkpoint_path — Path to checkpoint file.
- use_ema — Whether to use EMA weights if available.
- device — Device to load checkpoint to.
- strict — Whether to strictly enforce state_dict keys match.
- remap — Whether to remap state dict keys by order.
- filter_fn — Optional function to filter state dict.
- weights_only — Whether to load only weights (torch.load parameter).
Load checkpoint into model.
Native PyTorch checkpoints are loaded as state dictionaries. NumPy .npz/.npy` checkpoints are foreign, model-specific formats and are delegated to the model's `load_pretrained helper.
timm.models.load_state_dict
< source >( checkpoint_path: struse_ema: bool = Truedevice: typing.Union[str, torch.device] = 'cpu'weights_only: bool = True )
Load state dictionary from checkpoint file.
timm.models.resume_checkpoint
< source >( model: Modulecheckpoint_path: stroptimizer: typing.Optional[torch.optim.Optimizer] = Noneloss_scaler: typing.Optional[typing.Any] = Nonelog_info: bool = Trueweights_only: bool = True )
Resume training from checkpoint.
timm.models.save_for_hf
< source >( model: Modulesave_directory: strmodel_config: typing.Optional[dict] = Nonemodel_args: typing.Optional[dict] = Nonesafe_serialization: typing.Union[bool, typing.Literal['both']] = Falsedata_config: typing.Optional[dict] = None )
Save native weights and their current model and preprocessing configuration.
timm.models.push_to_hf_hub
< source >( model: Modulerepo_id: strcommit_message: str = 'Add model'token: typing.Optional[str] = Nonerevision: typing.Optional[str] = Noneprivate: bool = Falsecreate_pr: bool = Falsemodel_config: typing.Optional[dict] = Nonemodel_card: typing.Optional[dict] = Nonemodel_args: typing.Optional[dict] = Nonetask_name: str = 'image-classification'safe_serialization: typing.Union[bool, typing.Literal['both']] = 'both'data_config: typing.Optional[dict] = None )
Parameters
- (…) —
- model_args — Explicit reconstruction arguments supplementing those recorded by the factory.
- data_config — Preprocessing used with the exported checkpoint, including input size and normalization.
- safe_serialization (
boolor"both", optional, defaults toFalse) — Whether to save the model usingsafetensorsor the traditional PyTorch way (that usespickle). Can be set to"both"in order to push both safe and unsafe weights.
Custom models
timm.models.register_model
< source >( fn: typing.Callable[..., typing.Any] )
Decorator that registers a model entrypoint fn and any pretrained cfgs in its module’s default_cfgs.
Registering a name that already exists overwrites the previous registration and its pretrained cfgs.
timm.models.build_model_with_cfg
< source >( model_cls: typing.Union[typing.Type[~ModelT], typing.Callable[..., ~ModelT]]variant: strpretrained: boolpretrained_cfg: typing.Optional[typing.Dict] = Nonepretrained_cfg_overlay: typing.Optional[typing.Dict] = Nonemodel_cfg: typing.Optional[typing.Any] = Nonefeature_cfg: typing.Optional[typing.Dict] = Nonepretrained_strict: bool = Truepretrained_filter_fn: typing.Optional[typing.Callable] = Nonecache_dir: typing.Union[str, pathlib.Path, NoneType] = Nonekwargs_filter: typing.Optional[typing.Tuple[str]] = Nonepretrained_model_args: typing.Optional[typing.Dict] = None**kwargs )
Parameters
- model_cls — Model class
- variant — Model variant name
- pretrained — Load the pretrained weights
- pretrained_cfg — Model’s pretrained weight/task config
- pretrained_cfg_overlay — Entries that will override those in pretrained_cfg
- model_cfg — Model’s architecture config
- feature_cfg — Feature extraction adapter config
- pretrained_strict — Load pretrained weights strictly
- pretrained_filter_fn — Filter callable for pretrained weights
- cache_dir — Override model cache dir for Hugging Face Hub and Torch checkpoints
- kwargs_filter — Kwargs keys to filter (remove) before passing to model
- pretrained_model_args — Reconstruction arguments describing the source checkpoint.
- **kwargs — Model args passed through to model init
Build model with specified default_cfg and optional model_cfg
This helper fn aids in the construction of a model including:
- handling default_cfg and associated pretrained weight loading
- passing through optional model_cfg for models with config based arch spec
- features_only model adaptation
- pruning config / model adaptation