---
title: cv_vitb16_classification_vision-efficient-tuning-utuning
canonical_url: "https://www.modelscope.cn/models/iic/cv_vitb16_classification_vision-efficient-tuning-utuning"
md_url: "https://www.modelscope.cn/models/iic/cv_vitb16_classification_vision-efficient-tuning-utuning.md"
repository: iic/cv_vitb16_classification_vision-efficient-tuning-utuning
chinese_name: "基础视觉模型高效调优-UTuning"
last_updated: 2023-03-16
license: "Apache License 2.0"
pipeline_tag: vision-efficient-tuning
tasks:
  - vision-efficient-tuning
model_type:
  - Transformer
library_name:
  - pytorch
frameworks:
  - pytorch
domain:
  - cv
downloads: 34325
stars: 13
tags:
  - Alibaba
  - U-Tuning
  - "Vision Transformer"
  - "Parameter-efficient Transfer Learning"
---

# cv_vitb16_classification_vision-efficient-tuning-utuning

> cv_vitb16_classification_vision-efficient-tuning-utuning - iic 在 ModelScope 开源的模型。论文链接：Rethinking Efficient Tuning Methods from a Unified Perspective（arXiv）

iic/cv_vitb16_classification_vision-efficient-tuning-utuning 是 ModelScope 魔搭社区上的vision-efficient-tuning模型，采用 Apache License 2.0 许可。

- **Repository**: iic/cv_vitb16_classification_vision-efficient-tuning-utuning
- **License**: Apache License 2.0
- **Tasks**: vision-efficient-tuning
- **Tags**: Alibaba, U-Tuning, Vision Transformer, Parameter-efficient Transfer Learning
- **Downloads**: 34325
- **Stars**: 13
- **Last updated**: 2023-03-16

Source: https://www.modelscope.cn/models/iic/cv_vitb16_classification_vision-efficient-tuning-utuning

---

# 基础视觉模型高效调优：U-Tuning

**论文链接：**[Rethinking Efficient Tuning Methods from a Unified Perspective](https://arxiv.org/abs/2303.00690)**（arXiv）**

本工作从统一的角度对现有参数高效迁移学习方法（Parameter-efficient Transfer Learning, PETL）进行重新思考。一方面，进一步审视了现有的调优范式，提出了主流调优方法的并行化形式，以降低了模型结构的耦合度。另一方面，为参数高效的迁移学习提供了一个统一的框架，称之为U-Tuning（Unified Tuning）。

U-Tuning由具有冻结参数的操作（OP）和统一的轻量化可训练结构（U-Tuner）组成（见下图），该框架允许灵活插入或移除可训练的调优结构，不仅可以覆盖大多数现有方法，还可以推导出新的调优结构。该框架具备足够的通用性，并且派生的新结构在各种下游任务上实现了相当或更好的性能。

该页面展示了U-Tuning在图像分类任务上的应用，即给定一张图片，返回候选类别中的分类标签及置信度。

<center> <img src="./description/sketch_clean.png" alt="UTuning" width="400"/> <br> <div style="color:orange; border-bottom: 1px solid #d9d9d9; display: inline-block; color: #999; padding: 1px;">现有方法（左）和统一框架（右）的对比</div> </center>


## 模型描述

U-Tuning框架将统一公式中的Transformer的每个部分视为一个具有冻结预训练参数的操作函数OP，而每个调优部分则视为一个具有可学习参数的统一调优器U-Tuner。

当我们用类似的操作实例化OP和U-Tuner时，该公式覆盖所有现有的调优方法。同时，当我们用不同的构建模块实例化它们时，可以组合生成新的参数高效迁移方法。此外，与调优结构仅附加到操作子集的现有调整方法相比（如仅附加到MHA或仅附加到FFN），本方法可以将U-Tuner附加到所有操作（MHA和FFN）或甚至是Transformer Block。

具体两部分的实例化过程如下图：

<center> <img src="./description/UTuning_clean.png" alt="UTuning" width="800"/> <br> <div style="color:orange; border-bottom: 1px solid #d9d9d9; display: inline-block; color: #999; padding: 1px;">OP的实例化（左）和U-Tuner的实例化（右）以解耦的方式分别进行，两者均可以多项任意组合</div> </center>



## 期望模型使用方式以及适用范围

### 如何使用

基于 ModelScope 框架，通过调用预定义的 Pipeline 可实现快速调用。


#### 代码范例

```python
from modelscope.pipelines import pipeline

utuning_pipeline = pipeline('vision-efficient-tuning',
                            'damo/cv_vitb16_classification_vision-efficient-tuning-utuning',
                             model_revision='v1.0.0')
result = utuning_pipeline('https://modelscope.oss-cn-beijing.aliyuncs.com/test/images/vision_efficient_tuning_test_1.png')
print(f'Output: {result}.')            
```


### 模型局限性以及可能的偏差

- 本模型基于公开的[CIFAR100](https://www.cs.toronto.edu/~kriz/cifar.html)通用数据集训练，且仅适用于训练数据的覆盖类别，在具体应用场景下可能存在偏差。
- 本模型当前仅用于图像分类任务，同时该方法可用于其他模态输入（如文本、视频等）和其他视觉下游任务（如检测、分割等）。
- 本模型仅展示了U-Tuning方法的一种实例化形式，即原生Prefix、Prompt附加在MHA模块，原生Adapter附加在FFN模块；同时将各种调优方法进行并行化改进的展现形式将在后续的版本中发布，敬请关注。

## 训练数据介绍

1. [CIFAR100](https://www.cs.toronto.edu/~kriz/cifar.html) 通用图像分类数据集，包含100个类别。
2. [CUB-200-2011](https://www.vision.caltech.edu/datasets/cub_200_2011) 鸟类细粒度分类数据集，包含200个类别。
3. [NABirds](https://dl.allaboutbirds.org/nabirds) 鸟类细粒度分类数据集，包含555个类别。
4. [Oxford Flowers](https://www.robots.ox.ac.uk/~vgg/data/flowers/102/) 花卉细粒度分类数据集，包含102个类别。
5. [Stanford Cars](https://ai.stanford.edu/~jkrause/cars/car_dataset.html) 车辆细粒度分类数据集，包含196个类别。
6. [Stanford Dogs](http://vision.stanford.edu/aditya86/ImageNetDogs/) 犬类细粒度分类数据集，包含120个类别。


## 数据评估及结果

模型分别在不同的预训练模型和图像分类数据集下进行评估，结果如下：

|     Dataset     | ViT-B/16 (IN-21K) |
|:---------------:|:-----------------:|
|     CIFAR100    |       92.75%      |
|   CUB-200-2011  |       89.16%      |
|     NABirds     |       85.39%      |
| Oxford Flowers  |       99.15%      |
|  Stanford Cars  |       84.14%      |
|  Stanford Dogs  |       92.07%      |
|     Average     |       90.44%      |

其中，ViT-B/16模型使用 [ImageNet-21K](https://storage.googleapis.com/vit_models/imagenet21k/ViT-B_16.npz) 作为预训练模型

## 模型训练和验证

本模型训练过程仅实现了U-Tuning方法的一种实例化组合形式。将各种调优方法进行并行化的实现将在后续的版本中发布，敬请关注。

以下为使用[FME Benchmark](https://modelscope.cn/datasets/damo/foundation_model_evaluation_benchmark/summary)中的子数据集[OxfordFlowers](https://www.robots.ox.ac.uk/~vgg/data/flowers/102/)[[点击预览](https://modelscope.cn/datasets/damo/foundation_model_evaluation_benchmark/dataPeview)]进行finetune训练和评测的示例代码：

```python
import tempfile
from modelscope.msdatasets import MsDataset
from modelscope.metainfo import Trainers
from modelscope.trainers import build_trainer
from modelscope.utils.constant import DownloadMode

# 模型ID
model_id = 'damo/cv_vitb16_classification_vision-efficient-tuning-utuning'

# 加载训练集
ms_train_dataset = MsDataset.load(
    'foundation_model_evaluation_benchmark', 
    namespace='damo',
    subset_name='OxfordFlowers', 
    split='train',
	download_mode=DownloadMode.FORCE_REDOWNLOAD)   

# 加载验证集
ms_eval_dataset = MsDataset.load(
    'foundation_model_evaluation_benchmark', 
    namespace='damo',
    subset_name='OxfordFlowers', 
    split='eval',
	download_mode=DownloadMode.FORCE_REDOWNLOAD)      

tmp_dir = tempfile.TemporaryDirectory().name # 使用临时目录作为工作目录

# 修改配置文件
def cfg_modify_fn(cfg):
    max_epochs = 1                            # 最大训练轮次
    cfg.model.head.num_classes = 102          # 类别数
    cfg.model.finetune = True                 # 进行微调
    cfg.train.max_epochs = max_epochs         # 最大训练轮次
    cfg.train.lr_scheduler.T_max = max_epochs # 学习率调度器的参数
    return cfg

# 构建训练器
kwargs = dict(
    model=model_id,                 # 模型id
    work_dir=tmp_dir,               # 工作目录
    train_dataset=ms_train_dataset, # 训练集  
    eval_dataset=ms_eval_dataset,   # 验证集
    cfg_modify_fn=cfg_modify_fn     # 用于修改训练配置文件的回调函数
)
trainer = build_trainer(name=Trainers.vision_efficient_tuning, default_args=kwargs)

# 进行训练
trainer.train()

# 进行评估
result = trainer.evaluate()
print('result:', result)
```

训练说明见示例代码中的注释部分，详细的训练说明和用法见官方的[训练文档](https://modelscope.cn/docs/%E6%A8%A1%E5%9E%8B%E7%9A%84%E8%AE%AD%E7%BB%83Train)。

## 相关论文以及引用信息


如果该模型对您有所帮助，请引用下面的相关的论文：

```BibTeX
@article{jiang2023utuning,
  title={Rethinking Efficient Tuning Methods from a Unified Perspective},
  author={Jiang, Zeyinzi and Mao, Chaojie and Huang, Ziyuan and Lv, Yiliang and Zhao, Deli and Zhou, Jingren},
  journal={arXiv preprint arXiv:2303.00690},
  year={2023}
}
```
