timm (PyTorch Image Models)

repository·main·Indexed 12 days ago

https://github.com/huggingface/pytorch-image-models

A library providing various computer vision models, validation scripts, and benchmark results. It includes tools for feature extraction (unpooled, pooled, and multi-scale backbones), integration with the Hugging Face Hub for loading and sharing models, and detailed hyperparameter recipe tags for training.

Tokens
72.9K
Snippets
214
Records
277
Agent score
98%

What's inside timm

  1. Overview of the timm library

    main
    timm (PyTorch Image Models) is a comprehensive library for computer vision. It provides state-of-the-art (SOTA) models, specialized layers, utilities, optimizers, schedulers, data loaders, augmentations, and scripts for both training and evaluation. The library is designed for flexibility and includes over 700 pretrained models.
  2. Reference model implementations and papers

    main

    The timm repository provides implementations for a wide variety of computer vision architectures. Each model implementation is typically located in the timm/models/ directory. Below is a summary of key model families and their implementation files:

    Common Architectures

    • ResNet / ResNeXt: timm/models/resnet.py (includes variants like Squeeze-and-Excitation and ECAResNet)
    • EfficientNet: timm/models/efficientnet.py (includes NoisyStudent, AdvProp, and EdgeTPU variants)
    • Vision Transformer (ViT): timm/models/vision_transformer.py
    • MobileNet-V3: timm/models/mobilenetv3.py
    • Inception family: inception_v3.py, inception_v4.py, inception_resnet_v2.py
    • VGG: timm/models/vgg.py
    • Xception: timm/models/xception.py

    For specific model details, you can refer to the corresponding implementation file in the source code to see the exact architecture and the paper it is based on.

  3. Understand pretrained weight sources in timm

    main

    Most models included in timm come with pretrained weights. These weights are sourced from one of three ways:

    1. Original sources (from the authors of the paper).
    2. Ported weights (converted from other frameworks like TensorFlow to PyTorch).
    3. Weights trained from scratch using the included timm training scripts.

    You can find validation results for these weights in the project's results documentation.

  4. Handle pretrained weight remapping with checkpoint_filter_fn

    main

    When upgrading timm or using 3rd party checkpoints, weights may need remapping to match the current model implementation. This is handled by a checkpoint_filter_fn located within the specific model implementation module.

    • Automatic usage: The function is automatically called when loading weights using pretrained=True.
    • Manual usage: You can manually remap an old state dict to a current model instance by calling the checkpoint_filter_fn directly.
    • Remapping existing checkpoints: If a model's architecture has changed (e.g., to support features_only=True), you can pass the specific model's filter function to timm.models.load_checkpoint to ensure compatibility.
    timm.models.load_checkpoint(
        model,
        checkpoint_path,
        filter_fn=timm.models.swin_transformer_v2.checkpoint_filter_fn
    )
  5. Interpret benchmark and metadata CSV files

    main

    The results directory uses specific file prefixes to categorize data:

    • Benchmarks: CSV files starting with model_benchmark contain inference performance numbers across various accelerators and precisions. Currently, these are primarily run on RTX 3090 with AMP.
    • Metadata: CSV files starting with model_metadata contain information regarding the model's source training, such as the pretraining dataset and the technique used (e.g., distillation, SSL, WSL).
  6. Concept: Noisy Student Training

    main

    Noisy Student Training is a semi-supervised learning approach that combines self-training and distillation. It aims to improve model performance by using a larger 'student' model trained on a combination of labeled data and pseudo-labeled data generated by a 'teacher' model.

    The process follows three main steps:

    1. Teacher Training: Train a teacher model on labeled images.
    2. Pseudo-labeling: Use the teacher to generate pseudo labels on unlabeled images.
    3. Student Training: Train a student model (which is equal to or larger than the teacher) on both the original labeled images and the new pseudo-labeled images.

    To force the student to learn more robustly from the pseudo labels, noise is added during training via:

    • Input noise: e.g., RandAugment data augmentation.
    • Model noise: e.g., dropout and stochastic depth.
  7. Use architecture and pretrained_tag for model naming

    main

    In versions newer than 0.6.x, timm uses a naming convention combining the architecture and a pretrained_tag (e.g., resnet50.rsb_a1).

    • pretrained_tag: Represents the specific weight variant (such as a different head) for that architecture.
    • Default behavior: If you specify only the architecture name, timm defaults to the first weights defined in the default_cfgs for that model.
    • Renaming: Many previous model names that used suffixes to differentiate variants have been renamed to use the dot-separated tag format (e.g., vit_base_patch16_224_in21k becomes vit_base_patch16_224.augreg_in21k).
  8. Identify pretrained model hyperparameter families via tags

    main

    Most timm pretrained models include an identifier in their pretrained tag that corresponds to a specific family or version of hyperparameters (HParams) used during training. You can use these tags to understand the training recipe (optimizer, learning rate schedule, and augmentation strategies) applied to a model.

    Common tags include:

    • a1h, ah: Based on ResNet Strikes Back A1 recipe (uses LAMB, Cosine with warmup).
    • a1, a2, a3: ResNet Strikes Back A{1,2,3} recipes (uses LAMB with BCE loss).
    • b1, b2, b1k, b2k: Based on ResNet Strikes Back B recipe (uses RMSProp, Step decay).
    • c, c1, c2, c3, ch: Based on ResNet Strikes Back C recipes (uses SGD Nesterov with AGC).
    • d, d1, d2: Based on ResNet Strikes Back D recipe (uses AdamW with BCE loss).
    • sw: Swin Transformer recipe (basis for DeiT and ConvNeXt; uses AdamW with gradient clipping and EMA).
    • ra, ra2, ra3, racm, raa: RandAugment recipes.
    • am: AugMix recipe.
    • ram: AugMix with RandAugment recipe.
    • bt: Bag-of-Tricks recipe.
  9. Understand the validation and benchmark datasets in timm

    main

    The results/ directory contains performance metrics for models in the timm collection. Validation scores are provided for models with pretrained weights and ImageNet-1k heads, while benchmark numbers are available for all models.

    Available Datasets

    • ImageNet Validation (results-imagenet.csv): The standard 50,000 image ImageNet-1k validation set.
    • ImageNet-'Real Labels' (results-imagenet-real.csv): The standard validation set but with reassessed labels to correct original annotation errors.
    • ImageNetV2 Matched Frequency (results-imagenetv2-matched-frequency.csv): A 10,000 image test set sampled to replicate the original ImageNet curation process.
    • ImageNet-Sketch (results-sketch.csv): 50,000 non-photographic images (sketches/doodles) covering all 1000 ImageNet classes.
    • ImageNet-Adversarial (results-imagenet-a.csv): 7,500 naturally occurring adversarial images covering 200 classes. For a baseline comparison using the same 200 classes, refer to results-imagenet-a-clean.csv.
    • ImageNet-Rendition (results-imagenet-r.csv): 30,000 images representing renditions of 200 ImageNet classes. For a baseline comparison using the same 200 classes, refer to results-imagenet-r-clean.csv.
  10. Use Res2Net for image inference

    main

    To use a Res2Net model for inference, load a pretrained variant using timm.create_model, resolve the appropriate data configuration for preprocessing, and apply the transformation to your input image. Ensure you add a batch dimension before passing the tensor to the model.

    Common Res2Net variants include:

    • res2net101_26w_4s
    • res2net50_14w_8s
    • res2net50_26w_4s
    • res2net50_26w_6s
    • res2net50_26w_8s
    • res2net50_48w_2s
    import timm
    import torch
    import urllib
    from PIL import Image
    from timm.data import resolve_data_config
    from timm.data.transforms_factory import create_transform
    
    # 1. Load pretrained model
    model = timm.create_model('res2net101_26w_4s', pretrained=True)
    model.eval()
    
    # 2. Preprocess image
    config = resolve_data_config({}, model=model)
    transform = create_transform(**config)
    
    url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")
    urllib.request.urlretrieve(url, filename)
    img = Image.open(filename).convert('RGB')
    tensor = transform(img).unsqueeze(0) # transform and add batch dimension
    
    # 3. Get predictions
    with torch.inference_mode():
        out = model(tensor)
    probabilities = torch.nn.functional.softmax(out[0], dim=0)
  11. Finetune (Tensorflow) MixNet

    main

    To finetune a pretrained MixNet model for a specific number of classes, use timm.create_model and pass the num_classes argument. This automatically replaces the final classifier layer with a new one suitable for your target dataset.

    To perform the actual training, you should either write a custom training loop or adapt the existing timm training script.

    import timm
    # Replace NUM_FINETUNE_CLASSES with your target number of classes
    model = timm.create_model('tf_mixnet_l', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)