jennyxue commited on
Commit
ff60c54
·
verified ·
1 Parent(s): 7454fb6

Model card and the original license

Browse files
Files changed (1) hide show
  1. README.md +303 -0
README.md ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model: ZhengPeng7/BiRefNet
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 TensorRT
17
+
18
+ TensorRT engines of [BiRefNet](https://huggingface.co/ZhengPeng7/BiRefNet), 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-TensorRT/blob/main/fp16/config.json) | 0.0 kB | `a4218ae35651` | vs fp32: IoU 0.9980, MAE 0.0003; DIS5K MAE 0.0141, S 0.953; 241 ms a picture (ONNX fp16 583 ms), 2665 MiB |
34
+ | fp16 | [`fp16/cutout_trt.py`](https://huggingface.co/moonbox-dev/BiRefNet-TensorRT/blob/main/fp16/cutout_trt.py) | 1.7 kB | `5c0a5d2a60e5` | vs fp32: IoU 0.9980, MAE 0.0003; DIS5K MAE 0.0141, S 0.953; 241 ms a picture (ONNX fp16 583 ms), 2665 MiB |
35
+ | fp16 | [`fp16/model.engine`](https://huggingface.co/moonbox-dev/BiRefNet-TensorRT/blob/main/fp16/model.engine) | 717.8 MB | `04a22835cf6d` | vs fp32: IoU 0.9980, MAE 0.0003; DIS5K MAE 0.0141, S 0.953; 241 ms a picture (ONNX fp16 583 ms), 2665 MiB |
36
+ | fp16 | [`fp16/trt_runner.py`](https://huggingface.co/moonbox-dev/BiRefNet-TensorRT/blob/main/fp16/trt_runner.py) | 2.2 kB | `efa8ba97631b` | vs fp32: IoU 0.9980, MAE 0.0003; DIS5K MAE 0.0141, S 0.953; 241 ms a picture (ONNX fp16 583 ms), 2665 MiB |
37
+
38
+ ## How to run
39
+
40
+ BiRefNet (general) 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.0141 / 0.953 | 728 | 9531 MiB |
71
+ | ONNX fp16 | 0.9981 / 0.0002 | 0.0141 / 0.953 | 583 | 7890 MiB |
72
+ | TensorRT `fp16/` | 0.9980 / 0.0003 | 0.0141 / 0.953 | 241 | 2665 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](https://huggingface.co/ZhengPeng7/BiRefNet) at revision `e2bf8e4460`: 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://www.sciopen.com/article/pdf/10.26599/AIR.2024.9150038.pdf'><img src='https://img.shields.io/badge/Journal-Paper-red'></a>&ensp;
111
+ <a href='https://arxiv.org/pdf/2401.03407'><img src='https://img.shields.io/badge/arXiv-BiRefNet-red'></a>&ensp;
112
+ <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;
113
+ <a href='https://www.birefnet.top'><img src='https://img.shields.io/badge/Page-BiRefNet-red'></a>&ensp;
114
+ <a href='https://drive.google.com/drive/folders/1s2Xe0cjq-2ctnJBR24563yMSCOu4CcxM'><img src='https://img.shields.io/badge/Drive-Stuff-green'></a>&ensp;
115
+ <a href='LICENSE'><img src='https://img.shields.io/badge/License-MIT-yellow'></a>&ensp;
116
+ <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;
117
+ <a href='https://huggingface.co/ZhengPeng7/BiRefNet'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20HF%20Models-BiRefNet-blue'></a>&ensp;
118
+ <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;
119
+ <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;
120
+ </div>
121
+
122
+
123
+ | *DIS-Sample_1* | *DIS-Sample_2* |
124
+ | :------------------------------: | :-------------------------------: |
125
+ | <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" /> |
126
+
127
+ 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___).
128
+
129
+ Visit our GitHub repo: [https://github.com/ZhengPeng7/BiRefNet](https://github.com/ZhengPeng7/BiRefNet) for more details -- **codes**, **docs**, and **model zoo**!
130
+
131
+ ## How to use
132
+
133
+ ### 0. Install Packages:
134
+ ```
135
+ pip install -qr https://raw.githubusercontent.com/ZhengPeng7/BiRefNet/main/requirements.txt
136
+ ```
137
+
138
+ ### 1. Load BiRefNet:
139
+
140
+ #### Use codes + weights from HuggingFace
141
+ > 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).
142
+
143
+ ```python
144
+ # Load BiRefNet with weights
145
+ from transformers import AutoModelForImageSegmentation
146
+ birefnet = AutoModelForImageSegmentation.from_pretrained('ZhengPeng7/BiRefNet', trust_remote_code=True)
147
+ ```
148
+
149
+ #### Use codes from GitHub + weights from HuggingFace
150
+ > Only use the weights on HuggingFace -- Pro: codes are always latest; Con: Need to clone the BiRefNet repo from my GitHub.
151
+
152
+ ```shell
153
+ # Download codes
154
+ git clone https://github.com/ZhengPeng7/BiRefNet.git
155
+ cd BiRefNet
156
+ ```
157
+
158
+ ```python
159
+ # Use codes locally
160
+ from models.birefnet import BiRefNet
161
+
162
+ # Load weights from Hugging Face Models
163
+ birefnet = BiRefNet.from_pretrained('ZhengPeng7/BiRefNet')
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
+ import torch
172
+ from utils import check_state_dict
173
+
174
+ birefnet = BiRefNet(bb_pretrained=False)
175
+ state_dict = torch.load(PATH_TO_WEIGHT, map_location='cpu')
176
+ state_dict = check_state_dict(state_dict)
177
+ birefnet.load_state_dict(state_dict)
178
+ ```
179
+
180
+ #### Use the loaded BiRefNet for inference
181
+ ```python
182
+ # Imports
183
+ from PIL import Image
184
+ import matplotlib.pyplot as plt
185
+ import torch
186
+ from torchvision import transforms
187
+ from models.birefnet import BiRefNet
188
+
189
+ birefnet = ... # -- BiRefNet should be loaded with codes above, either way.
190
+ torch.set_float32_matmul_precision(['high', 'highest'][0])
191
+ birefnet.to('cuda')
192
+ birefnet.eval()
193
+ birefnet.half()
194
+
195
+ def extract_object(birefnet, imagepath):
196
+ # Data settings
197
+ image_size = (1024, 1024)
198
+ transform_image = transforms.Compose([
199
+ transforms.Resize(image_size),
200
+ transforms.ToTensor(),
201
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
202
+ ])
203
+
204
+ image = Image.open(imagepath)
205
+ input_images = transform_image(image).unsqueeze(0).to('cuda').half()
206
+
207
+ # Prediction
208
+ with torch.no_grad():
209
+ preds = birefnet(input_images)[-1].sigmoid().cpu()
210
+ pred = preds[0].squeeze()
211
+ pred_pil = transforms.ToPILImage()(pred)
212
+ mask = pred_pil.resize(image.size)
213
+ image.putalpha(mask)
214
+ return image, mask
215
+
216
+ # Visualization
217
+ plt.axis("off")
218
+ plt.imshow(extract_object(birefnet, imagepath='PATH-TO-YOUR_IMAGE.jpg')[0])
219
+ plt.show()
220
+
221
+ ```
222
+
223
+ ### 2. Use inference endpoint locally:
224
+ > You may need to click the *deploy* and set up the endpoint by yourself, which would make some costs.
225
+ ```
226
+ import requests
227
+ import base64
228
+ from io import BytesIO
229
+ from PIL import Image
230
+
231
+
232
+ YOUR_HF_TOKEN = 'xxx'
233
+ API_URL = "xxx"
234
+ headers = {
235
+ "Authorization": "Bearer {}".format(YOUR_HF_TOKEN)
236
+ }
237
+
238
+ def base64_to_bytes(base64_string):
239
+ # Remove the data URI prefix if present
240
+ if "data:image" in base64_string:
241
+ base64_string = base64_string.split(",")[1]
242
+
243
+ # Decode the Base64 string into bytes
244
+ image_bytes = base64.b64decode(base64_string)
245
+ return image_bytes
246
+
247
+ def bytes_to_base64(image_bytes):
248
+ # Create a BytesIO object to handle the image data
249
+ image_stream = BytesIO(image_bytes)
250
+
251
+ # Open the image using Pillow (PIL)
252
+ image = Image.open(image_stream)
253
+ return image
254
+
255
+ def query(payload):
256
+ response = requests.post(API_URL, headers=headers, json=payload)
257
+ return response.json()
258
+
259
+ output = query({
260
+ "inputs": "https://hips.hearstapps.com/hmg-prod/images/gettyimages-1229892983-square.jpg",
261
+ "parameters": {}
262
+ })
263
+
264
+ output_image = bytes_to_base64(base64_to_bytes(output))
265
+ output_image
266
+ ```
267
+
268
+
269
+ > This BiRefNet for standard dichotomous image segmentation (DIS) is trained on **DIS-TR** and validated on **DIS-TEs and DIS-VD**.
270
+
271
+ ## 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_).
272
+
273
+ This repo contains the weights of BiRefNet proposed in our paper, which has achieved the SOTA performance on three tasks (DIS, HRSOD, and COD).
274
+
275
+ Go to my GitHub page for BiRefNet codes and the latest updates: https://github.com/ZhengPeng7/BiRefNet :)
276
+
277
+
278
+ #### Try our online demos for inference:
279
+
280
+ + Online **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)
281
+ + **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)
282
+ + **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)
283
+ <img src="https://drive.google.com/thumbnail?id=12XmDhKtO1o2fEvBu4OE4ULVB2BK0ecWi&sz=w1080" />
284
+
285
+ ## Acknowledgement:
286
+
287
+ + Many thanks to @Freepik for their generous support on GPU resources for training higher resolution BiRefNet models and more of my explorations.
288
+ + Many thanks to @fal for their generous support on GPU resources for training better general BiRefNet models.
289
+ + Many thanks to @not-lain for his help on the better deployment of our BiRefNet model on HuggingFace.
290
+
291
+
292
+ ## Citation
293
+
294
+ ```
295
+ @article{zheng2024birefnet,
296
+ title={Bilateral Reference for High-Resolution Dichotomous Image Segmentation},
297
+ author={Zheng, Peng and Gao, Dehong and Fan, Deng-Ping and Liu, Li and Laaksonen, Jorma and Ouyang, Wanli and Sebe, Nicu},
298
+ journal={CAAI Artificial Intelligence Research},
299
+ volume = {3},
300
+ pages = {9150038},
301
+ year={2024}
302
+ }
303
+ ```