-
Notifications
You must be signed in to change notification settings - Fork 4
/
export.py
295 lines (266 loc) · 9 KB
/
export.py
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
import argparse
import warnings
warnings.filterwarnings("ignore", module="onnxconverter_common.float16")
import onnx
import torch
from onnxconverter_common import float16
from DeDoDe import DeDoDeDescriptorB, DeDoDeDetectorL, DeDoDeEnd2End, DualSoftMaxMatcher
from DeDoDe.utils import load_image
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument(
"--img_size",
nargs=2,
type=int,
default=[256, 256],
required=False,
help="Sample image size for ONNX tracing. Please provide two integers (height width). Ensure that you have enough memory to run the export.",
)
parser.add_argument(
"--detector",
type=str,
default="L",
choices=["L"],
required=False,
help="DeDoDe detector variant. Supported detectors are 'L'. Defaults to 'L'.",
)
parser.add_argument(
"--descriptor",
type=str,
default="B",
choices=["B"],
required=False,
help="DeDoDe descriptor variant. Supported descriptors are 'B'. Defaults to 'B'.",
)
parser.add_argument(
"--matcher",
type=str,
default="dual_softmax",
choices=["dual_softmax"],
required=False,
help="Matcher variant. Supported matchers are 'dual_softmax'. Defaults to 'dual_softmax'.",
)
parser.add_argument(
"--detector_path",
type=str,
default=None,
required=False,
help="Path to save the detector ONNX model.",
)
parser.add_argument(
"--descriptor_path",
type=str,
default=None,
required=False,
help="Path to save the descriptor ONNX model.",
)
parser.add_argument(
"--matcher_path",
type=str,
default=None,
required=False,
help="Path to save the matcher ONNX model.",
)
parser.add_argument(
"--end2end",
action="store_true",
help="Whether to export an end-to-end pipeline instead of individual models.",
)
parser.add_argument(
"--end2end_path",
type=str,
default=None,
required=False,
help="Path to save the end2end DeDoDe ONNX model.",
)
parser.add_argument(
"--dynamic_img_size",
action="store_true",
help="Whether to allow dynamic image sizes.",
)
parser.add_argument(
"--dynamic_batch",
action="store_true",
help="Whether to allow dynamic batch size.",
)
parser.add_argument(
"--fp16",
action="store_true",
help="Whether to also export float16 (half) ONNX model (CUDA only).",
)
# Detector-specific args:
parser.add_argument(
"--num_keypoints",
type=int,
default=1024,
required=False,
help="Number of keypoints outputted by the detector. This number must be smaller than image height * width. Defaults to 1024.",
)
return parser.parse_args()
def export_onnx(
img_size=[256, 256],
im_A_path="assets/im_A.jpg",
im_B_path="assets/im_B.jpg",
detector="L",
descriptor="B",
matcher="dual_softmax",
detector_path=None,
descriptor_path=None,
matcher_path=None,
end2end_path=None,
end2end=False,
dynamic_img_size=False,
dynamic_batch=False,
fp16=False,
num_keypoints=1024,
):
# Handle args.
H, W = img_size
assert (
H * W > num_keypoints
), "Number of keypoints must be smaller than image height * width."
if end2end:
assert (
detector_path is None and descriptor_path is None and matcher_path is None
), "Individual models will be combined in end2end export."
if end2end_path is None:
end2end_path = (
f"weights/dedode_end2end"
f"{f'_{H}x{W}' if not dynamic_img_size else ''}"
f"_{num_keypoints}"
".onnx"
)
else:
assert end2end_path is None, "Exporting individual models."
if detector_path is None:
detector_path = (
f"weights/detector_{detector}"
f"{f'_{H}x{W}' if not dynamic_img_size else ''}"
f"_{num_keypoints}"
".onnx"
)
if descriptor_path is None:
descriptor_path = (
f"weights/descriptor_{descriptor}"
f"{f'_{H}x{W}' if not dynamic_img_size else ''}"
f"_{num_keypoints}"
".onnx"
)
if matcher_path is None:
matcher_path = f"weights/matcher.onnx"
# Load inputs and models.
device = torch.device(
"cuda"
) # Can also export on CPU if you have more free RAM than VRAM. Must export on CUDA for FP16.
im_A = load_image(im_A_path, H=H, W=W).to(device)
im_B = load_image(im_B_path, H=H, W=W).to(device)
detector = DeDoDeDetectorL(num_keypoints=num_keypoints).eval().to(device)
descriptor = DeDoDeDescriptorB().eval().to(device)
matcher = (
DualSoftMaxMatcher(normalize=True, inv_temp=20, threshold=0.1).eval().to(device)
)
dedode_end2end = DeDoDeEnd2End(detector, descriptor, matcher)
# Export.
opset_version = 16 # Minimum 16 due to grid sample op.
if end2end:
images = torch.concat([im_A, im_B])
dynamic_axes = {
"images": {},
"matches_A": {0: "num_matches"},
"matches_B": {0: "num_matches"},
"batch_ids": {0: "num_matches"},
}
if dynamic_batch:
dynamic_axes["images"].update({0: "batch_size"})
if dynamic_img_size:
dynamic_axes["images"].update({2: "height", 3: "width"})
torch.onnx.export(
dedode_end2end,
images,
end2end_path,
input_names=["images"],
output_names=["matches_A", "matches_B", "batch_ids"],
opset_version=opset_version,
dynamic_axes=dynamic_axes,
)
if fp16:
convert_fp16(end2end_path)
else:
# Prepare intermediate inputs to individual models.
with torch.no_grad():
keypoints_A = detector(im_A)
keypoints_B = detector(im_B)
description_A = descriptor(im_A, keypoints_A)
description_B = descriptor(im_B, keypoints_B)
dynamic_axes = {"image": {}, "keypoints": {}}
if dynamic_batch:
dynamic_axes["image"].update({0: "batch_size"})
dynamic_axes["keypoints"].update({0: "batch_size"})
if dynamic_img_size:
dynamic_axes["image"].update({2: "height", 3: "width"})
torch.onnx.export(
detector,
im_A,
detector_path,
input_names=["image"],
output_names=["keypoints"],
opset_version=opset_version,
dynamic_axes=dynamic_axes,
)
if fp16:
convert_fp16(detector_path)
dynamic_axes = {"image": {}, "keypoints": {}, "description": {}}
if dynamic_batch:
dynamic_axes["image"].update({0: "batch_size"})
dynamic_axes["keypoints"].update({0: "batch_size"})
dynamic_axes["description"].update({0: "batch_size"})
if dynamic_img_size:
dynamic_axes["image"].update({2: "height", 3: "width"})
torch.onnx.export(
descriptor,
(im_A, keypoints_A),
descriptor_path,
input_names=["image", "keypoints"],
output_names=["description"],
opset_version=opset_version,
dynamic_axes=dynamic_axes,
)
if fp16:
convert_fp16(descriptor_path)
dynamic_axes = {
"keypoints_A": {},
"description_A": {},
"keypoints_B": {},
"description_B": {},
"matches_A": {0: "num_matches"},
"matches_B": {0: "num_matches"},
"batch_ids": {0: "num_matches"},
}
if dynamic_batch:
dynamic_axes["keypoints_A"].update({0: "batch_size"})
dynamic_axes["description_A"].update({0: "batch_size"})
dynamic_axes["keypoints_B"].update({0: "batch_size"})
dynamic_axes["description_B"].update({0: "batch_size"})
torch.onnx.export(
matcher,
(keypoints_A, description_A, keypoints_B, description_B),
matcher_path,
input_names=[
"keypoints_A",
"description_A",
"keypoints_B",
"description_B",
],
output_names=["matches_A", "matches_B", "batch_ids"],
opset_version=opset_version,
dynamic_axes=dynamic_axes,
)
if fp16:
convert_fp16(matcher_path)
def convert_fp16(onnx_model_path: str):
end2end_onnx = onnx.load(onnx_model_path)
end2end_fp16 = float16.convert_float_to_float16(end2end_onnx)
onnx.save(end2end_fp16, onnx_model_path.replace(".onnx", "_fp16.onnx"))
if __name__ == "__main__":
args = parse_args()
export_onnx(**vars(args))