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

#609 Ci fix

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:bugfix/infra-000_ci
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
  1. """
  2. Regnet - from paper: Designing Network Design Spaces - https://arxiv.org/pdf/2003.13678.pdf
  3. Implementation of paradigm described in paper published by Facebook AI Research (FAIR)
  4. @author: Signatrix GmbH
  5. Code taken from: https://github.com/signatrix/regnet - MIT Licence
  6. """
  7. import numpy as np
  8. import torch.nn as nn
  9. from math import sqrt
  10. from super_gradients.modules import Residual
  11. from super_gradients.training.models.sg_module import SgModule
  12. from super_gradients.training.utils.regularization_utils import DropPath
  13. from super_gradients.training.utils.utils import get_param
  14. class Head(nn.Module): # From figure 3
  15. def __init__(self, num_channels, num_classes, dropout_prob):
  16. super(Head, self).__init__()
  17. self.pool = nn.AdaptiveAvgPool2d(output_size=1)
  18. self.dropout = nn.Dropout(p=dropout_prob)
  19. self.fc = nn.Linear(num_channels, num_classes)
  20. def forward(self, x):
  21. x = self.pool(x)
  22. x = x.view(x.size(0), -1)
  23. x = self.dropout(x)
  24. x = self.fc(x)
  25. return x
  26. class Stem(nn.Module): # From figure 3
  27. def __init__(self, in_channels, out_channels):
  28. super(Stem, self).__init__()
  29. self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=2, padding=1, bias=False)
  30. self.bn = nn.BatchNorm2d(out_channels)
  31. self.rl = nn.ReLU()
  32. def forward(self, x):
  33. x = self.conv(x)
  34. x = self.bn(x)
  35. x = self.rl(x)
  36. return x
  37. class XBlock(nn.Module): # From figure 4
  38. def __init__(self, in_channels, out_channels, bottleneck_ratio, group_width, stride, se_ratio=None, droppath_prob=0.0):
  39. super(XBlock, self).__init__()
  40. inter_channels = int(out_channels // bottleneck_ratio)
  41. groups = int(inter_channels // group_width)
  42. self.conv_block_1 = nn.Sequential(nn.Conv2d(in_channels, inter_channels, kernel_size=1, bias=False), nn.BatchNorm2d(inter_channels), nn.ReLU())
  43. self.conv_block_2 = nn.Sequential(
  44. nn.Conv2d(inter_channels, inter_channels, kernel_size=3, stride=stride, groups=groups, padding=1, bias=False),
  45. nn.BatchNorm2d(inter_channels),
  46. nn.ReLU(),
  47. )
  48. if se_ratio is not None:
  49. se_channels = in_channels // se_ratio
  50. self.se = nn.Sequential(
  51. nn.AdaptiveAvgPool2d(output_size=1),
  52. nn.Conv2d(inter_channels, se_channels, kernel_size=1, bias=True),
  53. nn.ReLU(),
  54. nn.Conv2d(se_channels, inter_channels, kernel_size=1, bias=True),
  55. nn.Sigmoid(),
  56. Residual(),
  57. )
  58. self.se_residual = Residual()
  59. else:
  60. self.se = None
  61. self.conv_block_3 = nn.Sequential(nn.Conv2d(inter_channels, out_channels, kernel_size=1, bias=False), nn.BatchNorm2d(out_channels))
  62. if stride != 1 or in_channels != out_channels:
  63. self.shortcut = nn.Sequential(
  64. nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(out_channels), Residual()
  65. )
  66. else:
  67. self.shortcut = Residual()
  68. self.drop_path = DropPath(drop_prob=droppath_prob)
  69. self.rl = nn.ReLU()
  70. def forward(self, x):
  71. x1 = self.conv_block_1(x)
  72. x1 = self.conv_block_2(x1)
  73. if self.se is not None:
  74. x1 = self.se_residual(x1) * self.se(x1)
  75. x1 = self.conv_block_3(x1)
  76. x2 = self.shortcut(x)
  77. x1 = self.drop_path(x1)
  78. x = self.rl(x1 + x2)
  79. return x
  80. class Stage(nn.Module): # From figure 3
  81. def __init__(self, num_blocks, in_channels, out_channels, bottleneck_ratio, group_width, stride, se_ratio, droppath_prob):
  82. super(Stage, self).__init__()
  83. self.blocks = nn.Sequential()
  84. self.blocks.add_module("block_0", XBlock(in_channels, out_channels, bottleneck_ratio, group_width, stride, se_ratio, droppath_prob))
  85. for i in range(1, num_blocks):
  86. self.blocks.add_module("block_{}".format(i), XBlock(out_channels, out_channels, bottleneck_ratio, group_width, 1, se_ratio, droppath_prob))
  87. def forward(self, x):
  88. x = self.blocks(x)
  89. return x
  90. class AnyNetX(SgModule):
  91. def __init__(
  92. self,
  93. ls_num_blocks,
  94. ls_block_width,
  95. ls_bottleneck_ratio,
  96. ls_group_width,
  97. stride,
  98. num_classes,
  99. se_ratio,
  100. backbone_mode,
  101. dropout_prob=0.0,
  102. droppath_prob=0.0,
  103. input_channels=3,
  104. ):
  105. super(AnyNetX, self).__init__()
  106. verify_correctness_of_parameters(ls_num_blocks, ls_block_width, ls_bottleneck_ratio, ls_group_width)
  107. self.net = nn.Sequential()
  108. self.backbone_mode = backbone_mode
  109. prev_block_width = 32
  110. self.net.add_module("stem", Stem(in_channels=input_channels, out_channels=prev_block_width))
  111. for i, (num_blocks, block_width, bottleneck_ratio, group_width) in enumerate(zip(ls_num_blocks, ls_block_width, ls_bottleneck_ratio, ls_group_width)):
  112. self.net.add_module(
  113. "stage_{}".format(i), Stage(num_blocks, prev_block_width, block_width, bottleneck_ratio, group_width, stride, se_ratio, droppath_prob)
  114. )
  115. prev_block_width = block_width
  116. # FOR BACK BONE MODE - DO NOT ADD THE HEAD (AVG_POOL + FC)
  117. if not self.backbone_mode:
  118. self.net.add_module("head", Head(ls_block_width[-1], num_classes, dropout_prob))
  119. self.initialize_weight()
  120. self.ls_block_width = ls_block_width
  121. self.dropout_prob = dropout_prob
  122. def initialize_weight(self):
  123. for m in self.modules():
  124. if isinstance(m, nn.Conv2d):
  125. fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
  126. m.weight.data.normal_(mean=0.0, std=sqrt(2.0 / fan_out))
  127. elif isinstance(m, nn.BatchNorm2d):
  128. m.weight.data.fill_(1.0)
  129. m.bias.data.zero_()
  130. elif isinstance(m, nn.Linear):
  131. m.weight.data.normal_(mean=0.0, std=0.01)
  132. m.bias.data.zero_()
  133. def forward(self, x):
  134. x = self.net(x)
  135. return x
  136. def replace_head(self, new_num_classes=None, new_head=None):
  137. if new_num_classes is None and new_head is None:
  138. raise ValueError("At least one of new_num_classes, new_head must be given to replace output layer.")
  139. if new_head is not None:
  140. self.net.head = new_head
  141. else:
  142. self.net.head = Head(self.ls_block_width[-1], new_num_classes, self.dropout_prob)
  143. def regnet_params_to_blocks(initial_width, slope, quantized_param, network_depth, bottleneck_ratio, group_width):
  144. # We need to derive block width and number of blocks from initial parameters.
  145. parameterized_width = initial_width + slope * np.arange(network_depth) # From equation 2
  146. parameterized_block = np.log(parameterized_width / initial_width) / np.log(quantized_param) # From equation 3
  147. parameterized_block = np.round(parameterized_block)
  148. quantized_width = initial_width * np.power(quantized_param, parameterized_block)
  149. # We need to convert quantized_width to make sure that it is divisible by 8
  150. quantized_width = 8 * np.round(quantized_width / 8)
  151. ls_block_width, ls_num_blocks = np.unique(quantized_width.astype(np.int), return_counts=True)
  152. # At this points, for each stage, the above-calculated block width could be incompatible to group width
  153. # due to bottleneck ratio. Hence, we need to adjust the formers.
  154. # Group width could be swapped to number of groups, since their multiplication is block width
  155. ls_group_width = np.array([min(group_width, block_width // bottleneck_ratio) for block_width in ls_block_width])
  156. ls_block_width = (np.round(ls_block_width // bottleneck_ratio / group_width) * group_width).astype(np.int).tolist()
  157. ls_bottleneck_ratio = [bottleneck_ratio for _ in range(len(ls_block_width))]
  158. return ls_num_blocks, ls_block_width, ls_bottleneck_ratio, ls_group_width.tolist()
  159. class RegNetX(AnyNetX):
  160. def __init__(
  161. self, initial_width, slope, quantized_param, network_depth, bottleneck_ratio, group_width, stride, arch_params, se_ratio=None, input_channels=3
  162. ):
  163. ls_num_blocks, ls_block_width, ls_bottleneck_ratio, ls_group_width = regnet_params_to_blocks(
  164. initial_width, slope, quantized_param, network_depth, bottleneck_ratio, group_width
  165. )
  166. # GET THE BACKBONE MODE FROM arch_params IF EXISTS - O.W. - SET AS FALSE
  167. backbone_mode = get_param(arch_params, "backbone_mode", False)
  168. dropout_prob = get_param(arch_params, "dropout_prob", 0.0)
  169. droppath_prob = get_param(arch_params, "droppath_prob", 0.0)
  170. super(RegNetX, self).__init__(
  171. ls_num_blocks,
  172. ls_block_width,
  173. ls_bottleneck_ratio,
  174. ls_group_width,
  175. stride,
  176. arch_params.num_classes,
  177. se_ratio,
  178. backbone_mode,
  179. dropout_prob,
  180. droppath_prob,
  181. input_channels,
  182. )
  183. class RegNetY(RegNetX):
  184. # RegNetY = RegNetX + SE
  185. def __init__(self, initial_width, slope, quantized_param, network_depth, bottleneck_ratio, group_width, stride, arch_params, se_ratio, input_channels=3):
  186. super(RegNetY, self).__init__(
  187. initial_width, slope, quantized_param, network_depth, bottleneck_ratio, group_width, stride, arch_params, se_ratio, input_channels
  188. )
  189. def verify_correctness_of_parameters(ls_num_blocks, ls_block_width, ls_bottleneck_ratio, ls_group_width):
  190. """VERIFY THAT THE GIVEN PARAMETERS FIT THE SEARCH SPACE DEFINED IN THE REGNET PAPER"""
  191. err_message = "Parameters don't fit"
  192. assert len(set(ls_bottleneck_ratio)) == 1, f"{err_message} AnyNetXb"
  193. assert len(set(ls_group_width)) == 1, f"{err_message} AnyNetXc"
  194. assert all(i <= j for i, j in zip(ls_block_width, ls_block_width[1:])) is True, f"{err_message} AnyNetXd"
  195. if len(ls_num_blocks) > 2:
  196. assert all(i <= j for i, j in zip(ls_num_blocks[:-2], ls_num_blocks[1:-1])) is True, f"{err_message} AnyNetXe"
  197. # For each stage & each layer, number of channels (block width / bottleneck ratio) must be divisible by group width
  198. for block_width, bottleneck_ratio, group_width in zip(ls_block_width, ls_bottleneck_ratio, ls_group_width):
  199. assert int(block_width // bottleneck_ratio) % group_width == 0
  200. class CustomRegNet(RegNetX):
  201. def __init__(self, arch_params):
  202. """All parameters must be provided in arch_params other than SE"""
  203. super().__init__(
  204. initial_width=arch_params.initial_width,
  205. slope=arch_params.slope,
  206. quantized_param=arch_params.quantized_param,
  207. network_depth=arch_params.network_depth,
  208. bottleneck_ratio=arch_params.bottleneck_ratio,
  209. group_width=arch_params.group_width,
  210. stride=arch_params.stride,
  211. arch_params=arch_params,
  212. se_ratio=arch_params.se_ratio if hasattr(arch_params, "se_ratio") else None,
  213. input_channels=get_param(arch_params, "input_channels", 3),
  214. )
  215. class CustomAnyNet(AnyNetX):
  216. def __init__(self, arch_params):
  217. """All parameters must be provided in arch_params other than SE"""
  218. super().__init__(
  219. ls_num_blocks=arch_params.ls_num_blocks,
  220. ls_block_width=arch_params.ls_block_width,
  221. ls_bottleneck_ratio=arch_params.ls_bottleneck_ratio,
  222. ls_group_width=arch_params.ls_group_width,
  223. stride=arch_params.stride,
  224. num_classes=arch_params.num_classes,
  225. se_ratio=arch_params.se_ratio if hasattr(arch_params, "se_ratio") else None,
  226. backbone_mode=get_param(arch_params, "backbone_mode", False),
  227. dropout_prob=get_param(arch_params, "dropout_prob", 0),
  228. droppath_prob=get_param(arch_params, "droppath_prob", 0),
  229. input_channels=get_param(arch_params, "input_channels", 3),
  230. )
  231. class NASRegNet(RegNetX):
  232. def __init__(self, arch_params):
  233. """All parameters are provided as a single structure list: arch_params.structure"""
  234. structure = arch_params.structure
  235. super().__init__(
  236. initial_width=structure[0],
  237. slope=structure[1],
  238. quantized_param=structure[2],
  239. network_depth=structure[3],
  240. bottleneck_ratio=structure[4],
  241. group_width=structure[5],
  242. stride=structure[6],
  243. se_ratio=structure[7] if structure[7] > 0 else None,
  244. arch_params=arch_params,
  245. )
  246. class RegNetY200(RegNetY):
  247. def __init__(self, arch_params):
  248. super().__init__(24, 36, 2.5, 13, 1, 8, 2, arch_params, 4)
  249. class RegNetY400(RegNetY):
  250. def __init__(self, arch_params):
  251. super().__init__(48, 28, 2.1, 16, 1, 8, 2, arch_params, 4)
  252. class RegNetY600(RegNetY):
  253. def __init__(self, arch_params):
  254. super().__init__(48, 33, 2.3, 15, 1, 16, 2, arch_params, 4)
  255. class RegNetY800(RegNetY):
  256. def __init__(self, arch_params):
  257. super().__init__(56, 39, 2.4, 14, 1, 16, 2, arch_params, 4)
Discard
Tip!

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