-
Notifications
You must be signed in to change notification settings - Fork 32
/
losses.py
777 lines (656 loc) · 29.2 KB
/
losses.py
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
"""Supervised and unsupervised losses implemented in pytorch.
The lightning pose package defines each loss as its own class; an initialized loss
object, in addition to computing the loss, stores hyperparameters related to the loss
(weight in the final objective funcion, epsilon-insensitivity parameter, etc.)
A separate LossFactory class (defined in lightning_pose.losses.factory) collects all
losses for a given model and orchestrates their execution, logging, etc.
The general flow of each loss class is as follows:
- input: predicted and ground truth data
- step 0: remove ground truth samples containing nans if desired
- step 1: compute loss for each batch element/keypoint/etc
- step 2: epsilon-insensitivity: set loss to zero for any batch element with loss < epsilon
- step 3: reduce loss (usually mean)
- step 4: log values to a dict
- step 5: return weighted loss
"""
import warnings
from typing import Dict, List, Literal, Optional, Tuple, Type, Union
import lightning.pytorch as pl
import torch
from kornia.losses import js_div_loss_2d, kl_div_loss_2d
from omegaconf import ListConfig
from torch.nn import functional as F
from torchtyping import TensorType
from typeguard import typechecked
from lightning_pose.data.datamodules import BaseDataModule, UnlabeledDataModule
from lightning_pose.data.utils import generate_heatmaps
from lightning_pose.utils.pca import KeypointPCA
# to ignore imports for sphix-autoapidoc
__all__ = [
"Loss",
"HeatmapLoss",
"HeatmapMSELoss",
"HeatmapKLLoss",
"HeatmapJSLoss",
"PCALoss",
"TemporalLoss",
"TemporalHeatmapLoss",
"UnimodalLoss",
"RegressionMSELoss",
"RegressionRMSELoss",
"get_loss_classes",
]
_TORCH_DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# @typechecked
class Loss(pl.LightningModule):
"""Parent class for all losses."""
def __init__(
self,
data_module: Optional[Union[BaseDataModule, UnlabeledDataModule]] = None,
epsilon: Union[float, List[float]] = 0.0,
log_weight: float = 0.0,
**kwargs,
) -> None:
"""
Args:
data_module: give losses access to data for computing data-specific loss params
epsilon: loss values below epsilon will be zeroed out
log_weight: natural log of the weight in front of the loss term in the final
objective function
"""
super().__init__()
self.data_module = data_module
# epsilon can either by a float or a list of floats
self.epsilon = torch.tensor(epsilon, dtype=torch.float, device=self.device)
self.log_weight = torch.tensor(log_weight, dtype=torch.float, device=self.device)
self.loss_name = "base"
self.reduce_methods_dict = {"mean": torch.mean, "sum": torch.sum}
@property
def weight(self) -> TensorType[()]:
# weight = \sigma where our trainable parameter is \log(\sigma^2).
# i.e., we take the parameter as it is in the config and exponentiate it to
# enforce positivity
weight = 1.0 / (2.0 * torch.exp(self.log_weight))
return weight
def remove_nans(self, **kwargs):
# find nans in the targets, and do a masked_select operation
raise NotImplementedError
def compute_loss(self, **kwargs):
raise NotImplementedError
def rectify_epsilon(self, loss: torch.Tensor) -> torch.Tensor:
# loss values below epsilon as masked to zero
loss = F.relu(loss - self.epsilon)
return loss
def reduce_loss(self, loss: torch.Tensor, method: str = "mean") -> TensorType[()]:
return self.reduce_methods_dict[method](loss)
def log_loss(
self,
loss: torch.Tensor,
stage: Literal["train", "val", "test"],
) -> List[dict]:
loss_dict = {
"name": "%s_%s_loss" % (stage, self.loss_name),
"value": loss,
"prog_bar": True,
}
weight_dict = {
"name": "%s_weight" % self.loss_name,
"value": self.weight,
}
return [loss_dict, weight_dict]
def __call__(self, *args, **kwargs):
# give us the flow of operations, and we overwrite the methods, and determine
# their arguments which are in buffer
# self.remove_nans()
# self.compute_loss()
# self.rectify_epsilon()
# self.reduce_loss()
# self.log_loss()
# return self.weight * scalar_loss, logs
raise NotImplementedError
# @typechecked
class HeatmapLoss(Loss):
"""Parent class for different heatmap losses (MSE, Wasserstein, etc)."""
def __init__(
self,
data_module: Optional[Union[BaseDataModule, UnlabeledDataModule]] = None,
log_weight: float = 0.0,
**kwargs,
) -> None:
super().__init__(data_module=data_module, log_weight=log_weight)
def remove_nans(
self,
targets: TensorType["batch", "num_keypoints", "heatmap_height", "heatmap_width"],
predictions: TensorType["batch", "num_keypoints", "heatmap_height", "heatmap_width"],
) -> Tuple[
TensorType["num_valid_keypoints", "heatmap_height", "heatmap_width"],
TensorType["num_valid_keypoints", "heatmap_height", "heatmap_width"],
]:
squeezed_targets = targets.reshape(targets.shape[0], targets.shape[1], -1)
idxs_ignore = torch.all(squeezed_targets == 0.0, dim=-1)
return targets[~idxs_ignore], predictions[~idxs_ignore]
def compute_loss(self, **kwargs):
raise NotImplementedError
def __call__(
self,
heatmaps_targ: TensorType["batch", "num_keypoints", "heatmap_height", "heatmap_width"],
heatmaps_pred: TensorType["batch", "num_keypoints", "heatmap_height", "heatmap_width"],
stage: Optional[Literal["train", "val", "test"]] = None,
**kwargs,
) -> Tuple[TensorType[()], List[dict]]:
# give us the flow of operations, and we overwrite the methods, and determine
# their arguments which are in buffer
clean_targets, clean_predictions = self.remove_nans(
targets=heatmaps_targ, predictions=heatmaps_pred
)
elementwise_loss = self.compute_loss(
targets=clean_targets, predictions=clean_predictions
)
# epsilon_insensitive_loss = self.rectify_epsilon(loss=elementwise_loss)
scalar_loss = self.reduce_loss(elementwise_loss, method="mean")
logs = self.log_loss(loss=scalar_loss, stage=stage)
return self.weight * scalar_loss, logs
# @typechecked
class HeatmapMSELoss(HeatmapLoss):
"""MSE loss between heatmaps."""
def __init__(
self,
data_module: Optional[Union[BaseDataModule, UnlabeledDataModule]] = None,
log_weight: float = 0.0,
**kwargs,
) -> None:
super().__init__(data_module=data_module, log_weight=log_weight)
self.loss_name = "heatmap_mse"
def compute_loss(
self,
targets: TensorType["batch_x_num_keypoints", "heatmap_height", "heatmap_width"],
predictions: TensorType["batch_x_num_keypoints", "heatmap_height", "heatmap_width"],
) -> TensorType["batch_x_num_keypoints", "heatmap_height", "heatmap_width"]:
h = targets.shape[1]
w = targets.shape[2]
# multiply by number of pixels in heatmap to standardize loss range
loss = F.mse_loss(targets, predictions, reduction="none") * h * w
return loss
# @typechecked
class HeatmapKLLoss(HeatmapLoss):
"""Kullback-Leibler loss between heatmaps."""
def __init__(
self,
data_module: Optional[Union[BaseDataModule, UnlabeledDataModule]] = None,
log_weight: float = 0.0,
**kwargs,
) -> None:
super().__init__(data_module=data_module, log_weight=log_weight)
self.loss = kl_div_loss_2d
self.loss_name = "heatmap_kl"
def compute_loss(
self,
targets: TensorType["num_valid_keypoints", "heatmap_height", "heatmap_width"],
predictions: TensorType["num_valid_keypoints", "heatmap_height", "heatmap_width"],
) -> TensorType["num_valid_keypoints"]:
loss = self.loss(
predictions.unsqueeze(0) + 1e-10,
targets.unsqueeze(0) + 1e-10,
reduction="none",
)
return loss[0]
# @typechecked
class HeatmapJSLoss(HeatmapLoss):
"""Kullback-Leibler loss between heatmaps."""
def __init__(
self,
data_module: Optional[Union[BaseDataModule, UnlabeledDataModule]] = None,
log_weight: float = 0.0,
**kwargs,
) -> None:
super().__init__(data_module=data_module, log_weight=log_weight)
self.loss = js_div_loss_2d
self.loss_name = "heatmap_js"
def compute_loss(
self,
targets: TensorType["num_valid_keypoints", "heatmap_height", "heatmap_width"],
predictions: TensorType["num_valid_keypoints", "heatmap_height", "heatmap_width"],
) -> TensorType["num_valid_keypoints"]:
loss = self.loss(
predictions.unsqueeze(0) + 1e-10,
targets.unsqueeze(0) + 1e-10,
reduction="none",
)
return loss[0]
# @typechecked
class PCALoss(Loss):
"""Penalize predictions that fall outside a low-dimensional subspace."""
def __init__(
self,
loss_name: Literal["pca_singleview", "pca_multiview"],
components_to_keep: Union[int, float] = 0.95,
empirical_epsilon_percentile: float = 0.99,
epsilon: Optional[float] = None,
empirical_epsilon_multiplier: float = 1.0,
mirrored_column_matches: Optional[Union[ListConfig, List]] = None,
columns_for_singleview_pca: Optional[Union[ListConfig, List]] = None,
data_module: Optional[Union[BaseDataModule, UnlabeledDataModule]] = None,
log_weight: float = 0.0,
device: str = _TORCH_DEVICE,
**kwargs,
) -> None:
super().__init__(data_module=data_module, log_weight=log_weight)
self.loss_name = loss_name
if loss_name == "pca_multiview":
if mirrored_column_matches is None:
raise ValueError("must provide mirrored_column_matches in data config")
# the current data_module contains datasets that are loaded using augmentations. the
# current solution is to pass the data module to KeypointPCA, which then passes it to
# DataExtractor; we will also pass a "no_augmentation" arg to DataExtractor which will
# rebuild the data module with only resizing augmentations, then extract the data.
# initialize keypoint pca module
# this module will fit pca on training data, and will define the error metric
# and fuction to be used in model training.
self.pca = KeypointPCA(
loss_type=self.loss_name,
data_module=data_module,
components_to_keep=components_to_keep,
empirical_epsilon_percentile=empirical_epsilon_percentile,
mirrored_column_matches=mirrored_column_matches,
columns_for_singleview_pca=columns_for_singleview_pca,
device=device,
)
# compute all the parameters needed for the loss
self.pca()
# select epsilon based on constructor inputs
if epsilon is not None:
warnings.warn(
"Using absolute epsilon=%.2f for pca loss; empirical epsilon ignored"
% epsilon
)
self.epsilon = torch.tensor(epsilon, dtype=torch.float, device=self.device)
else:
# empirically compute epsilon, already converted to tensor
self.epsilon = self.pca.parameters["epsilon"] * empirical_epsilon_multiplier
warnings.warn(
"Using empirical epsilon=%.3f * multiplier=%.3f -> total=%.3f for %s loss"
% (
float(self.pca.parameters["epsilon"]),
float(empirical_epsilon_multiplier),
float(self.epsilon),
self.loss_name,
)
)
def remove_nans(self, **kwargs):
# find nans in the targets, and do a masked_select operation
pass
def compute_loss(
self,
predictions: TensorType["num_samples", "sample_dim"],
) -> TensorType["num_samples", -1]:
# compute either reprojection error or projection onto discarded evecs.
# they will vary in the last dim, hence -1.
return self.pca.compute_reprojection_error(data_arr=predictions)
def __call__(
self,
keypoints_pred: torch.Tensor,
stage: Optional[Literal["train", "val", "test"]] = None,
**kwargs,
) -> Tuple[TensorType[()], List[dict]]:
keypoints_pred = self.pca._format_data(data_arr=keypoints_pred)
elementwise_loss = self.compute_loss(predictions=keypoints_pred)
epsilon_insensitive_loss = self.rectify_epsilon(loss=elementwise_loss)
scalar_loss = self.reduce_loss(epsilon_insensitive_loss, method="mean")
logs = self.log_loss(loss=scalar_loss, stage=stage)
return self.weight * scalar_loss, logs
# @typechecked
class TemporalLoss(Loss):
"""Penalize temporal differences for each target.
Motion model: x_t = x_(t-1) + e_t, e_t ~ N(0, s)
"""
def __init__(
self,
data_module: Optional[Union[BaseDataModule, UnlabeledDataModule]] = None,
epsilon: Union[float, List[float]] = 0.0,
prob_threshold: float = 0.0,
log_weight: float = 0.0,
**kwargs,
) -> None:
super().__init__(data_module=data_module, epsilon=epsilon, log_weight=log_weight)
self.loss_name = "temporal"
self.prob_threshold = torch.tensor(prob_threshold, dtype=torch.float, device=self.device)
def rectify_epsilon(
self, loss: TensorType["batch_minus_one", "num_keypoints"]
) -> TensorType["batch_minus_one", "num_keypoints"]:
"""Rectify supporting a list of epsilons, one per bodypart.
Not implemented in Loss class, because shapes of broadcasting may vary"""
# self.epsilon is a tensor initialized in parent class
# repeating for broadcasting.
# note: this unsqueezing doesn't affect anything if epsilon is a scalar tensor,
# but it does if it's a tensor with multiple elements.
epsilon = self.epsilon.unsqueeze(0).repeat(loss.shape[0], 1).to(loss.device)
return F.relu(loss - epsilon)
def remove_nans(
self,
loss: TensorType["batch_minus_one", "num_keypoints"],
confidences: TensorType["batch", "num_keypoints"],
) -> TensorType["batch_minus_one", "num_keypoints"]:
# find nans in the targets, and do a masked_select operation
# get rid of unsupervised targets with extremely uncertain predictions or likely occlusions
idxs_ignore = confidences < self.prob_threshold
# ignore the loss values in the diff where one of the heatmaps is 'nan'
union_idxs_ignore = torch.zeros(
(confidences.shape[0] - 1, confidences.shape[1]), dtype=torch.bool
).to(_TORCH_DEVICE)
for i in range(confidences.shape[0] - 1):
union_idxs_ignore[i] = torch.logical_or(idxs_ignore[i], idxs_ignore[i + 1])
# clone loss and zero out the nan values
clean_loss = loss.clone()
clean_loss[union_idxs_ignore] = 0.0
return clean_loss
def compute_loss(
self,
predictions: TensorType["batch", "two_x_num_keypoints"],
) -> TensorType["batch_minus_one", "num_keypoints"]:
# return shape: (batch - 1, num_targets)
diffs = torch.diff(predictions, dim=0)
# return shape: (batch - 1, num_keypoints, 2)
reshape = torch.reshape(diffs, (diffs.shape[0], -1, 2))
# return shape (batch - 1, num_keypoints)
loss = torch.linalg.norm(reshape, ord=2, dim=2)
return loss
def __call__(
self,
keypoints_pred: TensorType["batch", "two_x_num_keypoints"],
confidences: TensorType["batch", "num_keypoints"] = None,
stage: Optional[Literal["train", "val", "test"]] = None,
**kwargs,
) -> Tuple[TensorType[()], List[dict]]:
elementwise_loss = self.compute_loss(predictions=keypoints_pred)
# do remove nans with loss to remove temporal difference values
clean_loss = (
self.remove_nans(loss=elementwise_loss, confidences=confidences)
if confidences is not None
else elementwise_loss
)
epsilon_insensitive_loss = self.rectify_epsilon(loss=clean_loss)
scalar_loss = self.reduce_loss(epsilon_insensitive_loss, method="mean")
logs = self.log_loss(loss=scalar_loss, stage=stage)
return self.weight * scalar_loss, logs
# @typechecked
class TemporalHeatmapLoss(Loss):
"""Penalize temporal differences for each heatmap.
Motion model: x_t = x_(t-1) + e_t, e_t ~ N(0, s)
"""
def __init__(
self,
loss_name: Literal["temporal_heatmap_mse", "temporal_heatmap_kl"],
data_module: Optional[Union[BaseDataModule, UnlabeledDataModule]] = None,
epsilon: Union[float, List[float]] = 0.0,
prob_threshold: float = 0.0,
log_weight: float = 0.0,
**kwargs,
) -> None:
super().__init__(data_module=data_module, epsilon=epsilon, log_weight=log_weight)
self.loss_name = loss_name
if self.loss_name == "temporal_heatmap_mse":
self.hmloss = None
elif self.loss_name == "temporal_heatmap_kl":
self.hmloss = kl_div_loss_2d
else:
raise NotImplementedError
self.prob_threshold = torch.tensor(
prob_threshold, dtype=torch.float, device=self.device
)
def rectify_epsilon(
self, loss: TensorType["batch_minus_one", "num_valid_keypoints"]
) -> TensorType["batch_minus_one", "num_valid_keypoints"]:
"""Rectify supporting a list of epsilons, one per bodypart.
Not implemented in Loss class, because shapes of broadcasting may vary"""
# self.epsilon is a tensor initialized in parent class
# repeating for broadcasting.
# note: this unsqueezing doesn't affect anything if epsilon is a scalar tensor,
# but it does if it's a tensor with multiple elements.
epsilon = self.epsilon.unsqueeze(0).repeat(loss.shape[0], 1).to(loss.device)
return F.relu(loss - epsilon)
def remove_nans(
self,
confidences: TensorType["batch", "num_keypoints"],
loss: TensorType["batch_minus_one", "num_keypoints"],
) -> TensorType["batch_minus_one", "num_keypoints"]:
# find nans in the targets, and do a masked_select operation
# get rid of unsupervised targets with extremely uncertain predictions or likely occlusions
idxs_ignore = confidences < self.prob_threshold
# ignore the loss values in the diff where one of the heatmaps is 'nan'
union_idxs_ignore = torch.zeros(
(confidences.shape[0] - 1, confidences.shape[1]), dtype=torch.bool
).to(_TORCH_DEVICE)
for i in range(confidences.shape[0] - 1):
union_idxs_ignore[i] = torch.logical_or(idxs_ignore[i], idxs_ignore[i + 1])
loss[union_idxs_ignore] = 0.0
return loss
def compute_loss(
self,
predictions: TensorType["batch", "num_valid_keypoints", "heatmap_height", "heatmap_width"],
) -> TensorType["batch_minus_one", "num_valid_keypoints"]:
# compute the differences between matching heatmaps for each keypoint
diffs = torch.zeros((predictions.shape[0] - 1, predictions.shape[1])).to(
_TORCH_DEVICE
)
for i in range(diffs.shape[0]):
if self.loss_name == "temporal_heatmap_mse":
curr_mse = F.mse_loss(
predictions[i], predictions[i + 1], reduction="none"
).reshape(predictions.shape[1], -1)
diffs[i] = torch.mean(curr_mse, dim=-1)
elif self.loss_name == "temporal_heatmap_kl":
diffs[i] = self.hmloss(
predictions[i].unsqueeze(0) + 1e-10,
predictions[i + 1].unsqueeze(0) + 1e-10,
reduction="none",
)
return diffs
def __call__(
self,
heatmaps_pred: TensorType["batch", "num_keypoints", "heatmap_height", "heatmap_width"],
confidences: TensorType["batch", "num_keypoints"],
stage: Optional[Literal["train", "val", "test"]] = None,
**kwargs,
) -> Tuple[TensorType[()], List[dict]]:
elementwise_loss = self.compute_loss(predictions=heatmaps_pred)
# remove nan after loss is computed to get rid of diff vals with a bad heatmap
clean_loss = self.remove_nans(confidences=confidences, loss=elementwise_loss)
epsilon_insensitive_loss = self.rectify_epsilon(loss=clean_loss)
scalar_loss = self.reduce_loss(epsilon_insensitive_loss, method="mean")
logs = self.log_loss(loss=scalar_loss, stage=stage)
return self.weight * scalar_loss, logs
# @typechecked
class UnimodalLoss(Loss):
"""Encourage heatmaps to be unimodal using various measures."""
def __init__(
self,
loss_name: Literal["unimodal_mse", "unimodal_kl", "unimodal_js"],
original_image_height: int,
original_image_width: int,
downsampled_image_height: int,
downsampled_image_width: int,
data_module: Optional[Union[BaseDataModule, UnlabeledDataModule]] = None,
prob_threshold: float = 0.0,
log_weight: float = 0.0,
uniform_heatmaps: bool = False,
**kwargs,
) -> None:
super().__init__(data_module=data_module, log_weight=log_weight)
self.loss_name = loss_name
self.original_image_height = original_image_height
self.original_image_width = original_image_width
self.downsampled_image_height = downsampled_image_height
self.downsampled_image_width = downsampled_image_width
self.uniform_heatmaps = uniform_heatmaps
self.prob_threshold = torch.tensor(
prob_threshold, dtype=torch.float, device=self.device
)
if self.loss_name == "unimodal_mse":
self.loss = None
elif self.loss_name == "unimodal_kl":
self.loss = kl_div_loss_2d
elif self.loss_name == "unimodal_js":
self.loss = js_div_loss_2d
else:
raise NotImplementedError
def remove_nans(
self,
targets: TensorType["batch", "num_keypoints", "heatmap_height", "heatmap_width"],
predictions: TensorType["batch", "num_keypoints", "heatmap_height", "heatmap_width"],
confidences: TensorType["batch", "num_keypoints"],
) -> Tuple[
TensorType["num_valid_keypoints", "heatmap_height", "heatmap_width"],
TensorType["num_valid_keypoints", "heatmap_height", "heatmap_width"],
]:
"""Remove nans from targets and predictions.
Args:
targets: (batch, num_keypoints, heatmap_height, heatmap_width)
predictions: (batch, num_keypoints, heatmap_height, heatmap_width)
confidences: (batch, num_keypoints)
Returns:
clean targets: concatenated across different images and keypoints
clean predictions: concatenated across different images and keypoints
"""
# use confidences to get rid of unsupervised targets with likely occlusions
idxs_ignore = confidences < self.prob_threshold
return targets[~idxs_ignore], predictions[~idxs_ignore]
def compute_loss(
self,
targets: TensorType["num_valid_keypoints", "heatmap_height", "heatmap_width"],
predictions: TensorType["num_valid_keypoints", "heatmap_height", "heatmap_width"],
) -> torch.Tensor:
if self.loss_name == "unimodal_mse":
return F.mse_loss(targets, predictions, reduction="none")
elif self.loss_name == "unimodal_kl":
return self.loss(
predictions.unsqueeze(0) + 1e-10,
targets.unsqueeze(0) + 1e-10,
reduction="none",
)
elif self.loss_name == "unimodal_js":
return self.loss(
predictions.unsqueeze(0) + 1e-10,
targets.unsqueeze(0) + 1e-10,
reduction="none",
)
else:
raise NotImplementedError
def __call__(
self,
keypoints_pred_augmented: TensorType["batch", "two_x_num_keypoints"],
heatmaps_pred: TensorType["batch", "num_keypoints", "heatmap_height", "heatmap_width"],
confidences: TensorType["batch", "num_keypoints"],
stage: Optional[Literal["train", "val", "test"]] = None,
**kwargs,
) -> Tuple[TensorType[()], List[dict]]:
"""Compute unimodal loss.
Args:
keypoints_pred_augmented: these are in the augmented image space
heatmaps_pred: also in the augmented space, matching the keypoints_pred_augmented
"""
# turn keypoint predictions into unimodal heatmaps
keypoints_pred = keypoints_pred_augmented.reshape(keypoints_pred_augmented.shape[0], -1, 2)
heatmaps_ideal = generate_heatmaps( # this process doesn't compute gradients
keypoints=keypoints_pred,
height=self.original_image_height,
width=self.original_image_width,
output_shape=(self.downsampled_image_height, self.downsampled_image_width),
uniform_heatmaps=self.uniform_heatmaps,
)
# remove invisible keypoints according to confidences
clean_targets, clean_predictions = self.remove_nans(
targets=heatmaps_ideal, predictions=heatmaps_pred, confidences=confidences
)
# compute loss just on the valid heatmaps
elementwise_loss = self.compute_loss(
targets=clean_targets, predictions=clean_predictions
)
scalar_loss = self.reduce_loss(elementwise_loss, method="mean")
logs = self.log_loss(loss=scalar_loss, stage=stage)
return self.weight * scalar_loss, logs
# @typechecked
class RegressionMSELoss(Loss):
"""MSE loss between ground truth and predicted coordinates."""
def __init__(
self,
data_module: Optional[Union[BaseDataModule, UnlabeledDataModule]] = None,
epsilon: float = 0.0,
log_weight: float = 0.0,
**kwargs,
) -> None:
super().__init__(data_module=data_module, epsilon=epsilon, log_weight=log_weight)
self.loss_name = "regression_mse"
def remove_nans(
self,
targets: TensorType["batch", "two_x_num_keypoints"],
predictions: TensorType["batch", "two_x_num_keypoints"],
) -> Tuple[TensorType["num_valid_keypoints"], TensorType["num_valid_keypoints"]]:
mask = targets == targets # keypoints is not none, bool
targets_masked = torch.masked_select(targets, mask)
predictions_masked = torch.masked_select(predictions, mask)
return targets_masked, predictions_masked
def compute_loss(
self,
targets: TensorType["batch_x_two_x_num_keypoints"],
predictions: TensorType["batch_x_two_x_num_keypoints"],
) -> TensorType["batch_x_two_x_num_keypoints"]:
loss = F.mse_loss(targets, predictions, reduction="none")
return loss
def __call__(
self,
keypoints_targ: TensorType["batch", "two_x_num_keypoints"],
keypoints_pred: TensorType["batch", "two_x_num_keypoints"],
stage: Optional[Literal["train", "val", "test"]] = None,
**kwargs,
) -> Tuple[TensorType[()], List[dict]]:
clean_targets, clean_predictions = self.remove_nans(
targets=keypoints_targ, predictions=keypoints_pred
)
elementwise_loss = self.compute_loss(
targets=clean_targets, predictions=clean_predictions
)
scalar_loss = self.reduce_loss(elementwise_loss, method="mean")
logs = self.log_loss(loss=scalar_loss, stage=stage)
return self.weight * scalar_loss, logs
# @typechecked
class RegressionRMSELoss(RegressionMSELoss):
"""Root MSE loss between ground truth and predicted coordinates."""
def __init__(
self,
data_module: Optional[Union[BaseDataModule, UnlabeledDataModule]] = None,
epsilon: float = 0.0,
log_weight: float = 0.0,
**kwargs,
) -> None:
super().__init__(data_module=data_module, epsilon=epsilon, log_weight=log_weight)
self.loss_name = "rmse"
def compute_loss(
self,
targets: TensorType["batch_x_two_x_num_keypoints"],
predictions: TensorType["batch_x_two_x_num_keypoints"],
) -> TensorType["batch_x_num_keypoints"]:
targs = targets.reshape(-1, 2)
preds = predictions.reshape(-1, 2)
loss = torch.mean(F.mse_loss(targs, preds, reduction="none"), dim=1)
return torch.sqrt(loss)
@typechecked
def get_loss_classes() -> Dict[str, Type[Loss]]:
"""Get a dict with all the loss classes.
Returns:
Dict[str, Callable]: [description]
"""
loss_dict = {
"regression": RegressionMSELoss,
"heatmap_mse": HeatmapMSELoss,
"heatmap_kl": HeatmapKLLoss,
"heatmap_js": HeatmapJSLoss,
"pca_multiview": PCALoss,
"pca_singleview": PCALoss,
"temporal": TemporalLoss,
"temporal_heatmap_mse": TemporalHeatmapLoss,
"temporal_heatmap_kl": TemporalHeatmapLoss,
"unimodal_mse": UnimodalLoss,
"unimodal_kl": UnimodalLoss,
"unimodal_js": UnimodalLoss,
}
return loss_dict