You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

356 lines
14KB

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