Instructions to use moonbox-dev/MobileSAM-TensorRT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- TensorRT
How to use moonbox-dev/MobileSAM-TensorRT with TensorRT:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Download README.md from moonbox-dev/MobileSAM-TensorRT: direct link, hf CLI and curl.
- Browser
- Download file 17.3 kB
-
https://huggingface.co/moonbox-dev/MobileSAM-TensorRT/resolve/main/README.md
- Command line
-
hf download hf://moonbox-dev/MobileSAM-TensorRT/README.md
-
curl -L -o README.md https://huggingface.co/moonbox-dev/MobileSAM-TensorRT/resolve/main/README.md
license: apache-2.0
pipeline_tag: mask-generation
library_name: tensorrt
tags:
- tensorrt
- moonbox
- mobilesam
- segment-anything
- sam
- image-segmentation
MobileSAM v2 TensorRT
TensorRT engines of MobileSAM v2, made by Moonbox for NVIDIA RTX GPUs. Each precision is one folder holding the
engine, trt_runner.py (a small numpy runner: TensorRT plus Polygraphy, no PyTorch) and a script that does the rest
of the pipeline. What the engine takes and returns is under How to run.
Compatibility. The engines are built hardware compatible (Ampere and newer: RTX 30, 40 and 50 series) and
version compatible (any TensorRT 10.x from 10.13 on, through its lean runtime). That costs a little speed against an
engine built for one GPU, but no rebuild is needed. Install the runtime with
pip install "tensorrt-cu12>=10.13,<11" "tensorrt-lean-cu12>=10.13,<11" polygraphy numpy.
Files
The last column is the benchmark (details under How to run).
| Precision | File | Size | sha256 | Benchmark |
|---|---|---|---|---|
| fp16 | fp16/decoder.engine |
75.1 MB | 553a0df66900 |
mask IoU vs the ONNX fp16 build 1.0000 mean / 1.0000 worst (32 masks); encoder 12.2 ms vs 27.6 ms |
| fp16 | fp16/encoder.engine |
90.8 MB | 2040ee2582d3 |
mask IoU vs the ONNX fp16 build 1.0000 mean / 1.0000 worst (32 masks); encoder 12.2 ms vs 27.6 ms |
| fp16 | fp16/pipeline.py |
4.2 kB | 7fcc838b105a |
mask IoU vs the ONNX fp16 build 1.0000 mean / 1.0000 worst (32 masks); encoder 12.2 ms vs 27.6 ms |
| fp16 | fp16/pipeline_trt.py |
3.9 kB | d64140902b63 |
mask IoU vs the ONNX fp16 build 1.0000 mean / 1.0000 worst (32 masks); encoder 12.2 ms vs 27.6 ms |
| fp16 | fp16/trt_runner.py |
3.3 kB | 0da2222f799a |
mask IoU vs the ONNX fp16 build 1.0000 mean / 1.0000 worst (32 masks); encoder 12.2 ms vs 27.6 ms |
How to run
MobileSAM, the promptable segmenter of MobileSAM v2 (a TinyViT image encoder and SAM's mask decoder), as TensorRT
engines plus pipeline_trt.py. It follows the repository's SamPredictor like this model's ONNX pipeline.py:
- Picture: the longest side resized to 1024, SAM's pixel mean / std, padded bottom-right to 1024 x 1024.
- Prompts: point prompts give three masks, box prompts one.
import sys
import numpy as np
from PIL import Image
sys.path.insert(0, "fp16")
from pipeline_trt import MobileSAMTrt
p = MobileSAMTrt("fp16")
rgb = np.asarray(Image.open("photo.jpg").convert("RGB"))
emb, size = p.embed(rgb) # the image embedding, once per picture
masks, scores = p.point(emb, size, [[410, 300]]) # 3 masks [3, H, W] (bool) for a foreground point
mask, score = p.box(emb, size, [100, 80, 620, 540]) # 1 mask for a box
Or python fp16/pipeline_trt.py photo.jpg masks.npz --point 410 300 --box 100 80 620 540. It needs numpy, Pillow,
TensorRT and Polygraphy; opencv-python makes the final mask resize fast.
The engines.
encoder.engine:image[1, 3, 1024, 1024] ->image_embeddings[1, 256, 64, 64].decoder.engine: SAM's ONNX decoder wrapper up to its low-resolution masks.- Inputs:
image_embeddings,point_coords[1, N, 2] with N from 1 to 10,point_labels,mask_input,has_mask_input. - Outputs:
iou_predictionsandlow_res_masks[1, 4, 256, 256].
- Inputs:
- Resizing to the picture: the wrapper's last step needs the picture size as a shape, which TensorRT can't take
as a float input.
pipeline_trt.pydoes it instead, with the same bilinear arithmetic (torch'salign_corners=False).
Precisions. fp16/, built from the ONNX fp16/ graphs: the encoder fp16, the decoder fp32, as in the ONNX build
(fp16 or int8 in the decoder cost the most mask IoU). No int8: TensorRT's int8 needs calibrated activations, and the
ONNX int8 encoder already fell below the pass mark.
Benchmark.
- Data: the first 8 photos of DIS5K-250, with a point prompt (3 masks) and the box prompt (1 mask) per photo, both from the ground truth: 32 masks.
- Run: the engines through
pipeline_trt.pyagainst the ONNXfp16/build through itspipeline.py(ONNX Runtime CUDA), on an RTX 3080 Laptop GPU. - Pass mark: IoU >= 0.99 against the ONNX build on every mask. The ONNX build itself is within IoU 0.977 of the original (SamPredictor, fp32) on its worst mask.
| mask IoU vs the ONNX build: mean / worst | encoder alone | per photo (incl. resizing) | |
|---|---|---|---|
ONNX fp16/ (CUDA) |
- | 27.6 ms | 116 ms |
TensorRT fp16/ |
1.0000 / 1.0000 | 12.2 ms | 132 ms |
The per-photo time is dominated by resizing DIS5K's large pictures on the CPU, so the engines' speed shows mostly in the encoder.
How these were made
From MobileSAM v2 at revision f706ad9c4e: each engine was built with TensorRT's builder from Moonbox's published
ONNX graph of the same model and precision. The network is strongly typed: every tensor keeps the precision the
ONNX graph gives it, so an fp16 engine computes what the fp16 ONNX build computes. Built on an RTX 3080 Laptop GPU,
it was benchmarked against the original before upload, 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
Faster Segment Anything (MobileSAM) and Everything (MobileSAMv2)
:pushpin: MobileSAMv2, available at ResearchGate and arXiv, replaces the grid-search prompt sampling in SAM with object-aware prompt sampling for faster segment everything(SegEvery).
:pushpin: MobileSAM, available at ResearchGate and arXiv, 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. 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.
:grapes: Media coverage and Projects that adapt from SAM to MobileSAM (Thank you all!)
2023/07/03: joliGEN supports MobileSAM for faster and lightweight mask refinement for image inpainting with Diffusion and GAN.
2023/07/03: 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 supports MobileSAM for faster and lightweight Inpaint Anything
2023/07/02: Personalize-SAM supports MobileSAM for faster and lightweight Personalize Segment Anything with 1 Shot
2023/07/01: MobileSAM-in-the-Browser makes an example implementation of MobileSAM in the browser.
2023/06/30: SegmentAnythingin3D supports MobileSAM to segment anything in 3D efficiently.
2023/06/30: MobileSAM has been featured by AK for the second time, see the link AK's MobileSAM tweet. Welcome to retweet.
2023/06/29: AnyLabeling supports MobileSAM for auto-labeling.
2023/06/29: SonarSAM supports MobileSAM for Image encoder full-finetuing.
2023/06/29: Stable Diffusion WebUIv supports MobileSAM.
2023/06/28: Grounding-SAM supports MobileSAM with Grounded-MobileSAM.
2023/06/27: MobileSAM has been featured by AK, see the link AK's MobileSAM tweet. Welcome to retweet.

: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.
:star: Original SAM and MobileSAM with a box as the prompt.
: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 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.
It requires latest version of gradio.
cd app
python app.py
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>)
Getting Started (MobileSAMv2)
Download the model weights from the checkpoints.
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 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!
@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)
SAM (Segment Anything) [bib]
@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}
}
TinyViT (TinyViT: Fast Pretraining Distillation for Small Vision Transformers) [bib]
@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}