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_detection_model_test.py 36 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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
  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 super_gradients.conversion.gs_utils import import_onnx_graphsurgeon_or_fail_with_instructions
  12. from super_gradients.training.utils.quantization.selective_quantization_utils import SelectiveQuantizer
  13. from torch import nn
  14. from torch.utils.data import DataLoader
  15. from super_gradients.common.object_names import Models
  16. from super_gradients.conversion.conversion_enums import ExportTargetBackend, ExportQuantizationMode, DetectionOutputFormatMode
  17. from super_gradients.conversion.onnx.nms import PickNMSPredictionsAndReturnAsFlatResult, PickNMSPredictionsAndReturnAsBatchedResult
  18. from super_gradients.conversion.tensorrt.nms import ConvertTRTFormatToFlatTensor
  19. from super_gradients.module_interfaces import ExportableObjectDetectionModel
  20. from super_gradients.module_interfaces.exportable_detector import ModelExportResult
  21. from super_gradients.training import models
  22. from super_gradients.training.dataloaders import coco2017_val # noqa
  23. from super_gradients.training.datasets.datasets_conf import COCO_DETECTION_CLASSES_LIST
  24. from super_gradients.training.utils.detection_utils import DetectionVisualization
  25. from super_gradients.training.utils.export_utils import infer_image_shape_from_model, infer_image_input_channels
  26. from super_gradients.training.utils.media.image import load_image
  27. gs = import_onnx_graphsurgeon_or_fail_with_instructions()
  28. class TestDetectionModelExport(unittest.TestCase):
  29. def setUp(self) -> None:
  30. logging.getLogger().setLevel(logging.DEBUG)
  31. this_dir = os.path.dirname(__file__)
  32. self.test_image_path = os.path.join(this_dir, "../data/tinycoco/images/val2017/000000444010.jpg")
  33. def test_the_most_common_export_use_case(self):
  34. """
  35. Test the most common export use case - export to ONNX with all default parameters
  36. """
  37. with tempfile.TemporaryDirectory() as tmpdirname:
  38. out_path = os.path.join(tmpdirname, "ppyoloe_s.onnx")
  39. ppyolo_e: ExportableObjectDetectionModel = models.get(Models.PP_YOLOE_S, pretrained_weights="coco")
  40. result = ppyolo_e.export(out_path)
  41. assert result.input_image_dtype == torch.uint8
  42. assert result.input_image_shape == (640, 640)
  43. assert result.input_image_channels == 3
  44. def test_models_produce_half(self):
  45. if not torch.cuda.is_available():
  46. self.skipTest("This test was skipped because target machine has not CUDA devices")
  47. input = torch.randn(1, 3, 640, 640).half().cuda()
  48. model = models.get(Models.YOLO_NAS_S, num_classes=80, pretrained_weights=None)
  49. model = nn.Sequential(model, model.get_decoding_module(100)).cuda().eval().half()
  50. output = model(input)
  51. assert output[0].dtype == torch.float16
  52. assert output[1].dtype == torch.float16
  53. model = models.get(Models.PP_YOLOE_S, num_classes=80, pretrained_weights=None)
  54. model = nn.Sequential(model, model.get_decoding_module(100)).cuda().eval().half()
  55. output = model(input)
  56. assert output[0].dtype == torch.float16
  57. assert output[1].dtype == torch.float16
  58. model = models.get(Models.YOLOX_S, num_classes=80, pretrained_weights=None)
  59. model = nn.Sequential(model, model.get_decoding_module(100)).cuda().eval().half()
  60. output = model(input)
  61. assert output[0].dtype == torch.float16
  62. assert output[1].dtype == torch.float16
  63. def test_infer_input_image_shape_from_model(self):
  64. assert infer_image_shape_from_model(models.get(Models.PP_YOLOE_S, num_classes=80, pretrained_weights=None)) is None
  65. assert infer_image_shape_from_model(models.get(Models.YOLO_NAS_S, num_classes=80, pretrained_weights=None)) is None
  66. assert infer_image_shape_from_model(models.get(Models.YOLOX_S, num_classes=80, pretrained_weights=None)) is None
  67. assert infer_image_shape_from_model(models.get(Models.PP_YOLOE_S, pretrained_weights="coco")) == (640, 640)
  68. assert infer_image_shape_from_model(models.get(Models.YOLO_NAS_S, pretrained_weights="coco")) == (640, 640)
  69. assert infer_image_shape_from_model(models.get(Models.YOLOX_S, pretrained_weights="coco")) == (640, 640)
  70. def test_infer_input_image_num_channels_from_model(self):
  71. assert infer_image_input_channels(models.get(Models.PP_YOLOE_S, num_classes=80, pretrained_weights=None)) == 3
  72. assert infer_image_input_channels(models.get(Models.YOLO_NAS_S, num_classes=80, pretrained_weights=None)) == 3
  73. assert infer_image_input_channels(models.get(Models.YOLOX_S, num_classes=80, pretrained_weights=None)) == 3
  74. assert infer_image_input_channels(models.get(Models.PP_YOLOE_S, pretrained_weights="coco")) == 3
  75. assert infer_image_input_channels(models.get(Models.YOLO_NAS_S, pretrained_weights="coco")) == 3
  76. assert infer_image_input_channels(models.get(Models.YOLOX_S, pretrained_weights="coco")) == 3
  77. def test_export_to_onnxruntime_flat(self):
  78. """
  79. Test export to ONNX with flat predictions
  80. """
  81. output_predictions_format = DetectionOutputFormatMode.FLAT_FORMAT
  82. confidence_threshold = 0.7
  83. nms_threshold = 0.6
  84. with tempfile.TemporaryDirectory() as tmpdirname:
  85. for model_type in [
  86. Models.YOLO_NAS_S,
  87. Models.PP_YOLOE_S,
  88. Models.YOLOX_S,
  89. ]:
  90. model_name = str(model_type).lower().replace(".", "_")
  91. out_path = os.path.join(tmpdirname, f"{model_name}_onnxruntime_flat.onnx")
  92. model_arch: ExportableObjectDetectionModel = models.get(model_name, pretrained_weights="coco")
  93. export_result = model_arch.export(
  94. out_path,
  95. input_image_shape=None, # Force .export() to infer image shape from the model itself
  96. engine=ExportTargetBackend.ONNXRUNTIME,
  97. output_predictions_format=output_predictions_format,
  98. confidence_threshold=confidence_threshold,
  99. nms_threshold=nms_threshold,
  100. )
  101. [flat_predictions] = self._run_inference_with_onnx(export_result)
  102. # Check that all predictions have confidence >= confidence_threshold
  103. assert (flat_predictions[:, 5] >= confidence_threshold).all()
  104. def test_export_to_onnxruntime_batch_format(self):
  105. output_predictions_format = DetectionOutputFormatMode.BATCH_FORMAT
  106. confidence_threshold = 0.7
  107. nms_threshold = 0.6
  108. with tempfile.TemporaryDirectory() as tmpdirname:
  109. for model_type in [
  110. Models.YOLO_NAS_S,
  111. Models.PP_YOLOE_S,
  112. Models.YOLOX_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: ExportableObjectDetectionModel = models.get(model_name, pretrained_weights="coco")
  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_S,
  135. Models.PP_YOLOE_S,
  136. Models.YOLOX_S,
  137. ]:
  138. model_name = str(model_type).lower().replace(".", "_")
  139. out_path = os.path.join(tmpdirname, f"{model_name}_tensorrt_flat.onnx")
  140. model_arch: ExportableObjectDetectionModel = models.get(model_name, pretrained_weights="coco")
  141. export_result = model_arch.export(
  142. out_path,
  143. input_image_shape=None, # Force .export() to infer image shape from the model itself
  144. engine=ExportTargetBackend.TENSORRT,
  145. output_predictions_format=output_predictions_format,
  146. confidence_threshold=confidence_threshold,
  147. nms_threshold=0.6,
  148. )
  149. assert export_result is not None
  150. def test_export_to_tensorrt_batch_format(self):
  151. output_predictions_format = DetectionOutputFormatMode.BATCH_FORMAT
  152. confidence_threshold = 0.25
  153. nms_threshold = 0.6
  154. with tempfile.TemporaryDirectory() as tmpdirname:
  155. for model_type in [
  156. Models.YOLO_NAS_S,
  157. Models.PP_YOLOE_S,
  158. Models.YOLOX_S,
  159. ]:
  160. model_name = str(model_type).lower().replace(".", "_")
  161. out_path = os.path.join(tmpdirname, f"{model_name}_tensorrt_batch.onnx")
  162. model_arch: ExportableObjectDetectionModel = models.get(model_name, pretrained_weights="coco")
  163. export_result = model_arch.export(
  164. out_path,
  165. input_image_shape=None, # Force .export() to infer image shape from the model itself
  166. engine=ExportTargetBackend.TENSORRT,
  167. output_predictions_format=output_predictions_format,
  168. nms_threshold=nms_threshold,
  169. confidence_threshold=confidence_threshold,
  170. )
  171. assert export_result is not None
  172. def test_export_to_tensorrt_batch_format_yolox_s(self):
  173. output_predictions_format = DetectionOutputFormatMode.BATCH_FORMAT
  174. confidence_threshold = 0.25
  175. nms_threshold = 0.6
  176. model_type = Models.YOLOX_S
  177. device = "cpu"
  178. with tempfile.TemporaryDirectory() as tmpdirname:
  179. model_name = str(model_type).lower().replace(".", "_")
  180. out_path = os.path.join(tmpdirname, f"{model_name}_tensorrt_batch.onnx")
  181. model_arch: ExportableObjectDetectionModel = models.get(model_name, pretrained_weights="coco")
  182. export_result = model_arch.export(
  183. out_path,
  184. input_image_shape=None, # Force .export() to infer image shape from the model itself
  185. device=device,
  186. engine=ExportTargetBackend.TENSORRT,
  187. output_predictions_format=output_predictions_format,
  188. nms_threshold=nms_threshold,
  189. confidence_threshold=confidence_threshold,
  190. )
  191. assert export_result is not None
  192. def test_export_to_tensorrt_batch_format_yolo_nas_s(self):
  193. output_predictions_format = DetectionOutputFormatMode.BATCH_FORMAT
  194. confidence_threshold = 0.25
  195. nms_threshold = 0.6
  196. model_type = Models.YOLO_NAS_S
  197. with tempfile.TemporaryDirectory() as tmpdirname:
  198. model_name = str(model_type).lower().replace(".", "_")
  199. out_path = os.path.join(tmpdirname, f"{model_name}_tensorrt_batch.onnx")
  200. model_arch: ExportableObjectDetectionModel = models.get(model_name, pretrained_weights="coco")
  201. export_result = model_arch.export(
  202. out_path,
  203. input_image_shape=None, # Force .export() to infer image shape from the model itself
  204. engine=ExportTargetBackend.TENSORRT,
  205. output_predictions_format=output_predictions_format,
  206. nms_threshold=nms_threshold,
  207. confidence_threshold=confidence_threshold,
  208. )
  209. assert export_result is not None
  210. def test_export_to_tensorrt_batch_format_ppyolo_e(self):
  211. output_predictions_format = DetectionOutputFormatMode.BATCH_FORMAT
  212. confidence_threshold = 0.25
  213. nms_threshold = 0.6
  214. model_type = Models.PP_YOLOE_S
  215. with tempfile.TemporaryDirectory() as tmpdirname:
  216. model_name = str(model_type).lower().replace(".", "_")
  217. out_path = os.path.join(tmpdirname, f"{model_name}_tensorrt_batch.onnx")
  218. model_arch: ExportableObjectDetectionModel = models.get(model_name, pretrained_weights="coco")
  219. export_result = model_arch.export(
  220. out_path,
  221. input_image_shape=None, # Force .export() to infer image shape from the model itself
  222. engine=ExportTargetBackend.TENSORRT,
  223. output_predictions_format=output_predictions_format,
  224. nms_threshold=nms_threshold,
  225. confidence_threshold=confidence_threshold,
  226. )
  227. assert export_result is not None
  228. def test_export_model_with_custom_input_image_shape(self):
  229. with tempfile.TemporaryDirectory() as tmpdirname:
  230. out_path = os.path.join(tmpdirname, "ppyoloe_s_custom_image_shape.onnx")
  231. ppyolo_e: ExportableObjectDetectionModel = models.get(Models.PP_YOLOE_S, pretrained_weights="coco")
  232. export_result = ppyolo_e.export(out_path, engine=ExportTargetBackend.ONNXRUNTIME, input_image_shape=(320, 320), output_predictions_format="flat")
  233. [flat_predictions] = self._run_inference_with_onnx(export_result)
  234. assert flat_predictions.shape[1] == 7
  235. def test_export_with_fp16_quantization(self):
  236. if torch.cuda.is_available():
  237. device = "cuda"
  238. elif torch.backends.mps.is_available():
  239. device = "mps"
  240. else:
  241. self.skipTest("No CUDA or MPS device available")
  242. max_predictions_per_image = 300
  243. with tempfile.TemporaryDirectory() as tmpdirname:
  244. tmpdirname = "."
  245. out_path = os.path.join(tmpdirname, "ppyoloe_s_with_fp16_quantization.onnx")
  246. ppyolo_e: ExportableObjectDetectionModel = models.get(Models.PP_YOLOE_S, pretrained_weights="coco")
  247. export_result = ppyolo_e.export(
  248. out_path,
  249. device=device,
  250. engine=ExportTargetBackend.ONNXRUNTIME,
  251. max_predictions_per_image=max_predictions_per_image,
  252. input_image_shape=(640, 640),
  253. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  254. quantization_mode=ExportQuantizationMode.FP16,
  255. )
  256. num_predictions, pred_boxes, pred_scores, pred_classes = self._run_inference_with_onnx(export_result)
  257. assert num_predictions.shape == (1, 1)
  258. assert pred_boxes.shape == (1, max_predictions_per_image, 4)
  259. assert pred_scores.shape == (1, max_predictions_per_image)
  260. assert pred_classes.shape == (1, max_predictions_per_image)
  261. assert pred_classes.dtype == np.int64
  262. def test_export_with_fp16_quantization_tensort(self):
  263. if torch.cuda.is_available():
  264. device = "cuda"
  265. elif torch.backends.mps.is_available():
  266. device = "mps"
  267. else:
  268. self.skipTest("No CUDA or MPS device available")
  269. max_predictions_per_image = 300
  270. with tempfile.TemporaryDirectory() as tmpdirname:
  271. out_path = os.path.join(tmpdirname, "ppyoloe_s_with_fp16_quantization.onnx")
  272. ppyolo_e: ExportableObjectDetectionModel = models.get(Models.PP_YOLOE_S, pretrained_weights="coco")
  273. export_result = ppyolo_e.export(
  274. out_path,
  275. device=device,
  276. engine=ExportTargetBackend.TENSORRT,
  277. max_predictions_per_image=max_predictions_per_image,
  278. input_image_shape=(640, 640),
  279. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  280. quantization_mode=ExportQuantizationMode.FP16,
  281. )
  282. assert export_result is not None
  283. def test_export_with_int8_quantization(self):
  284. with tempfile.TemporaryDirectory() as tmpdirname:
  285. out_path = os.path.join(tmpdirname, "ppyoloe_s_with_int8_quantization.onnx")
  286. dummy_calibration_dataset = [torch.randn((3, 640, 640), dtype=torch.float32) for _ in range(32)]
  287. dummy_calibration_loader = DataLoader(dummy_calibration_dataset, batch_size=8, num_workers=0)
  288. ppyolo_e: ExportableObjectDetectionModel = models.get(Models.PP_YOLOE_S, pretrained_weights="coco")
  289. export_result = ppyolo_e.export(
  290. out_path,
  291. engine=ExportTargetBackend.ONNXRUNTIME,
  292. max_predictions_per_image=300,
  293. input_image_shape=(640, 640),
  294. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  295. quantization_mode=ExportQuantizationMode.INT8,
  296. calibration_loader=dummy_calibration_loader,
  297. )
  298. num_predictions, pred_boxes, pred_scores, pred_classes = self._run_inference_with_onnx(export_result)
  299. assert num_predictions.shape == (1, 1)
  300. assert pred_boxes.shape == (1, 300, 4)
  301. assert pred_scores.shape == (1, 300)
  302. assert pred_classes.shape == (1, 300)
  303. assert pred_classes.dtype == np.int64
  304. def test_export_quantized_with_calibration_to_tensorrt(self):
  305. with tempfile.TemporaryDirectory() as tmpdirname:
  306. out_path = os.path.join(tmpdirname, "pp_yoloe_s_quantized_with_calibration.onnx")
  307. dummy_calibration_dataset = [torch.randn((3, 640, 640), dtype=torch.float32) for _ in range(32)]
  308. dummy_calibration_loader = DataLoader(dummy_calibration_dataset, batch_size=8)
  309. ppyolo_e: ExportableObjectDetectionModel = models.get(Models.PP_YOLOE_S, pretrained_weights="coco")
  310. export_result = ppyolo_e.export(
  311. out_path,
  312. engine=ExportTargetBackend.TENSORRT,
  313. max_predictions_per_image=300,
  314. input_image_shape=(640, 640),
  315. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  316. quantization_mode=ExportQuantizationMode.INT8,
  317. calibration_loader=dummy_calibration_loader,
  318. )
  319. assert export_result is not None
  320. def test_export_yolonas_quantized_with_calibration_to_tensorrt(self):
  321. with tempfile.TemporaryDirectory() as tmpdirname:
  322. out_path = os.path.join(tmpdirname, "yolonas_s_quantized_with_calibration.onnx")
  323. dummy_calibration_dataset = [torch.randn((3, 640, 640), dtype=torch.float32) for _ in range(32)]
  324. dummy_calibration_loader = DataLoader(dummy_calibration_dataset, batch_size=8)
  325. ppyolo_e: ExportableObjectDetectionModel = models.get(Models.YOLO_NAS_S, pretrained_weights="coco")
  326. export_result = ppyolo_e.export(
  327. out_path,
  328. engine=ExportTargetBackend.TENSORRT,
  329. num_pre_nms_predictions=300,
  330. max_predictions_per_image=100,
  331. input_image_shape=(640, 640),
  332. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  333. quantization_mode=ExportQuantizationMode.INT8,
  334. calibration_loader=dummy_calibration_loader,
  335. )
  336. assert export_result is not None
  337. def test_export_yolox_quantized_int8_with_calibration_to_tensorrt(self):
  338. with tempfile.TemporaryDirectory() as tmpdirname:
  339. out_path = os.path.join(tmpdirname, "yolox_quantized_with_calibration.onnx")
  340. dummy_calibration_dataset = [torch.randn((3, 640, 640), dtype=torch.float32) for _ in range(32)]
  341. dummy_calibration_loader = DataLoader(dummy_calibration_dataset, batch_size=8)
  342. ppyolo_e: ExportableObjectDetectionModel = models.get(Models.YOLOX_S, pretrained_weights="coco")
  343. export_result = ppyolo_e.export(
  344. out_path,
  345. engine=ExportTargetBackend.TENSORRT,
  346. num_pre_nms_predictions=300,
  347. max_predictions_per_image=100,
  348. input_image_shape=(640, 640),
  349. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  350. quantization_mode=ExportQuantizationMode.INT8,
  351. calibration_loader=dummy_calibration_loader,
  352. )
  353. assert export_result is not None
  354. def _run_inference_with_onnx(self, export_result: ModelExportResult):
  355. # onnx_filename = out_path, input_shape = export_result.image_shape, output_predictions_format = output_predictions_format
  356. image = self._get_image_as_bchw(export_result.input_image_shape)
  357. image_8u = self._get_image(export_result.input_image_shape)
  358. session = onnxruntime.InferenceSession(export_result.output)
  359. inputs = [o.name for o in session.get_inputs()]
  360. outputs = [o.name for o in session.get_outputs()]
  361. result = session.run(outputs, {inputs[0]: image})
  362. class_names = COCO_DETECTION_CLASSES_LIST
  363. color_mapping = DetectionVisualization._generate_color_mapping(len(class_names))
  364. if export_result.output_predictions_format == DetectionOutputFormatMode.FLAT_FORMAT:
  365. flat_predictions = result[0] # [N, (batch_index, x1, y1, x2, y2, score, class]
  366. assert flat_predictions.shape[1] == 7
  367. for i in range(flat_predictions.shape[0]):
  368. x1, y1, x2, y2 = flat_predictions[i, 1:5]
  369. class_score = flat_predictions[i, 5]
  370. class_label = int(flat_predictions[i, 6])
  371. image_8u = DetectionVisualization.draw_box_title(
  372. image_np=image_8u,
  373. x1=int(x1),
  374. y1=int(y1),
  375. x2=int(x2),
  376. y2=int(y2),
  377. class_id=class_label,
  378. class_names=class_names,
  379. color_mapping=color_mapping,
  380. box_thickness=2,
  381. pred_conf=class_score,
  382. )
  383. else:
  384. num_predictions, pred_boxes, pred_scores, pred_classes = result
  385. for pred_index in range(num_predictions[0, 0]):
  386. x1, y1, x2, y2 = pred_boxes[0, pred_index]
  387. class_score = pred_scores[0, pred_index]
  388. class_label = pred_classes[0, pred_index]
  389. image_8u = DetectionVisualization.draw_box_title(
  390. image_np=image_8u,
  391. x1=int(x1),
  392. y1=int(y1),
  393. x2=int(x2),
  394. y2=int(y2),
  395. class_id=class_label,
  396. class_names=class_names,
  397. color_mapping=color_mapping,
  398. box_thickness=2,
  399. pred_conf=class_score,
  400. )
  401. plt.figure(figsize=(10, 10))
  402. plt.imshow(image_8u)
  403. plt.title(os.path.basename(export_result.output))
  404. plt.tight_layout()
  405. plt.show()
  406. return result
  407. def test_export_already_quantized_model(self):
  408. model = models.get(Models.YOLO_NAS_S, pretrained_weights="coco")
  409. q_util = SelectiveQuantizer(
  410. default_quant_modules_calibrator_weights="max",
  411. default_quant_modules_calibrator_inputs="histogram",
  412. default_per_channel_quant_weights=True,
  413. default_learn_amax=False,
  414. verbose=True,
  415. )
  416. q_util.quantize_module(model)
  417. with tempfile.TemporaryDirectory() as tmpdirname:
  418. output_model1 = os.path.join(tmpdirname, "yolo_nas_s_quantized_explicit_int8.onnx")
  419. output_model2 = os.path.join(tmpdirname, "yolo_nas_s_quantized.onnx")
  420. # If model is already quantized to int8, the export should be successful but model should not be quantized again
  421. model.export(
  422. output_model1,
  423. quantization_mode=ExportQuantizationMode.INT8,
  424. )
  425. # If model is quantized but quantization mode is not specified, the export should be also successful
  426. # but model should not be quantized again
  427. model.export(
  428. output_model2,
  429. quantization_mode=None,
  430. )
  431. # If model is already quantized to int8, we should not be able to export model to FP16
  432. with self.assertRaises(RuntimeError):
  433. model.export(
  434. "yolo_nas_s_quantized.onnx",
  435. quantization_mode=ExportQuantizationMode.FP16,
  436. )
  437. # Assert two files are the same
  438. # with open(output_model1, "rb") as f1, open(output_model2, "rb") as f2:
  439. # assert hashlib.md5(f1.read()) == hashlib.md5(f2.read())
  440. def manual_test_export_export_all_variants(self):
  441. """
  442. This test is not run automatically, it is used to generate all possible export variants of the model
  443. for benchmarking purposes.
  444. """
  445. export_dir = "export_all_variants"
  446. os.makedirs(export_dir, exist_ok=True)
  447. benchmark_command_dir = "benchmark_command.sh"
  448. with open(benchmark_command_dir, "w") as f:
  449. pass
  450. for output_predictions_format in [DetectionOutputFormatMode.BATCH_FORMAT, DetectionOutputFormatMode.FLAT_FORMAT]:
  451. for engine in [ExportTargetBackend.ONNXRUNTIME, ExportTargetBackend.TENSORRT]:
  452. for quantization in [None, ExportQuantizationMode.FP16, ExportQuantizationMode.INT8]:
  453. device = "cpu"
  454. if torch.cuda.is_available():
  455. device = "cuda"
  456. elif torch.backends.mps.is_available() and quantization == ExportQuantizationMode.FP16:
  457. # Skip this case because when using MPS device we are getting:
  458. # RuntimeError: Placeholder storage has not been allocated on MPS device!
  459. # And when using CPU:
  460. # RuntimeError: RuntimeError: "slow_conv2d_cpu" not implemented for 'Half'
  461. continue
  462. # if quantization == ExportQuantizationMode.FP16 and device == "cpu":
  463. # # Skip this case because the FP16 quantization uses model inference
  464. # pass
  465. for model_type in [
  466. # Models.YOLOX_S don't have full support for YOLOX so it's commented out,
  467. Models.PP_YOLOE_S,
  468. Models.YOLO_NAS_S,
  469. ]:
  470. model_name = str(model_type).lower()
  471. model = models.get(model_type, pretrained_weights="coco")
  472. quantization_suffix = f"_{quantization.value}" if quantization is not None else ""
  473. onnx_filename = f"{model_name}_{engine.value}_{output_predictions_format.value}{quantization_suffix}.onnx"
  474. with self.subTest(msg=onnx_filename):
  475. model.export(
  476. os.path.join(export_dir, onnx_filename),
  477. device=device,
  478. quantization_mode=quantization,
  479. engine=engine,
  480. output_predictions_format=output_predictions_format,
  481. preprocessing=False,
  482. postprocessing=False,
  483. )
  484. with open(benchmark_command_dir, "a") as f:
  485. quantization_param = "--int8" if quantization == ExportQuantizationMode.INT8 else "--fp16"
  486. output_file_log = onnx_filename.replace(".onnx", ".log")
  487. trtexec_command = (
  488. f"/usr/src/tensorrt/bin/trtexec "
  489. f"--onnx=/deci/eugene/{onnx_filename} {quantization_param} "
  490. f"--avgRuns=100 --duration=15 > /deci/eugene/{output_file_log}\n"
  491. )
  492. f.write(trtexec_command)
  493. def test_trt_nms_convert_to_flat_result(self):
  494. batch_size = 7
  495. max_predictions_per_image = 100
  496. if torch.cuda.is_available():
  497. available_devices = ["cpu", "cuda"]
  498. available_dtypes = [torch.float16, torch.float32]
  499. else:
  500. available_devices = ["cpu"]
  501. available_dtypes = [torch.float32]
  502. for device in available_devices:
  503. for dtype in available_dtypes:
  504. num_detections = torch.randint(1, max_predictions_per_image, (batch_size, 1), dtype=torch.int32)
  505. detection_boxes = torch.randn((batch_size, max_predictions_per_image, 4), dtype=dtype)
  506. detection_scores = torch.randn((batch_size, max_predictions_per_image), dtype=dtype)
  507. detection_classes = torch.randint(0, 80, (batch_size, max_predictions_per_image), dtype=torch.int32)
  508. torch_module = ConvertTRTFormatToFlatTensor(batch_size, max_predictions_per_image)
  509. flat_predictions_torch = torch_module(num_detections, detection_boxes, detection_scores, detection_classes)
  510. print(flat_predictions_torch.shape, flat_predictions_torch.dtype, flat_predictions_torch)
  511. onnx_file = "ConvertTRTFormatToFlatTensor.onnx"
  512. graph = ConvertTRTFormatToFlatTensor.as_graph(
  513. batch_size=batch_size, max_predictions_per_image=max_predictions_per_image, dtype=dtype, device=device
  514. )
  515. model = gs.export_onnx(graph)
  516. onnx.checker.check_model(model)
  517. onnx.save(model, onnx_file)
  518. session = onnxruntime.InferenceSession(onnx_file)
  519. inputs = [o.name for o in session.get_inputs()]
  520. outputs = [o.name for o in session.get_outputs()]
  521. [flat_predictions_onnx] = session.run(
  522. output_names=outputs,
  523. input_feed={
  524. inputs[0]: num_detections.numpy(),
  525. inputs[1]: detection_boxes.numpy(),
  526. inputs[2]: detection_scores.numpy(),
  527. inputs[3]: detection_classes.numpy(),
  528. },
  529. )
  530. np.testing.assert_allclose(flat_predictions_torch.numpy(), flat_predictions_onnx, rtol=1e-3, atol=1e-3)
  531. def test_onnx_nms_flat_result(self):
  532. max_predictions = 100
  533. batch_size = 7
  534. if torch.cuda.is_available():
  535. available_devices = ["cpu", "cuda"]
  536. available_dtypes = [torch.float16, torch.float32]
  537. else:
  538. available_devices = ["cpu"]
  539. available_dtypes = [torch.float32]
  540. for device in available_devices:
  541. for dtype in available_dtypes:
  542. # Run a few tests to ensure ONNX model produces the same results as the PyTorch model
  543. # And also can handle dynamic shapes input
  544. pred_boxes = torch.randn((batch_size, max_predictions, 4), dtype=dtype)
  545. pred_scores = torch.randn((batch_size, max_predictions, 40), dtype=dtype)
  546. selected_indexes = torch.tensor([[6, 10, 4], [1, 13, 4], [2, 17, 2], [2, 18, 2]], dtype=torch.int64)
  547. torch_module = PickNMSPredictionsAndReturnAsFlatResult(
  548. batch_size=batch_size, num_pre_nms_predictions=max_predictions, max_predictions_per_image=max_predictions
  549. )
  550. torch_result = torch_module(pred_boxes, pred_scores, selected_indexes)
  551. with tempfile.TemporaryDirectory() as temp_dir:
  552. onnx_file = os.path.join(temp_dir, "PickNMSPredictionsAndReturnAsFlatResult.onnx")
  553. graph = PickNMSPredictionsAndReturnAsFlatResult.as_graph(
  554. batch_size=batch_size, num_pre_nms_predictions=max_predictions, max_predictions_per_image=max_predictions, device=device, dtype=dtype
  555. )
  556. model = gs.export_onnx(graph)
  557. onnx.checker.check_model(model)
  558. onnx.save(model, onnx_file)
  559. session = onnxruntime.InferenceSession(onnx_file)
  560. inputs = [o.name for o in session.get_inputs()]
  561. outputs = [o.name for o in session.get_outputs()]
  562. [onnx_result] = session.run(outputs, {inputs[0]: pred_boxes.numpy(), inputs[1]: pred_scores.numpy(), inputs[2]: selected_indexes.numpy()})
  563. np.testing.assert_allclose(torch_result.numpy(), onnx_result, rtol=1e-3, atol=1e-3)
  564. def test_onnx_nms_batch_result(self):
  565. max_predictions = 100
  566. batch_size = 7
  567. if torch.cuda.is_available():
  568. available_devices = ["cpu", "cuda"]
  569. available_dtypes = [torch.float16, torch.float32]
  570. else:
  571. available_devices = ["cpu"]
  572. available_dtypes = [torch.float32]
  573. for device in available_devices:
  574. for dtype in available_dtypes:
  575. # Run a few tests to ensure ONNX model produces the same results as the PyTorch model
  576. # And also can handle dynamic shapes input
  577. pred_boxes = torch.randn((batch_size, max_predictions, 4), dtype=dtype)
  578. pred_scores = torch.randn((batch_size, max_predictions, 40), dtype=dtype)
  579. selected_indexes = torch.tensor([[6, 10, 4], [1, 13, 4], [2, 17, 2], [2, 18, 2]], dtype=torch.int64)
  580. torch_module = PickNMSPredictionsAndReturnAsBatchedResult(
  581. batch_size=batch_size, num_pre_nms_predictions=max_predictions, max_predictions_per_image=max_predictions
  582. )
  583. torch_result = torch_module(pred_boxes, pred_scores, selected_indexes)
  584. with tempfile.TemporaryDirectory() as temp_dir:
  585. onnx_file = os.path.join(temp_dir, "PickNMSPredictionsAndReturnAsBatchedResult.onnx")
  586. graph = PickNMSPredictionsAndReturnAsBatchedResult.as_graph(
  587. batch_size=batch_size, num_pre_nms_predictions=max_predictions, max_predictions_per_image=max_predictions, device=device, dtype=dtype
  588. )
  589. model = gs.export_onnx(graph)
  590. onnx.checker.check_model(model)
  591. onnx.save(model, onnx_file)
  592. session = onnxruntime.InferenceSession(onnx_file)
  593. inputs = [o.name for o in session.get_inputs()]
  594. outputs = [o.name for o in session.get_outputs()]
  595. onnx_result = session.run(outputs, {inputs[0]: pred_boxes.numpy(), inputs[1]: pred_scores.numpy(), inputs[2]: selected_indexes.numpy()})
  596. np.testing.assert_allclose(torch_result[0].numpy(), onnx_result[0], rtol=1e-3, atol=1e-3)
  597. np.testing.assert_allclose(torch_result[1].numpy(), onnx_result[1], rtol=1e-3, atol=1e-3)
  598. np.testing.assert_allclose(torch_result[2].numpy(), onnx_result[2], rtol=1e-3, atol=1e-3)
  599. np.testing.assert_allclose(torch_result[3].numpy(), onnx_result[3], rtol=1e-3, atol=1e-3)
  600. def _get_image_as_bchw(self, image_shape=(640, 640)):
  601. """
  602. :param image_shape: Output image shape (rows, cols)
  603. :return: Image in NCHW format
  604. """
  605. image = load_image(self.test_image_path)
  606. image = cv2.resize(image, dsize=tuple(reversed(image_shape)), interpolation=cv2.INTER_LINEAR)
  607. image = np.transpose(np.expand_dims(image, 0), (0, 3, 1, 2))
  608. return image
  609. def _get_image(self, image_shape=(640, 640)):
  610. """
  611. :param image_shape: Output image shape (rows, cols)
  612. :return: Image in HWC format
  613. """
  614. image = load_image(self.test_image_path)
  615. image = cv2.resize(image, dsize=tuple(reversed(image_shape)), interpolation=cv2.INTER_LINEAR)
  616. return image
  617. if __name__ == "__main__":
  618. unittest.main()
Tip!

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

Comments

Loading...