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

zero_weight_decay_on_bias_bn_test.py 9.7 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
  1. import unittest
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. import torch
  5. from super_gradients.training.utils.optimizer_utils import separate_zero_wd_params_groups_for_optimizer
  6. from super_gradients.training.utils import HpmStruct
  7. from super_gradients.training.models.sg_module import SgModule
  8. class ToyLinearKernel(nn.Module):
  9. """
  10. Custom Toy linear module to test custom modules with bias parameter, that are not instances of primitive torch
  11. modules.
  12. """
  13. def __init__(self, in_features: int, out_features: int, bias: bool = True):
  14. super().__init__()
  15. self.weight = nn.Parameter(torch.Tensor(out_features, in_features))
  16. if bias:
  17. self.bias = nn.Parameter(torch.Tensor(out_features))
  18. else:
  19. self.register_parameter("bias", None)
  20. def forward(self, input: torch.Tensor):
  21. return F.linear(input, self.weight, self.bias)
  22. class ToySgModule(SgModule):
  23. """
  24. Toy Module to test zero of weight decay, support multiple group of parameters.
  25. """
  26. CONV_CLASSES = {1: nn.Conv1d, 2: nn.Conv2d, 3: nn.Conv3d}
  27. CONV_TRANSPOSE_CLASSES = {1: nn.ConvTranspose1d, 2: nn.ConvTranspose2d, 3: nn.ConvTranspose3d}
  28. BN_CLASSES = {1: nn.BatchNorm1d, 2: nn.BatchNorm2d, 3: nn.BatchNorm3d}
  29. def __init__(self, input_dimension=2, multiple_param_groups=False, module_groups=False, linear_cls=nn.Linear):
  30. """
  31. :param input_dimension: input dimension, 1 for 1D, 2 for 2D ...
  32. :param multiple_param_groups: if True create multiple param groups with different optimizer args.
  33. """
  34. super().__init__()
  35. num_classes = 10
  36. self.multiple_param_groups = multiple_param_groups
  37. self.module_groups = module_groups
  38. self.conv_cls = self.CONV_CLASSES[input_dimension]
  39. self.bn_cls = self.BN_CLASSES[input_dimension]
  40. self.conv_transpose_cls = self.CONV_TRANSPOSE_CLASSES[input_dimension]
  41. self.linear_cls = linear_cls
  42. self.num_conv = 0
  43. self.num_bn = 0
  44. self.num_biases = 0
  45. self.num_linear = 0
  46. self.base = nn.Sequential(
  47. self.conv1(3, 128, 2),
  48. self.conv1(128, 128, 2, bias=True),
  49. self.conv_transpose(128, 128),
  50. self.conv_transpose(128, 128, bias=True),
  51. )
  52. self.base_params = (self.num_no_decay_params(), self.num_decay_params())
  53. self.more_convs = nn.Sequential(
  54. self.conv1(128, 128, 1),
  55. self.conv1(128, 128, 2, bias=True),
  56. self.conv_transpose(128, 128),
  57. )
  58. self.avg_pool = nn.AdaptiveAvgPool2d(1)
  59. self.classifier = nn.Sequential(self.linear(128, 2 * num_classes, bias=False), self.linear(2 * num_classes, num_classes, bias=True))
  60. self.head = nn.Sequential(self.more_convs, self.avg_pool, self.classifier)
  61. self.head_params = (self.num_no_decay_params() - self.base_params[0], self.num_decay_params() - self.base_params[1])
  62. def conv1(self, ch_in: int, ch_out: int, stride: int, bias=False):
  63. self.num_conv += 1
  64. if bias:
  65. conv = self.conv_cls(ch_in, ch_out, 1, stride=stride, bias=bias)
  66. self.num_biases += 1
  67. else:
  68. conv = nn.Sequential(self.conv_cls(ch_in, ch_out, 1, stride=stride, bias=bias), self.bn_cls(ch_out), nn.ReLU())
  69. self.num_bn += 1
  70. return conv
  71. def conv_transpose(self, ch_in: int, ch_out: int, bias=False):
  72. self.num_conv += 1
  73. if bias:
  74. conv = self.conv_transpose_cls(ch_in, ch_out, 2, stride=2, bias=bias)
  75. self.num_biases += 1
  76. else:
  77. conv = nn.Sequential(self.conv_transpose_cls(ch_in, ch_out, 2, stride=2, bias=bias), self.bn_cls(ch_out), nn.ReLU())
  78. self.num_bn += 1
  79. return conv
  80. def linear(self, ch_in: int, ch_out: int, bias=False):
  81. self.num_linear += 1
  82. if bias:
  83. self.num_biases += 1
  84. return self.linear_cls(ch_in, ch_out, bias)
  85. def num_decay_params(self):
  86. return self.num_conv + self.num_linear
  87. def num_no_decay_params(self):
  88. return self.num_biases + 2 * self.num_bn
  89. def initialize_param_groups(self, lr: float, training_params: HpmStruct) -> list:
  90. # Example to different learning rates, similar to ShelfNet, in order to create multiple groups.
  91. if self.multiple_param_groups:
  92. params_list = [{"named_params": self.base.named_parameters(), "lr": lr}, {"named_params": self.head.named_parameters(), "lr": lr * 10}]
  93. return params_list
  94. return super().initialize_param_groups(lr, training_params)
  95. class ZeroWdForBnBiasTest(unittest.TestCase):
  96. """
  97. Testing if the optimizer parameters are divided into two groups with one being with weight_decay = 0
  98. """
  99. def setUp(self):
  100. # Define Parameters
  101. self.weight_decay = 0.01
  102. self.lr = 0.1
  103. # input dimension beside batch and channels, i.e 2 for vision, 1 for audio, 3 for point cloud.
  104. self.input_dimensions = (1, 2, 3)
  105. self.train_params_zero_wd = {"initial_lr": self.lr, "optimizer": "SGD", "optimizer_params": {"weight_decay": self.weight_decay, "momentum": 0.9}}
  106. def _assert_optimizer_param_groups(
  107. self, param_groups: list, excpected_num_groups: int, excpected_num_params_per_group: list, excpected_weight_decay_per_group: list
  108. ):
  109. """
  110. Helper method to assert, num of param_groups, num of parameters in each param group and weight decay value
  111. in each param group.
  112. """
  113. self.assertEqual(len(param_groups), excpected_num_groups, msg=f"Optimizer should have {excpected_num_groups} groups")
  114. for (param_group, excpected_num_params, excpected_weight_decay) in zip(param_groups, excpected_num_params_per_group, excpected_weight_decay_per_group):
  115. self.assertEqual(
  116. len(param_group["params"]),
  117. excpected_num_params,
  118. msg="Wrong number of params for optimizer param group, excpected: {}, found: {}".format(excpected_num_params, len(param_group["params"])),
  119. )
  120. self.assertEqual(
  121. param_group["weight_decay"],
  122. excpected_weight_decay,
  123. msg="Wrong weight decay value found for optimizer param group, excpected: {}, found: {}".format(
  124. excpected_weight_decay, param_group["weight_decay"]
  125. ),
  126. )
  127. def test_zero_wd_one_group(self):
  128. """
  129. test that one group of parameters are separated to weight_decay_params and without.
  130. """
  131. for input_dim in self.input_dimensions:
  132. net = ToySgModule(input_dimension=input_dim)
  133. train_params = HpmStruct(**self.train_params_zero_wd)
  134. optimizer_params_groups = separate_zero_wd_params_groups_for_optimizer(net, net.initialize_param_groups(self.lr, train_params), self.weight_decay)
  135. self._assert_optimizer_param_groups(
  136. optimizer_params_groups,
  137. excpected_num_groups=2,
  138. excpected_num_params_per_group=[net.num_no_decay_params(), net.num_decay_params()],
  139. excpected_weight_decay_per_group=[0, self.weight_decay],
  140. )
  141. def test_zero_wd_multiple_group(self):
  142. """
  143. test that 2 groups of parameters are separated to 2 groups of weight_decay_params and 2 groups without.
  144. """
  145. for input_dim in self.input_dimensions:
  146. net = ToySgModule(input_dimension=input_dim, multiple_param_groups=True)
  147. train_params = HpmStruct(**self.train_params_zero_wd)
  148. optimizer_params_groups = separate_zero_wd_params_groups_for_optimizer(net, net.initialize_param_groups(self.lr, train_params), self.weight_decay)
  149. self._assert_optimizer_param_groups(
  150. optimizer_params_groups,
  151. excpected_num_groups=4,
  152. excpected_num_params_per_group=[net.base_params[0], net.base_params[1], net.head_params[0], net.head_params[1]],
  153. excpected_weight_decay_per_group=[0, self.weight_decay, 0, self.weight_decay],
  154. )
  155. def test_zero_wd_sync_bn(self):
  156. """
  157. test affiliation of nn.SyncBatchNorm parameters to zero weight decay.
  158. """
  159. for input_dim in self.input_dimensions:
  160. net = ToySgModule(input_dimension=input_dim)
  161. # Convert to SyncBatchNorm
  162. net = nn.SyncBatchNorm.convert_sync_batchnorm(net)
  163. train_params = HpmStruct(**self.train_params_zero_wd)
  164. optimizer_params_groups = separate_zero_wd_params_groups_for_optimizer(net, net.initialize_param_groups(self.lr, train_params), self.weight_decay)
  165. self._assert_optimizer_param_groups(
  166. optimizer_params_groups,
  167. excpected_num_groups=2,
  168. excpected_num_params_per_group=[net.num_no_decay_params(), net.num_decay_params()],
  169. excpected_weight_decay_per_group=[0, self.weight_decay],
  170. )
  171. def test_zero_wd_custom_module_with_bias(self):
  172. """
  173. test affiliation of nn.SyncBatchNorm parameters to zero weight decay.
  174. """
  175. input_dim = 2
  176. net = ToySgModule(input_dimension=input_dim, linear_cls=ToyLinearKernel)
  177. train_params = HpmStruct(**self.train_params_zero_wd)
  178. optimizer_params_groups = separate_zero_wd_params_groups_for_optimizer(net, net.initialize_param_groups(self.lr, train_params), self.weight_decay)
  179. self._assert_optimizer_param_groups(
  180. optimizer_params_groups,
  181. excpected_num_groups=2,
  182. excpected_num_params_per_group=[net.num_no_decay_params(), net.num_decay_params()],
  183. excpected_weight_decay_per_group=[0, self.weight_decay],
  184. )
  185. if __name__ == "__main__":
  186. unittest.main()
Tip!

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

Comments

Loading...