yolov1_backbone.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import torch
  2. import torch.nn as nn
  3. import torch.utils.model_zoo as model_zoo
  4. __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
  5. 'resnet152']
  6. model_urls = {
  7. 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
  8. 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
  9. 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
  10. 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
  11. 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
  12. }
  13. # --------------------- Basic Module -----------------------
  14. def conv3x3(in_planes, out_planes, stride=1):
  15. """3x3 convolution with padding"""
  16. return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
  17. padding=1, bias=False)
  18. def conv1x1(in_planes, out_planes, stride=1):
  19. """1x1 convolution"""
  20. return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
  21. class BasicBlock(nn.Module):
  22. expansion = 1
  23. def __init__(self, inplanes, planes, stride=1, downsample=None):
  24. super(BasicBlock, self).__init__()
  25. self.conv1 = conv3x3(inplanes, planes, stride)
  26. self.bn1 = nn.BatchNorm2d(planes)
  27. self.relu = nn.ReLU(inplace=True)
  28. self.conv2 = conv3x3(planes, planes)
  29. self.bn2 = nn.BatchNorm2d(planes)
  30. self.downsample = downsample
  31. self.stride = stride
  32. def forward(self, x):
  33. identity = x
  34. out = self.conv1(x)
  35. out = self.bn1(out)
  36. out = self.relu(out)
  37. out = self.conv2(out)
  38. out = self.bn2(out)
  39. if self.downsample is not None:
  40. identity = self.downsample(x)
  41. out += identity
  42. out = self.relu(out)
  43. return out
  44. class Bottleneck(nn.Module):
  45. expansion = 4
  46. def __init__(self, inplanes, planes, stride=1, downsample=None):
  47. super(Bottleneck, self).__init__()
  48. self.conv1 = conv1x1(inplanes, planes)
  49. self.bn1 = nn.BatchNorm2d(planes)
  50. self.conv2 = conv3x3(planes, planes, stride)
  51. self.bn2 = nn.BatchNorm2d(planes)
  52. self.conv3 = conv1x1(planes, planes * self.expansion)
  53. self.bn3 = nn.BatchNorm2d(planes * self.expansion)
  54. self.relu = nn.ReLU(inplace=True)
  55. self.downsample = downsample
  56. self.stride = stride
  57. def forward(self, x):
  58. identity = x
  59. out = self.conv1(x)
  60. out = self.bn1(out)
  61. out = self.relu(out)
  62. out = self.conv2(out)
  63. out = self.bn2(out)
  64. out = self.relu(out)
  65. out = self.conv3(out)
  66. out = self.bn3(out)
  67. if self.downsample is not None:
  68. identity = self.downsample(x)
  69. out += identity
  70. out = self.relu(out)
  71. return out
  72. # --------------------- ResNet -----------------------
  73. class ResNet(nn.Module):
  74. def __init__(self, block, layers, zero_init_residual=False):
  75. super(ResNet, self).__init__()
  76. self.inplanes = 64
  77. self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
  78. bias=False)
  79. self.bn1 = nn.BatchNorm2d(64)
  80. self.relu = nn.ReLU(inplace=True)
  81. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  82. self.layer1 = self._make_layer(block, 64, layers[0])
  83. self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
  84. self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
  85. self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
  86. for m in self.modules():
  87. if isinstance(m, nn.Conv2d):
  88. nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
  89. elif isinstance(m, nn.BatchNorm2d):
  90. nn.init.constant_(m.weight, 1)
  91. nn.init.constant_(m.bias, 0)
  92. # Zero-initialize the last BN in each residual branch,
  93. # so that the residual branch starts with zeros, and each residual block behaves like an identity.
  94. # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
  95. if zero_init_residual:
  96. for m in self.modules():
  97. if isinstance(m, Bottleneck):
  98. nn.init.constant_(m.bn3.weight, 0)
  99. elif isinstance(m, BasicBlock):
  100. nn.init.constant_(m.bn2.weight, 0)
  101. def _make_layer(self, block, planes, blocks, stride=1):
  102. downsample = None
  103. if stride != 1 or self.inplanes != planes * block.expansion:
  104. downsample = nn.Sequential(
  105. conv1x1(self.inplanes, planes * block.expansion, stride),
  106. nn.BatchNorm2d(planes * block.expansion),
  107. )
  108. layers = []
  109. layers.append(block(self.inplanes, planes, stride, downsample))
  110. self.inplanes = planes * block.expansion
  111. for _ in range(1, blocks):
  112. layers.append(block(self.inplanes, planes))
  113. return nn.Sequential(*layers)
  114. def forward(self, x):
  115. """
  116. Input:
  117. x: (Tensor) -> [B, C, H, W]
  118. Output:
  119. c5: (Tensor) -> [B, C, H/32, W/32]
  120. """
  121. c1 = self.conv1(x) # [B, C, H/2, W/2]
  122. c1 = self.bn1(c1) # [B, C, H/2, W/2]
  123. c1 = self.relu(c1) # [B, C, H/2, W/2]
  124. c2 = self.maxpool(c1) # [B, C, H/4, W/4]
  125. c2 = self.layer1(c2) # [B, C, H/4, W/4]
  126. c3 = self.layer2(c2) # [B, C, H/8, W/8]
  127. c4 = self.layer3(c3) # [B, C, H/16, W/16]
  128. c5 = self.layer4(c4) # [B, C, H/32, W/32]
  129. return c5
  130. # --------------------- Fsnctions -----------------------
  131. def resnet18(pretrained=False, **kwargs):
  132. """Constructs a ResNet-18 model.
  133. Args:
  134. pretrained (bool): If True, returns a model pre-trained on ImageNet
  135. """
  136. model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
  137. if pretrained:
  138. # strict = False as we don't need fc layer params.
  139. model.load_state_dict(model_zoo.load_url(model_urls['resnet18']), strict=False)
  140. return model
  141. def resnet34(pretrained=False, **kwargs):
  142. """Constructs a ResNet-34 model.
  143. Args:
  144. pretrained (bool): If True, returns a model pre-trained on ImageNet
  145. """
  146. model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
  147. if pretrained:
  148. model.load_state_dict(model_zoo.load_url(model_urls['resnet34']), strict=False)
  149. return model
  150. def resnet50(pretrained=False, **kwargs):
  151. """Constructs a ResNet-50 model.
  152. Args:
  153. pretrained (bool): If True, returns a model pre-trained on ImageNet
  154. """
  155. model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
  156. if pretrained:
  157. model.load_state_dict(model_zoo.load_url(model_urls['resnet50']), strict=False)
  158. return model
  159. def resnet101(pretrained=False, **kwargs):
  160. """Constructs a ResNet-101 model.
  161. Args:
  162. pretrained (bool): If True, returns a model pre-trained on ImageNet
  163. """
  164. model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
  165. if pretrained:
  166. model.load_state_dict(model_zoo.load_url(model_urls['resnet101']), strict=False)
  167. return model
  168. def resnet152(pretrained=False, **kwargs):
  169. """Constructs a ResNet-152 model.
  170. Args:
  171. pretrained (bool): If True, returns a model pre-trained on ImageNet
  172. """
  173. model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
  174. if pretrained:
  175. model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))
  176. return model
  177. ## build resnet
  178. def build_backbone(model_name='resnet18', pretrained=False):
  179. if model_name == 'resnet18':
  180. model = resnet18(pretrained)
  181. feat_dim = 512
  182. elif model_name == 'resnet34':
  183. model = resnet34(pretrained)
  184. feat_dim = 512
  185. elif model_name == 'resnet50':
  186. model = resnet34(pretrained)
  187. feat_dim = 2048
  188. elif model_name == 'resnet101':
  189. model = resnet34(pretrained)
  190. feat_dim = 2048
  191. return model, feat_dim
  192. if __name__=='__main__':
  193. model, feat_dim = build_backbone(model_name='resnet18', pretrained=True)
  194. print(model)
  195. input = torch.randn(1, 3, 512, 512)
  196. output = model(input)