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 11 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
  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,
  30. linear_cls=nn.Linear):
  31. """
  32. :param input_dimension: input dimension, 1 for 1D, 2 for 2D ...
  33. :param multiple_param_groups: if True create multiple param groups with different optimizer args.
  34. """
  35. super().__init__()
  36. num_classes = 10
  37. self.multiple_param_groups = multiple_param_groups
  38. self.module_groups = module_groups
  39. self.conv_cls = self.CONV_CLASSES[input_dimension]
  40. self.bn_cls = self.BN_CLASSES[input_dimension]
  41. self.conv_transpose_cls = self.CONV_TRANSPOSE_CLASSES[input_dimension]
  42. self.linear_cls = linear_cls
  43. self.num_conv = 0
  44. self.num_bn = 0
  45. self.num_biases = 0
  46. self.num_linear = 0
  47. self.base = nn.Sequential(
  48. self.conv1(3, 128, 2),
  49. self.conv1(128, 128, 2, bias=True),
  50. self.conv_transpose(128, 128),
  51. self.conv_transpose(128, 128, bias=True),
  52. )
  53. self.base_params = (self.num_no_decay_params(), self.num_decay_params())
  54. self.more_convs = nn.Sequential(
  55. self.conv1(128, 128, 1),
  56. self.conv1(128, 128, 2, bias=True),
  57. self.conv_transpose(128, 128),
  58. )
  59. self.avg_pool = nn.AdaptiveAvgPool2d(1)
  60. self.classifier = nn.Sequential(
  61. self.linear(128, 2 * num_classes, bias=False),
  62. self.linear(2 * num_classes, num_classes, bias=True)
  63. )
  64. self.head = nn.Sequential(
  65. self.more_convs,
  66. self.avg_pool,
  67. self.classifier
  68. )
  69. self.head_params = (self.num_no_decay_params() - self.base_params[0], self.num_decay_params() - self.base_params[1])
  70. def conv1(self, ch_in: int, ch_out: int, stride: int, bias=False):
  71. self.num_conv += 1
  72. if bias:
  73. conv = self.conv_cls(ch_in, ch_out, 1, stride=stride, bias=bias)
  74. self.num_biases += 1
  75. else:
  76. conv = nn.Sequential(
  77. self.conv_cls(ch_in, ch_out, 1, stride=stride, bias=bias),
  78. self.bn_cls(ch_out),
  79. nn.ReLU()
  80. )
  81. self.num_bn += 1
  82. return conv
  83. def conv_transpose(self, ch_in: int, ch_out: int, bias=False):
  84. self.num_conv += 1
  85. if bias:
  86. conv = self.conv_transpose_cls(ch_in, ch_out, 2, stride=2, bias=bias)
  87. self.num_biases += 1
  88. else:
  89. conv = nn.Sequential(
  90. self.conv_transpose_cls(ch_in, ch_out, 2, stride=2, bias=bias),
  91. self.bn_cls(ch_out),
  92. nn.ReLU()
  93. )
  94. self.num_bn += 1
  95. return conv
  96. def linear(self, ch_in: int, ch_out: int, bias=False):
  97. self.num_linear += 1
  98. if bias:
  99. self.num_biases += 1
  100. return self.linear_cls(ch_in, ch_out, bias)
  101. def num_decay_params(self):
  102. return self.num_conv + self.num_linear
  103. def num_no_decay_params(self):
  104. return self.num_biases + 2 * self.num_bn
  105. def initialize_param_groups(self, lr: float, training_params: HpmStruct) -> list:
  106. # Example to different learning rates, similar to ShelfNet, in order to create multiple groups.
  107. if self.multiple_param_groups:
  108. params_list = [{'named_params': self.base.named_parameters(), 'lr': lr},
  109. {'named_params': self.head.named_parameters(), 'lr': lr * 10}]
  110. return params_list
  111. return super().initialize_param_groups(lr, training_params)
  112. class ZeroWdForBnBiasTest(unittest.TestCase):
  113. """
  114. Testing if the optimizer parameters are divided into two groups with one being with weight_decay = 0
  115. """
  116. def setUp(self):
  117. # Define Parameters
  118. self.weight_decay = 0.01
  119. self.lr = 0.1
  120. # input dimension beside batch and channels, i.e 2 for vision, 1 for audio, 3 for point cloud.
  121. self.input_dimensions = (1, 2, 3)
  122. self.train_params_zero_wd = {"initial_lr": self.lr,
  123. "optimizer": "SGD",
  124. "optimizer_params": {"weight_decay": self.weight_decay, "momentum": 0.9}}
  125. def _assert_optimizer_param_groups(self,
  126. param_groups: list,
  127. excpected_num_groups: int,
  128. excpected_num_params_per_group: list,
  129. excpected_weight_decay_per_group: list):
  130. """
  131. Helper method to assert, num of param_groups, num of parameters in each param group and weight decay value
  132. in each param group.
  133. """
  134. self.assertEqual(len(param_groups), excpected_num_groups,
  135. msg=f"Optimizer should have {excpected_num_groups} groups")
  136. for (param_group, excpected_num_params, excpected_weight_decay) in zip(param_groups,
  137. excpected_num_params_per_group,
  138. excpected_weight_decay_per_group):
  139. self.assertEqual(len(param_group["params"]), excpected_num_params,
  140. msg="Wrong number of params for optimizer param group, excpected: {}, found: {}".format(
  141. excpected_num_params, len(param_group["params"])))
  142. self.assertEqual(param_group['weight_decay'], excpected_weight_decay,
  143. msg="Wrong weight decay value found for optimizer param group, excpected: {}, found: {}".format(
  144. excpected_weight_decay, param_group["weight_decay"]))
  145. def test_zero_wd_one_group(self):
  146. """
  147. test that one group of parameters are separated to weight_decay_params and without.
  148. """
  149. for input_dim in self.input_dimensions:
  150. net = ToySgModule(input_dimension=input_dim)
  151. train_params = HpmStruct(**self.train_params_zero_wd)
  152. optimizer_params_groups = separate_zero_wd_params_groups_for_optimizer(
  153. net,
  154. net.initialize_param_groups(self.lr, train_params),
  155. self.weight_decay
  156. )
  157. self._assert_optimizer_param_groups(
  158. optimizer_params_groups,
  159. excpected_num_groups=2,
  160. excpected_num_params_per_group=[net.num_no_decay_params(), net.num_decay_params()],
  161. excpected_weight_decay_per_group=[0, self.weight_decay]
  162. )
  163. def test_zero_wd_multiple_group(self):
  164. """
  165. test that 2 groups of parameters are separated to 2 groups of weight_decay_params and 2 groups without.
  166. """
  167. for input_dim in self.input_dimensions:
  168. net = ToySgModule(input_dimension=input_dim, multiple_param_groups=True)
  169. train_params = HpmStruct(**self.train_params_zero_wd)
  170. optimizer_params_groups = separate_zero_wd_params_groups_for_optimizer(
  171. net,
  172. net.initialize_param_groups(self.lr, train_params),
  173. self.weight_decay
  174. )
  175. self._assert_optimizer_param_groups(
  176. optimizer_params_groups,
  177. excpected_num_groups=4,
  178. excpected_num_params_per_group=[net.base_params[0], net.base_params[1], net.head_params[0],
  179. net.head_params[1]],
  180. excpected_weight_decay_per_group=[0, self.weight_decay, 0, self.weight_decay]
  181. )
  182. def test_zero_wd_sync_bn(self):
  183. """
  184. test affiliation of nn.SyncBatchNorm parameters to zero weight decay.
  185. """
  186. for input_dim in self.input_dimensions:
  187. net = ToySgModule(input_dimension=input_dim)
  188. # Convert to SyncBatchNorm
  189. net = nn.SyncBatchNorm.convert_sync_batchnorm(net)
  190. train_params = HpmStruct(**self.train_params_zero_wd)
  191. optimizer_params_groups = separate_zero_wd_params_groups_for_optimizer(
  192. net,
  193. net.initialize_param_groups(self.lr, train_params),
  194. self.weight_decay
  195. )
  196. self._assert_optimizer_param_groups(
  197. optimizer_params_groups,
  198. excpected_num_groups=2,
  199. excpected_num_params_per_group=[net.num_no_decay_params(), net.num_decay_params()],
  200. excpected_weight_decay_per_group=[0, self.weight_decay]
  201. )
  202. def test_zero_wd_custom_module_with_bias(self):
  203. """
  204. test affiliation of nn.SyncBatchNorm parameters to zero weight decay.
  205. """
  206. input_dim = 2
  207. net = ToySgModule(input_dimension=input_dim, linear_cls=ToyLinearKernel)
  208. train_params = HpmStruct(**self.train_params_zero_wd)
  209. optimizer_params_groups = separate_zero_wd_params_groups_for_optimizer(
  210. net,
  211. net.initialize_param_groups(self.lr, train_params),
  212. self.weight_decay
  213. )
  214. self._assert_optimizer_param_groups(
  215. optimizer_params_groups,
  216. excpected_num_groups=2,
  217. excpected_num_params_per_group=[net.num_no_decay_params(), net.num_decay_params()],
  218. excpected_weight_decay_per_group=[0, self.weight_decay]
  219. )
  220. if __name__ == '__main__':
  221. unittest.main()
Tip!

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

Comments

Loading...