fpn.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import math
  2. import torch.nn as nn
  3. import torch.utils.model_zoo as model_zoo
  4. def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
  5. """3x3 convolution with padding"""
  6. return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
  7. padding=dilation, groups=groups, bias=False, dilation=dilation)
  8. def conv1x1(in_planes, out_planes, stride=1):
  9. """1x1 convolution"""
  10. return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
  11. class BasicBlock(nn.Module):
  12. expansion = 1
  13. def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, BatchNorm=None, groups=1,
  14. base_width=64):
  15. super(BasicBlock, self).__init__()
  16. if BatchNorm is None:
  17. BatchNorm = nn.BatchNorm2d
  18. if groups != 1 or base_width != 64:
  19. raise ValueError('BasicBlock only supports groups=1 and base_width=64')
  20. if dilation > 1:
  21. raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
  22. # Both self.conv1 and self.downsample layers downsample the input when stride != 1
  23. self.conv1 = conv3x3(inplanes, planes, stride)
  24. self.bn1 = BatchNorm(planes)
  25. self.relu = nn.ReLU(inplace=True)
  26. self.conv2 = conv3x3(planes, planes)
  27. self.bn2 = BatchNorm(planes)
  28. self.downsample = downsample
  29. self.stride = stride
  30. def forward(self, x):
  31. identity = x
  32. out = self.conv1(x)
  33. out = self.bn1(out)
  34. out = self.relu(out)
  35. out = self.conv2(out)
  36. out = self.bn2(out)
  37. if self.downsample is not None:
  38. identity = self.downsample(x)
  39. out += identity
  40. out = self.relu(out)
  41. return out
  42. class Bottleneck(nn.Module):
  43. expansion = 4
  44. def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, BatchNorm=None, groups=1,
  45. base_width=64):
  46. super(Bottleneck, self).__init__()
  47. width = int(planes * (base_width / 64.)) * groups
  48. self.conv1 = nn.Conv2d(inplanes, width, kernel_size=1, bias=False)
  49. self.bn1 = BatchNorm(width)
  50. self.conv2 = nn.Conv2d(width, width, kernel_size=3, stride=stride,
  51. dilation=dilation, padding=dilation, bias=False, groups=groups)
  52. self.bn2 = BatchNorm(width)
  53. self.conv3 = nn.Conv2d(width, planes * 4, kernel_size=1, bias=False)
  54. self.bn3 = BatchNorm(planes * 4)
  55. self.relu = nn.ReLU(inplace=True)
  56. self.downsample = downsample
  57. self.stride = stride
  58. self.dilation = dilation
  59. def forward(self, x):
  60. residual = x
  61. out = self.conv1(x)
  62. out = self.bn1(out)
  63. out = self.relu(out)
  64. out = self.conv2(out)
  65. out = self.bn2(out)
  66. out = self.relu(out)
  67. out = self.conv3(out)
  68. out = self.bn3(out)
  69. if self.downsample is not None:
  70. residual = self.downsample(x)
  71. out += residual
  72. out = self.relu(out)
  73. return out
  74. class ResNet(nn.Module):
  75. def __init__(self, arch, block, layers, output_stride, BatchNorm, pretrained=True):
  76. self.inplanes = 64
  77. self.layers = layers
  78. self.arch = arch
  79. super(ResNet, self).__init__()
  80. blocks = [1, 2, 4]
  81. if output_stride == 16:
  82. strides = [1, 2, 2, 1]
  83. dilations = [1, 1, 1, 2]
  84. elif output_stride == 8:
  85. strides = [1, 2, 1, 1]
  86. dilations = [1, 1, 2, 4]
  87. else:
  88. strides = [1, 2, 2, 2]
  89. dilations = [1, 1, 1, 1]
  90. if arch == 'resnext50':
  91. self.base_width = 4
  92. self.groups = 32
  93. else:
  94. self.base_width = 64
  95. self.groups = 1
  96. # Modules
  97. self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
  98. bias=False)
  99. self.bn1 = BatchNorm(64)
  100. self.relu = nn.ReLU(inplace=True)
  101. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  102. self.layer1 = self._make_layer(block, 64, layers[0], stride=strides[0], dilation=dilations[0], BatchNorm=BatchNorm)
  103. self.layer2 = self._make_layer(block, 128, layers[1], stride=strides[1], dilation=dilations[1], BatchNorm=BatchNorm)
  104. self.layer3 = self._make_layer(block, 256, layers[2], stride=strides[2], dilation=dilations[2], BatchNorm=BatchNorm)
  105. if self.arch == 'resnet18':
  106. self.layer4 = self._make_layer(block, 512, layers[3], stride=strides[3], dilation=dilations[3], BatchNorm=BatchNorm)
  107. else:
  108. self.layer4 = self._make_MG_unit(block, 512, blocks=blocks, stride=strides[3], dilation=dilations[3], BatchNorm=BatchNorm)
  109. # self.layer4 = self._make_layer(block, 512, layers[3], stride=strides[3], dilation=dilations[3], BatchNorm=BatchNorm)
  110. if self.arch == 'resnet18':
  111. self.toplayer = nn.Conv2d(512, 256, kernel_size=1, stride=1, padding=0)
  112. self.latlayer1 = nn.Conv2d(256, 256, kernel_size=1, stride=1, padding=0)
  113. self.latlayer2 = nn.Conv2d( 128, 256, kernel_size=1, stride=1, padding=0)
  114. self.latlayer3 = nn.Conv2d( 64, 256, kernel_size=1, stride=1, padding=0)
  115. else:
  116. self.toplayer = nn.Conv2d(2048, 256, kernel_size=1, stride=1, padding=0)
  117. self.latlayer1 = nn.Conv2d(1024, 256, kernel_size=1, stride=1, padding=0)
  118. self.latlayer2 = nn.Conv2d( 512, 256, kernel_size=1, stride=1, padding=0)
  119. self.latlayer3 = nn.Conv2d( 256, 256, kernel_size=1, stride=1, padding=0)
  120. self.smooth1 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
  121. self.smooth2 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
  122. self.smooth3 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
  123. self._init_weight()
  124. if pretrained:
  125. self._load_pretrained_model()
  126. def _make_layer(self, block, planes, blocks, stride=1, dilation=1, BatchNorm=None):
  127. downsample = None
  128. if stride != 1 or self.inplanes != planes * block.expansion:
  129. downsample = nn.Sequential(
  130. nn.Conv2d(self.inplanes, planes * block.expansion,
  131. kernel_size=1, stride=stride, bias=False),
  132. BatchNorm(planes * block.expansion),
  133. )
  134. layers = []
  135. layers.append(block(self.inplanes, planes, stride, dilation, downsample, BatchNorm, groups=self.groups, base_width=self.base_width))
  136. self.inplanes = planes * block.expansion
  137. for i in range(1, blocks):
  138. layers.append(block(self.inplanes, planes, dilation=dilation, BatchNorm=BatchNorm, groups=self.groups, base_width=self.base_width))
  139. return nn.Sequential(*layers)
  140. def _make_MG_unit(self, block, planes, blocks, stride=1, dilation=1, BatchNorm=None):
  141. downsample = None
  142. if stride != 1 or self.inplanes != planes * block.expansion:
  143. downsample = nn.Sequential(
  144. nn.Conv2d(self.inplanes, planes * block.expansion,
  145. kernel_size=1, stride=stride, bias=False),
  146. BatchNorm(planes * block.expansion),
  147. )
  148. layers = []
  149. layers.append(block(self.inplanes, planes, stride, dilation=blocks[0]*dilation,
  150. downsample=downsample, BatchNorm=BatchNorm, groups=self.groups, base_width=self.base_width))
  151. self.inplanes = planes * block.expansion
  152. for i in range(1, len(blocks)):
  153. layers.append(block(self.inplanes, planes, stride=1,
  154. dilation=blocks[i]*dilation, BatchNorm=BatchNorm, groups=self.groups, base_width=self.base_width))
  155. return nn.Sequential(*layers)
  156. def forward(self, input):
  157. # Bottom-up
  158. x = self.conv1(input)
  159. x = self.bn1(x)
  160. x = self.relu(x)
  161. c1 = self.maxpool(x)
  162. c2 = self.layer1(c1) # x4
  163. c3 = self.layer2(c2) #x8
  164. c4 = self.layer3(c3) #x16
  165. c5 = self.layer4(c4) #x16
  166. # Top-down
  167. p5 = self.toplayer(c5)
  168. p4 = nn.functional.upsample(p5, size=c4.size()[2:], mode='bilinear') + self.latlayer1(c4)
  169. p3 = nn.functional.upsample(p4, size=c3.size()[2:], mode='bilinear') + self.latlayer2(c3)
  170. p2 = nn.functional.upsample(p3, size=c2.size()[2:], mode='bilinear') + self.latlayer3(c2)
  171. p4 = self.smooth1(p4)
  172. p3 = self.smooth2(p3)
  173. p2 = self.smooth3(p2)
  174. return p2, p3, p4, p5
  175. def _init_weight(self):
  176. for m in self.modules():
  177. if isinstance(m, nn.Conv2d):
  178. n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
  179. m.weight.data.normal_(0, math.sqrt(2. / n))
  180. elif isinstance(m, nn.BatchNorm2d):
  181. m.weight.data.fill_(1)
  182. m.bias.data.zero_()
  183. def _load_pretrained_model(self):
  184. if self.arch == 'resnet101':
  185. pretrain_dict = model_zoo.load_url('https://download.pytorch.org/models/resnet101-5d3b4d8f.pth')
  186. elif self.arch == 'resnet50':
  187. pretrain_dict = model_zoo.load_url('https://download.pytorch.org/models/resnet50-19c8e357.pth')
  188. elif self.arch == 'resnet18':
  189. pretrain_dict = model_zoo.load_url('https://download.pytorch.org/models/resnet18-5c106cde.pth')
  190. elif self.arch == 'resnext50':
  191. pretrain_dict = model_zoo.load_url('https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth')
  192. model_dict = {}
  193. state_dict = self.state_dict()
  194. for k, v in pretrain_dict.items():
  195. if k in state_dict:
  196. model_dict[k] = v
  197. state_dict.update(model_dict)
  198. self.load_state_dict(state_dict)
  199. def FPN101(output_stride, BatchNorm=nn.BatchNorm2d, pretrained=True):
  200. """Constructs a ResNet-101 model.
  201. Args:
  202. pretrained (bool): If True, returns a model pre-trained on ImageNet
  203. """
  204. model = ResNet('resnet101', Bottleneck, [3, 4, 23, 3], output_stride, BatchNorm, pretrained=pretrained)
  205. return model
  206. def FPN50(output_stride, BatchNorm=nn.BatchNorm2d, pretrained=True):
  207. """Constructs a ResNet-50 model.
  208. Args:
  209. pretrained (bool): If True, returns a model pre-trained on ImageNet
  210. """
  211. model = ResNet('resnet50', Bottleneck, [3, 4, 6, 3], output_stride, BatchNorm, pretrained=pretrained)
  212. return model
  213. def FPN18(output_stride, BatchNorm=nn.BatchNorm2d, pretrained=True):
  214. model = ResNet('resnet18', BasicBlock, [2, 2, 2, 2], output_stride, BatchNorm, pretrained=pretrained)
  215. return model
  216. def ResNext50_FPN(output_stride, BatchNorm=nn.BatchNorm2d, pretrained=True):
  217. model = ResNet('resnext50', Bottleneck, [3, 4, 6, 3], output_stride, BatchNorm, pretrained=pretrained)
  218. return model
  219. if __name__ == "__main__":
  220. import torch
  221. model = FPN101(BatchNorm=nn.BatchNorm2d, pretrained=True, output_stride=8)
  222. input = torch.rand(1, 3, 480, 640)
  223. output = model(input)
  224. for out in output:
  225. print(out.size())
  226. # print(low_level_feat.size())