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

#381 Feature/sg 000 connect to lab

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:feature/sg-000_connect_to_lab
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
  1. """
  2. ShuffleNetV2 in PyTorch.
  3. See the paper "ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design" for more details.
  4. (https://arxiv.org/abs/1807.11164)
  5. Code taken from torchvision/models/shufflenetv2.py
  6. """
  7. from typing import List
  8. import torch
  9. from torch import Tensor
  10. import torch.nn as nn
  11. from super_gradients.training.utils import HpmStruct
  12. from super_gradients.training.models.sg_module import SgModule
  13. __all__ = [
  14. 'ShuffleNetV2Base', 'ShufflenetV2_x0_5', 'ShufflenetV2_x1_0',
  15. 'ShufflenetV2_x1_5', 'ShufflenetV2_x2_0', 'CustomizedShuffleNetV2'
  16. ]
  17. class ChannelShuffleInvertedResidual(nn.Module):
  18. """
  19. Implement Inverted Residual block as in [https://arxiv.org/abs/1807.11164] in Fig.3 (c) & (d):
  20. * When stride > 1
  21. - the whole input goes through branch1,
  22. - the whole input goes through branch2 ,
  23. and the arbitrary number of output channels are produced.
  24. * When stride == 1
  25. - half of input channels in are passed as identity,
  26. - another half of input channels goes through branch2,
  27. and the number of output channels after the block remains the same as in input.
  28. Channel shuffle is performed on a concatenation in both cases.
  29. """
  30. def __init__(self, inp: int, out: int, stride: int) -> None:
  31. super(ChannelShuffleInvertedResidual, self).__init__()
  32. assert 1 <= stride <= 3, "Illegal stride value"
  33. assert (stride != 1) or (inp == out), \
  34. "When stride == 1 num of input channels should be equal to the requested num of out output channels"
  35. self.stride = stride
  36. # half of requested out channels will be produced by each branch
  37. branch_features = out // 2
  38. if self.stride > 1:
  39. self.branch1 = nn.Sequential(
  40. nn.Conv2d(inp, inp, kernel_size=3, stride=self.stride, padding=1, bias=False, groups=inp),
  41. nn.BatchNorm2d(inp),
  42. nn.Conv2d(inp, branch_features, kernel_size=1, stride=1, padding=0, bias=False),
  43. nn.BatchNorm2d(branch_features),
  44. nn.ReLU(inplace=True),
  45. )
  46. else:
  47. # won't be called if self.stride == 1
  48. self.branch1 = nn.Identity()
  49. self.branch2 = nn.Sequential(
  50. # branch 2 operates on the whole input when stride > 1 and on half of it otherwise
  51. nn.Conv2d(inp if (self.stride > 1) else inp // 2, branch_features, kernel_size=1, stride=1, padding=0,
  52. bias=False),
  53. nn.BatchNorm2d(branch_features),
  54. nn.ReLU(inplace=True),
  55. nn.Conv2d(branch_features, branch_features, kernel_size=3, stride=self.stride, padding=1, bias=False,
  56. groups=branch_features),
  57. nn.BatchNorm2d(branch_features),
  58. nn.Conv2d(branch_features, branch_features, kernel_size=1, stride=1, padding=0, bias=False),
  59. nn.BatchNorm2d(branch_features),
  60. nn.ReLU(inplace=True)
  61. )
  62. @staticmethod
  63. def channel_shuffle(x: Tensor, groups: int) -> Tensor:
  64. """
  65. From "ShuffleNet V2: Practical Guidelines for EfficientCNN Architecture Design" (https://arxiv.org/abs/1807.11164):
  66. A “channel shuffle” operation is then introduced to enable
  67. information communication between different groups of channels and improve accuracy.
  68. The operation preserves x.size(), but shuffles its channels in the manner explained further in the example.
  69. Example:
  70. If group = 2 (2 branches with the same # of activation maps were concatenated before channel_shuffle),
  71. then activation maps in x are:
  72. from_B1, from_B1, ... from_B2, from_B2
  73. After channel_shuffle activation maps in x will be:
  74. from_B1, from_B2, ... from_B1, from_B2
  75. """
  76. batch_size, num_channels, height, width = x.size()
  77. channels_per_group = num_channels // groups
  78. # reshape
  79. x = x.view(batch_size, groups, channels_per_group, height, width)
  80. x = torch.transpose(x, 1, 2).contiguous()
  81. # flatten
  82. x = x.view(batch_size, -1, height, width)
  83. return x
  84. def forward(self, x: Tensor) -> Tensor:
  85. if self.stride == 1:
  86. # num channels remains the same due to assert that inp == out in __init__
  87. x1, x2 = x.chunk(2, dim=1)
  88. out = torch.cat((x1, self.branch2(x2)), dim=1)
  89. else:
  90. # inp num channels can change to a requested arbitrary out num channels
  91. out = torch.cat((self.branch1(x), self.branch2(x)), dim=1)
  92. out = self.channel_shuffle(out, 2)
  93. return out
  94. class ShuffleNetV2Base(SgModule):
  95. def __init__(self, structure: List[int], stages_out_channels: List[int],
  96. backbone_mode: bool = False, num_classes: int = 1000,
  97. block: nn.Module = ChannelShuffleInvertedResidual):
  98. super(ShuffleNetV2Base, self).__init__()
  99. self.backbone_mode = backbone_mode
  100. if len(structure) != 3:
  101. raise ValueError('expected structure as list of 3 positive ints')
  102. if len(stages_out_channels) != 5:
  103. raise ValueError('expected stages_out_channels as list of 5 positive ints')
  104. self.structure = structure
  105. self.out_channels = stages_out_channels
  106. input_channels = 3
  107. output_channels = self.out_channels[0]
  108. self.conv1 = nn.Sequential(
  109. nn.Conv2d(input_channels, output_channels, 3, 2, 1, bias=False),
  110. nn.BatchNorm2d(output_channels),
  111. nn.ReLU(inplace=True),
  112. )
  113. input_channels = output_channels
  114. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  115. # Static annotations for mypy
  116. self.layer2 = self._make_layer(block, input_channels, self.out_channels[1], self.structure[0])
  117. self.layer3 = self._make_layer(block, self.out_channels[1], self.out_channels[2], self.structure[1])
  118. self.layer4 = self._make_layer(block, self.out_channels[2], self.out_channels[3], self.structure[2])
  119. input_channels = self.out_channels[3]
  120. output_channels = self.out_channels[-1]
  121. self.conv5 = nn.Sequential(
  122. nn.Conv2d(input_channels, output_channels, 1, 1, 0, bias=False),
  123. nn.BatchNorm2d(output_channels),
  124. nn.ReLU(inplace=True),
  125. )
  126. if not self.backbone_mode:
  127. self.avgpool = nn.AdaptiveAvgPool2d(1)
  128. self.fc = nn.Linear(output_channels, num_classes)
  129. @staticmethod
  130. def _make_layer(block, input_channels, output_channels, repeats):
  131. # add first block with stride 2 to downsize the input
  132. seq = [block(input_channels, output_channels, 2)]
  133. for _ in range(repeats - 1):
  134. seq.append(block(output_channels, output_channels, 1))
  135. return nn.Sequential(*seq)
  136. def load_state_dict(self, state_dict, strict=True):
  137. """
  138. load_state_dict - Overloads the base method and calls it to load a modified dict for usage as a backbone
  139. :param state_dict: The state_dict to load
  140. :param strict: strict loading (see super() docs)
  141. """
  142. pretrained_model_weights_dict = state_dict.copy()
  143. if self.backbone_mode:
  144. # removing fc weights first not to break strict loading
  145. fc_weights_keys = [k for k in pretrained_model_weights_dict if 'fc' in k]
  146. for key in fc_weights_keys:
  147. pretrained_model_weights_dict.pop(key)
  148. super().load_state_dict(pretrained_model_weights_dict, strict)
  149. def forward(self, x: Tensor) -> Tensor:
  150. x = self.conv1(x)
  151. x = self.maxpool(x)
  152. x = self.layer2(x)
  153. x = self.layer3(x)
  154. x = self.layer4(x)
  155. x = self.conv5(x)
  156. if not self.backbone_mode:
  157. x = self.avgpool(x)
  158. x = x.view(x.size(0), -1)
  159. x = self.fc(x)
  160. return x
  161. class ShufflenetV2_x0_5(ShuffleNetV2Base):
  162. def __init__(self, arch_params: HpmStruct, num_classes: int = 1000, backbone_mode: bool = False):
  163. super().__init__([4, 8, 4], [24, 48, 96, 192, 1024],
  164. backbone_mode=backbone_mode,
  165. num_classes=num_classes or arch_params.num_classes)
  166. class ShufflenetV2_x1_0(ShuffleNetV2Base):
  167. def __init__(self, arch_params: HpmStruct, num_classes: int = 1000, backbone_mode: bool = False):
  168. super().__init__([4, 8, 4], [24, 116, 232, 464, 1024],
  169. backbone_mode=backbone_mode,
  170. num_classes=num_classes or arch_params.num_classes)
  171. class ShufflenetV2_x1_5(ShuffleNetV2Base):
  172. def __init__(self, arch_params: HpmStruct, num_classes: int = 1000, backbone_mode: bool = False):
  173. super().__init__([4, 8, 4], [24, 176, 352, 704, 1024],
  174. backbone_mode=backbone_mode,
  175. num_classes=num_classes or arch_params.num_classes)
  176. class ShufflenetV2_x2_0(ShuffleNetV2Base):
  177. def __init__(self, arch_params: HpmStruct, num_classes: int = 1000, backbone_mode: bool = False):
  178. super().__init__([4, 8, 4], [24, 244, 488, 976, 2048],
  179. backbone_mode=backbone_mode,
  180. num_classes=num_classes or arch_params.num_classes)
  181. class CustomizedShuffleNetV2(ShuffleNetV2Base):
  182. def __init__(self, arch_params: HpmStruct, num_classes: int = 1000, backbone_mode: bool = False):
  183. super().__init__(arch_params.structure, arch_params.stages_out_channels,
  184. backbone_mode=backbone_mode,
  185. num_classes=num_classes or arch_params.num_classes)
Discard
Tip!

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