res2net.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import torch.nn as nn
  2. import math
  3. import torch.utils.model_zoo as model_zoo
  4. import torch
  5. import torch.nn.functional as F
  6. __all__ = ['Res2Net', 'res2net50']
  7. class Bottle2neck(nn.Module):
  8. expansion = 4
  9. def __init__(self, inplanes, planes, stride=1, downsample=None, baseWidth=26, scale = 4, stype='normal'):
  10. """ Constructor
  11. Args:
  12. inplanes: input channel dimensionality
  13. planes: output channel dimensionality
  14. stride: conv stride. Replaces pooling layer.
  15. downsample: None when stride = 1
  16. baseWidth: basic width of conv3x3
  17. scale: number of scale.
  18. type: 'normal': normal set. 'stage': first block of a new stage.
  19. """
  20. super(Bottle2neck, self).__init__()
  21. width = int(math.floor(planes * (baseWidth/64.0)))
  22. self.conv1 = nn.Conv2d(inplanes, width*scale, kernel_size=1, bias=False)
  23. self.bn1 = nn.BatchNorm2d(width*scale)
  24. if scale == 1:
  25. self.nums = 1
  26. else:
  27. self.nums = scale -1
  28. if stype == 'stage':
  29. self.pool = nn.AvgPool2d(kernel_size=3, stride = stride, padding=1)
  30. convs = []
  31. bns = []
  32. for i in range(self.nums):
  33. convs.append(nn.Conv2d(width, width, kernel_size=3, stride = stride, padding=1, bias=False))
  34. bns.append(nn.BatchNorm2d(width))
  35. self.convs = nn.ModuleList(convs)
  36. self.bns = nn.ModuleList(bns)
  37. self.conv3 = nn.Conv2d(width*scale, planes * self.expansion, kernel_size=1, bias=False)
  38. self.bn3 = nn.BatchNorm2d(planes * self.expansion)
  39. self.relu = nn.ReLU(inplace=True)
  40. self.downsample = downsample
  41. self.stype = stype
  42. self.scale = scale
  43. self.width = width
  44. def forward(self, x):
  45. residual = x
  46. out = self.conv1(x)
  47. out = self.bn1(out)
  48. out = self.relu(out)
  49. spx = torch.split(out, self.width, 1)
  50. for i in range(self.nums):
  51. if i==0 or self.stype=='stage':
  52. sp = spx[i]
  53. else:
  54. sp = sp + spx[i]
  55. sp = self.convs[i](sp)
  56. sp = self.relu(self.bns[i](sp))
  57. if i==0:
  58. out = sp
  59. else:
  60. out = torch.cat((out, sp), 1)
  61. if self.scale != 1 and self.stype=='normal':
  62. out = torch.cat((out, spx[self.nums]),1)
  63. elif self.scale != 1 and self.stype=='stage':
  64. out = torch.cat((out, self.pool(spx[self.nums])),1)
  65. out = self.conv3(out)
  66. out = self.bn3(out)
  67. if self.downsample is not None:
  68. residual = self.downsample(x)
  69. out += residual
  70. out = self.relu(out)
  71. return out
  72. class Res2Net(nn.Module):
  73. def __init__(self, block, layers, baseWidth = 26, scale = 4, num_classes=1000):
  74. self.inplanes = 64
  75. super(Res2Net, self).__init__()
  76. self.baseWidth = baseWidth
  77. self.scale = scale
  78. self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
  79. bias=False)
  80. self.bn1 = nn.BatchNorm2d(64)
  81. self.relu = nn.ReLU(inplace=True)
  82. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  83. self.layer1 = self._make_layer(block, 64, layers[0])
  84. self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
  85. self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
  86. self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
  87. self.toplayer = nn.Conv2d(2048, 256, kernel_size=1, stride=1, padding=0)
  88. self.latlayer1 = nn.Conv2d(1024, 256, kernel_size=1, stride=1, padding=0)
  89. self.latlayer2 = nn.Conv2d( 512, 256, kernel_size=1, stride=1, padding=0)
  90. self.latlayer3 = nn.Conv2d( 256, 256, kernel_size=1, stride=1, padding=0)
  91. self.smooth1 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
  92. self.smooth2 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
  93. self.smooth3 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
  94. for m in self.modules():
  95. if isinstance(m, nn.Conv2d):
  96. nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
  97. elif isinstance(m, nn.BatchNorm2d):
  98. nn.init.constant_(m.weight, 1)
  99. nn.init.constant_(m.bias, 0)
  100. self._load_pretrained_model()
  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. nn.Conv2d(self.inplanes, planes * block.expansion,
  106. kernel_size=1, stride=stride, bias=False),
  107. nn.BatchNorm2d(planes * block.expansion),
  108. )
  109. layers = []
  110. layers.append(block(self.inplanes, planes, stride, downsample=downsample,
  111. stype='stage', baseWidth = self.baseWidth, scale=self.scale))
  112. self.inplanes = planes * block.expansion
  113. for i in range(1, blocks):
  114. layers.append(block(self.inplanes, planes, baseWidth = self.baseWidth, scale=self.scale))
  115. return nn.Sequential(*layers)
  116. def forward(self, input):
  117. # Bottom-up
  118. x = self.conv1(input)
  119. x = self.bn1(x)
  120. x = self.relu(x)
  121. c1 = self.maxpool(x)
  122. c2 = self.layer1(c1) # x4
  123. c3 = self.layer2(c2) #x8
  124. c4 = self.layer3(c3) #x16
  125. c5 = self.layer4(c4) #x32
  126. # Top-down
  127. p5 = self.toplayer(c5)
  128. p4 = nn.functional.upsample(p5, size=c4.size()[2:], mode='bilinear') + self.latlayer1(c4)
  129. p3 = nn.functional.upsample(p4, size=c3.size()[2:], mode='bilinear') + self.latlayer2(c3)
  130. p2 = nn.functional.upsample(p3, size=c2.size()[2:], mode='bilinear') + self.latlayer3(c2)
  131. p4 = self.smooth1(p4)
  132. p3 = self.smooth2(p3)
  133. p2 = self.smooth3(p2)
  134. return p2, p3, p4, p5
  135. def _load_pretrained_model(self):
  136. pretrain_dict = model_zoo.load_url('https://shanghuagao.oss-cn-beijing.aliyuncs.com/res2net/res2net50_26w_4s-06e79181.pth')
  137. model_dict = {}
  138. state_dict = self.state_dict()
  139. for k, v in pretrain_dict.items():
  140. if k in state_dict:
  141. model_dict[k] = v
  142. state_dict.update(model_dict)
  143. self.load_state_dict(state_dict)
  144. def res2net50_FPN(pretrained=True, **kwargs):
  145. """Constructs a Res2Net-50 model.
  146. Res2Net-50 refers to the Res2Net-50_26w_4s.
  147. Args:
  148. pretrained (bool): If True, returns a model pre-trained on ImageNet
  149. """
  150. model = Res2Net(Bottle2neck, [3, 4, 6, 3], baseWidth = 26, scale = 4, **kwargs)
  151. return model