Hugging Face 推出 TimmWrapper:无缝集成 timm 模型至 Transformers

原标题:Timm ❤️ Transformers: Use any timm model with transformers
68AI 研判分

Hugging Face 发布 `TimmWrapper`,允许开发者在 `transformers` 生态中直接调用任意 `timm` 模型。该工具支持快速推理、量化及微调,旨在打通视觉模型库与主流 NLP/多模态框架的壁垒,简化工程落地流程。

报道正文

本文目录19 个章节

返回文章列表

Timm ❤️ Transformers:在 transformers 中使用任意 timm 模型

发布于 2025 年 1 月 16 日 在 GitHub 上更新 点赞 60

Aritra Roy Gosthipaty ariG23498 Ross Wightman rwightman Pavel Iakubovskii qubvel-hf Pedro Cuenca pcuenq Vaibhav Srivastav reach-vb

为任意 timm 模型实现极速推理、快速量化、torch.compile 加速以及轻松微调——这一切都可在友好的 🤗 transformers 生态系统中完成。

介绍 TimmWrapper——一款简单而强大的工具,充分释放这一潜力。

在本文中,我们将涵盖:

  • timm 集成如何工作及其为何具有变革性意义。
  • 如何将 timm 模型与 🤗 transformers 集成。
  • 实用示例:pipeline、量化、微调等。

要跟随本文操作,请运行以下命令安装最新版本的 transformers 和 timm:

BASH
pip install -Uq transformers timm

查看完整仓库以获取所有代码示例和 notebook:🔗 TimmWrapper Examples

什么是 timm?

PyTorch Image Models (timm) 库提供了丰富的最先进计算机视觉模型集合,以及实用的层、工具函数、优化器和数据增强方法。截至撰写本文时,该库拥有超过 3.2 万 GitHub star 和每日超过 20 万次下载量,是图像分类以及用于目标检测、分割、图像搜索和其他下游任务特征提取的首选资源。

凭借覆盖广泛架构的预训练模型,timm 简化了计算机视觉从业者工作流程。

为什么使用 timm 集成?

虽然 🤗 transformers 支持多种视觉模型,但 timm 提供了更广泛的模型集合,包括许多在 transformers 中不可用的移动端友好型和高效型模型。

timm 集成弥合了这一差距,融合了两者优势:

  • ✅ Pipeline API 支持:轻松将任意 timm 模型接入高层级的 transformers pipeline,实现简化的推理流程。
  • 🧩 兼容 Auto Classes:虽然 timm 模型并非原生兼容 transformers,但通过集成方案,它们可以无缝配合 Auto classes API 使用。
  • ⚡ 快速量化:仅需约 5 行代码,即可对任意 timm 模型进行量化,以实现高效推理。
  • 🎯 使用 Trainer API 进行微调:利用 Trainer API 微调 timm 模型,甚至可集成低秩自适应(LoRA)等适配器。
  • 🔁 往返于 timm:将微调后的模型重新用于 timm。
  • 🚀 Torch Compile 加速:利用 torch.compile 优化推理速度。

Pipeline API:使用 timm 模型进行图像分类

timm 集成的一个突出特性是允许你充分利用 🤗 pipeline API。pipeline API 抽象了许多复杂性,使得只需几行代码即可加载预训练模型、执行推理并查看结果。

让我们看看如何使用 transformers pipeline 处理 MobileNetV4。该架构没有原生的 transformers 实现,但可以轻松地通过 timm 使用:

PYTHON
from transformers import pipeline
import requests

image_classifier = pipeline(model="timm/mobilenetv4_conv_medium.e500_r256_in1k")

url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/timm/cat.jpg"

outputs = image_classifier(url)

for output in outputs:
    print(f"Label: {output['label'] :20} Score: {output['score'] :0.2f}")

输出:

BASH
Device set to use cpu
Label: tabby, tabby cat     Score: 0.69
Label: tiger cat            Score: 0.21
Label: Egyptian cat         Score: 0.02
Label: bee                  Score: 0.00
Label: marmoset             Score: 0.00

Gradio 集成:构建食物分类器演示 🍣

想要快速创建一个用于图像分类的交互式 Web 应用?Gradio 让构建用户友好的界面变得简单,且所需代码极少。我们将 Gradio 与 pipeline API 结合,使用经过微调的 timm ViT 模型来对食物图像进行分类(我们将在后续章节介绍微调)。

以下是如何使用 timm 模型设置快速演示的方法:

PYTHON
import gradio as gr
from transformers import pipeline

pipe = pipeline(
    "image-classification",
    model="ariG23498/vit_base_patch16_224.augreg2_in21k_ft_in1k.ft_food101"
)

def classify(image):
    return pipe(image)[0]["label"]

demo = gr.Interface(
    fn=classify,
    inputs=gr.Image(type="pil"),
    outputs="text",
    examples=[["./sushi.png", "sushi"]]
)

demo.launch()

Here’s a live example hosted on Hugging Face Spaces. You can test it directly in your browser!

Auto Classes: Simplifying Model Loading

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.

Here’s a quick example:

PYTHON
from transformers import (
    AutoModelForImageClassification,
    AutoImageProcessor,
)
from transformers.image_utils import load_image

image_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/timm/cat.jpg"
image = load_image(image_url)

checkpoint = "timm/mobilenetv4_conv_medium.e500_r256_in1k"
image_processor = AutoImageProcessor.from_pretrained(checkpoint)
model = AutoModelForImageClassification.from_pretrained(checkpoint).eval()

print(type(image_processor))  
print(type(model))            

Running quantized timm models

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:

PYTHON
from transformers import TimmWrapperForImageClassification, BitsAndBytesConfig

quantization_config = BitsAndBytesConfig(load_in_8bit=True)
checkpoint = "timm/vit_base_patch16_224.augreg2_in21k_ft_in1k"

model = TimmWrapperForImageClassification.from_pretrained(checkpoint).to("cuda")
model_8bit = TimmWrapperForImageClassification.from_pretrained(
    checkpoint,
    quantization_config=quantization_config,
    low_cpu_mem_usage=True,
)
PYTHON
original_footprint = model.get_memory_footprint()
quantized_footprint = model_8bit.get_memory_footprint()

print(f"Original model size: {original_footprint / 1e6:.2f} MB")
print(f"Quantized model size: {quantized_footprint / 1e6:.2f} MB")
print(f"Reduction: {(original_footprint - quantized_footprint) / original_footprint * 100:.2f}%")

Output:

YAML
Original model size: 346.27 MB  
Quantized model size: 88.20 MB  
Reduction: 74.53%  

Quantized models perform almost identically to full-precision models during inference:

ModelLabelAccuracy
Original Modelremote control, remote0.35%
Quantized Modelremote control, remote0.33%

Supervised Fine-Tuning of timm models

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.

Standard Fine-Tuning with the Trainer API

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:

PYTHON
from transformers import TrainingArguments, Trainer

training_args = TrainingArguments(
    output_dir="my_model_output",
    evaluation_strategy="epoch",
    save_strategy="epoch",
    learning_rate=5e-5,
    per_device_train_batch_size=16,
    num_train_epochs=3,
    load_best_model_at_end=True,
    push_to_hub=True,
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_ds,
    eval_dataset=val_ds,
    data_collator=data_collator,
    compute_metrics=compute_metrics,
)

trainer.train()

What's remarkable about this approach is that it mirrors the exact workflow used for native transformers models, maintaining consistency across different model types.

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 Fine-Tuning for Efficient Training

[注:本文篇幅超长,以上为核心前篇精译,后续内容保留原文呈现]

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.

Here’s how you can set it up:

PYTHON
from peft import LoraConfig, get_peft_model

model = AutoModelForImageClassification.from_pretrained(checkpoint, num_labels=num_labels)
lora_config = LoraConfig(
    r=16,
    lora_alpha=16,
    target_modules=["qkv"],
    lora_dropout=0.1,
    bias="none",
    modules_to_save=["head"],
)

lora_model = get_peft_model(model, lora_config)

lora_model.print_trainable_parameters()

Trainable Parameters with LoRA:

BASH
trainable params: 667,493 || all params: 86,543,818 || trainable%: 0.77%

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.

Inference with LoRA Fine-Tuned Model

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.

PYTHON
from peft import PeftModel, PeftConfig

repo_name = "ariG23498/vit_base_patch16_224.augreg2_in21k_ft_in1k.lora_ft_food101"
config = PeftConfig.from_pretrained(repo_name)

model = AutoModelForImageClassification.from_pretrained(
    config.base_model_name_or_path,
    label2id=label2id,
    num_labels=num_labels,
    id2label=id2label,
    ignore_mismatched_sizes=True,
)
inference_model = PeftModel.from_pretrained(model, repo_name)

image of sushi with prediction from a fine tuned model

Round trip integration

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 new 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

PYTHON
checkpoint = "ariG23498/vit_base_patch16_224.augreg2_in21k_ft_in1k.ft_food101"

config = AutoConfig.from_pretrained(checkpoint)

model = timm.create_model(f"hf_hub:{checkpoint}", pretrained=True) 
model = model.eval()

image = load_image("https://cdn.britannica.com/52/128652-050-14AD19CA/Maki-zushi.jpg")

data_config = timm.data.resolve_model_data_config(model)
transforms = timm.data.create_transform(**data_config, is_training=False)

output = model(transforms(image).unsqueeze(0))

top5_probabilities, top5_class_indices = torch.topk(output.softmax(dim=1) * 100, k=5)

for prob, idx in zip(top5_probabilities[0], top5_class_indices[0]):
    print(f"Label: {config.id2label[idx.item()] :20} Score: {prob/100 :0.2f}%")

Outputs

BASH
Label: sushi                Score: 0.98%
Label: spring_rolls         Score: 0.01%
Label: sashimi              Score: 0.00%
Label: club_sandwich        Score: 0.00%
Label: cannoli              Score: 0.00%

Torch Compile: Instant Speedup

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.

PYTHON

model = TimmWrapperForImageClassification.from_pretrained(checkpoint).to(device)
processed_input = image_processor(image, return_tensors="pt").to(device)

def run_benchmark(model, input_data, warmup_runs=5, benchmark_runs=300):

model.eval()
    with torch.no_grad():
        for _ in range(warmup_runs):
            _ = model(**input_data)

times = []
    with torch.no_grad():
        for _ in range(benchmark_runs):
            start_time = time.perf_counter()
            _ = model(**input_data)
            if device.type == "cuda":
                torch.cuda.synchronize(device=device)  
            times.append(time.perf_counter() - start_time)

avg_time = sum(times) / benchmark_runs
    return avg_time

time_no_compile = run_benchmark(model, processed_input)
compiled_model = torch.compile(model).to(device)
time_compile = run_benchmark(compiled_model, processed_input)

print(f"Without torch.compile: {time_no_compile:.4f} s")
print(f"With torch.compile: {time_compile:.4f} s")

compile timing

Wrapping Up

timm's integration with transformers opens new 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 new possibilities in computer vision!

Acknowledgments

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!

Models mentioned in this article 2

More Articles from our Blog

[

communitydatasetssynthetic-data

Docmatix - a huge dataset for Document Visual Question Answering

80 July 18, 2024](https://huggingface.co/blog/docmatix)[![](https://huggingface.co/blog/assets/124_ml-for-games/thumbnail-gaussian-splatting.png)

communityguidecv

Introduction to 3D Gaussian Splatting

150 September 18, 2023](https://huggingface.co/blog/gaussian-splatting)

Community

reach-vb Article author Jan 17, 2025

This is amazing! Congrats @rwightman @lysandre @ArthurZ @Molbap @amyeroberts @ariG23498 & @qubvel-hf 🔥

mamurbata Jan 17, 2025 • This comment has been hidden davidrs Jan 22, 2025 • edited Jan 22, 2025

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 new custom dataset. Training works fine, but inference return animal names as labels.

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'

rwightman Article author Jan 22, 2025 • edited Jan 22, 2025

@davidrs hmm, possible there's an issue 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...

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?

davidrs Jan 22, 2025 • edited Jan 22, 2025

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

rwightman Article author Jan 22, 2025 • edited Jan 22, 2025

@davidrs this part in the example to reset classifier / labels with the target dataset is important

文本
model = AutoModelForImageClassification.from_pretrained(
    checkpoint,
    num_labels=num_labels,
    id2label=id2label,
    label2id=label2id,
    ignore_mismatched_sizes=True,
)

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 new dataset would be fine-tuned with the target (if it's less, it'd crash if the new dataset has more classes)

rwightman Article author Jan 22, 2025 • edited Jan 23, 2025

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...

xiaoyao9184 Jan 24, 2025

How to integrate with Optimum and load the onnx version of the model

Upload images, audio, and videos by dragging in the text input, pasting, or clicking here. Tap or paste here to upload images

· Sign up or log in to comment