File size: 8,682 Bytes
7c89e28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "LTj2A0RUQFNo"
   },
   "source": [
    "# Convert our BiRefNet weights to onnx format.\n",
    "\n",
    "> This colab file is modified from [Kazuhito00](https://github.com/Kazuhito00)'s nice work.\n",
    "\n",
    "> Repo: https://github.com/Kazuhito00/BiRefNet-ONNX-Sample  \n",
    "> Original Colab: https://colab.research.google.com/github/Kazuhito00/BiRefNet-ONNX-Sample/blob/main/Convert2ONNX.ipynb\n",
    "\n",
    "+ Currently, Colab with 12.7GB RAM / 15GB GPU Mem cannot hold the transformation of BiRefNet in default setting. So, I take BiRefNet with swin_v1_tiny backbone as an example."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Online Colab version: https://colab.research.google.com/drive/1z6OruR52LOvDDpnp516F-N4EyPGrp5om"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "781JHjLJmveh"
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "\n",
    "weights_file = 'BiRefNet-general-bb_swin_v1_tiny-epoch_232.pth'  # https://github.com/ZhengPeng7/BiRefNet/releases/download/v1/BiRefNet-general-bb_swin_v1_tiny-epoch_232.pth\n",
    "device = 'cuda' if torch.cuda.is_available() else 'cpu'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('config.py') as fp:\n",
    "    file_lines = fp.read()\n",
    "if 'swin_v1_tiny' in weights_file:\n",
    "    print('Set `swin_v1_tiny` as the backbone.')\n",
    "    file_lines = file_lines.replace(\n",
    "        '''\n",
    "            'pvt_v2_b2', 'pvt_v2_b5',               # 9-bs10, 10-bs5\n",
    "        ][6]\n",
    "        ''',\n",
    "        '''\n",
    "            'pvt_v2_b2', 'pvt_v2_b5',               # 9-bs10, 10-bs5\n",
    "        ][3]\n",
    "        ''',\n",
    "    )\n",
    "    with open('config.py', mode=\"w\") as fp:\n",
    "        fp.write(file_lines)\n",
    "else:\n",
    "    file_lines = file_lines.replace(\n",
    "        '''\n",
    "            'pvt_v2_b2', 'pvt_v2_b5',               # 9-bs10, 10-bs5\n",
    "        ][3]\n",
    "        ''',\n",
    "        '''\n",
    "            'pvt_v2_b2', 'pvt_v2_b5',               # 9-bs10, 10-bs5\n",
    "        ][6]\n",
    "        ''',\n",
    "    )\n",
    "    with open('config.py', mode=\"w\") as fp:\n",
    "        fp.write(file_lines)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "7lFgKfPS8Icy"
   },
   "outputs": [],
   "source": [
    "from utils import check_state_dict\n",
    "from models.birefnet import BiRefNet\n",
    "\n",
    "\n",
    "birefnet = BiRefNet(bb_pretrained=False)\n",
    "state_dict = torch.load('./{}'.format(weights_file), map_location=device)\n",
    "state_dict = check_state_dict(state_dict)\n",
    "birefnet.load_state_dict(state_dict)\n",
    "\n",
    "torch.set_float32_matmul_precision(['high', 'highest'][0])\n",
    "\n",
    "birefnet.to(device)\n",
    "_ = birefnet.eval()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "JVgJAdgxQVJW"
   },
   "source": [
    "# Process deform_conv2d in the conversion to ONNX"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "vJiZv0L75kTe"
   },
   "outputs": [],
   "source": [
    "from torchvision.ops.deform_conv import DeformConv2d\n",
    "import deform_conv2d_onnx_exporter\n",
    "\n",
    "# register deform_conv2d operator\n",
    "deform_conv2d_onnx_exporter.register_deform_conv2d_onnx_op()\n",
    "\n",
    "def convert_to_onnx(net, file_name='output.onnx', input_shape=(1024, 1024), device=device):\n",
    "    input = torch.randn(1, 3, input_shape[0], input_shape[1]).to(device)\n",
    "\n",
    "    input_layer_names = ['input_image']\n",
    "    output_layer_names = ['output_image']\n",
    "\n",
    "    torch.onnx.export(\n",
    "        net,\n",
    "        input,\n",
    "        file_name,\n",
    "        verbose=False,\n",
    "        opset_version=17,\n",
    "        input_names=input_layer_names,\n",
    "        output_names=output_layer_names,\n",
    "    )\n",
    "convert_to_onnx(birefnet, weights_file.replace('.pth', '.onnx'), input_shape=(1024, 1024), device=device)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "-eU-g40P1zS-"
   },
   "source": [
    "# Load ONNX weights and do the inference."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "LZ4HVqcoDvto"
   },
   "outputs": [],
   "source": [
    "from PIL import Image\n",
    "from torchvision import transforms\n",
    "\n",
    "\n",
    "transform_image = transforms.Compose([\n",
    "    transforms.Resize((1024, 1024)),\n",
    "    transforms.ToTensor(),\n",
    "    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n",
    "])\n",
    "\n",
    "imagepath = './Helicopter-HR.jpg'\n",
    "image = Image.open(imagepath)\n",
    "input_images = transform_image(image).unsqueeze(0).to(device)\n",
    "input_images_numpy = input_images.cpu().numpy()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "rwzdKX1EfYkd"
   },
   "outputs": [],
   "source": [
    "import onnxruntime\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "\n",
    "providers = ['CPUExecutionProvider'] if device == 'cpu' else ['CUDAExecutionProvider']\n",
    "onnx_session = onnxruntime.InferenceSession(\n",
    "    weights_file.replace('.pth', '.onnx'),\n",
    "    providers=providers\n",
    ")\n",
    "input_name = onnx_session.get_inputs()[0].name\n",
    "print(onnxruntime.get_device(), onnx_session.get_providers())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "DJVtxZUZum4-"
   },
   "outputs": [],
   "source": [
    "from time import time\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "time_st = time()\n",
    "pred_onnx = torch.tensor(\n",
    "    onnx_session.run(None, {input_name: input_images_numpy if device == 'cpu' else input_images_numpy})[-1]\n",
    ").squeeze(0).sigmoid().cpu()\n",
    "print(time() - time_st)\n",
    "\n",
    "plt.imshow(pred_onnx.squeeze(), cmap='gray'); plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with torch.no_grad():\n",
    "    preds = birefnet(input_images)[-1].sigmoid().cpu()\n",
    "plt.imshow(preds.squeeze(), cmap='gray'); plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "diff = abs(preds - pred_onnx)\n",
    "print('sum(diff):', diff.sum())\n",
    "plt.imshow((diff).squeeze(), cmap='gray'); plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "qzYHflt92Bjd"
   },
   "source": [
    "# Efficiency Comparison between .pth and .onnx"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "A5IYfT-uzphA",
    "outputId": "2999e345-950e-41b3-ddd3-9f58a71a3f21"
   },
   "outputs": [],
   "source": [
    "%%timeit\n",
    "with torch.no_grad():\n",
    "    preds = birefnet(input_images)[-1].sigmoid().cpu()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "G0Ul4rfNg1za"
   },
   "outputs": [],
   "source": [
    "%%timeit\n",
    "pred_onnx = torch.tensor(\n",
    "    onnx_session.run(None, {input_name: input_images_numpy})[-1]\n",
    ").squeeze(0).sigmoid().cpu()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "gpuType": "T4",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}