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

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

Comments

Loading...