|
1 | 1 | <!--Copyright 2022 The HuggingFace Team. All rights reserved.
|
2 | 2 |
|
3 |
| -Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with |
4 |
| -the License. You may obtain a copy of the License at |
| 3 | +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at |
5 | 4 |
|
6 |
| -http://www.apache.org/licenses/LICENSE-2.0 |
| 5 | +[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) |
7 | 6 |
|
8 |
| -Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on |
9 |
| -an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the |
10 |
| -specific language governing permissions and limitations under the License. |
| 7 | +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |
11 | 8 |
|
12 |
| -⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be |
13 |
| -rendered properly in your Markdown viewer. |
| 9 | +⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. |
14 | 10 |
|
15 | 11 | -->
|
16 | 12 |
|
| 13 | + |
| 14 | + |
17 | 15 | # MobileViT
|
18 | 16 |
|
19 |
| -<div class="flex flex-wrap space-x-1"> |
20 |
| -<img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> |
21 |
| -<img alt="TensorFlow" src="https://img.shields.io/badge/TensorFlow-FF6F00?style=flat&logo=tensorflow&logoColor=white"> |
| 17 | + |
| 18 | +<div style="float: right;"> |
| 19 | + <div class="flex flex-wrap space-x-2"> |
| 20 | + <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> |
| 21 | + <img alt="TensorFlow" src="https://img.shields.io/badge/TensorFlow-FF6F00?style=flat&logo=tensorflow&logoColor=white"> |
| 22 | + </div> |
22 | 23 | </div>
|
23 | 24 |
|
24 |
| -## Overview |
| 25 | +[MobileViT](https://huggingface.co/papers/2110.02178) is a lightweight vision transformer for mobile devices that merges CNNs's efficiency and inductive biases with transformers global context modeling. It treats transformers as convolutions, enabling global information processing without the heavy computational cost of standard ViTs. |
25 | 26 |
|
26 |
| -The MobileViT model was proposed in [MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer](https://huggingface.co/papers/2110.02178) by Sachin Mehta and Mohammad Rastegari. MobileViT introduces a new layer that replaces local processing in convolutions with global processing using transformers. |
27 | 27 |
|
28 |
| -The abstract from the paper is the following: |
| 28 | +<div class="flex justify-center"> |
| 29 | + <img src = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/MobileViT.png"> |
| 30 | +</div> |
| 31 | + |
29 | 32 |
|
30 |
| -*Light-weight convolutional neural networks (CNNs) are the de-facto for mobile vision tasks. Their spatial inductive biases allow them to learn representations with fewer parameters across different vision tasks. However, these networks are spatially local. To learn global representations, self-attention-based vision trans-formers (ViTs) have been adopted. Unlike CNNs, ViTs are heavy-weight. In this paper, we ask the following question: is it possible to combine the strengths of CNNs and ViTs to build a light-weight and low latency network for mobile vision tasks? Towards this end, we introduce MobileViT, a light-weight and general-purpose vision transformer for mobile devices. MobileViT presents a different perspective for the global processing of information with transformers, i.e., transformers as convolutions. Our results show that MobileViT significantly outperforms CNN- and ViT-based networks across different tasks and datasets. On the ImageNet-1k dataset, MobileViT achieves top-1 accuracy of 78.4% with about 6 million parameters, which is 3.2% and 6.2% more accurate than MobileNetv3 (CNN-based) and DeIT (ViT-based) for a similar number of parameters. On the MS-COCO object detection task, MobileViT is 5.7% more accurate than MobileNetv3 for a similar number of parameters.* |
| 33 | +You can find all the original MobileViT checkpoints under the [Apple](https://huggingface.co/apple/models?search=mobilevit) organization. |
31 | 34 |
|
32 |
| -This model was contributed by [matthijs](https://huggingface.co/Matthijs). The TensorFlow version of the model was contributed by [sayakpaul](https://huggingface.co/sayakpaul). The original code and weights can be found [here](https://github.com/apple/ml-cvnets). |
33 | 35 |
|
34 |
| -## Usage tips |
| 36 | +> [!TIP] |
| 37 | +> - This model was contributed by [matthijs](https://huggingface.co/Matthijs) and the TensorFlow version was contributed by [sayakpaul](https://huggingface.co/sayakpaul). |
| 38 | +> |
| 39 | +> Click on the MobileViT models in the right sidebar for more examples of how to apply MobileViT to different vision tasks. |
35 | 40 |
|
36 |
| -- MobileViT is more like a CNN than a Transformer model. It does not work on sequence data but on batches of images. Unlike ViT, there are no embeddings. The backbone model outputs a feature map. You can follow [this tutorial](https://keras.io/examples/vision/mobilevit) for a lightweight introduction. |
37 |
| -- One can use [`MobileViTImageProcessor`] to prepare images for the model. Note that if you do your own preprocessing, the pretrained checkpoints expect images to be in BGR pixel order (not RGB). |
38 |
| -- The available image classification checkpoints are pre-trained on [ImageNet-1k](https://huggingface.co/datasets/imagenet-1k) (also referred to as ILSVRC 2012, a collection of 1.3 million images and 1,000 classes). |
39 |
| -- The segmentation model uses a [DeepLabV3](https://huggingface.co/papers/1706.05587) head. The available semantic segmentation checkpoints are pre-trained on [PASCAL VOC](http://host.robots.ox.ac.uk/pascal/VOC/). |
40 |
| -- As the name suggests MobileViT was designed to be performant and efficient on mobile phones. The TensorFlow versions of the MobileViT models are fully compatible with [TensorFlow Lite](https://www.tensorflow.org/lite). |
41 | 41 |
|
42 |
| - You can use the following code to convert a MobileViT checkpoint (be it image classification or semantic segmentation) to generate a |
43 |
| - TensorFlow Lite model: |
| 42 | +The example below demonstrates how to do [Image Classification] with [`Pipeline`] and the [`AutoModel`] class. |
44 | 43 |
|
45 |
| -```py |
46 |
| -from transformers import TFMobileViTForImageClassification |
47 |
| -import tensorflow as tf |
| 44 | +<hfoptions id="usage"> |
| 45 | +<hfoption id="Pipeline"> |
48 | 46 |
|
| 47 | +```python |
49 | 48 |
|
50 |
| -model_ckpt = "apple/mobilevit-xx-small" |
51 |
| -model = TFMobileViTForImageClassification.from_pretrained(model_ckpt) |
| 49 | +import torch |
| 50 | +from transformers import pipeline |
52 | 51 |
|
53 |
| -converter = tf.lite.TFLiteConverter.from_keras_model(model) |
54 |
| -converter.optimizations = [tf.lite.Optimize.DEFAULT] |
55 |
| -converter.target_spec.supported_ops = [ |
56 |
| - tf.lite.OpsSet.TFLITE_BUILTINS, |
57 |
| - tf.lite.OpsSet.SELECT_TF_OPS, |
58 |
| -] |
59 |
| -tflite_model = converter.convert() |
60 |
| -tflite_filename = model_ckpt.split("/")[-1] + ".tflite" |
61 |
| -with open(tflite_filename, "wb") as f: |
62 |
| - f.write(tflite_model) |
| 52 | +classifier = pipeline( |
| 53 | + task="image-classification", |
| 54 | + model="apple/mobilevit-small", |
| 55 | + torch_dtype=torch.float16, device=0, |
| 56 | +) |
| 57 | + |
| 58 | +preds = classifier("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg") |
| 59 | +print(f"Prediction: {preds}\n") |
63 | 60 | ```
|
64 | 61 |
|
65 |
| - The resulting model will be just **about an MB** making it a good fit for mobile applications where resources and network |
66 |
| - bandwidth can be constrained. |
| 62 | +</hfoption> |
| 63 | + |
| 64 | +<hfoption id="AutoModel"> |
| 65 | + |
| 66 | +```python |
| 67 | + |
| 68 | +import torch |
| 69 | +import requests |
| 70 | +from PIL import Image |
| 71 | +from transformers import AutoImageProcessor, MobileViTForImageClassification |
| 72 | + |
| 73 | +image_processor = AutoImageProcessor.from_pretrained( |
| 74 | + "apple/mobilevit-small", |
| 75 | + use_fast=True, |
| 76 | +) |
| 77 | +model = MobileViTForImageClassification.from_pretrained("apple/mobilevit-small") |
| 78 | + |
| 79 | +url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" |
| 80 | +image = Image.open(requests.get(url, stream=True).raw) |
| 81 | +inputs = image_processor(image, return_tensors="pt").to("cuda") |
| 82 | + |
| 83 | +with torch.no_grad(): |
| 84 | + logits = model(**inputs).logits |
| 85 | +predicted_class_id = logits.argmax(dim=-1).item() |
| 86 | + |
| 87 | +class_labels = model.config.id2label |
| 88 | +predicted_class_label = class_labels[predicted_class_id] |
| 89 | +print(f"The predicted class label is:{predicted_class_label}") |
| 90 | +``` |
| 91 | + |
| 92 | +</hfoption> |
| 93 | +</hfoptions> |
| 94 | + |
| 95 | + |
67 | 96 |
|
68 |
| -## Resources |
69 | 97 |
|
70 |
| -A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with MobileViT. |
| 98 | +## Notes |
71 | 99 |
|
72 |
| -<PipelineTag pipeline="image-classification"/> |
| 100 | +- Does **not** operate on sequential data, it's purely designed for image tasks. |
| 101 | +- Feature maps are used directly instead of token embeddings. |
| 102 | +- Use [`MobileViTImageProcessor`] to preprocess images. |
| 103 | +- If using custom preprocessing, ensure that images are in **BGR** format (not RGB), as expected by the pretrained weights. |
| 104 | +- The classification models are pretrained on [ImageNet-1k](https://huggingface.co/datasets/imagenet-1k). |
| 105 | +- The segmentation models use a [DeepLabV3](https://huggingface.co/papers/1706.05587) head and are pretrained on [PASCAL VOC](http://host.robots.ox.ac.uk/pascal/VOC/). |
| 106 | +- TensorFlow versions are compatible with TensorFlow Lite, making them ideal for edge/mobile deployment. |
73 | 107 |
|
74 |
| -- [`MobileViTForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). |
75 |
| -- See also: [Image classification task guide](../tasks/image_classification) |
76 | 108 |
|
77 |
| -**Semantic segmentation** |
78 |
| -- [Semantic segmentation task guide](../tasks/semantic_segmentation) |
79 | 109 |
|
80 |
| -If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. |
81 | 110 |
|
| 111 | + |
82 | 112 | ## MobileViTConfig
|
83 | 113 |
|
84 | 114 | [[autodoc]] MobileViTConfig
|
@@ -138,4 +168,4 @@ If you're interested in submitting a resource to be included here, please feel f
|
138 | 168 | - call
|
139 | 169 |
|
140 | 170 | </tf>
|
141 |
| -</frameworkcontent> |
| 171 | +</frameworkcontent> |
0 commit comments