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

mask_loss_test.py 7.2 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
  1. import torch
  2. import unittest
  3. import torch.nn as nn
  4. from super_gradients.training.losses.mask_loss import MaskAttentionLoss
  5. from super_gradients.training.utils.segmentation_utils import to_one_hot
  6. class MaskAttentionLossTest(unittest.TestCase):
  7. def setUp(self) -> None:
  8. self.img_size = 32
  9. self.num_classes = 4
  10. self.batch = 3
  11. torch.manual_seed(65)
  12. def _get_default_predictions_tensor(self):
  13. return torch.randn(self.batch, self.num_classes, self.img_size, self.img_size)
  14. def _get_default_target_tensor(self):
  15. return torch.randint(0, self.num_classes, size=(self.batch, self.img_size, self.img_size))
  16. def _get_default_mask_tensor(self):
  17. mask = torch.zeros(self.batch, 1, self.img_size, self.img_size)
  18. # half tensor rows as 1
  19. mask[:, :, self.img_size // 2:] = 1
  20. return mask.float()
  21. def _assertion_torch_values(self, expected_value: torch.Tensor, found_value: torch.Tensor, rtol: float = 1e-5):
  22. self.assertTrue(
  23. torch.allclose(found_value, expected_value, rtol=rtol),
  24. msg=f"Unequal torch tensors: excepted: {expected_value}, found: {found_value}"
  25. )
  26. def test_with_cross_entropy_loss(self):
  27. """
  28. Test simple case using CrossEntropyLoss,
  29. shapes: predict [BxCxHxW], target [BxHxW], mask [Bx1xHxW]
  30. """
  31. predict = torch.randn(self.batch, self.num_classes, self.img_size, self.img_size)
  32. target = self._get_default_target_tensor()
  33. mask = self._get_default_mask_tensor()
  34. loss_weigths = [1., 0.5]
  35. ce_crit = nn.CrossEntropyLoss(reduction="none")
  36. mask_ce_crit = MaskAttentionLoss(criterion=ce_crit, loss_weights=loss_weigths)
  37. # expected result
  38. ce_loss = ce_crit(predict, target)
  39. _mask = mask.view_as(ce_loss)
  40. mask_loss = (ce_loss * _mask)
  41. mask_loss = mask_loss[_mask == 1] # consider only mask samples for mask loss computing
  42. expected_loss = ce_loss.mean() * loss_weigths[0] + mask_loss.mean() * loss_weigths[1]
  43. # mask ce loss result
  44. loss = mask_ce_crit(predict, target, mask)
  45. self._assertion_torch_values(expected_loss, loss)
  46. def test_with_binary_cross_entropy_loss(self):
  47. """
  48. Test case using BCEWithLogitsLoss, where mask is a spatial mask applied across all channels.
  49. shapes: predict [BxCxHxW], target (one-hot) [BxCxHxW], mask [Bx1xHxW]
  50. """
  51. predict = self._get_default_predictions_tensor()
  52. target = torch.randn(self.batch, self.num_classes, self.img_size, self.img_size)
  53. mask = self._get_default_mask_tensor()
  54. loss_weigths = [1., 0.5]
  55. ce_crit = nn.BCEWithLogitsLoss(reduction="none")
  56. mask_ce_crit = MaskAttentionLoss(criterion=ce_crit, loss_weights=loss_weigths)
  57. # expected result
  58. ce_loss = ce_crit(predict, target)
  59. _mask = mask.expand_as(ce_loss)
  60. mask_loss = (ce_loss * _mask)
  61. mask_loss = mask_loss[_mask == 1] # consider only mask samples for mask loss computing
  62. expected_loss = ce_loss.mean() * loss_weigths[0] + mask_loss.mean() * loss_weigths[1]
  63. # mask ce loss result
  64. loss = mask_ce_crit(predict, target, mask)
  65. self._assertion_torch_values(expected_loss, loss)
  66. def test_reduction_none(self):
  67. """
  68. Test case mask loss with reduction="none".
  69. shapes: predict [BxCxHxW], target [BxHxW], mask [Bx1xHxW], except output to be same as target shape.
  70. """
  71. predict = torch.randn(self.batch, self.num_classes, self.img_size, self.img_size)
  72. target = self._get_default_target_tensor()
  73. mask = self._get_default_mask_tensor()
  74. loss_weigths = [1., 0.5]
  75. ce_crit = nn.CrossEntropyLoss(reduction="none")
  76. mask_ce_crit = MaskAttentionLoss(criterion=ce_crit, loss_weights=loss_weigths, reduction="none")
  77. # expected result
  78. ce_loss = ce_crit(predict, target)
  79. _mask = mask.view_as(ce_loss)
  80. mask_loss = (ce_loss * _mask)
  81. expected_loss = ce_loss * loss_weigths[0] + mask_loss * loss_weigths[1]
  82. # mask ce loss result
  83. loss = mask_ce_crit(predict, target, mask)
  84. self._assertion_torch_values(expected_loss, loss)
  85. self.assertEqual(target.size(), loss.size())
  86. def test_assert_valid_arguments(self):
  87. # ce_criterion reduction must be none
  88. kwargs = {"criterion": nn.CrossEntropyLoss(reduction="mean")}
  89. self.failUnlessRaises(ValueError, MaskAttentionLoss, **kwargs)
  90. # loss_weights must have only 2 values
  91. kwargs = {"criterion": nn.CrossEntropyLoss(reduction="none"), "loss_weights": [1., 1., 1.]}
  92. self.failUnlessRaises(ValueError, MaskAttentionLoss, **kwargs)
  93. # mask loss_weight must be a positive value
  94. kwargs = {"criterion": nn.CrossEntropyLoss(reduction="none"), "loss_weights": [1., 0.]}
  95. self.failUnlessRaises(ValueError, MaskAttentionLoss, **kwargs)
  96. def test_multi_class_mask(self):
  97. """
  98. Test case using MSELoss, where there is different spatial masks per channel.
  99. shapes: predict [BxCxHxW], target [BxCxHxW], mask [BxCxHxW]
  100. """
  101. predict = self._get_default_predictions_tensor()
  102. # when using bce loss, target is usually a one hot vector and must be with the same shape as the prediction.
  103. target = self._get_default_target_tensor()
  104. target = to_one_hot(target, self.num_classes).float()
  105. mask = torch.randint(0, 2, size=(self.batch, self.num_classes, self.img_size, self.img_size)).float()
  106. loss_weigths = [1., 0.5]
  107. ce_crit = nn.MSELoss(reduction="none")
  108. mask_ce_crit = MaskAttentionLoss(criterion=ce_crit, loss_weights=loss_weigths)
  109. # expected result
  110. mse_loss = ce_crit(predict, target)
  111. mask_loss = (mse_loss * mask)
  112. mask_loss = mask_loss[mask == 1] # consider only mask samples for mask loss computing
  113. expected_loss = mse_loss.mean() * loss_weigths[0] + mask_loss.mean() * loss_weigths[1]
  114. # mask ce loss result
  115. loss = mask_ce_crit(predict, target, mask)
  116. self._assertion_torch_values(expected_loss, loss)
  117. def test_broadcast_exceptions(self):
  118. """
  119. Test assertion in mask broadcasting
  120. """
  121. predict = torch.randn(self.batch, self.num_classes, self.img_size, self.img_size)
  122. target = torch.randint(0, self.num_classes,
  123. size=(self.batch, self.num_classes, self.img_size, self.img_size)).float()
  124. loss_weigths = [1., 0.5]
  125. ce_crit = nn.BCEWithLogitsLoss(reduction="none")
  126. mask_ce_crit = MaskAttentionLoss(criterion=ce_crit, loss_weights=loss_weigths)
  127. # mask with wrong spatial size.
  128. mask = torch.zeros(self.batch, self.img_size, 1).float()
  129. self.failUnlessRaises(AssertionError, mask_ce_crit, *(predict, target, mask))
  130. # mask with wrong batch size.
  131. mask = torch.zeros(self.batch + 1, self.img_size, self.img_size).float()
  132. self.failUnlessRaises(AssertionError, mask_ce_crit, *(predict, target, mask))
  133. # mask with invalid channels num.
  134. mask = torch.zeros(self.batch, 2, self.img_size, self.img_size).float()
  135. self.failUnlessRaises(AssertionError, mask_ce_crit, *(predict, target, mask))
  136. if __name__ == '__main__':
  137. unittest.main()
Tip!

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

Comments

Loading...