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_pytorch.py 14 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
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
  1. import torch
  2. import torch.nn as nn
  3. # from .utils import load_state_dict_from_url
  4. from torch.utils.model_zoo import load_url as load_state_dict_from_url
  5. __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
  6. 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
  7. 'wide_resnet50_2', 'wide_resnet101_2']
  8. model_urls = {
  9. 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
  10. 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
  11. 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
  12. 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
  13. 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
  14. 'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
  15. 'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
  16. 'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
  17. 'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
  18. }
  19. def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
  20. """3x3 convolution with padding"""
  21. return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
  22. padding=dilation, groups=groups, bias=False, dilation=dilation)
  23. def conv1x1(in_planes, out_planes, stride=1):
  24. """1x1 convolution"""
  25. return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
  26. class BasicBlock(nn.Module):
  27. expansion = 1
  28. def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
  29. base_width=64, dilation=1, norm_layer=None, track_running_stats=True):
  30. super(BasicBlock, self).__init__()
  31. if norm_layer is None:
  32. norm_layer = nn.BatchNorm2d
  33. if groups != 1 or base_width != 64:
  34. raise ValueError('BasicBlock only supports groups=1 and base_width=64')
  35. if dilation > 1:
  36. raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
  37. # Both self.conv1 and self.downsample layers downsample the input when stride != 1
  38. self.conv1 = conv3x3(inplanes, planes, stride)
  39. self.bn1 = norm_layer(planes, track_running_stats=track_running_stats)
  40. self.relu = nn.ReLU(inplace=True)
  41. self.conv2 = conv3x3(planes, planes)
  42. self.bn2 = norm_layer(planes, track_running_stats=track_running_stats)
  43. self.downsample = downsample
  44. self.stride = stride
  45. def forward(self, x):
  46. identity = x
  47. out = self.conv1(x)
  48. out = self.bn1(out)
  49. out = self.relu(out)
  50. out = self.conv2(out)
  51. out = self.bn2(out)
  52. if self.downsample is not None:
  53. identity = self.downsample(x)
  54. out += identity
  55. out = self.relu(out)
  56. return out
  57. class Bottleneck(nn.Module):
  58. expansion = 4
  59. def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
  60. base_width=64, dilation=1, norm_layer=None, track_running_stats=True):
  61. super(Bottleneck, self).__init__()
  62. if norm_layer is None:
  63. norm_layer = nn.BatchNorm2d
  64. width = int(planes * (base_width / 64.)) * groups
  65. # Both self.conv2 and self.downsample layers downsample the input when stride != 1
  66. self.conv1 = conv1x1(inplanes, width)
  67. self.bn1 = norm_layer(width, track_running_stats=track_running_stats)
  68. self.conv2 = conv3x3(width, width, stride, groups, dilation)
  69. self.bn2 = norm_layer(width, track_running_stats=track_running_stats)
  70. self.conv3 = conv1x1(width, planes * self.expansion)
  71. self.bn3 = norm_layer(planes * self.expansion, track_running_stats=track_running_stats)
  72. self.relu = nn.ReLU(inplace=True)
  73. self.downsample = downsample
  74. self.stride = stride
  75. def forward(self, x):
  76. identity = x
  77. out = self.conv1(x)
  78. out = self.bn1(out)
  79. out = self.relu(out)
  80. out = self.conv2(out)
  81. out = self.bn2(out)
  82. out = self.relu(out)
  83. out = self.conv3(out)
  84. out = self.bn3(out)
  85. if self.downsample is not None:
  86. identity = self.downsample(x)
  87. out += identity
  88. out = self.relu(out)
  89. return out
  90. class ResNet(nn.Module):
  91. def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
  92. groups=1, width_per_group=64, replace_stride_with_dilation=None,
  93. norm_layer=None, tracking=True):
  94. super(ResNet, self).__init__()
  95. self.track_running_stats = tracking## added this
  96. if norm_layer is None:
  97. norm_layer = nn.BatchNorm2d
  98. self._norm_layer = norm_layer
  99. self.inplanes = 64
  100. self.dilation = 1
  101. if replace_stride_with_dilation is None:
  102. # each element in the tuple indicates if we should replace
  103. # the 2x2 stride with a dilated convolution instead
  104. replace_stride_with_dilation = [False, False, False]
  105. if len(replace_stride_with_dilation) != 3:
  106. raise ValueError("replace_stride_with_dilation should be None "
  107. "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
  108. self.groups = groups
  109. self.base_width = width_per_group
  110. self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
  111. bias=False)
  112. self.bn1 = norm_layer(self.inplanes, track_running_stats=self.track_running_stats)
  113. self.relu = nn.ReLU(inplace=True)
  114. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  115. self.layer1 = self._make_layer(block, 64, layers[0])
  116. self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
  117. dilate=replace_stride_with_dilation[0])
  118. self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
  119. dilate=replace_stride_with_dilation[1])
  120. self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
  121. dilate=replace_stride_with_dilation[2])
  122. self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
  123. self.fc = nn.Linear(512 * block.expansion, num_classes)
  124. for m in self.modules():
  125. if isinstance(m, nn.Conv2d):
  126. nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
  127. elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
  128. nn.init.constant_(m.weight, 1)
  129. nn.init.constant_(m.bias, 0)
  130. # Zero-initialize the last BN in each residual branch,
  131. # so that the residual branch starts with zeros, and each residual block behaves like an identity.
  132. # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
  133. if zero_init_residual:
  134. for m in self.modules():
  135. if isinstance(m, Bottleneck):
  136. nn.init.constant_(m.bn3.weight, 0)
  137. elif isinstance(m, BasicBlock):
  138. nn.init.constant_(m.bn2.weight, 0)
  139. def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
  140. norm_layer = self._norm_layer
  141. downsample = None
  142. previous_dilation = self.dilation
  143. if dilate:
  144. self.dilation *= stride
  145. stride = 1
  146. if stride != 1 or self.inplanes != planes * block.expansion:
  147. downsample = nn.Sequential(
  148. conv1x1(self.inplanes, planes * block.expansion, stride),
  149. norm_layer(planes * block.expansion, track_running_stats=self.track_running_stats),
  150. )
  151. layers = []
  152. layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
  153. self.base_width, previous_dilation, norm_layer))
  154. self.inplanes = planes * block.expansion
  155. for _ in range(1, blocks):
  156. layers.append(block(self.inplanes, planes, groups=self.groups,
  157. base_width=self.base_width, dilation=self.dilation,
  158. norm_layer=norm_layer, track_running_stats=self.track_running_stats))
  159. return nn.Sequential(*layers)
  160. def forward(self, x):
  161. x = self.conv1(x)
  162. x = self.bn1(x)
  163. x = self.relu(x)
  164. x = self.maxpool(x)
  165. x = self.layer1(x)
  166. x = self.layer2(x)
  167. x = self.layer3(x)
  168. x = self.layer4(x)
  169. x = self.avgpool(x)
  170. # x = torch.flatten(x, 1)
  171. # x = self.fc(x)
  172. return x
  173. def _resnet(arch, block, layers, pretrained, progress, **kwargs):
  174. model = ResNet(block, layers, **kwargs)
  175. print('pretrained:',pretrained)
  176. if pretrained:
  177. state_dict = load_state_dict_from_url(model_urls[arch],
  178. progress=progress)
  179. model.load_state_dict(state_dict, strict=False)## make strict False so that the running mean and avg can be ignored
  180. return model
  181. def resnet18(pretrained=False, progress=True, **kwargs):
  182. r"""ResNet-18 model from
  183. `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
  184. Args:
  185. pretrained (bool): If True, returns a model pre-trained on ImageNet
  186. progress (bool): If True, displays a progress bar of the download to stderr
  187. """
  188. return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,
  189. **kwargs)
  190. def resnet34(pretrained=False, progress=True, **kwargs):
  191. r"""ResNet-34 model from
  192. `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
  193. Args:
  194. pretrained (bool): If True, returns a model pre-trained on ImageNet
  195. progress (bool): If True, displays a progress bar of the download to stderr
  196. """
  197. return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,
  198. **kwargs)
  199. def resnet50(pretrained=False, progress=True, **kwargs):
  200. r"""ResNet-50 model from
  201. `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
  202. Args:
  203. pretrained (bool): If True, returns a model pre-trained on ImageNet
  204. progress (bool): If True, displays a progress bar of the download to stderr
  205. """
  206. return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,
  207. **kwargs)
  208. def resnet101(pretrained=False, progress=True, **kwargs):
  209. r"""ResNet-101 model from
  210. `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
  211. Args:
  212. pretrained (bool): If True, returns a model pre-trained on ImageNet
  213. progress (bool): If True, displays a progress bar of the download to stderr
  214. """
  215. return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress,
  216. **kwargs)
  217. def resnet152(pretrained=False, progress=True, **kwargs):
  218. r"""ResNet-152 model from
  219. `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
  220. Args:
  221. pretrained (bool): If True, returns a model pre-trained on ImageNet
  222. progress (bool): If True, displays a progress bar of the download to stderr
  223. """
  224. return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress,
  225. **kwargs)
  226. def resnext50_32x4d(pretrained=False, progress=True, **kwargs):
  227. r"""ResNeXt-50 32x4d model from
  228. `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
  229. Args:
  230. pretrained (bool): If True, returns a model pre-trained on ImageNet
  231. progress (bool): If True, displays a progress bar of the download to stderr
  232. """
  233. kwargs['groups'] = 32
  234. kwargs['width_per_group'] = 4
  235. return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3],
  236. pretrained, progress, **kwargs)
  237. def resnext101_32x8d(pretrained=False, progress=True, **kwargs):
  238. r"""ResNeXt-101 32x8d model from
  239. `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
  240. Args:
  241. pretrained (bool): If True, returns a model pre-trained on ImageNet
  242. progress (bool): If True, displays a progress bar of the download to stderr
  243. """
  244. kwargs['groups'] = 32
  245. kwargs['width_per_group'] = 8
  246. return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3],
  247. pretrained, progress, **kwargs)
  248. def wide_resnet50_2(pretrained=False, progress=True, **kwargs):
  249. r"""Wide ResNet-50-2 model from
  250. `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
  251. The model is the same as ResNet except for the bottleneck number of channels
  252. which is twice larger in every block. The number of channels in outer 1x1
  253. convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
  254. channels, and in Wide ResNet-50-2 has 2048-1024-2048.
  255. Args:
  256. pretrained (bool): If True, returns a model pre-trained on ImageNet
  257. progress (bool): If True, displays a progress bar of the download to stderr
  258. """
  259. kwargs['width_per_group'] = 64 * 2
  260. return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3],
  261. pretrained, progress, **kwargs)
  262. def wide_resnet101_2(pretrained=False, progress=True, **kwargs):
  263. r"""Wide ResNet-101-2 model from
  264. `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
  265. The model is the same as ResNet except for the bottleneck number of channels
  266. which is twice larger in every block. The number of channels in outer 1x1
  267. convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
  268. channels, and in Wide ResNet-50-2 has 2048-1024-2048.
  269. Args:
  270. pretrained (bool): If True, returns a model pre-trained on ImageNet
  271. progress (bool): If True, displays a progress bar of the download to stderr
  272. """
  273. kwargs['width_per_group'] = 64 * 2
  274. return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3],
  275. pretrained, progress, **kwargs)
Tip!

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

Comments

Loading...