Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

export_pose_model_export_test.py 27 KB

You have to be logged in to leave a comment. Sign In
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
  1. import logging
  2. import os
  3. import tempfile
  4. import unittest
  5. import cv2
  6. import numpy as np
  7. import onnx
  8. import onnxruntime
  9. import torch
  10. from matplotlib import pyplot as plt
  11. from torch import nn
  12. from torch.utils.data import DataLoader
  13. from super_gradients.common.object_names import Models
  14. from super_gradients.conversion.conversion_enums import ExportTargetBackend, ExportQuantizationMode, DetectionOutputFormatMode
  15. from super_gradients.conversion.gs_utils import import_onnx_graphsurgeon_or_fail_with_instructions
  16. from super_gradients.conversion.onnx.pose_nms import PoseNMSAndReturnAsBatchedResult, PoseNMSAndReturnAsFlatResult
  17. from super_gradients.module_interfaces import ExportablePoseEstimationModel, PoseEstimationModelExportResult
  18. from super_gradients.training import models
  19. from super_gradients.training.dataloaders import coco2017_val # noqa
  20. from super_gradients.training.pretrained_models import MODEL_URLS
  21. from super_gradients.training.processing.processing import default_yolo_nas_pose_coco_processing_params
  22. from super_gradients.training.utils.export_utils import infer_image_shape_from_model, infer_image_input_channels
  23. from super_gradients.training.utils.media.image import load_image
  24. from super_gradients.training.utils.quantization.selective_quantization_utils import SelectiveQuantizer
  25. from super_gradients.training.utils.visualization.pose_estimation import PoseVisualization
  26. gs = import_onnx_graphsurgeon_or_fail_with_instructions()
  27. class TestPoseEstimationModelExport(unittest.TestCase):
  28. def setUp(self) -> None:
  29. logging.getLogger().setLevel(logging.DEBUG)
  30. this_dir = os.path.dirname(__file__)
  31. self.test_image_path = os.path.join(this_dir, "../data/tinycoco/images/val2017/000000444010.jpg")
  32. self.default_pretrained_weights = "coco_pose"
  33. self.default_model = Models.YOLO_NAS_POSE_S
  34. MODEL_URLS[Models.YOLO_NAS_POSE_S + "_coco_pose"] = "file:///G:/super-gradients/checkpoints/coco2017_yolo_nas_pose_s_mosaic_v2_average_model.pth"
  35. params = default_yolo_nas_pose_coco_processing_params()
  36. self.edge_links = params["edge_links"]
  37. self.edge_colors = params["edge_colors"]
  38. self.keypoint_colors = params["keypoint_colors"]
  39. def test_export_model_on_small_size(self):
  40. with tempfile.TemporaryDirectory() as tmpdirname:
  41. for model_type in [
  42. Models.YOLO_NAS_POSE_S,
  43. ]:
  44. out_path = os.path.join(tmpdirname, model_type + ".onnx")
  45. model: ExportablePoseEstimationModel = models.get(model_type, pretrained_weights=self.default_pretrained_weights)
  46. result = model.export(
  47. out_path,
  48. input_image_shape=(64, 64),
  49. num_pre_nms_predictions=2000,
  50. max_predictions_per_image=1000,
  51. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  52. )
  53. assert result.input_image_dtype == torch.uint8
  54. assert result.input_image_shape == (64, 64)
  55. def test_the_most_common_export_use_case(self):
  56. """
  57. Test the most common export use case - export to ONNX with all default parameters
  58. """
  59. with tempfile.TemporaryDirectory() as tmpdirname:
  60. out_path = os.path.join(tmpdirname, "model.onnx")
  61. model: ExportablePoseEstimationModel = models.get(self.default_model, pretrained_weights=self.default_pretrained_weights)
  62. result = model.export(out_path)
  63. assert result.input_image_dtype == torch.uint8
  64. assert result.input_image_shape == (640, 640)
  65. assert result.input_image_channels == 3
  66. def test_models_produce_half(self):
  67. if not torch.cuda.is_available():
  68. self.skipTest("This test was skipped because target machine has not CUDA devices")
  69. input = torch.randn(1, 3, 640, 640).half().cuda()
  70. model = models.get(Models.YOLO_NAS_POSE_S, num_classes=17, pretrained_weights=None)
  71. model = nn.Sequential(model, model.get_decoding_module(100)).cuda().eval().half()
  72. output = model(input)
  73. assert output[0].dtype == torch.float16
  74. assert output[1].dtype == torch.float16
  75. def test_infer_input_image_shape_from_model(self):
  76. assert infer_image_shape_from_model(models.get(Models.YOLO_NAS_POSE_S, num_classes=17, pretrained_weights=None)) is None
  77. assert infer_image_shape_from_model(models.get(Models.YOLO_NAS_POSE_S, pretrained_weights=self.default_pretrained_weights)) == (640, 640)
  78. def test_infer_input_image_num_channels_from_model(self):
  79. assert infer_image_input_channels(models.get(Models.YOLO_NAS_POSE_S, num_classes=17, pretrained_weights=None)) == 3
  80. assert infer_image_input_channels(models.get(Models.YOLO_NAS_POSE_S, pretrained_weights=self.default_pretrained_weights)) == 3
  81. def test_export_to_onnxruntime_flat(self):
  82. """
  83. Test export to ONNX with flat predictions
  84. """
  85. output_predictions_format = DetectionOutputFormatMode.FLAT_FORMAT
  86. confidence_threshold = 0.7
  87. nms_threshold = 0.6
  88. with tempfile.TemporaryDirectory() as tmpdirname:
  89. for model_type in [
  90. Models.YOLO_NAS_POSE_S,
  91. ]:
  92. model_name = str(model_type).lower().replace(".", "_")
  93. out_path = os.path.join(tmpdirname, f"{model_name}_onnxruntime_flat.onnx")
  94. model_arch: ExportablePoseEstimationModel = models.get(model_name, pretrained_weights=self.default_pretrained_weights)
  95. export_result = model_arch.export(
  96. out_path,
  97. input_image_shape=None, # Force .export() to infer image shape from the model itself
  98. engine=ExportTargetBackend.ONNXRUNTIME,
  99. output_predictions_format=output_predictions_format,
  100. confidence_threshold=confidence_threshold,
  101. nms_threshold=nms_threshold,
  102. )
  103. [flat_predictions] = self._run_inference_with_onnx(export_result)
  104. # Check that all predictions have confidence >= confidence_threshold
  105. assert (flat_predictions[:, 5] >= confidence_threshold).all()
  106. def test_export_to_onnxruntime_batch_format(self):
  107. output_predictions_format = DetectionOutputFormatMode.BATCH_FORMAT
  108. confidence_threshold = 0.7
  109. nms_threshold = 0.6
  110. with tempfile.TemporaryDirectory() as tmpdirname:
  111. for model_type in [
  112. Models.YOLO_NAS_POSE_S,
  113. ]:
  114. model_name = str(model_type).lower().replace(".", "_")
  115. out_path = os.path.join(tmpdirname, f"{model_name}_onnxruntime_batch.onnx")
  116. model_arch: ExportablePoseEstimationModel = models.get(model_name, pretrained_weights=self.default_pretrained_weights)
  117. export_result = model_arch.export(
  118. out_path,
  119. input_image_shape=None, # Force .export() to infer image shape from the model itself
  120. engine=ExportTargetBackend.ONNXRUNTIME,
  121. output_predictions_format=output_predictions_format,
  122. nms_threshold=nms_threshold,
  123. confidence_threshold=confidence_threshold,
  124. )
  125. self._run_inference_with_onnx(export_result)
  126. def test_export_to_tensorrt_flat(self):
  127. """
  128. Test export to tensorrt with flat predictions
  129. """
  130. output_predictions_format = DetectionOutputFormatMode.FLAT_FORMAT
  131. confidence_threshold = 0.7
  132. with tempfile.TemporaryDirectory() as tmpdirname:
  133. for model_type in [
  134. Models.YOLO_NAS_POSE_S,
  135. ]:
  136. model_name = str(model_type).lower().replace(".", "_")
  137. out_path = os.path.join(tmpdirname, f"{model_name}_tensorrt_flat.onnx")
  138. model_arch: ExportablePoseEstimationModel = models.get(model_name, pretrained_weights=self.default_pretrained_weights)
  139. export_result = model_arch.export(
  140. out_path,
  141. input_image_shape=None, # Force .export() to infer image shape from the model itself
  142. engine=ExportTargetBackend.TENSORRT,
  143. output_predictions_format=output_predictions_format,
  144. confidence_threshold=confidence_threshold,
  145. nms_threshold=0.6,
  146. )
  147. assert export_result is not None
  148. def test_export_to_tensorrt_batch_format(self):
  149. output_predictions_format = DetectionOutputFormatMode.BATCH_FORMAT
  150. confidence_threshold = 0.25
  151. nms_threshold = 0.6
  152. with tempfile.TemporaryDirectory() as tmpdirname:
  153. for model_type in [
  154. Models.YOLO_NAS_POSE_S,
  155. ]:
  156. model_name = str(model_type).lower().replace(".", "_")
  157. out_path = os.path.join(tmpdirname, f"{model_name}_tensorrt_batch.onnx")
  158. model_arch: ExportablePoseEstimationModel = models.get(model_name, pretrained_weights=self.default_pretrained_weights)
  159. export_result = model_arch.export(
  160. out_path,
  161. input_image_shape=None, # Force .export() to infer image shape from the model itself
  162. engine=ExportTargetBackend.TENSORRT,
  163. output_predictions_format=output_predictions_format,
  164. nms_threshold=nms_threshold,
  165. confidence_threshold=confidence_threshold,
  166. )
  167. assert export_result is not None
  168. def test_export_to_tensorrt_batch_format_YOLO_NAS_POSE_S(self):
  169. output_predictions_format = DetectionOutputFormatMode.BATCH_FORMAT
  170. confidence_threshold = 0.25
  171. nms_threshold = 0.6
  172. model_type = Models.YOLO_NAS_POSE_S
  173. with tempfile.TemporaryDirectory() as tmpdirname:
  174. model_name = str(model_type).lower().replace(".", "_")
  175. out_path = os.path.join(tmpdirname, f"{model_name}_tensorrt_batch.onnx")
  176. model_arch: ExportablePoseEstimationModel = models.get(model_name, pretrained_weights=self.default_pretrained_weights)
  177. export_result = model_arch.export(
  178. out_path,
  179. input_image_shape=None, # Force .export() to infer image shape from the model itself
  180. engine=ExportTargetBackend.TENSORRT,
  181. output_predictions_format=output_predictions_format,
  182. nms_threshold=nms_threshold,
  183. confidence_threshold=confidence_threshold,
  184. )
  185. assert export_result is not None
  186. def test_export_model_with_custom_input_image_shape(self):
  187. with tempfile.TemporaryDirectory() as tmpdirname:
  188. out_path = os.path.join(tmpdirname, "ppyoloe_s_custom_image_shape.onnx")
  189. model: ExportablePoseEstimationModel = models.get(Models.YOLO_NAS_POSE_S, pretrained_weights=self.default_pretrained_weights)
  190. export_result = model.export(out_path, engine=ExportTargetBackend.ONNXRUNTIME, input_image_shape=(320, 320), output_predictions_format="flat")
  191. [flat_predictions] = self._run_inference_with_onnx(export_result)
  192. bbox_dims = 4
  193. pose_score_dims = 1
  194. pose_coords_dims = 17 * 3
  195. assert flat_predictions.shape[1] == bbox_dims + pose_score_dims + pose_coords_dims
  196. def test_export_with_fp16_quantization(self):
  197. if torch.cuda.is_available():
  198. device = "cuda"
  199. elif torch.backends.mps.is_available():
  200. device = "mps"
  201. else:
  202. self.skipTest("No CUDA or MPS device available")
  203. return
  204. max_predictions_per_image = 300
  205. with tempfile.TemporaryDirectory() as tmpdirname:
  206. out_path = os.path.join(tmpdirname, "model_with_fp16_quantization.onnx")
  207. model: ExportablePoseEstimationModel = models.get(Models.YOLO_NAS_POSE_S, pretrained_weights=self.default_pretrained_weights)
  208. export_result = model.export(
  209. out_path,
  210. device=device,
  211. engine=ExportTargetBackend.ONNXRUNTIME,
  212. max_predictions_per_image=max_predictions_per_image,
  213. input_image_shape=(640, 640),
  214. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  215. quantization_mode=ExportQuantizationMode.FP16,
  216. )
  217. num_predictions, pred_boxes, pred_scores, pred_classes = self._run_inference_with_onnx(export_result)
  218. assert num_predictions.shape == (1, 1)
  219. assert pred_boxes.shape == (1, max_predictions_per_image, 4)
  220. assert pred_scores.shape == (1, max_predictions_per_image)
  221. assert pred_classes.shape == (1, max_predictions_per_image)
  222. assert pred_classes.dtype == np.int64
  223. def test_export_with_fp16_quantization_tensort(self):
  224. if torch.cuda.is_available():
  225. device = "cuda"
  226. elif torch.backends.mps.is_available():
  227. device = "mps"
  228. else:
  229. self.skipTest("No CUDA or MPS device available")
  230. max_predictions_per_image = 300
  231. with tempfile.TemporaryDirectory() as tmpdirname:
  232. out_path = os.path.join(tmpdirname, "model_s_with_fp16_quantization.onnx")
  233. model: ExportablePoseEstimationModel = models.get(Models.YOLO_NAS_POSE_S, pretrained_weights=self.default_pretrained_weights)
  234. export_result = model.export(
  235. out_path,
  236. device=device,
  237. engine=ExportTargetBackend.TENSORRT,
  238. max_predictions_per_image=max_predictions_per_image,
  239. input_image_shape=(640, 640),
  240. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  241. quantization_mode=ExportQuantizationMode.FP16,
  242. )
  243. assert export_result is not None
  244. def test_export_with_int8_quantization(self):
  245. with tempfile.TemporaryDirectory() as tmpdirname:
  246. out_path = os.path.join(tmpdirname, "model_s_with_int8_quantization.onnx")
  247. dummy_calibration_dataset = [torch.randn((3, 640, 640), dtype=torch.float32) for _ in range(32)]
  248. dummy_calibration_loader = DataLoader(dummy_calibration_dataset, batch_size=8, num_workers=0)
  249. ppyolo_e: ExportablePoseEstimationModel = models.get(Models.YOLO_NAS_POSE_S, pretrained_weights=self.default_pretrained_weights)
  250. export_result = ppyolo_e.export(
  251. out_path,
  252. engine=ExportTargetBackend.ONNXRUNTIME,
  253. max_predictions_per_image=300,
  254. input_image_shape=(640, 640),
  255. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  256. quantization_mode=ExportQuantizationMode.INT8,
  257. calibration_loader=dummy_calibration_loader,
  258. )
  259. num_predictions, pred_boxes, pred_scores, pred_classes = self._run_inference_with_onnx(export_result)
  260. assert num_predictions.shape == (1, 1)
  261. assert pred_boxes.shape == (1, 300, 4)
  262. assert pred_scores.shape == (1, 300)
  263. assert pred_classes.shape == (1, 300)
  264. assert pred_classes.dtype == np.int64
  265. def test_export_quantized_with_calibration_to_tensorrt(self):
  266. with tempfile.TemporaryDirectory() as tmpdirname:
  267. out_path = os.path.join(tmpdirname, "model_quantized_with_calibration.onnx")
  268. dummy_calibration_dataset = [torch.randn((3, 640, 640), dtype=torch.float32) for _ in range(32)]
  269. dummy_calibration_loader = DataLoader(dummy_calibration_dataset, batch_size=8)
  270. ppyolo_e: ExportablePoseEstimationModel = models.get(Models.YOLO_NAS_POSE_S, pretrained_weights=self.default_pretrained_weights)
  271. export_result = ppyolo_e.export(
  272. out_path,
  273. engine=ExportTargetBackend.TENSORRT,
  274. max_predictions_per_image=300,
  275. input_image_shape=(640, 640),
  276. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  277. quantization_mode=ExportQuantizationMode.INT8,
  278. calibration_loader=dummy_calibration_loader,
  279. )
  280. assert export_result is not None
  281. def test_export_yolonas_quantized_with_calibration_to_tensorrt(self):
  282. with tempfile.TemporaryDirectory() as tmpdirname:
  283. out_path = os.path.join(tmpdirname, "yolonas_s_quantized_with_calibration.onnx")
  284. dummy_calibration_dataset = [torch.randn((3, 640, 640), dtype=torch.float32) for _ in range(32)]
  285. dummy_calibration_loader = DataLoader(dummy_calibration_dataset, batch_size=8)
  286. ppyolo_e: ExportablePoseEstimationModel = models.get(Models.YOLO_NAS_POSE_S, pretrained_weights=self.default_pretrained_weights)
  287. export_result = ppyolo_e.export(
  288. out_path,
  289. engine=ExportTargetBackend.TENSORRT,
  290. num_pre_nms_predictions=300,
  291. max_predictions_per_image=100,
  292. input_image_shape=(640, 640),
  293. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  294. quantization_mode=ExportQuantizationMode.INT8,
  295. calibration_loader=dummy_calibration_loader,
  296. )
  297. assert export_result is not None
  298. def _run_inference_with_onnx(self, export_result: PoseEstimationModelExportResult):
  299. # onnx_filename = out_path, input_shape = export_result.image_shape, output_predictions_format = output_predictions_format
  300. image = self._get_image_as_bchw(export_result.input_image_shape)
  301. image_8u = self._get_image(export_result.input_image_shape)
  302. session = onnxruntime.InferenceSession(export_result.output)
  303. inputs = [o.name for o in session.get_inputs()]
  304. outputs = [o.name for o in session.get_outputs()]
  305. result = session.run(outputs, {inputs[0]: image})
  306. if export_result.output_predictions_format == DetectionOutputFormatMode.FLAT_FORMAT:
  307. flat_predictions = result[0] # [N, (batch_index, x1, y1, x2, y2, score, class]
  308. assert flat_predictions.shape[1] == 1 + 4 + 1 + 17 * 3
  309. boxes = flat_predictions[:, 1:5]
  310. scores = flat_predictions[:, 5]
  311. poses = flat_predictions[:, 6:].reshape(-1, 17, 3)
  312. image_8u = PoseVisualization.draw_poses(
  313. image_8u,
  314. poses=poses,
  315. boxes=boxes,
  316. scores=scores,
  317. show_keypoint_confidence=True,
  318. edge_links=self.edge_links,
  319. edge_colors=self.edge_colors,
  320. keypoint_colors=self.keypoint_colors,
  321. )
  322. else:
  323. # Hard-coded unpacking for batch size 1
  324. [num_predictions], [pred_boxes], [pred_scores], [pred_joints] = result
  325. image_8u = PoseVisualization.draw_poses(
  326. image_8u,
  327. poses=pred_joints[0 : num_predictions[0]],
  328. boxes=pred_boxes[0 : num_predictions[0]],
  329. scores=pred_scores[0 : num_predictions[0]],
  330. show_keypoint_confidence=True,
  331. edge_links=self.edge_links,
  332. edge_colors=self.edge_colors,
  333. keypoint_colors=self.keypoint_colors,
  334. )
  335. plt.figure(figsize=(10, 10))
  336. plt.imshow(image_8u)
  337. plt.title(os.path.basename(export_result.output))
  338. plt.tight_layout()
  339. plt.show()
  340. return result
  341. def test_export_already_quantized_model(self):
  342. model = models.get(Models.YOLO_NAS_POSE_S, pretrained_weights=self.default_pretrained_weights)
  343. q_util = SelectiveQuantizer(
  344. default_quant_modules_calibrator_weights="max",
  345. default_quant_modules_calibrator_inputs="histogram",
  346. default_per_channel_quant_weights=True,
  347. default_learn_amax=False,
  348. verbose=True,
  349. )
  350. q_util.quantize_module(model)
  351. with tempfile.TemporaryDirectory() as tmpdirname:
  352. output_model1 = os.path.join(tmpdirname, "YOLO_NAS_POSE_S_quantized_explicit_int8.onnx")
  353. output_model2 = os.path.join(tmpdirname, "YOLO_NAS_POSE_S_quantized.onnx")
  354. # If model is already quantized to int8, the export should be successful but model should not be quantized again
  355. model.export(
  356. output_model1,
  357. quantization_mode=ExportQuantizationMode.INT8,
  358. )
  359. # If model is quantized but quantization mode is not specified, the export should be also successful
  360. # but model should not be quantized again
  361. model.export(
  362. output_model2,
  363. quantization_mode=None,
  364. )
  365. # If model is already quantized to int8, we should not be able to export model to FP16
  366. with self.assertRaises(RuntimeError):
  367. model.export(
  368. "YOLO_NAS_POSE_S_quantized.onnx",
  369. quantization_mode=ExportQuantizationMode.FP16,
  370. )
  371. # Assert two files are the same
  372. # with open(output_model1, "rb") as f1, open(output_model2, "rb") as f2:
  373. # assert hashlib.md5(f1.read()) == hashlib.md5(f2.read())
  374. def test_onnx_nms_flat_result(self):
  375. max_predictions = 100
  376. batch_size = 7
  377. num_joints = 17
  378. if torch.cuda.is_available():
  379. available_devices = ["cpu", "cuda"]
  380. available_dtypes = [torch.float16, torch.float32]
  381. else:
  382. available_devices = ["cpu"]
  383. available_dtypes = [torch.float32]
  384. for device in available_devices:
  385. for dtype in available_dtypes:
  386. # Run a few tests to ensure ONNX model produces the same results as the PyTorch model
  387. # And also can handle dynamic shapes input
  388. pred_boxes = torch.randn((batch_size, max_predictions, 4), dtype=dtype)
  389. pred_scores = torch.randn((batch_size, max_predictions, 1), dtype=dtype)
  390. pred_joints = torch.randn((batch_size, max_predictions, num_joints, 3), dtype=dtype)
  391. selected_indexes = torch.tensor([[6, 0, 4], [1, 0, 3], [2, 0, 2], [2, 0, 1]], dtype=torch.int64)
  392. torch_module = PoseNMSAndReturnAsFlatResult(
  393. batch_size=batch_size, num_pre_nms_predictions=max_predictions, max_predictions_per_image=max_predictions
  394. )
  395. torch_result = torch_module(pred_boxes, pred_scores, pred_joints, selected_indexes)
  396. with tempfile.TemporaryDirectory() as temp_dir:
  397. onnx_file = os.path.join(temp_dir, "PoseNMSAndReturnAsFlatResult.onnx")
  398. graph = PoseNMSAndReturnAsFlatResult.as_graph(
  399. batch_size=batch_size, num_pre_nms_predictions=max_predictions, max_predictions_per_image=max_predictions, device=device, dtype=dtype
  400. )
  401. model = gs.export_onnx(graph)
  402. onnx.checker.check_model(model)
  403. onnx.save(model, onnx_file)
  404. session = onnxruntime.InferenceSession(onnx_file)
  405. inputs = [o.name for o in session.get_inputs()]
  406. outputs = [o.name for o in session.get_outputs()]
  407. [onnx_result] = session.run(
  408. outputs,
  409. {inputs[0]: pred_boxes.numpy(), inputs[1]: pred_scores.numpy(), inputs[2]: pred_joints.numpy(), inputs[3]: selected_indexes.numpy()},
  410. )
  411. np.testing.assert_allclose(torch_result.numpy(), onnx_result, rtol=1e-3, atol=1e-3)
  412. def test_onnx_nms_batch_result(self):
  413. max_predictions = 100
  414. batch_size = 7
  415. num_joints = 17
  416. if torch.cuda.is_available():
  417. available_devices = ["cpu", "cuda"]
  418. available_dtypes = [torch.float16, torch.float32]
  419. else:
  420. available_devices = ["cpu"]
  421. available_dtypes = [torch.float32]
  422. for device in available_devices:
  423. for dtype in available_dtypes:
  424. # Run a few tests to ensure ONNX model produces the same results as the PyTorch model
  425. # And also can handle dynamic shapes input
  426. pred_boxes = torch.randn((batch_size, max_predictions, 4), dtype=dtype)
  427. pred_scores = torch.randn((batch_size, max_predictions, 1), dtype=dtype)
  428. pred_joints = torch.randn((batch_size, max_predictions, num_joints, 3), dtype=dtype)
  429. selected_indexes = torch.tensor([[6, 0, 4], [1, 0, 3], [2, 0, 2], [2, 0, 1]], dtype=torch.int64)
  430. torch_module = PoseNMSAndReturnAsBatchedResult(
  431. batch_size=batch_size, num_pre_nms_predictions=max_predictions, max_predictions_per_image=max_predictions
  432. )
  433. torch_result = torch_module(pred_boxes, pred_scores, pred_joints, selected_indexes)
  434. with tempfile.TemporaryDirectory() as temp_dir:
  435. onnx_file = os.path.join(temp_dir, "PoseNMSAndReturnAsBatchedResult.onnx")
  436. graph = PoseNMSAndReturnAsBatchedResult.as_graph(
  437. batch_size=batch_size, num_pre_nms_predictions=max_predictions, max_predictions_per_image=max_predictions, device=device, dtype=dtype
  438. )
  439. model = gs.export_onnx(graph)
  440. onnx.checker.check_model(model)
  441. onnx.save(model, onnx_file)
  442. session = onnxruntime.InferenceSession(onnx_file)
  443. inputs = [o.name for o in session.get_inputs()]
  444. outputs = [o.name for o in session.get_outputs()]
  445. onnx_result = session.run(
  446. outputs,
  447. {inputs[0]: pred_boxes.numpy(), inputs[1]: pred_scores.numpy(), inputs[2]: pred_joints.numpy(), inputs[3]: selected_indexes.numpy()},
  448. )
  449. np.testing.assert_allclose(torch_result[0].numpy(), onnx_result[0], rtol=1e-3, atol=1e-3)
  450. np.testing.assert_allclose(torch_result[1].numpy(), onnx_result[1], rtol=1e-3, atol=1e-3)
  451. np.testing.assert_allclose(torch_result[2].numpy(), onnx_result[2], rtol=1e-3, atol=1e-3)
  452. np.testing.assert_allclose(torch_result[3].numpy(), onnx_result[3], rtol=1e-3, atol=1e-3)
  453. def _get_image_as_bchw(self, image_shape=(640, 640)):
  454. """
  455. :param image_shape: Output image shape (rows, cols)
  456. :return: Image in NCHW format
  457. """
  458. image = load_image(self.test_image_path)
  459. image = cv2.resize(image, dsize=tuple(reversed(image_shape)), interpolation=cv2.INTER_LINEAR)
  460. image = np.transpose(np.expand_dims(image, 0), (0, 3, 1, 2))
  461. return image
  462. def _get_image(self, image_shape=(640, 640)):
  463. """
  464. :param image_shape: Output image shape (rows, cols)
  465. :return: Image in HWC format
  466. """
  467. image = load_image(self.test_image_path)
  468. image = cv2.resize(image, dsize=tuple(reversed(image_shape)), interpolation=cv2.INTER_LINEAR)
  469. return image
  470. if __name__ == "__main__":
  471. unittest.main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...