File size: 16,577 Bytes
b9c04f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
---
license: apache-2.0
pipeline_tag: mask-generation
library_name: onnx
tags:
- onnx
- moonbox
- onnxruntime
- mobilesam
- segment-anything
- sam
- image-segmentation
- promptable-segmentation
---

# MobileSAM v2 ONNX

ONNX builds of [MobileSAM v2](https://github.com/ChaoningZhang/MobileSAM), made by Moonbox for on-device use with ONNX Runtime (CPU, CUDA, DirectML). Each
precision is one folder holding the graphs and a small Python `pipeline.py` that does the rest (image preprocessing,
prompt coordinates, mask upsampling); what the graphs take and return is under *How to run*.

## Files

The last column is the benchmark against the original PyTorch model (details under *How to run*): IoU of every
predicted mask with the original's on the same pictures and prompts.

| Precision | File | Size | sha256 | Benchmark |
|---|---|---|---|---|
| fp16 | [`fp16/decoder.onnx`](https://huggingface.co/moonbox-dev/MobileSAM-ONNX/blob/main/fp16/decoder.onnx) | 16.5 MB | `6d0602745ee8` | encoder fp16, decoder fp32: mask IoU 0.998 mean / 0.977 worst (fp32 graphs 0.99999 / 0.99998) |
| fp16 | [`fp16/encoder.onnx`](https://huggingface.co/moonbox-dev/MobileSAM-ONNX/blob/main/fp16/encoder.onnx) | 14.1 MB | `69e5ab89f4aa` | encoder fp16, decoder fp32: mask IoU 0.998 mean / 0.977 worst (fp32 graphs 0.99999 / 0.99998) |
| fp16 | [`fp16/pipeline.py`](https://huggingface.co/moonbox-dev/MobileSAM-ONNX/blob/main/fp16/pipeline.py) | 4.2 kB | `7fcc838b105a` | encoder fp16, decoder fp32: mask IoU 0.998 mean / 0.977 worst (fp32 graphs 0.99999 / 0.99998) |

## How to run

MobileSAM (the promptable segmenter of MobileSAM v2: a TinyViT-5M image encoder with SAM's prompt encoder and mask
decoder, 9.8 M parameters) as two ONNX graphs plus `pipeline.py`, a numpy runtime that reproduces the repository's
`SamPredictor` around them. MobileSAM v2's object-aware prompt sampler (an ultralytics YOLOv8, AGPL-3.0, weights only
on Google Drive) and its prompt-guided decoder (a pickled `nn.Module`, which would need unsafe unpickling to read) are
not included.

- `encoder.onnx`: `image` [1, 3, 1024, 1024] (normalised, padded) -> `image_embeddings` [1, 256, 64, 64]. Run it once
  per image.
- `decoder.onnx`: the repository's own `SamOnnxModel` (SAM's ONNX decoder wrapper, all 4 masks):
  `image_embeddings`, `point_coords` [1, N, 2] and `point_labels` [1, N] (1 / 0 points, 2 / 3 box corners, -1
  padding), `mask_input` [1, 1, 256, 256], `has_mask_input` [1], `orig_im_size` [2] -> `masks` [1, 4, H, W] (logits
  at the image size), `iou_predictions` [1, 4], `low_res_masks` [1, 4, 256, 256].

`pipeline.py` resizes the longest side to 1024 (Pillow bilinear, as the repository's ResizeLongestSide), applies SAM's
pixel mean / std and pads bottom-right to 1024 x 1024. It scales the prompt coordinates the same way, and returns
masks 1-3 for multimask point prompts and mask 0 for a box, as SamPredictor does. It needs numpy, onnxruntime (or
onnxruntime-gpu) and Pillow:

```python
import sys, numpy as np
from PIL import Image
sys.path.insert(0, "fp16")
import pipeline
sam = pipeline.MobileSAM("fp16")
emb, size = sam.embed(np.array(Image.open("photo.jpg").convert("RGB")))
masks, scores = sam.point(emb, size, [[410, 300]])          # 3 masks [3, H, W] (bool)
box_mask, score = sam.box(emb, size, [120, 80, 700, 560])
```

**Precisions.** `fp16/`: the encoder fp16 weights and math with fp32 inputs / outputs, the decoder fp32 (16 MB; in
fp16 it moved the worst mask to IoU 0.915). No int8 or int4: weight-only int8 on the encoder put the worst mask at IoU
0.69, 4-bit at 0.50, for 3-5 MB less. No bf16: fp16 passes.

**Benchmark.** Eight photos (the first eight of the lab's DIS5K-250 set). Each gets a positive point (the ground-truth
foreground pixel nearest its centroid; 3 masks) and the ground truth's bounding box (1 mask), so 32 masks per build.
The original is the repository's SamPredictor in float32. The builds get the image it preprocesses and the same prompt
coordinates (the conversion measured alone). Pass: IoU with the original's mask at least 0.95 on every mask.

| | worst mask IoU | mean mask IoU |
|---|---|---|
| ONNX graphs in float32 (not published) | 0.99998 | 0.99999 |
| `fp16/` | 0.977 | 0.998 |

Graphs checked against the original modules (largest absolute difference, float32): encoder 2.9e-6 of 0.56, decoder
1.2e-5 of 8.4 (masks).

## How these were made

From [MobileSAM v2](https://github.com/ChaoningZhang/MobileSAM) at revision `f706ad9c4e`. The graphs were exported from the original PyTorch modules with
torch.onnx (opset 17 / 18) and checked against them. Weight-only quantization: int8 is a per-output-channel int8
weight behind DequantizeLinear, int4 is ONNX Runtime's MatMulNBits (block 32). Each card above says which precision
every graph uses. Every precision was benchmarked against the original before upload (pass: IoU at least 0.95 on every
mask, otherwise marked below threshold), and the `sha256` column above is what the files must hash to.

## License

apache-2.0. These files are a derivative of the original model and carry its license: it is copied in this
repository, and it governs your use of these files. The original model card follows unchanged.

---

# Original model card

<p float="center">
  <img src="https://raw.githubusercontent.com/ChaoningZhang/MobileSAM/f706ad9c4eb7f219c00d9050e46328518ffb65d2/assets/logo2.png?raw=true" width="99.1%" />
</p>

# Faster Segment Anything (MobileSAM) and Everything (MobileSAMv2)
:pushpin: MobileSAMv2, available at [ResearchGate](https://www.researchgate.net/publication/376579294_MobileSAMv2_Faster_Segment_Anything_to_Everything) and [arXiv](https://arxiv.org/abs/2312.09579.pdf), replaces the grid-search prompt sampling in SAM with object-aware prompt sampling for faster **segment everything(SegEvery)**.

:pushpin: MobileSAM, available at [ResearchGate](https://www.researchgate.net/publication/371851844_Faster_Segment_Anything_Towards_Lightweight_SAM_for_Mobile_Applications) and [arXiv](https://arxiv.org/pdf/2306.14289.pdf), replaces the heavyweight image encoder in SAM with a lightweight image encoder for faster **segment anything(SegAny)**. 


**Support for ONNX model export**. Feel free to test it on your devices and share your results with us.

**A demo of MobileSAM** running on **CPU** is open at [hugging face demo](https://huggingface.co/spaces/dhkim2810/MobileSAM). On our own Mac i5 CPU, it takes around 3s. On the hugging face demo, the interface and inferior CPUs make it slower but still works fine. Stayed tuned for a new version with more features! You can also run a demo of MobileSAM on [your local PC](https://github.com/ChaoningZhang/MobileSAM/tree/master/app).

:grapes: Media coverage and Projects that adapt from SAM to MobileSAM (Thank you all!)
* **2023/07/03**: [joliGEN](https://github.com/jolibrain/joliGEN) supports MobileSAM for faster and lightweight mask refinement for image inpainting with Diffusion and GAN.
* **2023/07/03**: [MobileSAM-in-the-Browser](https://github.com/akbartus/MobileSAM-in-the-Browser) shows a demo of running MobileSAM on the browser of your local PC or Mobile phone.
* **2023/07/02**: [Inpaint-Anything](https://github.com/qiaoyu1002/Inpaint-Anything) supports MobileSAM for faster and lightweight Inpaint Anything
* **2023/07/02**: [Personalize-SAM](https://github.com/qiaoyu1002/Personalize-SAM) supports MobileSAM for faster and lightweight Personalize Segment Anything with 1 Shot
* **2023/07/01**: [MobileSAM-in-the-Browser](https://github.com/akbartus/MobileSAM-in-the-Browser) makes an example implementation of MobileSAM in the browser.
* **2023/06/30**: [SegmentAnythingin3D](https://github.com/Jumpat/SegmentAnythingin3D) supports MobileSAM to segment anything in 3D efficiently.
* **2023/06/30**: MobileSAM has been featured by [AK](https://twitter.com/_akhaliq?lang=en) for the second time, see the link [AK's MobileSAM tweet](https://twitter.com/_akhaliq/status/1674410573075718145). Welcome to retweet.
* **2023/06/29**: [AnyLabeling](https://github.com/vietanhdev/anylabeling) supports MobileSAM for auto-labeling. 
* **2023/06/29**: [SonarSAM](https://github.com/wangsssky/SonarSAM) supports MobileSAM for Image encoder full-finetuing. 
* **2023/06/29**: [Stable Diffusion WebUIv](https://github.com/continue-revolution/sd-webui-segment-anything) supports MobileSAM. 

* **2023/06/28**: [Grounding-SAM](https://github.com/IDEA-Research/Grounded-Segment-Anything) supports MobileSAM with [Grounded-MobileSAM](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/main/EfficientSAM). 

* **2023/06/27**: MobileSAM has been featured by [AK](https://twitter.com/_akhaliq?lang=en), see the link [AK's MobileSAM tweet](https://twitter.com/_akhaliq/status/1673585099097636864). Welcome to retweet.
![MobileSAM](https://raw.githubusercontent.com/ChaoningZhang/MobileSAM/f706ad9c4eb7f219c00d9050e46328518ffb65d2/assets/model_diagram.jpg?raw=true)

:star: **How is MobileSAM trained?** MobileSAM is trained on a single GPU with 100k datasets (1% of the original images) for less than a day. The training code will be available soon.

:star: **How to Adapt from SAM to MobileSAM?** Since MobileSAM keeps exactly the same pipeline as the original SAM, we inherit pre-processing, post-processing, and all other interfaces from the original SAM. Therefore, by assuming everything is exactly the same except for a smaller image encoder, those who use the original SAM for their projects can **adapt to MobileSAM with almost zero effort**.
 
:star: **MobileSAM performs on par with the original SAM (at least visually)** and keeps exactly the same pipeline as the original SAM except for a change on the image encoder. Specifically, we replace the original heavyweight ViT-H encoder (632M) with a much smaller Tiny-ViT (5M). On a single GPU, MobileSAM runs around 12ms per image: 8ms on the image encoder and 4ms on the mask decoder. 

* The comparison of ViT-based image encoder is summarzed as follows: 

    Image Encoder                                      | Original SAM | MobileSAM 
    :-----------------------------------------:|:---------|:-----:
    Parameters      |  611M   | 5M
    Speed      |  452ms  | 8ms

* Original SAM and MobileSAM have exactly the same prompt-guided mask decoder: 

    Mask Decoder                                      | Original SAM | MobileSAM 
    :-----------------------------------------:|:---------|:-----:
    Parameters      |  3.876M   | 3.876M
    Speed      |  4ms  | 4ms

* The comparison of the whole pipeline is summarized as follows:

    Whole Pipeline (Enc+Dec)                                      | Original SAM | MobileSAM 
    :-----------------------------------------:|:---------|:-----:
    Parameters      |  615M   | 9.66M
    Speed      |  456ms  | 12ms

:star: **Original SAM and MobileSAM with a point as the prompt.**  

<p float="left">
  <img src="https://raw.githubusercontent.com/ChaoningZhang/MobileSAM/f706ad9c4eb7f219c00d9050e46328518ffb65d2/assets/mask_point.jpg?raw=true" width="99.1%" />
</p>

:star: **Original SAM and MobileSAM with a box as the prompt.** 
<p float="left">
  <img src="https://raw.githubusercontent.com/ChaoningZhang/MobileSAM/f706ad9c4eb7f219c00d9050e46328518ffb65d2/assets/mask_box.jpg?raw=true" width="99.1%" />
</p>

:muscle: **Is MobileSAM faster and smaller than FastSAM? Yes!** 
MobileSAM is around 7 times smaller and around 5 times faster than the concurrent FastSAM. 
The comparison of the whole pipeline is summarzed as follows: 
Whole Pipeline (Enc+Dec)                                      | FastSAM | MobileSAM 
:-----------------------------------------:|:---------|:-----:
Parameters      |  68M   | 9.66M
Speed      |  64ms  |12ms

:muscle: **Does MobileSAM aign better with the original SAM than FastSAM? Yes!** 
FastSAM is suggested to work with multiple points, thus we compare the mIoU with two prompt points (with different pixel distances) and show the resutls as follows. Higher mIoU indicates higher alignment. 
mIoU                                     | FastSAM | MobileSAM 
:-----------------------------------------:|:---------|:-----:
100      |  0.27   | 0.73
200      |  0.33  |0.71
300      |  0.37  |0.74
400      |  0.41  |0.73
500      |  0.41  |0.73








## Installation

The code requires `python>=3.8`, as well as `pytorch>=1.7` and `torchvision>=0.8`. Please follow the instructions [here](https://pytorch.org/get-started/locally/) to install both PyTorch and TorchVision dependencies. Installing both PyTorch and TorchVision with CUDA support is strongly recommended.

Install Mobile Segment Anything:

```
pip install git+https://github.com/ChaoningZhang/MobileSAM.git
```

or clone the repository locally and install with

```
git clone git@github.com:ChaoningZhang/MobileSAM.git
cd MobileSAM; pip install -e .
```

## Demo

Once installed MobileSAM, you can run demo on your local PC or check out our [HuggingFace Demo](https://huggingface.co/spaces/dhkim2810/MobileSAM).

It requires latest version of [gradio](https://gradio.app).

```
cd app
python app.py
```

## <a name="GettingStarted"></a>Getting Started
The MobileSAM can be loaded in the following ways:

```
from mobile_sam import sam_model_registry, SamAutomaticMaskGenerator, SamPredictor

model_type = "vit_t"
sam_checkpoint = "./weights/mobile_sam.pt"

device = "cuda" if torch.cuda.is_available() else "cpu"

mobile_sam = sam_model_registry[model_type](https://raw.githubusercontent.com/ChaoningZhang/MobileSAM/f706ad9c4eb7f219c00d9050e46328518ffb65d2/checkpoint=sam_checkpoint)
mobile_sam.to(device=device)
mobile_sam.eval()

predictor = SamPredictor(mobile_sam)
predictor.set_image(<your_image>)
masks, _, _ = predictor.predict(<input_prompts>)
```

or generate masks for an entire image:

```
from mobile_sam import SamAutomaticMaskGenerator

mask_generator = SamAutomaticMaskGenerator(mobile_sam)
masks = mask_generator.generate(<your_image>)
```
## <a name="GettingStarted"></a>Getting Started (MobileSAMv2)
Download the model weights from the [checkpoints](https://drive.google.com/file/d/1dE-YAG-1mFCBmao2rHDp0n-PP4eH7SjE/view?usp=sharing).

After downloading the model weights, faster SegEvery with MobileSAMv2 can be simply used as follows:
```
cd MobileSAMv2
bash ./experiments/mobilesamv2.sh
```
## ONNX Export
**MobileSAM** now supports ONNX export. Export the model with

```
python scripts/export_onnx_model.py --checkpoint ./weights/mobile_sam.pt --model-type vit_t --output ./mobile_sam.onnx
```

Also check the [example notebook](https://github.com/ChaoningZhang/MobileSAM/blob/master/notebooks/onnx_model_example.ipynb) to follow detailed steps.
We recommend to use `onnx==1.12.0` and `onnxruntime==1.13.1` which is tested.


## BibTex of our MobileSAM
If you use MobileSAM in your research, please use the following BibTeX entry. :mega: Thank you!

```bibtex
@article{mobile_sam,
  title={Faster Segment Anything: Towards Lightweight SAM for Mobile Applications},
  author={Zhang, Chaoning and Han, Dongshen and Qiao, Yu and Kim, Jung Uk and Bae, Sung-Ho and Lee, Seungkyu and Hong, Choong Seon},
  journal={arXiv preprint arXiv:2306.14289},
  year={2023}
}
```

## Acknowledgement

This work was supported by Institute of Information & communications Technology Planning & Evaluation (IITP) grant funded by the Korea government(MSIT) (No.RS-2022-00155911, Artificial Intelligence Convergence Innovation Human Resources Development (Kyung Hee University)),(No.2019-0-01287, Evolvable Deep Learning Model Generation Platform for Edge Computing)

<details>
<summary>
<a href="https://github.com/facebookresearch/segment-anything">SAM</a> (Segment Anything) [<b>bib</b>]
</summary>

```bibtex
@article{kirillov2023segany,
  title={Segment Anything}, 
  author={Kirillov, Alexander and Mintun, Eric and Ravi, Nikhila and Mao, Hanzi and Rolland, Chloe and Gustafson, Laura and Xiao, Tete and Whitehead, Spencer and Berg, Alexander C. and Lo, Wan-Yen and Doll{\'a}r, Piotr and Girshick, Ross},
  journal={arXiv:2304.02643},
  year={2023}
}
```
</details>



<details>
<summary>
<a href="https://github.com/microsoft/Cream/tree/main/TinyViT">TinyViT</a> (TinyViT: Fast Pretraining Distillation for Small Vision Transformers) [<b>bib</b>]
</summary>

```bibtex
@InProceedings{tiny_vit,
  title={TinyViT: Fast Pretraining Distillation for Small Vision Transformers},
  author={Wu, Kan and Zhang, Jinnian and Peng, Houwen and Liu, Mengchen and Xiao, Bin and Fu, Jianlong and Yuan, Lu},
  booktitle={European conference on computer vision (ECCV)},
  year={2022}
```
</details>