jennyxue commited on
Commit
d4516da
·
verified ·
1 Parent(s): 65b8e2d

Model card and the original license

Browse files
Files changed (1) hide show
  1. README.md +258 -0
README.md ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model: ZhengPeng7/BiRefNet_lite
3
+ base_model_relation: quantized
4
+ license: mit
5
+ pipeline_tag: image-segmentation
6
+ library_name: tensorrt
7
+ tags:
8
+ - tensorrt
9
+ - moonbox
10
+ - birefnet
11
+ - background-removal
12
+ - dichotomous-image-segmentation
13
+ - image-segmentation
14
+ ---
15
+
16
+ # BiRefNet-lite TensorRT
17
+
18
+ TensorRT engines of [BiRefNet-lite](https://huggingface.co/ZhengPeng7/BiRefNet_lite), made by Moonbox for NVIDIA RTX GPUs. Each precision is one folder holding the
19
+ engine, `trt_runner.py` (a small numpy runner: TensorRT plus Polygraphy, no PyTorch) and a script that does the rest
20
+ of the pipeline. What the engine takes and returns is under *How to run*.
21
+
22
+ **Compatibility.** The engines are built *hardware compatible* (Ampere and newer: RTX 30, 40 and 50 series) and
23
+ *version compatible* (any TensorRT 10.x from 10.13 on, through its lean runtime). That costs a little speed against an
24
+ engine built for one GPU, but no rebuild is needed. Install the runtime with
25
+ `pip install "tensorrt-cu12>=10.13,<11" "tensorrt-lean-cu12>=10.13,<11" polygraphy numpy`.
26
+
27
+ ## Files
28
+
29
+ The last column is the benchmark (details under *How to run*).
30
+
31
+ | Precision | File | Size | sha256 | Benchmark |
32
+ |---|---|---|---|---|
33
+ | fp16 | [`fp16/config.json`](https://huggingface.co/moonbox-dev/BiRefNet_lite-TensorRT/blob/main/fp16/config.json) | 0.0 kB | `a4218ae35651` | vs fp32: IoU 0.9980, MAE 0.0003; DIS5K MAE 0.0171, S 0.939; 198 ms a picture (ONNX fp16 372 ms), 1595 MiB |
34
+ | fp16 | [`fp16/cutout_trt.py`](https://huggingface.co/moonbox-dev/BiRefNet_lite-TensorRT/blob/main/fp16/cutout_trt.py) | 1.7 kB | `5c0a5d2a60e5` | vs fp32: IoU 0.9980, MAE 0.0003; DIS5K MAE 0.0171, S 0.939; 198 ms a picture (ONNX fp16 372 ms), 1595 MiB |
35
+ | fp16 | [`fp16/model.engine`](https://huggingface.co/moonbox-dev/BiRefNet_lite-TensorRT/blob/main/fp16/model.engine) | 236.7 MB | `177067fcf72c` | vs fp32: IoU 0.9980, MAE 0.0003; DIS5K MAE 0.0171, S 0.939; 198 ms a picture (ONNX fp16 372 ms), 1595 MiB |
36
+ | fp16 | [`fp16/trt_runner.py`](https://huggingface.co/moonbox-dev/BiRefNet_lite-TensorRT/blob/main/fp16/trt_runner.py) | 2.2 kB | `efa8ba97631b` | vs fp32: IoU 0.9980, MAE 0.0003; DIS5K MAE 0.0171, S 0.939; 198 ms a picture (ONNX fp16 372 ms), 1595 MiB |
37
+
38
+ ## How to run
39
+
40
+ BiRefNet_lite (general, Swin-T backbone) as a TensorRT engine built from Moonbox's fp16 ONNX graph of the official model.
41
+
42
+ ```python
43
+ import sys
44
+ from PIL import Image
45
+ sys.path.insert(0, "fp16")
46
+ import json, cutout_trt
47
+ from trt_runner import Engine
48
+ e = Engine("fp16/model.engine")
49
+ cfg = json.load(open("fp16/config.json"))
50
+ img = Image.open("photo.jpg").convert("RGB")
51
+ img.putalpha(cutout_trt.matte(e, img, cfg)); img.save("cutout.png")
52
+ ```
53
+
54
+ Or `python fp16/cutout_trt.py photo.jpg cutout.png`. The engine takes the picture resized to 1024 x 1024, RGB in 0-1
55
+ with the ImageNet mean / std, as [1, 3, 1024, 1024]. It returns a single output, the matte (sigmoid applied). `cutout_trt.py` resizes the matte back to the picture's
56
+ size.
57
+
58
+ **Precisions.** fp16 only: the fp16 ONNX graph's weights and math (fp32 inputs and outputs). No int8: the ONNX int8
59
+ build is weight-only, while TensorRT's int8 needs calibrated activations.
60
+
61
+ **Benchmark.**
62
+ - **Data:** the [DIS5K](https://github.com/xuebinqin/DIS) test sets, 250 pictures (DIS-TE1..4 and DIS-VD, 50 each), on
63
+ an RTX 3080 Laptop GPU.
64
+ - **Fidelity:** agreement with the fp32 ONNX graph's mattes: IoU of the masks at 0.5, mean absolute difference.
65
+ - **Quality:** MAE and S-measure against the ground truth (PySODMetrics, on masks shrunk to at most 2048 px).
66
+ - **Pass mark:** MAE <= 0.005 and IoU >= 0.98 against fp32, as for this model's other builds.
67
+
68
+ | | vs fp32: IoU / MAE | DIS5K MAE / S-measure | ms a picture | peak GPU memory |
69
+ |---|---|---|---|---|
70
+ | ONNX fp32 (reference) | - | 0.0171 / 0.939 | 438 | 6883 MiB |
71
+ | ONNX fp16 | 0.9981 / 0.0002 | 0.0171 / 0.939 | 372 | 5933 MiB |
72
+ | TensorRT `fp16/` | 0.9980 / 0.0003 | 0.0171 / 0.939 | 198 | 1595 MiB |
73
+
74
+ The times are medians per picture, including the resizing to and from 1024 x 1024. The ONNX rows used ONNX Runtime's
75
+ CUDA provider.
76
+
77
+ ## How these were made
78
+
79
+ From [BiRefNet-lite](https://huggingface.co/ZhengPeng7/BiRefNet_lite) at revision `aa62cd87ea`: each engine was built with TensorRT's builder from Moonbox's published
80
+ ONNX graph of the same model and precision. The network is *strongly typed*: every tensor keeps the precision the
81
+ ONNX graph gives it, so an fp16 engine computes what the fp16 ONNX build computes. Built on an RTX 3080 Laptop GPU,
82
+ it was benchmarked against the original before upload, and the `sha256` column above is what the files must hash to.
83
+
84
+ ## License
85
+
86
+ MIT. These files are a derivative of the original model and carry its license: it is copied in this
87
+ repository, and it governs your use of these files. The original model card follows unchanged.
88
+
89
+ ---
90
+
91
+ # Original model card
92
+
93
+ <h1 align="center">Bilateral Reference for High-Resolution Dichotomous Image Segmentation</h1>
94
+
95
+ <div align='center'>
96
+ <a href='https://scholar.google.com/citations?user=TZRzWOsAAAAJ' target='_blank'><strong>Peng Zheng</strong></a><sup> 1,4,5,6</sup>,&thinsp;
97
+ <a href='https://scholar.google.com/citations?user=0uPb8MMAAAAJ' target='_blank'><strong>Dehong Gao</strong></a><sup> 2</sup>,&thinsp;
98
+ <a href='https://scholar.google.com/citations?user=kakwJ5QAAAAJ' target='_blank'><strong>Deng-Ping Fan</strong></a><sup> 1*</sup>,&thinsp;
99
+ <a href='https://scholar.google.com/citations?user=9cMQrVsAAAAJ' target='_blank'><strong>Li Liu</strong></a><sup> 3</sup>,&thinsp;
100
+ <a href='https://scholar.google.com/citations?user=qQP6WXIAAAAJ' target='_blank'><strong>Jorma Laaksonen</strong></a><sup> 4</sup>,&thinsp;
101
+ <a href='https://scholar.google.com/citations?user=pw_0Z_UAAAAJ' target='_blank'><strong>Wanli Ouyang</strong></a><sup> 5</sup>,&thinsp;
102
+ <a href='https://scholar.google.com/citations?user=stFCYOAAAAAJ' target='_blank'><strong>Nicu Sebe</strong></a><sup> 6</sup>
103
+ </div>
104
+
105
+ <div align='center'>
106
+ <sup>1 </sup>Nankai University&ensp; <sup>2 </sup>Northwestern Polytechnical University&ensp; <sup>3 </sup>National University of Defense Technology&ensp; <sup>4 </sup>Aalto University&ensp; <sup>5 </sup>Shanghai AI Laboratory&ensp; <sup>6 </sup>University of Trento&ensp;
107
+ </div>
108
+
109
+ <div align="center" style="display: flex; justify-content: center; flex-wrap: wrap;">
110
+ <a href='https://arxiv.org/pdf/2401.03407'><img src='https://img.shields.io/badge/arXiv-BiRefNet-red'></a>&ensp;
111
+ <a href='https://drive.google.com/file/d/1aBnJ_R9lbnC2dm8dqD0-pzP2Cu-U1Xpt/view?usp=drive_link'><img src='https://img.shields.io/badge/中文版-BiRefNet-red'></a>&ensp;
112
+ <a href='https://www.birefnet.top'><img src='https://img.shields.io/badge/Page-BiRefNet-red'></a>&ensp;
113
+ <a href='https://drive.google.com/drive/folders/1s2Xe0cjq-2ctnJBR24563yMSCOu4CcxM'><img src='https://img.shields.io/badge/Drive-Stuff-green'></a>&ensp;
114
+ <a href='LICENSE'><img src='https://img.shields.io/badge/License-MIT-yellow'></a>&ensp;
115
+ <a href='https://huggingface.co/spaces/ZhengPeng7/BiRefNet_demo'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20HF%20Spaces-BiRefNet-blue'></a>&ensp;
116
+ <a href='https://huggingface.co/ZhengPeng7/BiRefNet'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20HF%20Models-BiRefNet-blue'></a>&ensp;
117
+ <a href='https://colab.research.google.com/drive/14Dqg7oeBkFEtchaHLNpig2BcdkZEogba?usp=drive_link'><img src='https://img.shields.io/badge/Single_Image_Inference-F9AB00?style=for-the-badge&logo=googlecolab&color=525252'></a>&ensp;
118
+ <a href='https://colab.research.google.com/drive/1MaEiBfJ4xIaZZn0DqKrhydHB8X97hNXl#scrollTo=DJ4meUYjia6S'><img src='https://img.shields.io/badge/Inference_&_Evaluation-F9AB00?style=for-the-badge&logo=googlecolab&color=525252'></a>&ensp;
119
+ </div>
120
+
121
+
122
+ | *DIS-Sample_1* | *DIS-Sample_2* |
123
+ | :------------------------------: | :-------------------------------: |
124
+ | <img src="https://drive.google.com/thumbnail?id=1ItXaA26iYnE8XQ_GgNLy71MOWePoS2-g&sz=w400" /> | <img src="https://drive.google.com/thumbnail?id=1Z-esCujQF_uEa_YJjkibc3NUrW4aR_d4&sz=w400" /> |
125
+
126
+ This repo is the official implementation of "[**Bilateral Reference for High-Resolution Dichotomous Image Segmentation**](https://arxiv.org/pdf/2401.03407.pdf)" (___CAAI AIR 2024___).
127
+
128
+ Visit our GitHub repo: [https://github.com/ZhengPeng7/BiRefNet](https://github.com/ZhengPeng7/BiRefNet) for more details -- **codes**, **docs**, and **model zoo**!
129
+
130
+ ## How to use (this tiny version)
131
+
132
+ ### 0. Install Packages:
133
+ ```
134
+ pip install -qr https://raw.githubusercontent.com/ZhengPeng7/BiRefNet/main/requirements.txt
135
+ ```
136
+
137
+ ### 1. Load BiRefNet:
138
+
139
+ #### Use codes + weights from HuggingFace
140
+ > Only use the weights on HuggingFace -- Pro: No need to download BiRefNet codes manually; Con: Codes on HuggingFace might not be latest version (I'll try to keep them always latest).
141
+
142
+ ```python
143
+ # Load BiRefNet with weights
144
+ from transformers import AutoModelForImageSegmentation
145
+ birefnet = AutoModelForImageSegmentation.from_pretrained('zhengpeng7/BiRefNet_lite', trust_remote_code=True)
146
+ ```
147
+
148
+ #### Use codes from GitHub + weights from HuggingFace
149
+ > Only use the weights on HuggingFace -- Pro: codes are always the latest; Con: Need to clone the BiRefNet repo from my GitHub.
150
+
151
+ ```shell
152
+ # Download codes
153
+ git clone https://github.com/ZhengPeng7/BiRefNet.git
154
+ cd BiRefNet
155
+ ```
156
+
157
+ ```python
158
+ # Use codes locally
159
+ from models.birefnet import BiRefNet
160
+
161
+ # Load weights from Hugging Face Models
162
+ ### >>> Remember to set the `bb` in `config.py` as `swin_v1_t` to use this tiny version. <<< ###
163
+ birefnet = BiRefNet.from_pretrained('zhengpeng7/BiRefNet_lite')
164
+ ```
165
+
166
+ #### Use codes from GitHub + weights from local space
167
+ > Only use the weights and codes both locally.
168
+
169
+ ```python
170
+ # Use codes and weights locally
171
+ ### >>> Remember to set the `bb` in `config.py` as `swin_v1_t` to use this tiny version. <<< ###
172
+ import torch
173
+ from utils import check_state_dict
174
+
175
+ birefnet = BiRefNet(bb_pretrained=False)
176
+ state_dict = torch.load(PATH_TO_WEIGHT, map_location='cpu')
177
+ state_dict = check_state_dict(state_dict)
178
+ birefnet.load_state_dict(state_dict)
179
+ ```
180
+
181
+ #### Use the loaded BiRefNet for inference
182
+ ```python
183
+ # Imports
184
+ from PIL import Image
185
+ import matplotlib.pyplot as plt
186
+ import torch
187
+ from torchvision import transforms
188
+ from models.birefnet import BiRefNet
189
+
190
+ birefnet = ... # -- BiRefNet should be loaded with codes above, either way.
191
+ torch.set_float32_matmul_precision(['high', 'highest'][0])
192
+ birefnet.to('cuda')
193
+ birefnet.eval()
194
+ birefnet.half()
195
+
196
+ def extract_object(birefnet, imagepath):
197
+ # Data settings
198
+ image_size = (1024, 1024)
199
+ transform_image = transforms.Compose([
200
+ transforms.Resize(image_size),
201
+ transforms.ToTensor(),
202
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
203
+ ])
204
+
205
+ image = Image.open(imagepath)
206
+ input_images = transform_image(image).unsqueeze(0).to('cuda').half()
207
+
208
+ # Prediction
209
+ with torch.no_grad():
210
+ preds = birefnet(input_images)[-1].sigmoid().cpu()
211
+ pred = preds[0].squeeze()
212
+ pred_pil = transforms.ToPILImage()(pred)
213
+ mask = pred_pil.resize(image.size)
214
+ image.putalpha(mask)
215
+ return image, mask
216
+
217
+ # Visualization
218
+ plt.axis("off")
219
+ plt.imshow(extract_object(birefnet, imagepath='PATH-TO-YOUR_IMAGE.jpg')[0])
220
+ plt.show()
221
+
222
+ ```
223
+
224
+
225
+ > This BiRefNet for standard dichotomous image segmentation (DIS) is trained on **DIS-TR** and validated on **DIS-TEs and DIS-VD**.
226
+
227
+ ## This repo holds the official model weights of "[<ins>Bilateral Reference for High-Resolution Dichotomous Image Segmentation</ins>](https://arxiv.org/pdf/2401.03407)" (_CAAI AIR 2024_).
228
+
229
+ This repo contains the weights of BiRefNet proposed in our paper, which has achieved the SOTA performance on three tasks (DIS, HRSOD, and COD).
230
+
231
+ Go to my GitHub page for BiRefNet codes and the latest updates: https://github.com/ZhengPeng7/BiRefNet :)
232
+
233
+
234
+ #### Try our online demos for inference:
235
+
236
+ + Online **Single Image Inference** on Colab: [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/14Dqg7oeBkFEtchaHLNpig2BcdkZEogba?usp=drive_link)
237
+ + **Online Inference with GUI on Hugging Face** with adjustable resolutions: [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/ZhengPeng7/BiRefNet_demo)
238
+ + **Inference and evaluation** of your given weights: [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1MaEiBfJ4xIaZZn0DqKrhydHB8X97hNXl#scrollTo=DJ4meUYjia6S)
239
+ <img src="https://drive.google.com/thumbnail?id=12XmDhKtO1o2fEvBu4OE4ULVB2BK0ecWi&sz=w1080" />
240
+
241
+ ## Acknowledgement:
242
+
243
+ + Many thanks to @fal for their generous support on GPU resources for training better BiRefNet models.
244
+ + Many thanks to @not-lain for his help on the better deployment of our BiRefNet model on HuggingFace.
245
+
246
+
247
+ ## Citation
248
+
249
+ ```
250
+ @article{zheng2024birefnet,
251
+ title={Bilateral Reference for High-Resolution Dichotomous Image Segmentation},
252
+ author={Zheng, Peng and Gao, Dehong and Fan, Deng-Ping and Liu, Li and Laaksonen, Jorma and Ouyang, Wanli and Sebe, Nicu},
253
+ journal={CAAI Artificial Intelligence Research},
254
+ volume = {3},
255
+ pages = {9150038},
256
+ year={2024}
257
+ }
258
+ ```