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 37 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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
  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_export_model_on_small_size(self):
  34. with tempfile.TemporaryDirectory() as tmpdirname:
  35. for model_type in [
  36. Models.YOLO_NAS_S,
  37. Models.PP_YOLOE_S,
  38. Models.YOLOX_S,
  39. ]:
  40. out_path = os.path.join(tmpdirname, model_type + ".onnx")
  41. ppyolo_e: ExportableObjectDetectionModel = models.get(model_type, pretrained_weights="coco")
  42. result = ppyolo_e.export(
  43. out_path,
  44. input_image_shape=(64, 64),
  45. num_pre_nms_predictions=2000,
  46. max_predictions_per_image=1000,
  47. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  48. )
  49. assert result.input_image_dtype == torch.uint8
  50. assert result.input_image_shape == (64, 64)
  51. def test_the_most_common_export_use_case(self):
  52. """
  53. Test the most common export use case - export to ONNX with all default parameters
  54. """
  55. with tempfile.TemporaryDirectory() as tmpdirname:
  56. out_path = os.path.join(tmpdirname, "ppyoloe_s.onnx")
  57. ppyolo_e: ExportableObjectDetectionModel = models.get(Models.PP_YOLOE_S, pretrained_weights="coco")
  58. result = ppyolo_e.export(out_path)
  59. assert result.input_image_dtype == torch.uint8
  60. assert result.input_image_shape == (640, 640)
  61. assert result.input_image_channels == 3
  62. def test_models_produce_half(self):
  63. if not torch.cuda.is_available():
  64. self.skipTest("This test was skipped because target machine has not CUDA devices")
  65. input = torch.randn(1, 3, 640, 640).half().cuda()
  66. model = models.get(Models.YOLO_NAS_S, num_classes=80, pretrained_weights=None)
  67. model = nn.Sequential(model, model.get_decoding_module(100)).cuda().eval().half()
  68. output = model(input)
  69. assert output[0].dtype == torch.float16
  70. assert output[1].dtype == torch.float16
  71. model = models.get(Models.PP_YOLOE_S, num_classes=80, pretrained_weights=None)
  72. model = nn.Sequential(model, model.get_decoding_module(100)).cuda().eval().half()
  73. output = model(input)
  74. assert output[0].dtype == torch.float16
  75. assert output[1].dtype == torch.float16
  76. model = models.get(Models.YOLOX_S, num_classes=80, pretrained_weights=None)
  77. model = nn.Sequential(model, model.get_decoding_module(100)).cuda().eval().half()
  78. output = model(input)
  79. assert output[0].dtype == torch.float16
  80. assert output[1].dtype == torch.float16
  81. def test_infer_input_image_shape_from_model(self):
  82. assert infer_image_shape_from_model(models.get(Models.PP_YOLOE_S, num_classes=80, pretrained_weights=None)) is None
  83. assert infer_image_shape_from_model(models.get(Models.YOLO_NAS_S, num_classes=80, pretrained_weights=None)) is None
  84. assert infer_image_shape_from_model(models.get(Models.YOLOX_S, num_classes=80, pretrained_weights=None)) is None
  85. assert infer_image_shape_from_model(models.get(Models.PP_YOLOE_S, pretrained_weights="coco")) == (640, 640)
  86. assert infer_image_shape_from_model(models.get(Models.YOLO_NAS_S, pretrained_weights="coco")) == (640, 640)
  87. assert infer_image_shape_from_model(models.get(Models.YOLOX_S, pretrained_weights="coco")) == (640, 640)
  88. def test_infer_input_image_num_channels_from_model(self):
  89. assert infer_image_input_channels(models.get(Models.PP_YOLOE_S, num_classes=80, pretrained_weights=None)) == 3
  90. assert infer_image_input_channels(models.get(Models.YOLO_NAS_S, num_classes=80, pretrained_weights=None)) == 3
  91. assert infer_image_input_channels(models.get(Models.YOLOX_S, num_classes=80, pretrained_weights=None)) == 3
  92. assert infer_image_input_channels(models.get(Models.PP_YOLOE_S, pretrained_weights="coco")) == 3
  93. assert infer_image_input_channels(models.get(Models.YOLO_NAS_S, pretrained_weights="coco")) == 3
  94. assert infer_image_input_channels(models.get(Models.YOLOX_S, pretrained_weights="coco")) == 3
  95. def test_export_to_onnxruntime_flat(self):
  96. """
  97. Test export to ONNX with flat predictions
  98. """
  99. output_predictions_format = DetectionOutputFormatMode.FLAT_FORMAT
  100. confidence_threshold = 0.7
  101. nms_threshold = 0.6
  102. with tempfile.TemporaryDirectory() as tmpdirname:
  103. for model_type in [
  104. Models.YOLO_NAS_S,
  105. Models.PP_YOLOE_S,
  106. Models.YOLOX_S,
  107. ]:
  108. model_name = str(model_type).lower().replace(".", "_")
  109. out_path = os.path.join(tmpdirname, f"{model_name}_onnxruntime_flat.onnx")
  110. model_arch: ExportableObjectDetectionModel = models.get(model_name, pretrained_weights="coco")
  111. export_result = model_arch.export(
  112. out_path,
  113. input_image_shape=None, # Force .export() to infer image shape from the model itself
  114. engine=ExportTargetBackend.ONNXRUNTIME,
  115. output_predictions_format=output_predictions_format,
  116. confidence_threshold=confidence_threshold,
  117. nms_threshold=nms_threshold,
  118. )
  119. [flat_predictions] = self._run_inference_with_onnx(export_result)
  120. # Check that all predictions have confidence >= confidence_threshold
  121. assert (flat_predictions[:, 5] >= confidence_threshold).all()
  122. def test_export_to_onnxruntime_batch_format(self):
  123. output_predictions_format = DetectionOutputFormatMode.BATCH_FORMAT
  124. confidence_threshold = 0.7
  125. nms_threshold = 0.6
  126. with tempfile.TemporaryDirectory() as tmpdirname:
  127. for model_type in [
  128. Models.YOLO_NAS_S,
  129. Models.PP_YOLOE_S,
  130. Models.YOLOX_S,
  131. ]:
  132. model_name = str(model_type).lower().replace(".", "_")
  133. out_path = os.path.join(tmpdirname, f"{model_name}_onnxruntime_batch.onnx")
  134. model_arch: ExportableObjectDetectionModel = models.get(model_name, pretrained_weights="coco")
  135. export_result = model_arch.export(
  136. out_path,
  137. input_image_shape=None, # Force .export() to infer image shape from the model itself
  138. engine=ExportTargetBackend.ONNXRUNTIME,
  139. output_predictions_format=output_predictions_format,
  140. nms_threshold=nms_threshold,
  141. confidence_threshold=confidence_threshold,
  142. )
  143. self._run_inference_with_onnx(export_result)
  144. def test_export_to_tensorrt_flat(self):
  145. """
  146. Test export to tensorrt with flat predictions
  147. """
  148. output_predictions_format = DetectionOutputFormatMode.FLAT_FORMAT
  149. confidence_threshold = 0.7
  150. with tempfile.TemporaryDirectory() as tmpdirname:
  151. for model_type in [
  152. Models.YOLO_NAS_S,
  153. Models.PP_YOLOE_S,
  154. Models.YOLOX_S,
  155. ]:
  156. model_name = str(model_type).lower().replace(".", "_")
  157. out_path = os.path.join(tmpdirname, f"{model_name}_tensorrt_flat.onnx")
  158. model_arch: ExportableObjectDetectionModel = models.get(model_name, pretrained_weights="coco")
  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. confidence_threshold=confidence_threshold,
  165. nms_threshold=0.6,
  166. )
  167. assert export_result is not None
  168. def test_export_to_tensorrt_batch_format(self):
  169. output_predictions_format = DetectionOutputFormatMode.BATCH_FORMAT
  170. confidence_threshold = 0.25
  171. nms_threshold = 0.6
  172. with tempfile.TemporaryDirectory() as tmpdirname:
  173. for model_type in [
  174. Models.YOLO_NAS_S,
  175. Models.PP_YOLOE_S,
  176. Models.YOLOX_S,
  177. ]:
  178. model_name = str(model_type).lower().replace(".", "_")
  179. out_path = os.path.join(tmpdirname, f"{model_name}_tensorrt_batch.onnx")
  180. model_arch: ExportableObjectDetectionModel = models.get(model_name, pretrained_weights="coco")
  181. export_result = model_arch.export(
  182. out_path,
  183. input_image_shape=None, # Force .export() to infer image shape from the model itself
  184. engine=ExportTargetBackend.TENSORRT,
  185. output_predictions_format=output_predictions_format,
  186. nms_threshold=nms_threshold,
  187. confidence_threshold=confidence_threshold,
  188. )
  189. assert export_result is not None
  190. def test_export_to_tensorrt_batch_format_yolox_s(self):
  191. output_predictions_format = DetectionOutputFormatMode.BATCH_FORMAT
  192. confidence_threshold = 0.25
  193. nms_threshold = 0.6
  194. model_type = Models.YOLOX_S
  195. device = "cpu"
  196. with tempfile.TemporaryDirectory() as tmpdirname:
  197. model_name = str(model_type).lower().replace(".", "_")
  198. out_path = os.path.join(tmpdirname, f"{model_name}_tensorrt_batch.onnx")
  199. model_arch: ExportableObjectDetectionModel = models.get(model_name, pretrained_weights="coco")
  200. export_result = model_arch.export(
  201. out_path,
  202. input_image_shape=None, # Force .export() to infer image shape from the model itself
  203. device=device,
  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_yolo_nas_s(self):
  211. output_predictions_format = DetectionOutputFormatMode.BATCH_FORMAT
  212. confidence_threshold = 0.25
  213. nms_threshold = 0.6
  214. model_type = Models.YOLO_NAS_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_to_tensorrt_batch_format_ppyolo_e(self):
  229. output_predictions_format = DetectionOutputFormatMode.BATCH_FORMAT
  230. confidence_threshold = 0.25
  231. nms_threshold = 0.6
  232. model_type = Models.PP_YOLOE_S
  233. with tempfile.TemporaryDirectory() as tmpdirname:
  234. model_name = str(model_type).lower().replace(".", "_")
  235. out_path = os.path.join(tmpdirname, f"{model_name}_tensorrt_batch.onnx")
  236. model_arch: ExportableObjectDetectionModel = models.get(model_name, pretrained_weights="coco")
  237. export_result = model_arch.export(
  238. out_path,
  239. input_image_shape=None, # Force .export() to infer image shape from the model itself
  240. engine=ExportTargetBackend.TENSORRT,
  241. output_predictions_format=output_predictions_format,
  242. nms_threshold=nms_threshold,
  243. confidence_threshold=confidence_threshold,
  244. )
  245. assert export_result is not None
  246. def test_export_model_with_custom_input_image_shape(self):
  247. with tempfile.TemporaryDirectory() as tmpdirname:
  248. out_path = os.path.join(tmpdirname, "ppyoloe_s_custom_image_shape.onnx")
  249. ppyolo_e: ExportableObjectDetectionModel = models.get(Models.PP_YOLOE_S, pretrained_weights="coco")
  250. export_result = ppyolo_e.export(out_path, engine=ExportTargetBackend.ONNXRUNTIME, input_image_shape=(320, 320), output_predictions_format="flat")
  251. [flat_predictions] = self._run_inference_with_onnx(export_result)
  252. assert flat_predictions.shape[1] == 7
  253. def test_export_with_fp16_quantization(self):
  254. if torch.cuda.is_available():
  255. device = "cuda"
  256. elif torch.backends.mps.is_available():
  257. device = "mps"
  258. else:
  259. self.skipTest("No CUDA or MPS device available")
  260. max_predictions_per_image = 300
  261. with tempfile.TemporaryDirectory() as tmpdirname:
  262. out_path = os.path.join(tmpdirname, "ppyoloe_s_with_fp16_quantization.onnx")
  263. ppyolo_e: ExportableObjectDetectionModel = models.get(Models.PP_YOLOE_S, pretrained_weights="coco")
  264. export_result = ppyolo_e.export(
  265. out_path,
  266. device=device,
  267. engine=ExportTargetBackend.ONNXRUNTIME,
  268. max_predictions_per_image=max_predictions_per_image,
  269. input_image_shape=(640, 640),
  270. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  271. quantization_mode=ExportQuantizationMode.FP16,
  272. )
  273. num_predictions, pred_boxes, pred_scores, pred_classes = self._run_inference_with_onnx(export_result)
  274. assert num_predictions.shape == (1, 1)
  275. assert pred_boxes.shape == (1, max_predictions_per_image, 4)
  276. assert pred_scores.shape == (1, max_predictions_per_image)
  277. assert pred_classes.shape == (1, max_predictions_per_image)
  278. assert pred_classes.dtype == np.int64
  279. def test_export_with_fp16_quantization_tensort(self):
  280. if torch.cuda.is_available():
  281. device = "cuda"
  282. elif torch.backends.mps.is_available():
  283. device = "mps"
  284. else:
  285. self.skipTest("No CUDA or MPS device available")
  286. max_predictions_per_image = 300
  287. with tempfile.TemporaryDirectory() as tmpdirname:
  288. out_path = os.path.join(tmpdirname, "ppyoloe_s_with_fp16_quantization.onnx")
  289. ppyolo_e: ExportableObjectDetectionModel = models.get(Models.PP_YOLOE_S, pretrained_weights="coco")
  290. export_result = ppyolo_e.export(
  291. out_path,
  292. device=device,
  293. engine=ExportTargetBackend.TENSORRT,
  294. max_predictions_per_image=max_predictions_per_image,
  295. input_image_shape=(640, 640),
  296. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  297. quantization_mode=ExportQuantizationMode.FP16,
  298. )
  299. assert export_result is not None
  300. def test_export_with_int8_quantization(self):
  301. with tempfile.TemporaryDirectory() as tmpdirname:
  302. out_path = os.path.join(tmpdirname, "ppyoloe_s_with_int8_quantization.onnx")
  303. dummy_calibration_dataset = [torch.randn((3, 640, 640), dtype=torch.float32) for _ in range(32)]
  304. dummy_calibration_loader = DataLoader(dummy_calibration_dataset, batch_size=8, num_workers=0)
  305. ppyolo_e: ExportableObjectDetectionModel = models.get(Models.PP_YOLOE_S, pretrained_weights="coco")
  306. export_result = ppyolo_e.export(
  307. out_path,
  308. engine=ExportTargetBackend.ONNXRUNTIME,
  309. max_predictions_per_image=300,
  310. input_image_shape=(640, 640),
  311. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  312. quantization_mode=ExportQuantizationMode.INT8,
  313. calibration_loader=dummy_calibration_loader,
  314. )
  315. num_predictions, pred_boxes, pred_scores, pred_classes = self._run_inference_with_onnx(export_result)
  316. assert num_predictions.shape == (1, 1)
  317. assert pred_boxes.shape == (1, 300, 4)
  318. assert pred_scores.shape == (1, 300)
  319. assert pred_classes.shape == (1, 300)
  320. assert pred_classes.dtype == np.int64
  321. def test_export_quantized_with_calibration_to_tensorrt(self):
  322. with tempfile.TemporaryDirectory() as tmpdirname:
  323. out_path = os.path.join(tmpdirname, "pp_yoloe_s_quantized_with_calibration.onnx")
  324. dummy_calibration_dataset = [torch.randn((3, 640, 640), dtype=torch.float32) for _ in range(32)]
  325. dummy_calibration_loader = DataLoader(dummy_calibration_dataset, batch_size=8)
  326. ppyolo_e: ExportableObjectDetectionModel = models.get(Models.PP_YOLOE_S, pretrained_weights="coco")
  327. export_result = ppyolo_e.export(
  328. out_path,
  329. engine=ExportTargetBackend.TENSORRT,
  330. max_predictions_per_image=300,
  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_yolonas_quantized_with_calibration_to_tensorrt(self):
  338. with tempfile.TemporaryDirectory() as tmpdirname:
  339. out_path = os.path.join(tmpdirname, "yolonas_s_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.YOLO_NAS_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 test_export_yolox_quantized_int8_with_calibration_to_tensorrt(self):
  355. with tempfile.TemporaryDirectory() as tmpdirname:
  356. out_path = os.path.join(tmpdirname, "yolox_quantized_with_calibration.onnx")
  357. dummy_calibration_dataset = [torch.randn((3, 640, 640), dtype=torch.float32) for _ in range(32)]
  358. dummy_calibration_loader = DataLoader(dummy_calibration_dataset, batch_size=8)
  359. ppyolo_e: ExportableObjectDetectionModel = models.get(Models.YOLOX_S, pretrained_weights="coco")
  360. export_result = ppyolo_e.export(
  361. out_path,
  362. engine=ExportTargetBackend.TENSORRT,
  363. num_pre_nms_predictions=300,
  364. max_predictions_per_image=100,
  365. input_image_shape=(640, 640),
  366. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  367. quantization_mode=ExportQuantizationMode.INT8,
  368. calibration_loader=dummy_calibration_loader,
  369. )
  370. assert export_result is not None
  371. def _run_inference_with_onnx(self, export_result: ModelExportResult):
  372. # onnx_filename = out_path, input_shape = export_result.image_shape, output_predictions_format = output_predictions_format
  373. image = self._get_image_as_bchw(export_result.input_image_shape)
  374. image_8u = self._get_image(export_result.input_image_shape)
  375. session = onnxruntime.InferenceSession(export_result.output)
  376. inputs = [o.name for o in session.get_inputs()]
  377. outputs = [o.name for o in session.get_outputs()]
  378. result = session.run(outputs, {inputs[0]: image})
  379. class_names = COCO_DETECTION_CLASSES_LIST
  380. color_mapping = DetectionVisualization._generate_color_mapping(len(class_names))
  381. if export_result.output_predictions_format == DetectionOutputFormatMode.FLAT_FORMAT:
  382. flat_predictions = result[0] # [N, (batch_index, x1, y1, x2, y2, score, class]
  383. assert flat_predictions.shape[1] == 7
  384. for i in range(flat_predictions.shape[0]):
  385. x1, y1, x2, y2 = flat_predictions[i, 1:5]
  386. class_score = flat_predictions[i, 5]
  387. class_label = int(flat_predictions[i, 6])
  388. image_8u = DetectionVisualization.draw_box_title(
  389. image_np=image_8u,
  390. x1=int(x1),
  391. y1=int(y1),
  392. x2=int(x2),
  393. y2=int(y2),
  394. class_id=class_label,
  395. class_names=class_names,
  396. color_mapping=color_mapping,
  397. box_thickness=2,
  398. pred_conf=class_score,
  399. )
  400. else:
  401. num_predictions, pred_boxes, pred_scores, pred_classes = result
  402. for pred_index in range(num_predictions[0, 0]):
  403. x1, y1, x2, y2 = pred_boxes[0, pred_index]
  404. class_score = pred_scores[0, pred_index]
  405. class_label = pred_classes[0, pred_index]
  406. image_8u = DetectionVisualization.draw_box_title(
  407. image_np=image_8u,
  408. x1=int(x1),
  409. y1=int(y1),
  410. x2=int(x2),
  411. y2=int(y2),
  412. class_id=class_label,
  413. class_names=class_names,
  414. color_mapping=color_mapping,
  415. box_thickness=2,
  416. pred_conf=class_score,
  417. )
  418. plt.figure(figsize=(10, 10))
  419. plt.imshow(image_8u)
  420. plt.title(os.path.basename(export_result.output))
  421. plt.tight_layout()
  422. plt.show()
  423. return result
  424. def test_export_already_quantized_model(self):
  425. model = models.get(Models.YOLO_NAS_S, pretrained_weights="coco")
  426. q_util = SelectiveQuantizer(
  427. default_quant_modules_calibrator_weights="max",
  428. default_quant_modules_calibrator_inputs="histogram",
  429. default_per_channel_quant_weights=True,
  430. default_learn_amax=False,
  431. verbose=True,
  432. )
  433. q_util.quantize_module(model)
  434. with tempfile.TemporaryDirectory() as tmpdirname:
  435. output_model1 = os.path.join(tmpdirname, "yolo_nas_s_quantized_explicit_int8.onnx")
  436. output_model2 = os.path.join(tmpdirname, "yolo_nas_s_quantized.onnx")
  437. # If model is already quantized to int8, the export should be successful but model should not be quantized again
  438. model.export(
  439. output_model1,
  440. quantization_mode=ExportQuantizationMode.INT8,
  441. )
  442. # If model is quantized but quantization mode is not specified, the export should be also successful
  443. # but model should not be quantized again
  444. model.export(
  445. output_model2,
  446. quantization_mode=None,
  447. )
  448. # If model is already quantized to int8, we should not be able to export model to FP16
  449. with self.assertRaises(RuntimeError):
  450. model.export(
  451. "yolo_nas_s_quantized.onnx",
  452. quantization_mode=ExportQuantizationMode.FP16,
  453. )
  454. # Assert two files are the same
  455. # with open(output_model1, "rb") as f1, open(output_model2, "rb") as f2:
  456. # assert hashlib.md5(f1.read()) == hashlib.md5(f2.read())
  457. def manual_test_export_export_all_variants(self):
  458. """
  459. This test is not run automatically, it is used to generate all possible export variants of the model
  460. for benchmarking purposes.
  461. """
  462. export_dir = "export_all_variants"
  463. os.makedirs(export_dir, exist_ok=True)
  464. benchmark_command_dir = "benchmark_command.sh"
  465. with open(benchmark_command_dir, "w") as f:
  466. pass
  467. for output_predictions_format in [DetectionOutputFormatMode.BATCH_FORMAT, DetectionOutputFormatMode.FLAT_FORMAT]:
  468. for engine in [ExportTargetBackend.ONNXRUNTIME, ExportTargetBackend.TENSORRT]:
  469. for quantization in [None, ExportQuantizationMode.FP16, ExportQuantizationMode.INT8]:
  470. device = "cpu"
  471. if torch.cuda.is_available():
  472. device = "cuda"
  473. elif torch.backends.mps.is_available() and quantization == ExportQuantizationMode.FP16:
  474. # Skip this case because when using MPS device we are getting:
  475. # RuntimeError: Placeholder storage has not been allocated on MPS device!
  476. # And when using CPU:
  477. # RuntimeError: RuntimeError: "slow_conv2d_cpu" not implemented for 'Half'
  478. continue
  479. # if quantization == ExportQuantizationMode.FP16 and device == "cpu":
  480. # # Skip this case because the FP16 quantization uses model inference
  481. # pass
  482. for model_type in [
  483. Models.YOLOX_S,
  484. Models.PP_YOLOE_S,
  485. Models.YOLO_NAS_S,
  486. ]:
  487. model_name = str(model_type).lower()
  488. model = models.get(model_type, pretrained_weights="coco")
  489. quantization_suffix = f"_{quantization.value}" if quantization is not None else ""
  490. onnx_filename = f"{model_name}_{engine.value}_{output_predictions_format.value}{quantization_suffix}.onnx"
  491. with self.subTest(msg=onnx_filename):
  492. model.export(
  493. os.path.join(export_dir, onnx_filename),
  494. device=device,
  495. quantization_mode=quantization,
  496. engine=engine,
  497. output_predictions_format=output_predictions_format,
  498. preprocessing=False,
  499. postprocessing=False,
  500. )
  501. with open(benchmark_command_dir, "a") as f:
  502. quantization_param = "--int8" if quantization == ExportQuantizationMode.INT8 else "--fp16"
  503. output_file_log = onnx_filename.replace(".onnx", ".log")
  504. trtexec_command = (
  505. f"/usr/src/tensorrt/bin/trtexec "
  506. f"--onnx=/deci/eugene/{onnx_filename} {quantization_param} "
  507. f"--avgRuns=100 --duration=15 > /deci/eugene/{output_file_log}\n"
  508. )
  509. f.write(trtexec_command)
  510. def test_trt_nms_convert_to_flat_result(self):
  511. batch_size = 7
  512. max_predictions_per_image = 100
  513. if torch.cuda.is_available():
  514. available_devices = ["cpu", "cuda"]
  515. available_dtypes = [torch.float16, torch.float32]
  516. else:
  517. available_devices = ["cpu"]
  518. available_dtypes = [torch.float32]
  519. for device in available_devices:
  520. for dtype in available_dtypes:
  521. num_detections = torch.randint(1, max_predictions_per_image, (batch_size, 1), dtype=torch.int32)
  522. detection_boxes = torch.randn((batch_size, max_predictions_per_image, 4), dtype=dtype)
  523. detection_scores = torch.randn((batch_size, max_predictions_per_image), dtype=dtype)
  524. detection_classes = torch.randint(0, 80, (batch_size, max_predictions_per_image), dtype=torch.int32)
  525. torch_module = ConvertTRTFormatToFlatTensor(batch_size, max_predictions_per_image)
  526. flat_predictions_torch = torch_module(num_detections, detection_boxes, detection_scores, detection_classes)
  527. print(flat_predictions_torch.shape, flat_predictions_torch.dtype, flat_predictions_torch)
  528. onnx_file = "ConvertTRTFormatToFlatTensor.onnx"
  529. graph = ConvertTRTFormatToFlatTensor.as_graph(
  530. batch_size=batch_size, max_predictions_per_image=max_predictions_per_image, dtype=dtype, device=device
  531. )
  532. model = gs.export_onnx(graph)
  533. onnx.checker.check_model(model)
  534. onnx.save(model, onnx_file)
  535. session = onnxruntime.InferenceSession(onnx_file)
  536. inputs = [o.name for o in session.get_inputs()]
  537. outputs = [o.name for o in session.get_outputs()]
  538. [flat_predictions_onnx] = session.run(
  539. output_names=outputs,
  540. input_feed={
  541. inputs[0]: num_detections.numpy(),
  542. inputs[1]: detection_boxes.numpy(),
  543. inputs[2]: detection_scores.numpy(),
  544. inputs[3]: detection_classes.numpy(),
  545. },
  546. )
  547. np.testing.assert_allclose(flat_predictions_torch.numpy(), flat_predictions_onnx, rtol=1e-3, atol=1e-3)
  548. def test_onnx_nms_flat_result(self):
  549. max_predictions = 100
  550. batch_size = 7
  551. if torch.cuda.is_available():
  552. available_devices = ["cpu", "cuda"]
  553. available_dtypes = [torch.float16, torch.float32]
  554. else:
  555. available_devices = ["cpu"]
  556. available_dtypes = [torch.float32]
  557. for device in available_devices:
  558. for dtype in available_dtypes:
  559. # Run a few tests to ensure ONNX model produces the same results as the PyTorch model
  560. # And also can handle dynamic shapes input
  561. pred_boxes = torch.randn((batch_size, max_predictions, 4), dtype=dtype)
  562. pred_scores = torch.randn((batch_size, max_predictions, 40), dtype=dtype)
  563. selected_indexes = torch.tensor([[6, 10, 4], [1, 13, 4], [2, 17, 2], [2, 18, 2]], dtype=torch.int64)
  564. torch_module = PickNMSPredictionsAndReturnAsFlatResult(
  565. batch_size=batch_size, num_pre_nms_predictions=max_predictions, max_predictions_per_image=max_predictions
  566. )
  567. torch_result = torch_module(pred_boxes, pred_scores, selected_indexes)
  568. with tempfile.TemporaryDirectory() as temp_dir:
  569. onnx_file = os.path.join(temp_dir, "PickNMSPredictionsAndReturnAsFlatResult.onnx")
  570. graph = PickNMSPredictionsAndReturnAsFlatResult.as_graph(
  571. batch_size=batch_size, num_pre_nms_predictions=max_predictions, max_predictions_per_image=max_predictions, device=device, dtype=dtype
  572. )
  573. model = gs.export_onnx(graph)
  574. onnx.checker.check_model(model)
  575. onnx.save(model, onnx_file)
  576. session = onnxruntime.InferenceSession(onnx_file)
  577. inputs = [o.name for o in session.get_inputs()]
  578. outputs = [o.name for o in session.get_outputs()]
  579. [onnx_result] = session.run(outputs, {inputs[0]: pred_boxes.numpy(), inputs[1]: pred_scores.numpy(), inputs[2]: selected_indexes.numpy()})
  580. np.testing.assert_allclose(torch_result.numpy(), onnx_result, rtol=1e-3, atol=1e-3)
  581. def test_onnx_nms_batch_result(self):
  582. max_predictions = 100
  583. batch_size = 7
  584. if torch.cuda.is_available():
  585. available_devices = ["cpu", "cuda"]
  586. available_dtypes = [torch.float16, torch.float32]
  587. else:
  588. available_devices = ["cpu"]
  589. available_dtypes = [torch.float32]
  590. for device in available_devices:
  591. for dtype in available_dtypes:
  592. # Run a few tests to ensure ONNX model produces the same results as the PyTorch model
  593. # And also can handle dynamic shapes input
  594. pred_boxes = torch.randn((batch_size, max_predictions, 4), dtype=dtype)
  595. pred_scores = torch.randn((batch_size, max_predictions, 40), dtype=dtype)
  596. selected_indexes = torch.tensor([[6, 10, 4], [1, 13, 4], [2, 17, 2], [2, 18, 2]], dtype=torch.int64)
  597. torch_module = PickNMSPredictionsAndReturnAsBatchedResult(
  598. batch_size=batch_size, num_pre_nms_predictions=max_predictions, max_predictions_per_image=max_predictions
  599. )
  600. torch_result = torch_module(pred_boxes, pred_scores, selected_indexes)
  601. with tempfile.TemporaryDirectory() as temp_dir:
  602. onnx_file = os.path.join(temp_dir, "PickNMSPredictionsAndReturnAsBatchedResult.onnx")
  603. graph = PickNMSPredictionsAndReturnAsBatchedResult.as_graph(
  604. batch_size=batch_size, num_pre_nms_predictions=max_predictions, max_predictions_per_image=max_predictions, device=device, dtype=dtype
  605. )
  606. model = gs.export_onnx(graph)
  607. onnx.checker.check_model(model)
  608. onnx.save(model, onnx_file)
  609. session = onnxruntime.InferenceSession(onnx_file)
  610. inputs = [o.name for o in session.get_inputs()]
  611. outputs = [o.name for o in session.get_outputs()]
  612. onnx_result = session.run(outputs, {inputs[0]: pred_boxes.numpy(), inputs[1]: pred_scores.numpy(), inputs[2]: selected_indexes.numpy()})
  613. np.testing.assert_allclose(torch_result[0].numpy(), onnx_result[0], rtol=1e-3, atol=1e-3)
  614. np.testing.assert_allclose(torch_result[1].numpy(), onnx_result[1], rtol=1e-3, atol=1e-3)
  615. np.testing.assert_allclose(torch_result[2].numpy(), onnx_result[2], rtol=1e-3, atol=1e-3)
  616. np.testing.assert_allclose(torch_result[3].numpy(), onnx_result[3], rtol=1e-3, atol=1e-3)
  617. def _get_image_as_bchw(self, image_shape=(640, 640)):
  618. """
  619. :param image_shape: Output image shape (rows, cols)
  620. :return: Image in NCHW format
  621. """
  622. image = load_image(self.test_image_path)
  623. image = cv2.resize(image, dsize=tuple(reversed(image_shape)), interpolation=cv2.INTER_LINEAR)
  624. image = np.transpose(np.expand_dims(image, 0), (0, 3, 1, 2))
  625. return image
  626. def _get_image(self, image_shape=(640, 640)):
  627. """
  628. :param image_shape: Output image shape (rows, cols)
  629. :return: Image in HWC format
  630. """
  631. image = load_image(self.test_image_path)
  632. image = cv2.resize(image, dsize=tuple(reversed(image_shape)), interpolation=cv2.INTER_LINEAR)
  633. return image
  634. if __name__ == "__main__":
  635. unittest.main()
Tip!

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

Comments

Loading...