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
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
  1. """
  2. Implementation of paper: "Rethink Dilated Convolution for Real-time Semantic Segmentation", https://arxiv.org/pdf/2111.09957.pdf
  3. Based on original implementation: https://github.com/RolandGao/RegSeg, cloned 23/12/2021, commit c07a833
  4. """
  5. from typing import List
  6. import torch
  7. import torch.nn as nn
  8. from super_gradients.training.models import SgModule
  9. from super_gradients.training.utils import HpmStruct, get_param
  10. from super_gradients.modules import ConvBNReLU
  11. DEFAULT_REGSEG48_BACKBONE_PARAMS = {
  12. "stages": [
  13. [
  14. [48, [1], 16, 2, 4]
  15. ],
  16. [
  17. [128, [1], 16, 2, 4],
  18. *[[128, [1], 16, 1, 4]] * 2
  19. ],
  20. [
  21. [256, [1], 16, 2, 4],
  22. [256, [1], 16, 1, 4],
  23. [256, [1, 2], 16, 1, 4],
  24. *[[256, [1, 4], 16, 1, 4]] * 4,
  25. *[[256, [1, 14], 16, 1, 4]] * 6,
  26. [320, [1, 14], 16, 1, 4]
  27. ]
  28. ]
  29. }
  30. DEFAULT_REGSEG53_BACKBONE_PARAMS = {
  31. "stages": [
  32. [
  33. [48, [1], 24, 2, 4],
  34. [48, [1], 24, 1, 4]
  35. ],
  36. [
  37. [120, [1], 24, 2, 4],
  38. *[[120, [1], 24, 1, 4]] * 5
  39. ],
  40. [
  41. [336, [1], 24, 2, 4],
  42. [336, [1], 24, 1, 4],
  43. [336, [1, 2], 24, 1, 4],
  44. *[[336, [1, 4], 24, 1, 4]] * 4,
  45. *[[336, [1, 14], 24, 1, 4]] * 6,
  46. [384, [1, 14], 24, 1, 4]
  47. ]
  48. ]
  49. }
  50. DEFAULT_REGSEG48_DECODER_PARAMS = {
  51. "projection_out_channels": [8, 128, 128],
  52. "interpolation": 'bilinear'
  53. }
  54. DEFAULT_REGSEG53_DECODER_PARAMS = {
  55. "projection_out_channels": [16, 256, 256],
  56. "interpolation": 'bilinear'
  57. }
  58. DEFAULT_REGSEG_HEAD_PARAMS = {
  59. "dropout": 0.0,
  60. "interpolation": 'bilinear',
  61. "align_corners": False,
  62. "upsample_factor": 4
  63. }
  64. DEFAULT_REGSEG48_HEAD_PARAMS = {
  65. "mid_channels": 64,
  66. **DEFAULT_REGSEG_HEAD_PARAMS
  67. }
  68. DEFAULT_REGSEG53_HEAD_PARAMS = {
  69. "mid_channels": 128,
  70. **DEFAULT_REGSEG_HEAD_PARAMS
  71. }
  72. class SqueezeAndExcitationBlock(nn.Module):
  73. def __init__(self, in_channels: int, bottleneck_channels: int):
  74. super().__init__()
  75. self.se_block = nn.Sequential(
  76. nn.AdaptiveAvgPool2d(1),
  77. nn.Conv2d(in_channels, bottleneck_channels, 1, bias=True),
  78. nn.ReLU(inplace=True),
  79. nn.Conv2d(bottleneck_channels, in_channels, 1, bias=True),
  80. nn.Sigmoid()
  81. )
  82. def forward(self, x):
  83. y = self.se_block(x)
  84. return x * y
  85. class AdaptiveShortcutBlock(nn.Module):
  86. """
  87. Adaptive shortcut makes the following adaptations, if needed:
  88. Applying pooling if stride > 1
  89. Applying 1x1 conv if in/out channels are different or if pooling was applied
  90. If stride is 1 and in/out channels are the same, then the shortcut is just an identity
  91. """
  92. def __init__(self, in_channels: int, out_channels: int, stride: int):
  93. super().__init__()
  94. shortcut_layers = [nn.Identity()]
  95. if stride != 1:
  96. shortcut_layers[0] = nn.AvgPool2d(stride, stride, ceil_mode=True) # override the identity layer
  97. if in_channels != out_channels or stride != 1:
  98. shortcut_layers.append(
  99. ConvBNReLU(in_channels, out_channels, kernel_size=1, bias=False, use_activation=False)
  100. )
  101. self.shortcut = nn.Sequential(*shortcut_layers)
  102. def forward(self, x):
  103. return self.shortcut(x)
  104. class SplitDilatedGroupConvBlock(nn.Module):
  105. """
  106. Splits the input to "dilation groups", following grouped convolution with different dilation for each group
  107. """
  108. def __init__(self, in_channels: int, split_dilations: List[int], group_width_per_split: int, stride: int,
  109. bias: bool):
  110. """
  111. :param split_dilations: a list specifying the required dilations.
  112. the input will be split into len(dilations) groups,
  113. group [i] will be convolved with grouped dilated (dilations[i]) convolution
  114. :param group_width_per_split: the group width for the *inner* dilated convolution
  115. """
  116. super().__init__()
  117. self.num_splits = len(split_dilations)
  118. assert (in_channels % self.num_splits == 0), \
  119. f"Cannot split {in_channels} to {self.num_splits} groups with equal size."
  120. group_channels = in_channels // self.num_splits
  121. assert (group_channels % group_width_per_split == 0), \
  122. f"Cannot split {group_channels} channels ({in_channels} / {self.num_splits} splits)" \
  123. f" to groups with {group_width_per_split} channels per group."
  124. inner_groups = group_channels // group_width_per_split
  125. self.convs = nn.ModuleList(
  126. nn.Conv2d(group_channels, group_channels, 3, padding=d, dilation=d,
  127. stride=stride, bias=bias, groups=inner_groups)
  128. for d in split_dilations
  129. )
  130. self._splits = [in_channels // self.num_splits] * self.num_splits
  131. def forward(self, x):
  132. x = torch.split(x, self._splits, dim=1)
  133. return torch.cat([self.convs[i](x[i]) for i in range(self.num_splits)], dim=1)
  134. class DBlock(nn.Module):
  135. def __init__(self, in_channels: int, out_channels: int, dilations: List[int],
  136. group_width: int, stride: int, se_ratio: int = 4):
  137. """
  138. :param dilations: a list specifying the required dilations.
  139. the input will be split into len(dilations) groups,
  140. group [i] will be convolved with grouped dilated (dilations[i]) convolution
  141. :param group_width: the group width for the dilated convolution(s)
  142. :param se_ratio: the ratio of the squeeze-and-excitation block w.r.t in_channels (as in the paper)
  143. for example: a value of 4 translates to in_channels // 4
  144. """
  145. super().__init__()
  146. self.in_channels = in_channels
  147. self.out_channels = out_channels
  148. self.dilations = dilations
  149. self.group_width = group_width
  150. self.stride = stride
  151. self.se_ratio = se_ratio
  152. self.shortcut = AdaptiveShortcutBlock(in_channels, out_channels, stride)
  153. groups = out_channels // group_width
  154. if len(dilations) == 1: # minor optimization: no need to split if we only have 1 dilation group
  155. dilation = dilations[0]
  156. dilated_conv = nn.Conv2d(out_channels, out_channels, 3, stride=stride, groups=groups,
  157. padding=dilation, dilation=dilation, bias=False)
  158. else:
  159. dilated_conv = SplitDilatedGroupConvBlock(out_channels, dilations, group_width_per_split=group_width,
  160. stride=stride, bias=False)
  161. self.d_block_path = nn.Sequential(
  162. ConvBNReLU(in_channels, out_channels, kernel_size=1, bias=False),
  163. dilated_conv,
  164. nn.BatchNorm2d(out_channels),
  165. nn.ReLU(inplace=True),
  166. # the ratio of se block applied to `in_channels` as in the original paper
  167. SqueezeAndExcitationBlock(out_channels, in_channels // se_ratio),
  168. ConvBNReLU(out_channels, out_channels, 1, use_activation=False, bias=False)
  169. )
  170. self.relu = nn.ReLU(inplace=True)
  171. def forward(self, x):
  172. x1 = self.shortcut(x)
  173. x2 = self.d_block_path(x)
  174. out = self.relu(x1 + x2)
  175. return out
  176. def __str__(self):
  177. return f"{self.__class__.__name__}_in{self.in_channels}_out{self.out_channels}" \
  178. f"_d{self.dilations}_gw{self.group_width}_s{self.stride}_se{self.se_ratio}"
  179. class RegSegDecoder(nn.Module):
  180. """
  181. This implementation follows the paper. No 'pattern' in this decoder, so it is specific to 3 stages
  182. """
  183. def __init__(self, backbone_output_channels: List[int], decoder_config: dict):
  184. super().__init__()
  185. projection_out_channels = decoder_config['projection_out_channels']
  186. assert len(backbone_output_channels) == len(projection_out_channels) == 3, \
  187. "This decoder is specific for 3 stages"
  188. self.projections = nn.ModuleList([
  189. ConvBNReLU(in_channels, out_channels, 1, bias=False)
  190. for in_channels, out_channels in zip(backbone_output_channels, projection_out_channels)
  191. ])
  192. self.upsample = nn.Upsample(scale_factor=2, mode=decoder_config['interpolation'], align_corners=True)
  193. mid_channels = projection_out_channels[1]
  194. self.conv_bn_relu = ConvBNReLU(in_channels=mid_channels, out_channels=mid_channels // 2,
  195. kernel_size=3, padding=1, bias=False)
  196. self.out_channels = mid_channels // 2 + projection_out_channels[0] # original implementation: concat
  197. def forward(self, x_stages):
  198. proj2 = self.projections[2](x_stages[2])
  199. proj2 = self.upsample(proj2)
  200. proj1 = self.projections[1](x_stages[1])
  201. proj1 = proj1 + proj2
  202. proj1 = self.conv_bn_relu(proj1)
  203. proj1 = self.upsample(proj1)
  204. proj0 = self.projections[0](x_stages[0])
  205. proj0 = torch.cat((proj1, proj0), dim=1)
  206. return proj0
  207. class RegSegHead(nn.Module):
  208. def __init__(self, in_channels: int, num_classes: int, head_config: dict):
  209. super().__init__()
  210. layers = list()
  211. layers.append(ConvBNReLU(in_channels, head_config['mid_channels'], 3, bias=False, padding=1))
  212. if head_config['dropout'] > 0:
  213. layers.append(nn.Dropout(head_config['dropout'], inplace=False))
  214. layers.append(nn.Conv2d(head_config['mid_channels'], num_classes, 1))
  215. layers.append(nn.Upsample(scale_factor=head_config['upsample_factor'],
  216. mode=head_config['interpolation'], align_corners=head_config['align_corners']))
  217. self.head = nn.Sequential(*layers)
  218. def forward(self, x):
  219. return self.head(x)
  220. class RegSegBackbone(nn.Module):
  221. def __init__(self, in_channels: int, backbone_config: dict):
  222. super().__init__()
  223. self.stages, self.backbone_output_channels = \
  224. self._generate_stages(in_channels, backbone_config["stages"])
  225. @staticmethod
  226. def _generate_stages(in_channels, backbone_stages):
  227. prev_out_channels = in_channels
  228. backbone_channels = list()
  229. stages = nn.ModuleList()
  230. for stage in backbone_stages:
  231. stage_blocks = nn.Sequential()
  232. for i, (out_channels, dilations, group_width, stride, se_ratio) in enumerate(stage):
  233. d_block = DBlock(prev_out_channels, out_channels, dilations, group_width, stride, se_ratio)
  234. prev_out_channels = d_block.out_channels
  235. stage_blocks.add_module(f"{str(d_block)}#{i}", d_block) # NOTE: {i} distinguishes blocks with same name
  236. stages.append(stage_blocks)
  237. backbone_channels.append(prev_out_channels)
  238. return stages, backbone_channels
  239. def forward(self, x):
  240. outputs = list()
  241. x_in = x
  242. for stage in self.stages:
  243. x_out = stage(x_in)
  244. outputs.append(x_out)
  245. x_in = x_out # last stage out is next stage in
  246. return outputs
  247. def get_backbone_output_number_of_channels(self):
  248. return self.backbone_output_channels
  249. class RegSeg(SgModule):
  250. def __init__(self, stem, backbone, decoder, head):
  251. super().__init__()
  252. self.stem = stem
  253. self.backbone = backbone
  254. self.decoder = decoder
  255. self.head = head
  256. def forward(self, x):
  257. x = self.stem(x)
  258. x = self.backbone(x)
  259. x = self.decoder(x)
  260. x = self.head(x)
  261. return x
  262. def initialize_param_groups(self, lr: float, training_params: HpmStruct) -> list:
  263. multiply_head_lr = get_param(training_params, "multiply_head_lr", 1)
  264. multiply_lr_params, no_multiply_params = {}, {}
  265. for name, param in self.named_parameters():
  266. if "head." in name:
  267. multiply_lr_params[name] = param
  268. else:
  269. no_multiply_params[name] = param
  270. multiply_lr_params, no_multiply_params = multiply_lr_params.items(), no_multiply_params.items()
  271. param_groups = [{"named_params": no_multiply_params, "lr": lr, "name": "no_multiply_params"},
  272. {"named_params": multiply_lr_params, "lr": lr * multiply_head_lr, "name": "multiply_lr_params"}]
  273. return param_groups
  274. def update_param_groups(self, param_groups: list, lr: float, epoch: int, iter: int, training_params: HpmStruct,
  275. total_batch: int) -> list:
  276. multiply_head_lr = get_param(training_params, "multiply_head_lr", 1)
  277. for param_group in param_groups:
  278. param_group['lr'] = lr
  279. if param_group["name"] == "multiply_lr_params":
  280. param_group['lr'] *= multiply_head_lr
  281. return param_groups
  282. def replace_head(self, new_num_classes: int, head_config: dict):
  283. self.head = RegSegHead(self.decoder.out_channels, new_num_classes, head_config)
  284. class RegSeg48(RegSeg):
  285. def __init__(self, arch_params: HpmStruct):
  286. num_classes = get_param(arch_params, "num_classes")
  287. stem = ConvBNReLU(in_channels=3, out_channels=32, kernel_size=3, stride=2, padding=1)
  288. backbone = RegSegBackbone(in_channels=32, backbone_config=DEFAULT_REGSEG48_BACKBONE_PARAMS)
  289. decoder = RegSegDecoder(
  290. backbone.get_backbone_output_number_of_channels(),
  291. DEFAULT_REGSEG48_DECODER_PARAMS
  292. )
  293. head = RegSegHead(decoder.out_channels, num_classes, DEFAULT_REGSEG48_HEAD_PARAMS)
  294. super().__init__(stem, backbone, decoder, head)
  295. def replace_head(self, new_num_classes: int, head_config: dict = None):
  296. head_config = head_config or DEFAULT_REGSEG48_HEAD_PARAMS
  297. super().replace_head(new_num_classes, head_config)
  298. class RegSeg53(RegSeg):
  299. def __init__(self, arch_params: HpmStruct):
  300. num_classes = get_param(arch_params, "num_classes")
  301. stem = ConvBNReLU(in_channels=3, out_channels=32, kernel_size=3, stride=2, padding=1)
  302. backbone = RegSegBackbone(in_channels=32, backbone_config=DEFAULT_REGSEG53_BACKBONE_PARAMS)
  303. decoder = RegSegDecoder(
  304. backbone.get_backbone_output_number_of_channels(),
  305. DEFAULT_REGSEG53_DECODER_PARAMS
  306. )
  307. head = RegSegHead(decoder.out_channels, num_classes, DEFAULT_REGSEG53_HEAD_PARAMS)
  308. super().__init__(stem, backbone, decoder, head)
  309. def replace_head(self, new_num_classes: int, head_config: dict = None):
  310. head_config = head_config or DEFAULT_REGSEG53_HEAD_PARAMS
  311. super().replace_head(new_num_classes, head_config)
Discard
Tip!

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