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

export_pose_estimation_model_test.py 10 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
  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 torch import nn
  11. from super_gradients.common.object_names import Models
  12. from super_gradients.conversion.conversion_enums import ExportTargetBackend, DetectionOutputFormatMode
  13. from super_gradients.conversion.gs_utils import import_onnx_graphsurgeon_or_fail_with_instructions
  14. from super_gradients.module_interfaces import ExportablePoseEstimationModel, PoseEstimationModelExportResult
  15. from super_gradients.training import models
  16. from super_gradients.training.dataloaders import coco2017_val # noqa
  17. from super_gradients.training.processing.processing import (
  18. default_yolo_nas_pose_coco_processing_params,
  19. ComposeProcessing,
  20. ReverseImageChannels,
  21. KeypointsLongestMaxSizeRescale,
  22. KeypointsBottomRightPadding,
  23. StandardizeImage,
  24. ImagePermute,
  25. )
  26. from super_gradients.training.utils.media.image import load_image
  27. from super_gradients.training.utils.visualization.pose_estimation import PoseVisualization
  28. gs = import_onnx_graphsurgeon_or_fail_with_instructions()
  29. class TestPoseEstimationModelExport(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. self.default_params = default_yolo_nas_pose_coco_processing_params()
  35. self.default_model = Models.YOLO_NAS_POSE_S
  36. # Custom preprocessing params for 20 keypoints
  37. self.custom_params = dict(
  38. image_processor=ComposeProcessing(
  39. [
  40. ReverseImageChannels(),
  41. KeypointsLongestMaxSizeRescale(output_shape=(640, 640)),
  42. KeypointsBottomRightPadding(output_shape=(640, 640), pad_value=127),
  43. StandardizeImage(max_value=255.0),
  44. ImagePermute(permutation=(2, 0, 1)),
  45. ]
  46. ),
  47. edge_links=[], # No skeleton
  48. edge_colors=[],
  49. keypoint_colors=np.random.randint(0, 255, size=(20, 3)).tolist(),
  50. )
  51. def test_export_model_on_small_size(self):
  52. with tempfile.TemporaryDirectory() as tmpdirname:
  53. for model_type in [
  54. Models.YOLO_NAS_POSE_S,
  55. ]:
  56. out_path = os.path.join(tmpdirname, model_type + ".onnx")
  57. model: ExportablePoseEstimationModel = models.get(model_type, num_classes=17)
  58. model.set_dataset_processing_params(**default_yolo_nas_pose_coco_processing_params())
  59. export_result = model.export(
  60. out_path,
  61. input_image_shape=(64, 64),
  62. num_pre_nms_predictions=2000,
  63. max_predictions_per_image=1000,
  64. output_predictions_format=DetectionOutputFormatMode.BATCH_FORMAT,
  65. )
  66. assert export_result.input_image_dtype == torch.uint8
  67. assert export_result.input_image_shape == (64, 64)
  68. print(export_result.usage_instructions)
  69. def test_the_most_common_export_use_case(self):
  70. """
  71. Test the most common export use case - export to ONNX with all default parameters
  72. """
  73. with tempfile.TemporaryDirectory() as tmpdirname:
  74. out_path = os.path.join(tmpdirname, "model.onnx")
  75. model: ExportablePoseEstimationModel = models.get(self.default_model, num_classes=17)
  76. model.set_dataset_processing_params(**self.default_params)
  77. export_result = model.export(out_path)
  78. assert export_result.input_image_dtype == torch.uint8
  79. assert export_result.input_image_shape == (640, 640)
  80. assert export_result.input_image_channels == 3
  81. print(export_result.usage_instructions)
  82. def test_models_produce_half(self):
  83. if not torch.cuda.is_available():
  84. self.skipTest("This test was skipped because target machine has not CUDA devices")
  85. input = torch.randn(1, 3, 640, 640).half().cuda()
  86. model = models.get(Models.YOLO_NAS_POSE_S, num_classes=17)
  87. model = nn.Sequential(model, model.get_decoding_module(100)).cuda().eval().half()
  88. output = model(input)
  89. assert output[0].dtype == torch.float16
  90. assert output[1].dtype == torch.float16
  91. def test_export_to_onnxruntime_flat(self):
  92. """
  93. Test export to ONNX with flat predictions
  94. """
  95. output_predictions_format = DetectionOutputFormatMode.FLAT_FORMAT
  96. confidence_threshold = 0.7
  97. nms_threshold = 0.6
  98. with tempfile.TemporaryDirectory() as tmpdirname:
  99. for model_type in [
  100. Models.YOLO_NAS_POSE_S,
  101. ]:
  102. model_name = str(model_type).lower().replace(".", "_")
  103. out_path = os.path.join(tmpdirname, f"{model_name}_onnxruntime_flat.onnx")
  104. # Intentionaly export with 20 keypoints to ensure NMS/postprocessing works correctly
  105. model_arch: ExportablePoseEstimationModel = models.get(model_name, num_classes=20)
  106. model_arch.set_dataset_processing_params(**self.custom_params)
  107. export_result = model_arch.export(
  108. out_path,
  109. engine=ExportTargetBackend.ONNXRUNTIME,
  110. output_predictions_format=output_predictions_format,
  111. confidence_threshold=confidence_threshold,
  112. nms_threshold=nms_threshold,
  113. )
  114. print(export_result.usage_instructions)
  115. [flat_predictions] = self._run_inference_with_onnx(export_result, params=self.custom_params)
  116. # Check that all predictions have confidence >= confidence_threshold
  117. assert (flat_predictions[:, 5] >= confidence_threshold).all()
  118. def test_export_to_onnxruntime_batch_format(self):
  119. output_predictions_format = DetectionOutputFormatMode.BATCH_FORMAT
  120. confidence_threshold = 0.7
  121. nms_threshold = 0.6
  122. with tempfile.TemporaryDirectory() as tmpdirname:
  123. for model_type in [
  124. Models.YOLO_NAS_POSE_S,
  125. ]:
  126. model_name = str(model_type).lower().replace(".", "_")
  127. out_path = os.path.join(tmpdirname, f"{model_name}_onnxruntime_batch.onnx")
  128. # Intentionaly export with 20 keypoints to ensure NMS/postprocessing works correctly
  129. model_arch: ExportablePoseEstimationModel = models.get(model_name, num_classes=20)
  130. model_arch.set_dataset_processing_params(**self.custom_params)
  131. export_result = model_arch.export(
  132. out_path,
  133. engine=ExportTargetBackend.ONNXRUNTIME,
  134. output_predictions_format=output_predictions_format,
  135. nms_threshold=nms_threshold,
  136. confidence_threshold=confidence_threshold,
  137. )
  138. print(export_result.usage_instructions)
  139. self._run_inference_with_onnx(export_result, params=self.custom_params)
  140. def _run_inference_with_onnx(self, export_result: PoseEstimationModelExportResult, params=None):
  141. if params is None:
  142. params = self.default_params
  143. # onnx_filename = out_path, input_shape = export_result.image_shape, output_predictions_format = output_predictions_format
  144. image = self._get_image_as_bchw(export_result.input_image_shape)
  145. image_8u = self._get_image(export_result.input_image_shape)
  146. session = onnxruntime.InferenceSession(export_result.output)
  147. inputs = [o.name for o in session.get_inputs()]
  148. outputs = [o.name for o in session.get_outputs()]
  149. result = session.run(outputs, {inputs[0]: image})
  150. num_keypoints = len(params["keypoint_colors"])
  151. if export_result.output_predictions_format == DetectionOutputFormatMode.FLAT_FORMAT:
  152. flat_predictions = result[0] # [N, (batch_index, x1, y1, x2, y2, score, num_keypoints * 3)]
  153. print(flat_predictions.shape[1])
  154. print(1 + 4 + 1 + num_keypoints * 3)
  155. assert flat_predictions.shape[1] == 1 + 4 + 1 + num_keypoints * 3
  156. boxes = flat_predictions[:, 1:5]
  157. scores = flat_predictions[:, 5]
  158. poses = flat_predictions[:, 6:].reshape(-1, num_keypoints, 3)
  159. image_8u = PoseVisualization.draw_poses(
  160. image=image_8u,
  161. poses=poses,
  162. boxes=boxes,
  163. scores=scores,
  164. is_crowd=None,
  165. show_keypoint_confidence=True,
  166. edge_links=params["edge_links"],
  167. edge_colors=params["edge_colors"],
  168. keypoint_colors=params["keypoint_colors"],
  169. )
  170. else:
  171. # Hard-coded unpacking for batch size 1
  172. [num_predictions], [pred_boxes], [pred_scores], [pred_joints] = result
  173. image_8u = PoseVisualization.draw_poses(
  174. image=image_8u,
  175. poses=pred_joints[0 : num_predictions[0]],
  176. boxes=pred_boxes[0 : num_predictions[0]],
  177. scores=pred_scores[0 : num_predictions[0]],
  178. is_crowd=None,
  179. show_keypoint_confidence=True,
  180. edge_links=params["edge_links"],
  181. edge_colors=params["edge_colors"],
  182. keypoint_colors=params["keypoint_colors"],
  183. )
  184. plt.figure(figsize=(10, 10))
  185. plt.imshow(image_8u)
  186. plt.title(os.path.basename(export_result.output))
  187. plt.tight_layout()
  188. plt.show()
  189. return result
  190. def _get_image_as_bchw(self, image_shape=(640, 640)):
  191. """
  192. :param image_shape: Output image shape (rows, cols)
  193. :return: Image in NCHW format
  194. """
  195. image = load_image(self.test_image_path)
  196. image = cv2.resize(image, dsize=tuple(reversed(image_shape)), interpolation=cv2.INTER_LINEAR)
  197. image = np.transpose(np.expand_dims(image, 0), (0, 3, 1, 2))
  198. return image
  199. def _get_image(self, image_shape=(640, 640)):
  200. """
  201. :param image_shape: Output image shape (rows, cols)
  202. :return: Image in HWC format
  203. """
  204. image = load_image(self.test_image_path)
  205. image = cv2.resize(image, dsize=tuple(reversed(image_shape)), interpolation=cv2.INTER_LINEAR)
  206. return image
  207. if __name__ == "__main__":
  208. unittest.main()
Tip!

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

Comments

Loading...