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

#378 Feature/sg 281 add kd notebook

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:feature/SG-281-add_kd_notebook
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from typing import Union, List, Tuple
  5. from super_gradients.training.utils.module_utils import ConvBNReLU, make_upsample_module
  6. from super_gradients.common import UpsampleMode
  7. from super_gradients.training.models.segmentation_models.stdc import SegmentationHead, AbstractSTDCBackbone,\
  8. STDC1Backbone, STDC2Backbone
  9. from super_gradients.training.models.segmentation_models.segmentation_module import SegmentationModule
  10. from super_gradients.training.utils import HpmStruct, get_param
  11. class SPPM(nn.Module):
  12. """
  13. Simple Pyramid Pooling context Module.
  14. """
  15. def __init__(self,
  16. in_channels: int,
  17. inter_channels: int,
  18. out_channels: int,
  19. pool_sizes: List[Union[int, Tuple[int, int]]],
  20. upsample_mode: Union[UpsampleMode, str] = UpsampleMode.BILINEAR,
  21. align_corners: bool = False):
  22. """
  23. :param inter_channels: num channels in each pooling branch.
  24. :param out_channels: The number of output channels after pyramid pooling module.
  25. :param pool_sizes: spatial output sizes of the pooled feature maps.
  26. """
  27. super().__init__()
  28. self.branches = nn.ModuleList([
  29. nn.Sequential(
  30. nn.AdaptiveAvgPool2d(pool_size),
  31. ConvBNReLU(in_channels, inter_channels, kernel_size=1, bias=False),
  32. ) for pool_size in pool_sizes
  33. ])
  34. self.conv_out = ConvBNReLU(inter_channels, out_channels, kernel_size=3, padding=1, bias=False)
  35. self.out_channels = out_channels
  36. self.upsample_mode = upsample_mode
  37. self.align_corners = align_corners
  38. self.pool_sizes = pool_sizes
  39. def forward(self, x):
  40. out = None
  41. input_shape = x.shape[2:]
  42. for branch in self.branches:
  43. y = branch(x)
  44. y = F.interpolate(y, size=input_shape, mode=self.upsample_mode, align_corners=self.align_corners)
  45. out = y if out is None else out + y
  46. out = self.conv_out(out)
  47. return out
  48. def prep_model_for_conversion(self, input_size: Union[tuple, list], stride_ratio: int = 32, **kwargs):
  49. """
  50. Replace Global average pooling with fixed kernels Average pooling, since dynamic kernel sizes are not supported
  51. when compiling to ONNX: `Unsupported: ONNX export of operator adaptive_avg_pool2d, input size not accessible.`
  52. """
  53. input_size = [x / stride_ratio for x in input_size[-2:]]
  54. for branch in self.branches:
  55. global_pool: nn.AdaptiveAvgPool2d = branch[0]
  56. out_size = global_pool.output_size
  57. out_size = out_size if isinstance(out_size, (tuple, list)) else (out_size, out_size)
  58. kernel_size = [int(i / o) for i, o in zip(input_size, out_size)]
  59. branch[0] = nn.AvgPool2d(kernel_size=kernel_size, stride=kernel_size)
  60. class UAFM(nn.Module):
  61. """
  62. Unified Attention Fusion Module, which uses mean and max values across the spatial dimensions.
  63. """
  64. def __init__(self,
  65. in_channels: int,
  66. skip_channels: int,
  67. out_channels: int,
  68. up_factor: int,
  69. upsample_mode: Union[UpsampleMode, str] = UpsampleMode.BILINEAR,
  70. align_corners: bool = False):
  71. """
  72. :params in_channels: num_channels of input feature map.
  73. :param skip_channels: num_channels of skip connection feature map.
  74. :param out_channels: num out channels after features fusion.
  75. :param up_factor: upsample scale factor of the input feature map.
  76. :param upsample_mode: see UpsampleMode for valid options.
  77. """
  78. super().__init__()
  79. self.conv_atten = nn.Sequential(
  80. ConvBNReLU(4, 2, kernel_size=3, padding=1, bias=False),
  81. ConvBNReLU(2, 1, kernel_size=3, padding=1, bias=False, use_activation=False)
  82. )
  83. self.proj_skip = nn.Identity() if skip_channels == in_channels else \
  84. ConvBNReLU(skip_channels, in_channels, kernel_size=3, padding=1, bias=False)
  85. self.up_x = nn.Identity() if up_factor == 1 else \
  86. make_upsample_module(scale_factor=up_factor, upsample_mode=upsample_mode, align_corners=align_corners)
  87. self.conv_out = ConvBNReLU(in_channels, out_channels, kernel_size=3, padding=1, bias=False)
  88. def forward(self, x, skip):
  89. """
  90. :param x: input feature map to upsample before fusion.
  91. :param skip: skip connection feature map.
  92. """
  93. x = self.up_x(x)
  94. skip = self.proj_skip(skip)
  95. atten = torch.cat([
  96. *self._avg_max_spatial_reduce(x, use_concat=False),
  97. *self._avg_max_spatial_reduce(skip, use_concat=False)
  98. ], dim=1)
  99. atten = self.conv_atten(atten)
  100. atten = torch.sigmoid(atten)
  101. out = x * atten + skip * (1 - atten)
  102. out = self.conv_out(out)
  103. return out
  104. @staticmethod
  105. def _avg_max_spatial_reduce(x, use_concat: bool = False):
  106. reduced = [
  107. torch.mean(x, dim=1, keepdim=True),
  108. torch.max(x, dim=1, keepdim=True)[0]
  109. ]
  110. if use_concat:
  111. reduced = torch.cat(reduced, dim=1)
  112. return reduced
  113. class PPLiteSegEncoder(nn.Module):
  114. """
  115. Encoder for PPLiteSeg, include backbone followed by a context module.
  116. """
  117. def __init__(self,
  118. backbone: AbstractSTDCBackbone,
  119. projection_channels_list: List[int],
  120. context_module: nn.Module):
  121. super().__init__()
  122. self.backbone = backbone
  123. self.context_module = context_module
  124. feats_channels = backbone.get_backbone_output_number_of_channels()
  125. self.proj_convs = nn.ModuleList([
  126. ConvBNReLU(feat_ch, proj_ch, kernel_size=3, padding=1, bias=False)
  127. for feat_ch, proj_ch in zip(feats_channels, projection_channels_list)
  128. ])
  129. self.projection_channels_list = projection_channels_list
  130. def get_output_number_of_channels(self) -> List[int]:
  131. channels_list = self.projection_channels_list
  132. if hasattr(self.context_module, "out_channels"):
  133. channels_list.append(self.context_module.out_channels)
  134. return channels_list
  135. def forward(self, x):
  136. feats = self.backbone(x)
  137. y = self.context_module(feats[-1])
  138. feats = [conv(f) for conv, f in zip(self.proj_convs, feats)]
  139. return feats + [y]
  140. class PPLiteSegDecoder(nn.Module):
  141. """
  142. PPLiteSegDecoder using UAFM blocks to fuse feature maps.
  143. """
  144. def __init__(self,
  145. encoder_channels: List[int],
  146. up_factors: List[int],
  147. out_channels: List[int],
  148. upsample_mode,
  149. align_corners: bool):
  150. super().__init__()
  151. # Make a copy of channels list, to prevent out of scope changes.
  152. encoder_channels = encoder_channels.copy()
  153. encoder_channels.reverse()
  154. in_channels = encoder_channels.pop(0)
  155. # TODO - assert argument length
  156. self.up_stages = nn.ModuleList()
  157. for skip_ch, up_factor, out_ch in zip(encoder_channels, up_factors, out_channels):
  158. self.up_stages.append(UAFM(
  159. in_channels=in_channels,
  160. skip_channels=skip_ch,
  161. out_channels=out_ch,
  162. up_factor=up_factor,
  163. upsample_mode=upsample_mode,
  164. align_corners=align_corners
  165. ))
  166. in_channels = out_ch
  167. def forward(self, feats: List[torch.Tensor]):
  168. feats.reverse()
  169. x = feats.pop(0)
  170. for up_stage, skip in zip(self.up_stages, feats):
  171. x = up_stage(x, skip)
  172. return x
  173. class PPLiteSegBase(SegmentationModule):
  174. """
  175. The PP_LiteSeg implementation based on PaddlePaddle.
  176. The original article refers to "Juncai Peng, Yi Liu, Shiyu Tang, Yuying Hao, Lutao Chu,
  177. Guowei Chen, Zewu Wu, Zeyu Chen, Zhiliang Yu, Yuning Du, Qingqing Dang,Baohua Lai,
  178. Qiwen Liu, Xiaoguang Hu, Dianhai Yu, Yanjun Ma. PP-LiteSeg: A Superior Real-Time Semantic
  179. Segmentation Model. https://arxiv.org/abs/2204.02681".
  180. """
  181. def __init__(self,
  182. num_classes,
  183. backbone: AbstractSTDCBackbone,
  184. projection_channels_list: List[int],
  185. sppm_inter_channels: int,
  186. sppm_out_channels: int,
  187. sppm_pool_sizes: List[int],
  188. sppm_upsample_mode: Union[UpsampleMode, str],
  189. align_corners: bool,
  190. decoder_up_factors: List[int],
  191. decoder_channels: List[int],
  192. decoder_upsample_mode: Union[UpsampleMode, str],
  193. head_scale_factor: int,
  194. head_upsample_mode: Union[UpsampleMode, str],
  195. head_mid_channels: int,
  196. dropout: float,
  197. use_aux_heads: bool,
  198. aux_hidden_channels: List[int],
  199. aux_scale_factors: List[int]
  200. ):
  201. """
  202. :param backbone: Backbone nn.Module should implement the abstract class `AbstractSTDCBackbone`.
  203. :param projection_channels_list: channels list to project encoder features before fusing with the decoder
  204. stream.
  205. :param sppm_inter_channels: num channels in each sppm pooling branch.
  206. :param sppm_out_channels: The number of output channels after sppm module.
  207. :param sppm_pool_sizes: spatial output sizes of the pooled feature maps.
  208. :param sppm_upsample_mode: Upsample mode to original size after pooling.
  209. :param decoder_up_factors: list upsample factor per decoder stage.
  210. :param decoder_channels: list of num_channels per decoder stage.
  211. :param decoder_upsample_mode: upsample mode in decoder stages, see UpsampleMode for valid options.
  212. :param head_scale_factor: scale factor for final the segmentation head logits.
  213. :param head_upsample_mode: upsample mode to final prediction sizes, see UpsampleMode for valid options.
  214. :param head_mid_channels: num of hidden channels in segmentation head.
  215. :param use_aux_heads: set True when training, output extra Auxiliary feature maps from the encoder module.
  216. :param aux_hidden_channels: List of hidden channels in auxiliary segmentation heads.
  217. :param aux_scale_factors: list of uppsample factors for final auxiliary heads logits.
  218. """
  219. super().__init__(use_aux_heads=use_aux_heads)
  220. # Init Encoder
  221. backbone_out_channels = backbone.get_backbone_output_number_of_channels()
  222. assert len(backbone_out_channels) == len(projection_channels_list), \
  223. f"The length of backbone outputs ({backbone_out_channels}) should match the length of projection channels" \
  224. f"({len(projection_channels_list)})."
  225. context = SPPM(in_channels=backbone_out_channels[-1],
  226. inter_channels=sppm_inter_channels,
  227. out_channels=sppm_out_channels,
  228. pool_sizes=sppm_pool_sizes,
  229. upsample_mode=sppm_upsample_mode,
  230. align_corners=align_corners)
  231. self.encoder = PPLiteSegEncoder(backbone=backbone,
  232. context_module=context,
  233. projection_channels_list=projection_channels_list)
  234. encoder_channels = self.encoder.get_output_number_of_channels()
  235. # Init Decoder
  236. self.decoder = PPLiteSegDecoder(encoder_channels=encoder_channels,
  237. up_factors=decoder_up_factors,
  238. out_channels=decoder_channels,
  239. upsample_mode=decoder_upsample_mode,
  240. align_corners=align_corners)
  241. # Init Segmentation classification heads
  242. self.seg_head = nn.Sequential(
  243. SegmentationHead(in_channels=decoder_channels[-1],
  244. mid_channels=head_mid_channels,
  245. num_classes=num_classes,
  246. dropout=dropout),
  247. make_upsample_module(scale_factor=head_scale_factor, upsample_mode=head_upsample_mode,
  248. align_corners=align_corners)
  249. )
  250. # Auxiliary heads
  251. if self.use_aux_heads:
  252. encoder_out_channels = projection_channels_list
  253. self.aux_heads = nn.ModuleList([
  254. nn.Sequential(
  255. SegmentationHead(backbone_ch, hidden_ch, num_classes, dropout=dropout),
  256. make_upsample_module(scale_factor=scale_factor, upsample_mode=head_upsample_mode,
  257. align_corners=align_corners)
  258. ) for backbone_ch, hidden_ch, scale_factor in zip(encoder_out_channels, aux_hidden_channels,
  259. aux_scale_factors)
  260. ])
  261. self.init_params()
  262. def _remove_auxiliary_heads(self):
  263. if hasattr(self, "aux_heads"):
  264. del self.aux_heads
  265. @property
  266. def backbone(self) -> nn.Module:
  267. """
  268. Support SG load backbone when training.
  269. """
  270. return self.encoder.backbone
  271. def forward(self, x):
  272. feats = self.encoder(x)
  273. if self.use_aux_heads:
  274. enc_feats = feats[:-1]
  275. x = self.decoder(feats)
  276. x = self.seg_head(x)
  277. if not self.use_aux_heads:
  278. return x
  279. aux_feats = [aux_head(feat) for feat, aux_head in zip(enc_feats, self.aux_heads)]
  280. return tuple([x] + aux_feats)
  281. def initialize_param_groups(self, lr: float, training_params: HpmStruct) -> list:
  282. """
  283. Custom param groups for training:
  284. - Different lr for backbone and the rest, if `multiply_head_lr` key is in `training_params`.
  285. """
  286. multiply_head_lr = get_param(training_params, "multiply_head_lr", 1)
  287. multiply_lr_params, no_multiply_params = self._separate_lr_multiply_params()
  288. param_groups = [{"named_params": no_multiply_params, "lr": lr, "name": "no_multiply_params"},
  289. {"named_params": multiply_lr_params, "lr": lr * multiply_head_lr, "name": "multiply_lr_params"}]
  290. return param_groups
  291. def update_param_groups(self, param_groups: list, lr: float, epoch: int, iter: int, training_params: HpmStruct,
  292. total_batch: int) -> list:
  293. multiply_head_lr = get_param(training_params, "multiply_head_lr", 1)
  294. for param_group in param_groups:
  295. param_group['lr'] = lr
  296. if param_group["name"] == "multiply_lr_params":
  297. param_group['lr'] *= multiply_head_lr
  298. return param_groups
  299. def _separate_lr_multiply_params(self):
  300. """
  301. Separate backbone params from the rest.
  302. :return: iterators of groups named_parameters.
  303. """
  304. multiply_lr_params, no_multiply_params = {}, {}
  305. for name, param in self.named_parameters():
  306. if "encoder.backbone" in name:
  307. no_multiply_params[name] = param
  308. else:
  309. multiply_lr_params[name] = param
  310. return multiply_lr_params.items(), no_multiply_params.items()
  311. def prep_model_for_conversion(self, input_size: Union[tuple, list], stride_ratio: int = 32, **kwargs):
  312. super().prep_model_for_conversion(input_size, **kwargs)
  313. if isinstance(self.encoder.context_module, SPPM):
  314. self.encoder.context_module.prep_model_for_conversion(input_size=input_size, stride_ratio=stride_ratio)
  315. def replace_head(self, new_num_classes: int, **kwargs):
  316. for module in self.modules():
  317. if isinstance(module, SegmentationHead):
  318. module.replace_num_classes(new_num_classes)
  319. class PPLiteSegB(PPLiteSegBase):
  320. def __init__(self, arch_params: HpmStruct):
  321. backbone = STDC2Backbone(in_channels=get_param(arch_params, "in_channels", 3),
  322. out_down_ratios=[8, 16, 32])
  323. super().__init__(num_classes=get_param(arch_params, "num_classes"),
  324. backbone=backbone,
  325. projection_channels_list=[96, 128, 128],
  326. sppm_inter_channels=128,
  327. sppm_out_channels=128,
  328. sppm_pool_sizes=[1, 2, 4],
  329. sppm_upsample_mode="bilinear",
  330. align_corners=False,
  331. decoder_up_factors=[1, 2, 2],
  332. decoder_channels=[128, 96, 64],
  333. decoder_upsample_mode="bilinear",
  334. head_scale_factor=8,
  335. head_upsample_mode="bilinear",
  336. head_mid_channels=64,
  337. dropout=get_param(arch_params, "dropout", 0.),
  338. use_aux_heads=get_param(arch_params, "use_aux_heads", False),
  339. aux_hidden_channels=[32, 64, 64],
  340. aux_scale_factors=[8, 16, 32])
  341. class PPLiteSegT(PPLiteSegBase):
  342. def __init__(self, arch_params: HpmStruct):
  343. backbone = STDC1Backbone(in_channels=get_param(arch_params, "in_channels", 3),
  344. out_down_ratios=[8, 16, 32])
  345. super().__init__(num_classes=get_param(arch_params, "num_classes"),
  346. backbone=backbone,
  347. projection_channels_list=[64, 128, 128],
  348. sppm_inter_channels=128,
  349. sppm_out_channels=128,
  350. sppm_pool_sizes=[1, 2, 4],
  351. sppm_upsample_mode="bilinear",
  352. align_corners=False,
  353. decoder_up_factors=[1, 2, 2],
  354. decoder_channels=[128, 64, 32],
  355. decoder_upsample_mode="bilinear",
  356. head_scale_factor=8,
  357. head_upsample_mode="bilinear",
  358. head_mid_channels=32,
  359. dropout=get_param(arch_params, "dropout", 0.),
  360. use_aux_heads=get_param(arch_params, "use_aux_heads", False),
  361. aux_hidden_channels=[32, 64, 64],
  362. aux_scale_factors=[8, 16, 32])
Discard
Tip!

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