Get lightning-fast inference, quick quantization, torch.compile boosts, and effortless fine-tuning for any timm model—all within the friendly 🤗 transformers ecosystem.
Enter TimmWrapper—a simple, yet powerful tool that unlocks this potential.
To follow along with this blog post, install the latest version of transformers and timm by running:. (Related: Fine-Tune XLSR-Wav2Vec2 for low-resource ASR with 🤗 Tra...)
Check out the full repository for all code examples and notebooks: 🔗 TimmWrapper Examples.
The PyTorch Image Models (timm) library offers a rich collection of state-of-the-art computer vision models, along with useful layers, utilities, optimizers, and data augmentations. With more than 32K GitHub stars and more than 200K daily downloads at the time of writing, it's a go-to resource for image classification and feature extraction for object detection, segmentation, image search, and other downstream tasks. (Related: Tech Report: Accelerating PyTorch Transformers with Int...)
With pre-trained models covering a wide range of architectures, timm simplifies the workflow for computer vision practitioners.
While 🤗 transformers supports several vision models, timm offers an even broader collection, including many mobile-friendly and efficient models not available in transformers.
The timm integration bridges this gap, bringing the best of both worlds:.
Industry observers note that one of the standout features of the timm integration is that it allows you to leverage the 🤗 pipeline API. The pipeline API abstracts away a lot of complexity, making it easy to load a pre-trained model, perform inference, and view results with a few lines of code.
According to recent reports, let's see how to use a transformers pipeline with the MobileNetV4. This architecture does not have a native transformers implementation, but can be easily used from timm:.
Sources indicate that want to quickly create an interactive web app for image classification? Gradio makes it simple to build a user-friendly interface with minimal code. Let's combine Gradio with the pipeline API to classify food images using a fine-tuned timm ViT model (we will cover fine tuning in a later section).
Here’s how you can set up a quick demo with a timm model:.
It has been revealed that here’s a live example hosted on Hugging Face Spaces. You can test it directly in your browser!
The 🤗 transformers library provides Auto Classes to abstract away the complexity of loading models and processors. With the TimmWrapper, you can use AutoModelForImageClassification and AutoImageProcessor to load any timm model effortlessly.
Recent findings suggest that quantization is a powerful technique to reduce model size and speed up inference, especially for deployment on resource-constrained devices. With the timm integration, you can quantize any timm model on the fly with just a few lines of code using BitsAndBytesConfig from bitsandbytes.
Here’s how simple it is to quantize a timm model:.
Quantized models perform almost identically to full-precision models during inference:.
Fine-tuning a timm model with the Trainer API from 🤗 transformers is straightforward and highly flexible. You can fine-tune your model on custom datasets using the Trainer class, which handles the training loop, logging, and evaluation. Additionally, you can fine-tune using LoRA (Low-Rank Adaptation) to train efficiently with fewer parameters.
This section gives a quick overview of both standard fine-tuning and LoRA fine-tuning, with links to the complete code.
The Trainer API makes it easy to set up training with minimal code. Here's an outline of what a fine-tuning setup looks like:.
What's remarkable about this approach is that it mirrors the exact workflow used for native transformers models, maintaining consistency across different model types.
Industry observers note that this means you can use the familiar Trainer API to fine-tune not just Transformers models, but also any timm model—bringing powerful models from the timm library into the Hugging Face ecosystem with minimal adjustments. This significantly broadens the scope of models you can fine-tune using the same trusted tools and workflows.
Model Example:Fine-tuned ViT on Food-101: vit_base_patch16_224.augreg2_in21k_ft_in1k.ft_food101.
LoRA (Low-Rank Adaptation) allows you to fine-tune large models efficiently by training only a few additional parameters, rather than the full set of model weights. This makes fine-tuning faster, and allows the use of consumer hardware. You can fine-tune a timm model using LoRA with the PEFT library.
Trainable Parameters with LoRA:.
Model Example:LoRA Fine-Tuned ViT on Food-101: vit_base_patch16_224.augreg2_in21k_ft_in1k.lora_ft_food101.
LoRA is just one example of efficient adapter-based fine-tuning methods you can apply to timm models. The integration of timm with the 🤗 ecosystem opens up a wide variety of parameter-efficient fine-tuning (PEFT) techniques, allowing you to choose the method that best fits your use case.
Once the model is LoRA fine-tuned, we only push the adapter weights to the Hugging Face Hub. This section helps you to download the adapter weights, merge the adapter weights with the base model, and then perform inference.
It has been revealed that one of Ross' (creator of timm) favourite features is that this integration maintains full 'round-trip' compatibility. Namely, using the wrapper one can fine-tune a timm model on a newly introduced dataset using transformer's Trainer, publish the resulting model to the Hugging Face hub, and then load the fine-tuned model in timm again using timm.create_model('hf-hub:my_org/my_fine_tuned_model', pretrained=True).
Let us see how we can load our fine tuned model ariG23498/vit_base_patch16_224.augreg2_in21k_ft_in1k.ft_food101 with timm.
It has been revealed that with torch.compile in PyTorch 2.0, you can achieve faster inference by compiling your model with just one line of code. The timm integration is fully compatible with torch.compile. Here's a quick benchmark to compare inference time with and without torch.compile using the TimmWrapper.
timm's integration with transformers opens fresh doors for leveraging state-of-the-art vision models with minimal effort. Whether you're looking to fine-tune, quantize, or simply run inference, this integration provides a unified API to streamline your workflow.
Start exploring today and unlock newly introduced possibilities in computer vision!
Recent findings suggest that we want to give a huge shout-out to the folks who made this integration happen in Transformers PR #34564. In no particular order, a big thanks to Pavel Iakubovskii, Ross Wightman, Lysandre Debut, Pablo Montalvo, Arthur Zucker, and Amy Roberts for all your incredible work. Your combined efforts took this feature from an idea to something everyone can now enjoy!
This is amazing! Congrats @rwightman @lysandre @ArthurZ @Molbap @amyeroberts @ariG23498 & @qubvel-hf 🔥.
Very excited for this, thank you! We were just about to switch to timm and this makes it even easier!
Maybe a simple naive question, I'm trying to put together a demo training script that loads the base model from:TimmWrapperForImageClassification.from_pretrained("timm/mobilenetv4_conv_medium.e500_r256_in1k").to("cuda").
but then trains on the food101 dataset, just to illustrate training on a fresh custom dataset. Training works fine, but inference return animal names as labels.
According to recent reports, should I be setting: label2id, num_labels, id2label, params when I load the finetuned model? It seems to store the data somewhere during training, but trainingarguments don't allow me to set TypeError: TrainingArguments.__init__() got an unexpected keyword argument 'label2id'.
@davidrs hmm, possible there's an matter with the label handling, there was a change made to the integration near release to keep the labels compatible with timm use (keep label_names field instead of id2label/label2id), there's actually a mix of the two cases and many of @ariG23498 fine-tunes have the id2label, though I was told at release time it should be producing label_names...
Recent findings suggest that do you have a public model I could look at? You're using the example image classification script in Transformers (https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) or using Trainer directly yourself in a custom script/notebook as in the example above?
My bad, I missed the top blog link with more complete code examples, maybe that would help me https://github.com/ariG23498/timm-wrapper-examples/blob/main/%2304_sft.ipynb.
Trainer directly in custom script, I made a Colab notebook that illustrates what I'm currently trying, in the prediction test at the end the labels are not food:https://colab.research.google.com/drive/14jTpetYR61B6EVoJ6o8_B8gi6-SiizCA?usp=sharing.
@davidrs this part in the example to reset classifier / labels with the target dataset is crucial.
If you don't do that I believe it gets pushed with the original labels, an imagenet-1k (1000) class classifier, etc. Though I guess the lowest 'n' classes that are in the fresh dataset would be fine-tuned with the target (if it's less, it'd crash if the new dataset has more classes).
FWIW, I just found a bug in the pipeline, it's applying sigmoid instead of softmax by default due to a bug (https://github.com/huggingface/transformers/pull/35848), so add function_to_apply='softmax' if you want softmax probs... this is not specific to the timm integration and looks like it's been there a while. I did confirm that if you set the labels as above the fine-tuned timm model will predict with the correct labels and should push to hub with those as well...
How to integrate with Optimum and load the onnx version of the model.