fpn.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. import math
  2. from jittor import nn
  3. def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
  4. conv=nn.Conv(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
  5. jt.init.relu_invariant_gauss_(conv.weight, mode="fan_out")
  6. return conv
  7. def conv1x1(in_planes, out_planes, stride=1):
  8. conv=nn.Conv(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
  9. jt.init.relu_invariant_gauss_(conv.weight, mode="fan_out")
  10. return conv
  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()
  26. self.conv2 = conv3x3(planes, planes)
  27. self.bn2 = BatchNorm(planes)
  28. self.downsample = downsample
  29. self.stride = stride
  30. def execute(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()
  56. self.downsample = downsample
  57. self.stride = stride
  58. self.dilation = dilation
  59. def execute(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()
  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. if pretrained:
  124. self._load_pretrained_model()
  125. def _make_layer(self, block, planes, blocks, stride=1, dilation=1, BatchNorm=None):
  126. downsample = None
  127. if stride != 1 or self.inplanes != planes * block.expansion:
  128. downsample = nn.Sequential(
  129. nn.Conv2d(self.inplanes, planes * block.expansion,
  130. kernel_size=1, stride=stride, bias=False),
  131. BatchNorm(planes * block.expansion),
  132. )
  133. layers = []
  134. layers.append(block(self.inplanes, planes, stride, dilation, downsample, BatchNorm, groups=self.groups, base_width=self.base_width))
  135. self.inplanes = planes * block.expansion
  136. for i in range(1, blocks):
  137. layers.append(block(self.inplanes, planes, dilation=dilation, BatchNorm=BatchNorm, groups=self.groups, base_width=self.base_width))
  138. return nn.Sequential(*layers)
  139. def _make_MG_unit(self, block, planes, blocks, stride=1, dilation=1, BatchNorm=None):
  140. downsample = None
  141. if stride != 1 or self.inplanes != planes * block.expansion:
  142. downsample = nn.Sequential(
  143. nn.Conv2d(self.inplanes, planes * block.expansion,
  144. kernel_size=1, stride=stride, bias=False),
  145. BatchNorm(planes * block.expansion),
  146. )
  147. layers = []
  148. layers.append(block(self.inplanes, planes, stride, dilation=blocks[0]*dilation,
  149. downsample=downsample, BatchNorm=BatchNorm, groups=self.groups, base_width=self.base_width))
  150. self.inplanes = planes * block.expansion
  151. for i in range(1, len(blocks)):
  152. layers.append(block(self.inplanes, planes, stride=1,
  153. dilation=blocks[i]*dilation, BatchNorm=BatchNorm, groups=self.groups, base_width=self.base_width))
  154. return nn.Sequential(*layers)
  155. def execute(self, input):
  156. # Bottom-up
  157. x = self.conv1(input)
  158. x = self.bn1(x)
  159. x = self.relu(x)
  160. c1 = self.maxpool(x)
  161. c2 = self.layer1(c1) # x4
  162. c3 = self.layer2(c2) #x8
  163. c4 = self.layer3(c3) #x16
  164. c5 = self.layer4(c4) #x16
  165. # Top-down
  166. p5 = self.toplayer(c5)
  167. p4 = nn.upsample(p5, size=c4.size()[2:], mode='bilinear') + self.latlayer1(c4)
  168. p3 = nn.upsample(p4, size=c3.size()[2:], mode='bilinear') + self.latlayer2(c3)
  169. p2 = nn.upsample(p3, size=c2.size()[2:], mode='bilinear') + self.latlayer3(c2)
  170. p4 = self.smooth1(p4)
  171. p3 = self.smooth2(p3)
  172. p2 = self.smooth3(p2)
  173. return p2, p3, p4, p5
  174. def _load_pretrained_model(self):
  175. self.load("jittorhub://resnet50.pkl")
  176. # pretrain_dict = model_zoo.load_url('https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth')
  177. # model_dict = {}
  178. # state_dict = self.state_dict()
  179. # for k, v in pretrain_dict.items():
  180. # if k in state_dict:
  181. # model_dict[k] = v
  182. # state_dict.update(model_dict)
  183. # self.load_state_dict(state_dict)
  184. def FPN50(output_stride, BatchNorm=nn.BatchNorm2d, pretrained=True):
  185. """Constructs a ResNet-50 model.
  186. Args:
  187. pretrained (bool): If True, returns a model pre-trained on ImageNet
  188. """
  189. model = ResNet('resnet50', Bottleneck, [3, 4, 6, 3], output_stride, BatchNorm, pretrained=pretrained)
  190. return model
  191. model = FPN50(output_stride=16)