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

test_yolo_nas_pose.py 15 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
  1. import hashlib
  2. import os
  3. import unittest
  4. from typing import List
  5. import numpy as np
  6. import torch
  7. from torch.optim import Adam
  8. from torch.utils.tensorboard import SummaryWriter
  9. from super_gradients.common import StrictLoad
  10. from super_gradients.common.object_names import Models
  11. from super_gradients.training import models
  12. from super_gradients.training.dataloaders import get_data_loader
  13. from super_gradients.training.datasets import COCOKeypointsDataset
  14. from super_gradients.training.losses import YoloNASPoseLoss
  15. from super_gradients.training.metrics.pose_estimation_metrics import PoseEstimationPredictions, PoseEstimationMetrics
  16. from super_gradients.training.models.pose_estimation_models import YoloNASPose
  17. from super_gradients.training.utils.callbacks import ExtremeBatchPoseEstimationVisualizationCallback
  18. class YoloNASPoseTests(unittest.TestCase):
  19. # def test_forwarad(self):
  20. # model = models.get(Models.YOLO_NAS_POSE_S, num_classes=17)
  21. # input = torch.randn((1, 3, 640, 640))
  22. # decoded_predictions, raw_predictions = model(input)
  23. # pred_bboxes, pred_scores, pred_pose_coords, pred_pose_scores = decoded_predictions
  24. # cls_score_list, reg_distri_list, pose_regression_list, anchors, anchor_points, num_anchors_list, stride_tensor = raw_predictions
  25. # pass
  26. #
  27. # def test_loss_function(self):
  28. # model = models.get(Models.YOLO_NAS_POSE_S, num_classes=17)
  29. # input = torch.randn((3, 3, 640, 640))
  30. # decoded_predictions, raw_predictions = model(input)
  31. # pred_bboxes, pred_scores, pred_pose_coords, pred_pose_scores = decoded_predictions
  32. # cls_score_list, reg_distri_list, pose_regression_list, anchors, anchor_points, num_anchors_list, stride_tensor = raw_predictions
  33. #
  34. # cls_score_list = torch.nn.Parameter(cls_score_list.detach())
  35. # reg_distri_list = torch.nn.Parameter(reg_distri_list.detach())
  36. # pose_regression_list = torch.nn.Parameter(pose_regression_list.detach())
  37. #
  38. # optimizable_parameters = [cls_score_list, reg_distri_list, pose_regression_list]
  39. # optimizer = Adam(optimizable_parameters, lr=0.01)
  40. #
  41. # criterion = YoloNASPoseLoss(
  42. # num_classes=17,
  43. # oks_sigmas=torch.tensor([0.026, 0.025, 0.025, 0.035, 0.035, 0.079, 0.079, 0.072, 0.072, 0.062, 0.062, 0.107, 0.107, 0.087, 0.087, 0.089, 0.089]),
  44. # )
  45. #
  46. # # A single tensor of shape (N, 1 + 4 + Num Joints * 3) (batch_index, x1, y1, x2, y2, [x, y, visibility] * Num Joints)
  47. # # First image has 1 object, second image has 2 objects, third image has no objects
  48. #
  49. # target_boxes = flat_collate_tensors_with_batch_index(
  50. # [
  51. # torch.tensor([[10, 10, 100, 200]]),
  52. # torch.tensor([[300, 500, 400, 550], [200, 200, 400, 400]]),
  53. # torch.zeros((0, 4)),
  54. # ]
  55. # ).float()
  56. #
  57. # target_poses = flat_collate_tensors_with_batch_index(
  58. # [
  59. # torch.randn((1, 17, 3)), # First image has 1 object
  60. # torch.randn((2, 17, 3)), # Second image has 2 objects
  61. # torch.zeros((0, 17, 3)), # Third image has no objects
  62. # ]
  63. # ).float()
  64. # target_poses[..., 3] = 2.0 # Mark all joints as visible
  65. #
  66. # targets = (target_boxes, target_poses)
  67. # for _ in range(100):
  68. # optimizer.zero_grad()
  69. # raw_predictions = (cls_score_list, reg_distri_list, pose_regression_list, anchors, anchor_points, num_anchors_list, stride_tensor)
  70. # loss = criterion(outputs=(decoded_predictions, raw_predictions), targets=targets)
  71. # loss[0].backward()
  72. # pprint(loss)
  73. # optimizer.step()
  74. #
  75. # def test_flat_collate_2d(self):
  76. # values = [
  77. # torch.randn([1, 4]),
  78. # torch.randn([2, 4]),
  79. # torch.randn([0, 4]),
  80. # torch.randn([3, 4]),
  81. # ]
  82. #
  83. # flat_tensor = flat_collate_tensors_with_batch_index(values)
  84. # undo_values = undo_flat_collate_tensors_with_batch_index(flat_tensor, 4)
  85. # assert len(undo_values) == len(values)
  86. # assert (undo_values[0] == values[0]).all()
  87. # assert (undo_values[1] == values[1]).all()
  88. # assert (undo_values[2] == values[2]).all()
  89. # assert (undo_values[3] == values[3]).all()
  90. #
  91. # def test_flat_collate_3d(self):
  92. # values = [
  93. # torch.randn([1, 17, 3]),
  94. # torch.randn([2, 17, 3]),
  95. # torch.randn([0, 17, 3]),
  96. # torch.randn([3, 17, 3]),
  97. # ]
  98. #
  99. # flat_tensor = flat_collate_tensors_with_batch_index(values)
  100. # undo_values = undo_flat_collate_tensors_with_batch_index(flat_tensor, 4)
  101. # assert len(undo_values) == len(values)
  102. # assert (undo_values[0] == values[0]).all()
  103. # assert (undo_values[1] == values[1]).all()
  104. # assert (undo_values[2] == values[2]).all()
  105. # assert (undo_values[3] == values[3]).all()
  106. #
  107. # def test_dataloader(self):
  108. # loader = get_data_loader(
  109. # config_name="coco_pose_estimation_yolo_nas_dataset_params",
  110. # dataset_cls=COCOKeypointsDataset,
  111. # train=False,
  112. # dataset_params=dict(data_dir="g:/coco2017"),
  113. # dataloader_params=dict(num_workers=0, batch_size=32),
  114. # )
  115. # dataset = loader.dataset
  116. # edge_links = dataset.edge_links
  117. # edge_colors = dataset.edge_colors
  118. # keypoint_colors = dataset.keypoint_colors
  119. #
  120. # batch = next(iter(loader))
  121. # images, (boxes, joints), extras = batch
  122. #
  123. # batch_size = len(images)
  124. #
  125. # images = ExtremeBatchPoseEstimationVisualizationCallback.universal_undo_preprocessing_fn(images)
  126. #
  127. # target_joints_unpacked = undo_flat_collate_tensors_with_batch_index(joints, batch_size)
  128. # target_bboxes_unpacked = undo_flat_collate_tensors_with_batch_index(boxes, batch_size)
  129. # batch_results = ExtremeBatchPoseEstimationVisualizationCallback.visualize_batch(
  130. # images,
  131. # keypoints=target_joints_unpacked,
  132. # scores=None,
  133. # edge_links=edge_links,
  134. # edge_colors=edge_colors,
  135. # keypoint_colors=keypoint_colors,
  136. # bboxes=target_bboxes_unpacked,
  137. # )
  138. #
  139. # for image in batch_results:
  140. # plt.figure(figsize=(10, 10))
  141. # plt.imshow(image)
  142. # plt.show()
  143. #
  144. # pass
  145. def test_single_batch_overfit(self):
  146. batch_size = 56
  147. num_classes = 17
  148. loader = get_data_loader(
  149. config_name="coco_pose_estimation_yolo_nas_dataset_params",
  150. dataset_cls=COCOKeypointsDataset,
  151. train=False,
  152. dataset_params=dict(data_dir="g:/coco2017", include_empty_samples=False),
  153. dataloader_params=dict(num_workers=0, batch_size=batch_size),
  154. )
  155. dataset = loader.dataset
  156. edge_links = dataset.edge_links
  157. edge_colors = dataset.edge_colors
  158. keypoint_colors = dataset.keypoint_colors
  159. oks_sigmas = np.array([0.026, 0.025, 0.025, 0.035, 0.035, 0.079, 0.079, 0.072, 0.072, 0.062, 0.062, 0.107, 0.107, 0.087, 0.087, 0.089, 0.089])
  160. batch = next(iter(loader))
  161. images, (boxes, joints), extras = batch
  162. images_8u = ExtremeBatchPoseEstimationVisualizationCallback.universal_undo_preprocessing_fn(images)
  163. classification_loss_types = ["bce", "focal"] # noqa
  164. regression_iou_loss_types = ["ciou"] # noqa
  165. pose_classification_loss_types = ["focal", "bce"] # noqa
  166. use_cocoeval_formula_types = [True] # noqa
  167. use_offset_compensation_types = [True, False] # noqa
  168. hyperparameters_grid = []
  169. # for use_offset_compensation in use_offset_compensation_types:
  170. # for classification_loss_type in classification_loss_types:
  171. # for regression_iou_loss_type in regression_iou_loss_types:
  172. # for pose_classification_loss_type in pose_classification_loss_types:
  173. # for use_cocoeval_formula in use_cocoeval_formula_types:
  174. # hyperparameters_grid.append(
  175. # dict(
  176. # learning_rate=1e-3,
  177. # classification_loss_type=classification_loss_type,
  178. # regression_iou_loss_type=regression_iou_loss_type,
  179. # pose_classification_loss_type=pose_classification_loss_type,
  180. # classification_loss_weight=1.0,
  181. # iou_loss_weight=2.5,
  182. # dfl_loss_weight=0.5,
  183. # pose_cls_loss_weight=1.0,
  184. # pose_reg_loss_weight=1.0,
  185. # use_cocoeval_formula=use_cocoeval_formula,
  186. # use_offset_compensation=use_offset_compensation,
  187. # )
  188. # )
  189. # grid search over loss weights
  190. for cls_loss_weight in [0.1, 0.5, 1.0]:
  191. for dfl_loss_weight in [0.01, 0.1, 0.5]:
  192. for pose_reg_loss_weight in [1, 5, 10]:
  193. hyperparameters_grid.append(
  194. dict(
  195. learning_rate=1e-3,
  196. classification_loss_type="focal",
  197. regression_iou_loss_type="ciou",
  198. pose_classification_loss_type="focal",
  199. classification_loss_weight=cls_loss_weight,
  200. iou_loss_weight=2.5,
  201. dfl_loss_weight=dfl_loss_weight,
  202. pose_cls_loss_weight=1.0,
  203. pose_reg_loss_weight=pose_reg_loss_weight,
  204. use_cocoeval_formula=True,
  205. use_offset_compensation=True,
  206. )
  207. )
  208. torch.backends.cudnn.deterministic = True
  209. torch.backends.cudnn.benchmark = True
  210. for trial in hyperparameters_grid:
  211. log_dir = "runs/" + hashlib.md5(str(trial).encode("utf-8")).hexdigest()
  212. os.makedirs(log_dir, exist_ok=True)
  213. writer = SummaryWriter(log_dir)
  214. torch.cuda.manual_seed_all(0)
  215. model: YoloNASPose = models.get(
  216. Models.YOLO_NAS_POSE_S,
  217. arch_params=dict(heads=dict(YoloNASPoseNDFLHeads=dict(compensate_grid_cell_offset=trial["use_offset_compensation"]))),
  218. num_classes=num_classes,
  219. checkpoint_path="https://sghub.deci.ai/models/yolo_nas_s_coco.pth",
  220. strict_load=StrictLoad.KEY_MATCHING,
  221. ).cuda()
  222. optimizer = Adam(model.parameters(), lr=trial["learning_rate"], weight_decay=0.0)
  223. loss = YoloNASPoseLoss(
  224. num_classes=num_classes,
  225. oks_sigmas=oks_sigmas,
  226. reg_max=16,
  227. classification_loss_type=trial["classification_loss_type"],
  228. regression_iou_loss_type=trial["regression_iou_loss_type"],
  229. classification_loss_weight=trial["classification_loss_weight"],
  230. iou_loss_weight=trial["iou_loss_weight"],
  231. dfl_loss_weight=trial["dfl_loss_weight"],
  232. pose_cls_loss_weight=trial["pose_cls_loss_weight"],
  233. pose_reg_loss_weight=trial["pose_reg_loss_weight"],
  234. use_cocoeval_formula=trial["use_cocoeval_formula"],
  235. pose_classification_loss_type=trial["pose_classification_loss_type"],
  236. ).cuda()
  237. inputs = images.cuda()
  238. targets = boxes.cuda(), joints.cuda()
  239. scaler = torch.cuda.amp.GradScaler()
  240. callback = model.get_post_prediction_callback(conf=0.1, iou=0.7, post_nms_max_predictions=30)
  241. metric = PoseEstimationMetrics(
  242. oks_sigmas=oks_sigmas,
  243. post_prediction_callback=callback,
  244. num_joints=num_classes,
  245. )
  246. global_step = 0
  247. for epoch in range(50):
  248. for step in range(100):
  249. optimizer.zero_grad(set_to_none=True)
  250. with torch.cuda.amp.autocast(enabled=True):
  251. outputs = model(inputs)
  252. loss_for_backward, loss_components = loss(outputs, targets)
  253. scaler.scale(loss_for_backward).backward()
  254. scaler.step(optimizer)
  255. scaler.update()
  256. loss_components_dict = {k: v.item() for k, v in zip(loss.component_names, loss_components)}
  257. print(loss_components_dict, "epoch", epoch, "step", step)
  258. for k, v in loss_components_dict.items():
  259. writer.add_scalar(f"loss/{k}", v, global_step)
  260. for param_group_index, param_group in enumerate(optimizer.param_groups):
  261. lr = param_group["lr"]
  262. writer.add_scalar(f"optimizer/pg_{param_group_index}_lr", lr, global_step)
  263. global_step += 1
  264. # End of "epoch"
  265. metric.reset()
  266. metric(outputs, targets, **extras)
  267. metrics = metric.compute()
  268. # Reduce LR
  269. for param_group in optimizer.param_groups:
  270. param_group["lr"] *= 0.98
  271. predictions: List[PoseEstimationPredictions] = callback(outputs)
  272. batch_results = ExtremeBatchPoseEstimationVisualizationCallback.visualize_batch(
  273. images_8u,
  274. keypoints=[p.poses for p in predictions],
  275. bboxes=[p.bboxes for p in predictions],
  276. scores=[p.scores for p in predictions],
  277. edge_links=edge_links,
  278. edge_colors=edge_colors,
  279. keypoint_colors=keypoint_colors,
  280. )
  281. for image_index, image in enumerate(batch_results):
  282. writer.add_image(f"predictions/{image_index}", batch_results[image_index], global_step, dataformats="HWC")
  283. for metric_name, metric_value in metrics.items():
  284. writer.add_scalar("metrics/" + metric_name, metric_value, global_step)
  285. # End of training - log final scores and hyperparameters
  286. writer.add_hparams(
  287. trial,
  288. metric_dict=metrics,
  289. hparam_domain_discrete={
  290. "classification_loss_type": ["focal", "bce"],
  291. "regression_iou_loss_type": ["giou", "ciou"],
  292. "pose_classification_loss_type": ["bce", "focal"],
  293. "use_cocoeval_formula": [True, False],
  294. "use_offset_compensation": [True, False],
  295. },
  296. )
  297. if __name__ == "__main__":
  298. unittest.main()
Tip!

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

Comments

Loading...