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

resnet.py 12 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
  1. """ResNet in PyTorch.
  2. For Pre-activation ResNet, see 'preact_resnet.py'.
  3. Reference:
  4. [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
  5. Deep Residual Learning for Image Recognition. arXiv:1512.03385
  6. Pre-trained ImageNet models: 'deci-model-repository/resnet?/ckpt_best.pth' => ? = the type of resnet (e.g. 18, 34...)
  7. Pre-trained CIFAR10 models: 'deci-model-repository/CIFAR_NAS_#?_????_?/ckpt_best.pth' => ? = num of model, structure, width_mult
  8. Code adapted from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
  9. """
  10. import torch.nn as nn
  11. import torch.nn.functional as F
  12. from collections import OrderedDict
  13. from super_gradients.training.models import SgModule
  14. def width_multiplier(original, factor):
  15. return int(original * factor)
  16. class BasicBlock(nn.Module):
  17. def __init__(self, in_planes, planes, stride=1, expansion=1, final_relu=True):
  18. super(BasicBlock, self).__init__()
  19. self.expansion = expansion
  20. self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
  21. self.bn1 = nn.BatchNorm2d(planes)
  22. self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
  23. self.bn2 = nn.BatchNorm2d(planes)
  24. self.final_relu = final_relu
  25. self.shortcut = nn.Sequential()
  26. if stride != 1 or in_planes != self.expansion * planes:
  27. self.shortcut = nn.Sequential(
  28. nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False),
  29. nn.BatchNorm2d(self.expansion * planes)
  30. )
  31. def forward(self, x):
  32. out = F.relu(self.bn1(self.conv1(x)))
  33. out = self.bn2(self.conv2(out))
  34. out += self.shortcut(x)
  35. if self.final_relu:
  36. out = F.relu(out)
  37. return out
  38. class Bottleneck(nn.Module):
  39. def __init__(self, in_planes, planes, stride=1, expansion=4, final_relu=True):
  40. super(Bottleneck, self).__init__()
  41. self.expansion = expansion
  42. self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
  43. self.bn1 = nn.BatchNorm2d(planes)
  44. self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
  45. self.bn2 = nn.BatchNorm2d(planes)
  46. self.conv3 = nn.Conv2d(planes, self.expansion * planes, kernel_size=1, bias=False)
  47. self.bn3 = nn.BatchNorm2d(self.expansion * planes)
  48. self.final_relu = final_relu
  49. self.shortcut = nn.Sequential()
  50. if stride != 1 or in_planes != self.expansion * planes:
  51. self.shortcut = nn.Sequential(
  52. nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False),
  53. nn.BatchNorm2d(self.expansion * planes)
  54. )
  55. def forward(self, x):
  56. out = F.relu(self.bn1(self.conv1(x)))
  57. out = F.relu(self.bn2(self.conv2(out)))
  58. out = self.bn3(self.conv3(out))
  59. out += self.shortcut(x)
  60. if self.final_relu:
  61. out = F.relu(out)
  62. return out
  63. class CifarResNet(SgModule):
  64. def __init__(self, block, num_blocks, num_classes=10, width_mult=1, expansion=1):
  65. super(CifarResNet, self).__init__()
  66. self.expansion = expansion
  67. self.structure = [num_blocks, width_mult]
  68. self.in_planes = width_multiplier(64, width_mult)
  69. self.conv1 = nn.Conv2d(3, width_multiplier(64, width_mult), kernel_size=3, stride=1, padding=1, bias=False)
  70. self.bn1 = nn.BatchNorm2d(width_multiplier(64, width_mult))
  71. self.layer1 = self._make_layer(block, width_multiplier(64, width_mult), num_blocks[0], stride=1)
  72. self.layer2 = self._make_layer(block, width_multiplier(128, width_mult), num_blocks[1], stride=2)
  73. self.layer3 = self._make_layer(block, width_multiplier(256, width_mult), num_blocks[2], stride=2)
  74. self.layer4 = self._make_layer(block, width_multiplier(512, width_mult), num_blocks[3], stride=2)
  75. self.avgpool = nn.AdaptiveAvgPool2d(1)
  76. self.linear = nn.Linear(width_multiplier(512, width_mult) * self.expansion, num_classes)
  77. def _make_layer(self, block, planes, num_blocks, stride):
  78. strides = [stride] + [1] * (num_blocks - 1)
  79. layers = []
  80. if num_blocks == 0:
  81. # When the number of blocks is zero but spatial dimension and/or number of filters about to change we put 1
  82. # 3X3 conv layer to make this change to the new dimensions.
  83. if stride != 1 or self.in_planes != planes:
  84. layers.append(nn.Sequential(
  85. nn.Conv2d(self.in_planes, planes, kernel_size=3, stride=stride, bias=False, padding=1),
  86. nn.BatchNorm2d(planes))
  87. )
  88. self.in_planes = planes
  89. else:
  90. for stride in strides:
  91. layers.append(block(self.in_planes, planes, stride))
  92. self.in_planes = planes * self.expansion
  93. return nn.Sequential(*layers)
  94. def forward(self, x):
  95. out = F.relu(self.bn1(self.conv1(x)))
  96. out = self.layer1(out)
  97. out = self.layer2(out)
  98. out = self.layer3(out)
  99. out = self.layer4(out)
  100. out = self.avgpool(out)
  101. out = out.view(out.size(0), -1)
  102. out = self.linear(out)
  103. return out
  104. class ResNet(SgModule):
  105. def __init__(self, block, num_blocks: list, num_classes: int = 10, width_mult: float = 1, expansion: int = 1,
  106. input_batchnorm: bool = False, backbone_mode: bool = False):
  107. super(ResNet, self).__init__()
  108. self.expansion = expansion
  109. self.backbone_mode = backbone_mode
  110. self.structure = [num_blocks, width_mult]
  111. self.in_planes = width_multiplier(64, width_mult)
  112. self.input_batchnorm = input_batchnorm
  113. if self.input_batchnorm:
  114. self.bn0 = nn.BatchNorm2d(3)
  115. self.conv1 = nn.Conv2d(3, width_multiplier(64, width_mult), kernel_size=7, stride=2, padding=3, bias=False)
  116. self.bn1 = nn.BatchNorm2d(width_multiplier(64, width_mult))
  117. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  118. self.layer1 = self._make_layer(block, width_multiplier(64, width_mult), num_blocks[0], stride=1)
  119. self.layer2 = self._make_layer(block, width_multiplier(128, width_mult), num_blocks[1], stride=2)
  120. self.layer3 = self._make_layer(block, width_multiplier(256, width_mult), num_blocks[2], stride=2)
  121. self.layer4 = self._make_layer(block, width_multiplier(512, width_mult), num_blocks[3], stride=2)
  122. if not self.backbone_mode:
  123. # IF RESNET IS IN BACK_BONE MODE WE DON'T NEED THE FINAL CLASSIFIER LAYERS, BUT ONLY THE NET BLOCK STRUCTURE
  124. self.linear = nn.Linear(width_multiplier(512, width_mult) * self.expansion, num_classes)
  125. self.avgpool = nn.AdaptiveAvgPool2d(1)
  126. self.width_mult = width_mult
  127. def _make_layer(self, block, planes, num_blocks, stride):
  128. strides = [stride] + [1] * (num_blocks - 1)
  129. layers = []
  130. if num_blocks == 0:
  131. # When the number of blocks is zero but spatial dimension and/or number of filters about to change we put 1
  132. # 3X3 conv layer to make this change to the new dimensions.
  133. if stride != 1 or self.in_planes != planes:
  134. layers.append(nn.Sequential(
  135. nn.Conv2d(self.in_planes, planes, kernel_size=3, stride=stride, bias=False, padding=1),
  136. nn.BatchNorm2d(planes))
  137. )
  138. self.in_planes = planes
  139. else:
  140. for stride in strides:
  141. layers.append(block(self.in_planes, planes, stride))
  142. self.in_planes = planes * self.expansion
  143. return nn.Sequential(*layers)
  144. def forward(self, x):
  145. if self.input_batchnorm:
  146. x = self.bn0(x)
  147. out = F.relu(self.bn1(self.conv1(x)))
  148. out = self.maxpool(out)
  149. out = self.layer1(out)
  150. out = self.layer2(out)
  151. out = self.layer3(out)
  152. out = self.layer4(out)
  153. if not self.backbone_mode:
  154. # IF RESNET IS *NOT* IN BACK_BONE MODE WE NEED THE FINAL CLASSIFIER LAYERS OUTPUTS
  155. out = self.avgpool(out)
  156. out = out.squeeze(dim=2).squeeze(dim=2)
  157. out = self.linear(out)
  158. return out
  159. def load_state_dict(self, state_dict, strict=True):
  160. """
  161. load_state_dict - Overloads the base method and calls it to load a modified dict for usage as a backbone
  162. :param state_dict: The state_dict to load
  163. :param strict: strict loading (see super() docs)
  164. """
  165. pretrained_model_weights_dict = state_dict.copy()
  166. if self.backbone_mode:
  167. # FIRST LET'S POP THE LAST TWO LAYERS - NO NEED TO LOAD THEIR VALUES SINCE THEY ARE IRRELEVANT AS A BACKBONE
  168. pretrained_model_weights_dict.popitem()
  169. pretrained_model_weights_dict.popitem()
  170. pretrained_backbone_weights_dict = OrderedDict()
  171. for layer_name, weights in pretrained_model_weights_dict.items():
  172. # GET THE LAYER NAME WITHOUT THE 'module.' PREFIX
  173. name_without_module_prefix = layer_name.split('module.')[1]
  174. # MAKE SURE THESE ARE NOT THE FINAL LAYERS
  175. pretrained_backbone_weights_dict[name_without_module_prefix] = weights
  176. # RETURNING THE UNMODIFIED/MODIFIED STATE DICT DEPENDING ON THE backbone_mode VALUE
  177. super().load_state_dict(pretrained_backbone_weights_dict, strict)
  178. else:
  179. super().load_state_dict(pretrained_model_weights_dict, strict)
  180. def replace_head(self, new_num_classes=None, new_head=None):
  181. if new_num_classes is None and new_head is None:
  182. raise ValueError("At least one of new_num_classes, new_head must be given to replace output layer.")
  183. if new_head is not None:
  184. self.linear = new_head
  185. else:
  186. self.linear = nn.Linear(width_multiplier(512, self.width_mult) * self.expansion, new_num_classes)
  187. def ResNet18(arch_params, num_classes=None, backbone_mode=None):
  188. return ResNet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes or arch_params.num_classes,
  189. backbone_mode=backbone_mode)
  190. def ResNet18Cifar(arch_params, num_classes=None):
  191. return CifarResNet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes or arch_params.num_classes)
  192. def ResNet34(arch_params, num_classes=None, backbone_mode=None):
  193. return ResNet(BasicBlock, [3, 4, 6, 3], num_classes=num_classes or arch_params.num_classes,
  194. backbone_mode=backbone_mode)
  195. def ResNet50(arch_params, num_classes=None, backbone_mode=None):
  196. return ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes or arch_params.num_classes,
  197. backbone_mode=backbone_mode, expansion=4)
  198. def ResNet50_3343(arch_params, num_classes=None, backbone_mode=None):
  199. return ResNet(Bottleneck, [3, 3, 4, 3], num_classes=num_classes or arch_params.num_classes,
  200. backbone_mode=backbone_mode, expansion=4)
  201. def ResNet101(arch_params, num_classes=None, backbone_mode=None):
  202. return ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes or arch_params.num_classes,
  203. backbone_mode=backbone_mode, expansion=4)
  204. def ResNet152(arch_params, num_classes=None, backbone_mode=None):
  205. return ResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes or arch_params.num_classes,
  206. backbone_mode=backbone_mode, expansion=4)
  207. def CustomizedResnetCifar(arch_params, num_classes=None):
  208. return CifarResNet(BasicBlock, arch_params.structure, width_mult=arch_params.width_mult,
  209. num_classes=num_classes or arch_params.num_classes)
  210. def CustomizedResnet50Cifar(arch_params, num_classes=None):
  211. return CifarResNet(Bottleneck, arch_params.structure, width_mult=arch_params.width_mult,
  212. num_classes=num_classes or arch_params.num_classes, expansion=4)
  213. def CustomizedResnet(arch_params, num_classes=None, backbone_mode=None):
  214. return ResNet(BasicBlock, arch_params.structure, width_mult=arch_params.width_mult,
  215. num_classes=num_classes or arch_params.num_classes, backbone_mode=backbone_mode)
  216. def CustomizedResnet50(arch_params, num_classes=None, backbone_mode=None):
  217. return ResNet(Bottleneck, arch_params.structure, width_mult=arch_params.width_mult,
  218. num_classes=num_classes or arch_params.num_classes, backbone_mode=backbone_mode, expansion=4)
Tip!

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

Comments

Loading...