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

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

Comments

Loading...