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_segmentation_model_test.py 11 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
  1. import logging
  2. import os
  3. import tempfile
  4. import unittest
  5. import cv2
  6. import numpy as np
  7. import onnxruntime
  8. import torch
  9. from matplotlib import pyplot as plt
  10. from super_gradients.common.object_names import Models
  11. from super_gradients.conversion.conversion_enums import ExportQuantizationMode
  12. from super_gradients.conversion.gs_utils import import_onnx_graphsurgeon_or_install
  13. from super_gradients.import_utils import import_pytorch_quantization_or_install
  14. from super_gradients.module_interfaces import ExportableSegmentationModel, SegmentationModelExportResult
  15. from super_gradients.training import models
  16. from super_gradients.training.datasets.datasets_conf import CITYSCAPES_DEFAULT_SEGMENTATION_CLASSES_LIST
  17. from super_gradients.training.utils.detection_utils import DetectionVisualization
  18. from super_gradients.training.utils.export_utils import infer_image_shape_from_model, infer_image_input_channels
  19. from super_gradients.training.utils.media.image import load_image
  20. from super_gradients.training.utils.visualization.segmentation import overlay_segmentation
  21. from torch.utils.data import DataLoader
  22. gs = import_onnx_graphsurgeon_or_install()
  23. import_pytorch_quantization_or_install()
  24. class TestSegmentationModelExport(unittest.TestCase):
  25. def setUp(self) -> None:
  26. logging.getLogger().setLevel(logging.DEBUG)
  27. this_dir = os.path.dirname(__file__)
  28. self.test_image_path = os.path.join(this_dir, "../data/tinycoco/images/train2017/000000017627.jpg")
  29. self.models_to_test = [
  30. Models.DDRNET_23,
  31. Models.SEGFORMER_B0,
  32. Models.PP_LITE_T_SEG50,
  33. Models.STDC1_SEG50,
  34. ]
  35. def test_infer_input_image_shape_from_model(self):
  36. assert infer_image_shape_from_model(models.get(Models.DDRNET_23, num_classes=80, pretrained_weights=None)) is None
  37. assert infer_image_shape_from_model(models.get(Models.SEGFORMER_B0, num_classes=80, pretrained_weights=None)) is None
  38. assert infer_image_shape_from_model(models.get(Models.PP_LITE_T_SEG, num_classes=80, pretrained_weights=None)) is None
  39. assert infer_image_shape_from_model(models.get(Models.DDRNET_23, pretrained_weights="cityscapes")) == (1024, 2048)
  40. assert infer_image_shape_from_model(models.get(Models.SEGFORMER_B0, pretrained_weights="cityscapes")) == (1024, 2048)
  41. assert infer_image_shape_from_model(models.get(Models.PP_LITE_T_SEG50, pretrained_weights="cityscapes")) == (512, 1024)
  42. assert infer_image_shape_from_model(models.get(Models.STDC1_SEG50, pretrained_weights="cityscapes")) == (512, 1024)
  43. def test_infer_input_image_num_channels_from_model(self):
  44. assert infer_image_input_channels(models.get(Models.DDRNET_23, num_classes=80, pretrained_weights=None)) == 3
  45. assert infer_image_input_channels(models.get(Models.SEGFORMER_B0, num_classes=80, pretrained_weights=None)) == 3
  46. assert infer_image_input_channels(models.get(Models.PP_LITE_T_SEG50, num_classes=80, pretrained_weights=None)) == 3
  47. assert infer_image_input_channels(models.get(Models.STDC1_SEG50, num_classes=80, pretrained_weights=None)) == 3
  48. assert infer_image_input_channels(models.get(Models.DDRNET_23, pretrained_weights="cityscapes")) == 3
  49. assert infer_image_input_channels(models.get(Models.SEGFORMER_B0, pretrained_weights="cityscapes")) == 3
  50. assert infer_image_input_channels(models.get(Models.PP_LITE_T_SEG50, pretrained_weights="cityscapes")) == 3
  51. assert infer_image_input_channels(models.get(Models.STDC1_SEG50, pretrained_weights="cityscapes")) == 3
  52. def test_export_to_onnxruntime_and_run(self):
  53. """
  54. Test export to ONNX with flat predictions
  55. """
  56. with tempfile.TemporaryDirectory() as tmpdirname:
  57. for model_type in self.models_to_test:
  58. with self.subTest(model_type=model_type):
  59. model_name = str(model_type).lower().replace(".", "_")
  60. out_path = os.path.join(tmpdirname, f"{model_name}_onnxruntime_flat.onnx")
  61. model_arch: ExportableSegmentationModel = models.get(model_name, pretrained_weights="cityscapes")
  62. export_result = model_arch.export(
  63. out_path,
  64. input_image_shape=(640, 640), # Force .export() to infer image shape from the model itself
  65. )
  66. [segmentation_mask] = self._run_inference_with_onnx(export_result)
  67. self.assertTrue(segmentation_mask.shape[0] == 1)
  68. self.assertTrue(segmentation_mask.shape[1] == 640)
  69. self.assertTrue(segmentation_mask.shape[2] == 640)
  70. def test_export_model_with_binary_head(self):
  71. """
  72. Test export to ONNX with flat predictions
  73. """
  74. with tempfile.TemporaryDirectory() as tmpdirname:
  75. for model_type in self.models_to_test:
  76. with self.subTest(model_type=model_type):
  77. model_name = str(model_type).lower().replace(".", "_")
  78. out_path = os.path.join(tmpdirname, f"{model_name}_onnxruntime_flat.onnx")
  79. model_arch: ExportableSegmentationModel = models.get(model_name, pretrained_weights="cityscapes")
  80. model_arch.replace_head(new_num_classes=1)
  81. export_result = model_arch.export(
  82. out_path,
  83. confidence_threshold=0.5,
  84. input_image_shape=(640, 640), # Force .export() to infer image shape from the model itself
  85. )
  86. [segmentation_mask] = self._run_inference_with_onnx(export_result)
  87. self.assertTrue(np.isin(segmentation_mask, [0, 1]).all())
  88. self.assertTrue(segmentation_mask.shape[0] == 1)
  89. self.assertTrue(segmentation_mask.shape[1] == 640)
  90. self.assertTrue(segmentation_mask.shape[2] == 640)
  91. def test_export_int8_quantized_with_calibration(self):
  92. with tempfile.TemporaryDirectory() as tmpdirname:
  93. for model_type in self.models_to_test:
  94. with self.subTest(model_type=model_type):
  95. model_name = str(model_type).lower().replace(".", "_")
  96. out_path = os.path.join(tmpdirname, f"{model_name}.onnx")
  97. dummy_calibration_dataset = [torch.randn((3, 640, 640), dtype=torch.float32) for _ in range(32)]
  98. dummy_calibration_loader = DataLoader(dummy_calibration_dataset, batch_size=8)
  99. model_arch: ExportableSegmentationModel = models.get(model_name, pretrained_weights="cityscapes")
  100. export_result = model_arch.export(
  101. out_path,
  102. input_image_shape=(640, 640), # Force .export() to infer image shape from the model itself
  103. quantization_mode=ExportQuantizationMode.INT8,
  104. calibration_loader=dummy_calibration_loader,
  105. )
  106. [segmentation_mask] = self._run_inference_with_onnx(export_result)
  107. self.assertTrue(segmentation_mask.shape[0] == 1)
  108. self.assertTrue(segmentation_mask.shape[1] == 640)
  109. self.assertTrue(segmentation_mask.shape[2] == 640)
  110. def _run_inference_with_onnx(self, export_result: SegmentationModelExportResult):
  111. # onnx_filename = out_path, input_shape = export_result.image_shape, output_predictions_format = output_predictions_format
  112. image = self._get_image_as_bchw(export_result.input_image_shape)
  113. image_8u = self._get_image(export_result.input_image_shape)
  114. session = onnxruntime.InferenceSession(export_result.output)
  115. inputs = [o.name for o in session.get_inputs()]
  116. outputs = [o.name for o in session.get_outputs()]
  117. result = session.run(outputs, {inputs[0]: image})
  118. class_names = CITYSCAPES_DEFAULT_SEGMENTATION_CLASSES_LIST
  119. color_mapping = DetectionVisualization._generate_color_mapping(len(class_names))
  120. segmentation_mask = result[0][0] # [H, W]
  121. overlay = overlay_segmentation(
  122. pred_mask=segmentation_mask, image=image_8u, alpha=0.5, num_classes=len(class_names), colors=color_mapping, class_names=class_names
  123. )
  124. plt.figure(figsize=(10, 10))
  125. plt.imshow(overlay)
  126. plt.title(os.path.basename(export_result.output))
  127. plt.tight_layout()
  128. plt.show()
  129. return result
  130. def test_export_already_quantized_model(self):
  131. from super_gradients.training.utils.quantization import SelectiveQuantizer
  132. for model_type in self.models_to_test:
  133. with self.subTest(model_type=model_type):
  134. model = models.get(model_type, pretrained_weights="cityscapes")
  135. q_util = SelectiveQuantizer(
  136. default_quant_modules_calibrator_weights="max",
  137. default_quant_modules_calibrator_inputs="histogram",
  138. default_per_channel_quant_weights=True,
  139. default_learn_amax=False,
  140. verbose=True,
  141. )
  142. q_util.quantize_module(model)
  143. with tempfile.TemporaryDirectory() as tmpdirname:
  144. output_model1 = os.path.join(tmpdirname, f"{model_type}_quantized_explicit_int8.onnx")
  145. output_model2 = os.path.join(tmpdirname, f"{model_type}_quantized.onnx")
  146. # If model is already quantized to int8, the export should be successful but model should not be quantized again
  147. model.export(
  148. output_model1,
  149. quantization_mode=ExportQuantizationMode.INT8,
  150. )
  151. # If model is quantized but quantization mode is not specified, the export should be also successful
  152. # but model should not be quantized again
  153. model.export(
  154. output_model2,
  155. quantization_mode=None,
  156. )
  157. # If model is already quantized to int8, we should not be able to export model to FP16
  158. with self.assertRaises(RuntimeError):
  159. model.export(
  160. "yolo_nas_s_quantized.onnx",
  161. quantization_mode=ExportQuantizationMode.FP16,
  162. )
  163. def _get_image_as_bchw(self, image_shape=(640, 640)):
  164. """
  165. :param image_shape: Output image shape (rows, cols)
  166. :return: Image in NCHW format
  167. """
  168. image = load_image(self.test_image_path)
  169. image = cv2.resize(image, dsize=tuple(reversed(image_shape)), interpolation=cv2.INTER_LINEAR)
  170. image = np.transpose(np.expand_dims(image, 0), (0, 3, 1, 2))
  171. return image
  172. def _get_image(self, image_shape=(640, 640)):
  173. """
  174. :param image_shape: Output image shape (rows, cols)
  175. :return: Image in HWC format
  176. """
  177. image = load_image(self.test_image_path)
  178. image = cv2.resize(image, dsize=tuple(reversed(image_shape)), interpolation=cv2.INTER_LINEAR)
  179. return image
  180. if __name__ == "__main__":
  181. unittest.main()
Tip!

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

Comments

Loading...