forked from cvg/LightGlue
-
Notifications
You must be signed in to change notification settings - Fork 35
/
dynamo.py
285 lines (252 loc) · 11.1 KB
/
dynamo.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
from pathlib import Path
from typing import Annotated, Optional
import cv2
import typer
from lightglue_dynamo.cli_utils import check_multiple_of
from lightglue_dynamo.config import Extractor, InferenceDevice
app = typer.Typer()
@app.callback()
def callback():
"""LightGlue Dynamo CLI"""
@app.command()
def export(
extractor_type: Annotated[Extractor, typer.Argument()] = Extractor.superpoint,
output: Annotated[
Optional[Path], # typer does not support Path | None # noqa: UP007
typer.Option("-o", "--output", dir_okay=False, writable=True, help="Path to save exported model."),
] = None,
batch_size: Annotated[
int,
typer.Option(
"-b", "--batch-size", min=0, help="Batch size of exported ONNX model. Set to 0 to mark as dynamic."
),
] = 0,
height: Annotated[
int, typer.Option("-h", "--height", min=0, help="Height of input image. Set to 0 to mark as dynamic.")
] = 0,
width: Annotated[
int, typer.Option("-w", "--width", min=0, help="Width of input image. Set to 0 to mark as dynamic.")
] = 0,
num_keypoints: Annotated[
int, typer.Option(min=128, help="Number of keypoints outputted by feature extractor.")
] = 1024,
fuse_multi_head_attention: Annotated[
bool,
typer.Option(
"--fuse-multi-head-attention",
help="Fuse multi-head attention subgraph into one optimized operation. (ONNX Runtime-only).",
),
] = False,
opset: Annotated[int, typer.Option(min=16, max=20, help="ONNX opset version of exported model.")] = 17,
fp16: Annotated[bool, typer.Option("--fp16", help="Whether to also convert to FP16.")] = False,
):
"""Export LightGlue to ONNX."""
import onnx
import torch
from onnxruntime.tools.symbolic_shape_infer import SymbolicShapeInference
from onnxruntime.transformers.float16 import convert_float_to_float16
from lightglue_dynamo.models import DISK, LightGlue, Pipeline, SuperPoint
from lightglue_dynamo.ops import use_fused_multi_head_attention
match extractor_type:
case Extractor.superpoint:
extractor = SuperPoint(num_keypoints=num_keypoints)
case Extractor.disk:
extractor = DISK(num_keypoints=num_keypoints)
matcher = LightGlue(**extractor_type.lightglue_config)
pipeline = Pipeline(extractor, matcher).eval()
if output is None:
output = Path(f"weights/{extractor_type}_lightglue_pipeline.onnx")
check_multiple_of(batch_size, 2)
check_multiple_of(height, extractor_type.input_dim_divisor)
check_multiple_of(width, extractor_type.input_dim_divisor)
if height > 0 and width > 0 and num_keypoints > height * width:
raise typer.BadParameter("num_keypoints cannot be greater than height * width.")
if fuse_multi_head_attention:
typer.echo(
"Warning: Multi-head attention nodes will be fused. Exported model will only work with ONNX Runtime CPU & CUDA execution providers."
)
if torch.__version__ < "2.4":
raise typer.Abort("Fused multi-head attention requires PyTorch 2.4 or later.")
use_fused_multi_head_attention()
dynamic_axes = {"images": {}, "keypoints": {}}
if batch_size == 0:
dynamic_axes["images"][0] = "batch_size"
dynamic_axes["keypoints"][0] = "batch_size"
if height == 0:
dynamic_axes["images"][2] = "height"
if width == 0:
dynamic_axes["images"][3] = "width"
dynamic_axes |= {"matches": {0: "num_matches"}, "mscores": {0: "num_matches"}}
torch.onnx.export(
pipeline,
torch.zeros(batch_size or 2, extractor_type.input_channels, height or 256, width or 256),
str(output),
input_names=["images"],
output_names=["keypoints", "matches", "mscores"],
opset_version=opset,
dynamic_axes=dynamic_axes,
)
onnx.checker.check_model(output)
onnx.save_model(SymbolicShapeInference.infer_shapes(onnx.load_model(output), auto_merge=True), output) # type: ignore
typer.echo(f"Successfully exported model to {output}")
if fp16:
typer.echo(
"Converting to FP16. Warning: This FP16 model should NOT be used for TensorRT. TRT provides its own fp16 option."
)
onnx.save_model(convert_float_to_float16(onnx.load_model(output)), output.with_suffix(".fp16.onnx"))
@app.command()
def infer(
model_path: Annotated[Path, typer.Argument(exists=True, dir_okay=False, readable=True, help="Path to ONNX model.")],
left_image_path: Annotated[
Path, typer.Argument(exists=True, dir_okay=False, readable=True, help="Path to first image.")
],
right_image_path: Annotated[
Path, typer.Argument(exists=True, dir_okay=False, readable=True, help="Path to second image.")
],
extractor_type: Annotated[Extractor, typer.Argument()] = Extractor.superpoint,
output_path: Annotated[
Optional[Path], # noqa: UP007
typer.Option(
"-o",
"--output",
dir_okay=False,
writable=True,
help="Path to save output matches figure. If not given, show visualization.",
),
] = None,
height: Annotated[
int,
typer.Option("-h", "--height", min=1, help="Height of input image at which to perform inference."),
] = 1024,
width: Annotated[
int,
typer.Option("-w", "--width", min=1, help="Width of input image at which to perform inference."),
] = 1024,
device: Annotated[
InferenceDevice, typer.Option("-d", "--device", help="Device to run inference on.")
] = InferenceDevice.cpu,
fp16: Annotated[bool, typer.Option("--fp16", help="Whether model uses FP16 precision.")] = False,
profile: Annotated[bool, typer.Option("--profile", help="Whether to profile model execution.")] = False,
):
"""Run inference for LightGlue ONNX model."""
import numpy as np
import onnxruntime as ort
from lightglue_dynamo import viz
from lightglue_dynamo.preprocessors import DISKPreprocessor, SuperPointPreprocessor
raw_images = [left_image_path, right_image_path]
raw_images = [cv2.resize(cv2.imread(str(i)), (width, height)) for i in raw_images]
images = np.stack(raw_images)
match extractor_type:
case Extractor.superpoint:
images = SuperPointPreprocessor.preprocess(images)
case Extractor.disk:
images = DISKPreprocessor.preprocess(images)
images = images.astype(np.float16 if fp16 and device != InferenceDevice.tensorrt else np.float32)
session_options = ort.SessionOptions()
session_options.enable_profiling = profile
# session_options.optimized_model_filepath = "weights/ort_optimized.onnx"
providers = [("CPUExecutionProvider", {})]
if device == InferenceDevice.cuda:
providers.insert(0, ("CUDAExecutionProvider", {}))
elif device == InferenceDevice.tensorrt:
providers.insert(0, ("CUDAExecutionProvider", {}))
providers.insert(
0,
(
"TensorrtExecutionProvider",
{
"trt_engine_cache_enable": True,
"trt_engine_cache_path": "weights/.trtcache_engines",
"trt_timing_cache_enable": True,
"trt_timing_cache_path": "weights/.trtcache_timings",
"trt_fp16_enable": fp16,
},
),
)
elif device == InferenceDevice.openvino:
providers.insert(0, ("OpenVINOExecutionProvider", {}))
session = ort.InferenceSession(model_path, session_options, providers)
for _ in range(100 if profile else 1):
keypoints, matches, mscores = session.run(None, {"images": images})
viz.plot_images(raw_images)
viz.plot_matches(keypoints[0][matches[..., 1]], keypoints[1][matches[..., 2]], color="lime", lw=0.2)
if output_path is None:
viz.plt.show()
else:
viz.save_plot(output_path)
@app.command()
def trtexec(
model_path: Annotated[
Path,
typer.Argument(exists=True, dir_okay=False, readable=True, help="Path to ONNX model or built TensorRT engine."),
],
left_image_path: Annotated[
Path, typer.Argument(exists=True, dir_okay=False, readable=True, help="Path to first image.")
],
right_image_path: Annotated[
Path, typer.Argument(exists=True, dir_okay=False, readable=True, help="Path to second image.")
],
extractor_type: Annotated[Extractor, typer.Argument()] = Extractor.superpoint,
output_path: Annotated[
Optional[Path], # noqa: UP007
typer.Option(
"-o",
"--output",
dir_okay=False,
writable=True,
help="Path to save output matches figure. If not given, show visualization.",
),
] = None,
height: Annotated[
int,
typer.Option("-h", "--height", min=1, help="Height of input image at which to perform inference."),
] = 1024,
width: Annotated[
int,
typer.Option("-w", "--width", min=1, help="Width of input image at which to perform inference."),
] = 1024,
fp16: Annotated[bool, typer.Option("--fp16", help="Whether model uses FP16 precision.")] = False,
profile: Annotated[bool, typer.Option("--profile", help="Whether to profile model execution.")] = False,
):
"""Run pure TensorRT inference for LightGlue model using Polygraphy (requires TensorRT to be installed)."""
import numpy as np
from polygraphy.backend.common import BytesFromPath
from polygraphy.backend.trt import (
CreateConfig,
EngineFromBytes,
EngineFromNetwork,
NetworkFromOnnxPath,
SaveEngine,
TrtRunner,
)
from lightglue_dynamo import viz
from lightglue_dynamo.preprocessors import DISKPreprocessor, SuperPointPreprocessor
raw_images = [left_image_path, right_image_path]
raw_images = [cv2.resize(cv2.imread(str(i)), (width, height)) for i in raw_images]
images = np.stack(raw_images)
match extractor_type:
case Extractor.superpoint:
images = SuperPointPreprocessor.preprocess(images)
case Extractor.disk:
images = DISKPreprocessor.preprocess(images)
images = images.astype(np.float32)
# Build TensorRT engine
if model_path.suffix == ".engine":
build_engine = EngineFromBytes(BytesFromPath(str(model_path)))
else: # .onnx
build_engine = EngineFromNetwork(NetworkFromOnnxPath(str(model_path)), config=CreateConfig(fp16=fp16))
build_engine = SaveEngine(build_engine, str(model_path.with_suffix(".engine")))
with TrtRunner(build_engine) as runner:
for _ in range(10 if profile else 1): # Warm-up if profiling
outputs = runner.infer(feed_dict={"images": images})
keypoints, matches, mscores = outputs["keypoints"], outputs["matches"], outputs["mscores"] # noqa: F841
if profile:
typer.echo(f"Inference Time: {runner.last_inference_time():.3f} s")
viz.plot_images(raw_images)
viz.plot_matches(keypoints[0][matches[..., 1]], keypoints[1][matches[..., 2]], color="lime", lw=0.2)
if output_path is None:
viz.plt.show()
else:
viz.save_plot(output_path)
if __name__ == "__main__":
app()