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

model_define.py 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import os
  2. import torch
  3. from torch import nn
  4. import torch.nn.functional as F
  5. from collections import OrderedDict
  6. class ASPP(nn.Module):
  7. # have bias and relu, no bn
  8. def __init__(self, in_channel=512, depth=256):
  9. super().__init__()
  10. # global average pooling : init nn.AdaptiveAvgPool2d ;also forward torch.mean(,,keep_dim=True)
  11. self.mean = nn.AdaptiveAvgPool2d((1, 1))
  12. self.conv = nn.Sequential(nn.Conv2d(in_channel, depth, 1, 1),
  13. nn.ReLU(inplace=True))
  14. self.atrous_block1 = nn.Sequential(nn.Conv2d(in_channel, depth, 1, 1),
  15. nn.ReLU(inplace=True))
  16. self.atrous_block6 = nn.Sequential(
  17. nn.Conv2d(in_channel, depth, 3, 1, padding=3, dilation=3),
  18. nn.ReLU(inplace=True))
  19. self.atrous_block12 = nn.Sequential(
  20. nn.Conv2d(in_channel, depth, 3, 1, padding=6, dilation=6),
  21. nn.ReLU(inplace=True))
  22. self.atrous_block18 = nn.Sequential(
  23. nn.Conv2d(in_channel, depth, 3, 1, padding=9, dilation=9),
  24. nn.ReLU(inplace=True))
  25. self.conv_1x1_output = nn.Sequential(nn.Conv2d(depth * 5, depth, 1, 1),
  26. nn.ReLU(inplace=True))
  27. def forward(self, x):
  28. size = x.shape[2:]
  29. image_features = self.mean(x)
  30. image_features = self.conv(image_features)
  31. image_features = F.interpolate(image_features,
  32. size=size,
  33. mode='bilinear',
  34. align_corners=True)
  35. atrous_block1 = self.atrous_block1(x)
  36. atrous_block6 = self.atrous_block6(x)
  37. atrous_block12 = self.atrous_block12(x)
  38. atrous_block18 = self.atrous_block18(x)
  39. net = self.conv_1x1_output(
  40. torch.cat([
  41. image_features, atrous_block1, atrous_block6, atrous_block12,
  42. atrous_block18
  43. ],
  44. dim=1))
  45. return net
  46. class ResNet(nn.Module):
  47. def __init__(self, block, layers, num_classes=18, zero_init_residual=False,
  48. groups=1, width_per_group=64, replace_stride_with_dilation=None,
  49. norm_layer=None):
  50. super(ResNet, self).__init__()
  51. if norm_layer is None:
  52. norm_layer = nn.BatchNorm2d
  53. self._norm_layer = norm_layer
  54. self.inplanes = 64
  55. self.dilation = 1
  56. if replace_stride_with_dilation is None:
  57. # each element in the tuple indicates if we should replace
  58. # the 2x2 stride with a dilated convolution instead
  59. replace_stride_with_dilation = [False, False, False]
  60. if len(replace_stride_with_dilation) != 3:
  61. raise ValueError("replace_stride_with_dilation should be None "
  62. "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
  63. self.groups = groups
  64. self.base_width = width_per_group
  65. self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
  66. bias=False)
  67. self.bn1 = norm_layer(self.inplanes)
  68. self.relu = nn.ReLU(inplace=True)
  69. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  70. self.layer1 = self._make_layer(block, 64, layers[0])
  71. self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
  72. dilate=replace_stride_with_dilation[0])
  73. self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
  74. dilate=replace_stride_with_dilation[1])
  75. self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
  76. dilate=replace_stride_with_dilation[2])
  77. self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
  78. self.fc = nn.Linear(512 * block.expansion, num_classes)
  79. for m in self.modules():
  80. if isinstance(m, nn.Conv2d):
  81. nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
  82. elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
  83. nn.init.constant_(m.weight, 1)
  84. nn.init.constant_(m.bias, 0)
  85. # Zero-initialize the last BN in each residual branch,
  86. # so that the residual branch starts with zeros, and each residual block behaves like an identity.
  87. # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
  88. if zero_init_residual:
  89. for m in self.modules():
  90. if isinstance(m, Bottleneck):
  91. nn.init.constant_(m.bn3.weight, 0)
  92. elif isinstance(m, BasicBlock):
  93. nn.init.constant_(m.bn2.weight, 0)
  94. def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
  95. norm_layer = self._norm_layer
  96. downsample = None
  97. previous_dilation = self.dilation
  98. if dilate:
  99. self.dilation *= stride
  100. stride = 1
  101. if stride != 1 or self.inplanes != planes * block.expansion:
  102. downsample = nn.Sequential(
  103. conv1x1(self.inplanes, planes * block.expansion, stride),
  104. norm_layer(planes * block.expansion),
  105. )
  106. layers = []
  107. layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
  108. self.base_width, previous_dilation, norm_layer))
  109. self.inplanes = planes * block.expansion
  110. for _ in range(1, blocks):
  111. layers.append(block(self.inplanes, planes, groups=self.groups,
  112. base_width=self.base_width, dilation=self.dilation,
  113. norm_layer=norm_layer))
  114. return nn.Sequential(*layers)
  115. def forward(self, x):
  116. x = self.conv1(x)
  117. x = self.bn1(x)
  118. x = self.relu(x)
  119. x = self.maxpool(x)
  120. x = self.layer1(x)
  121. x = self.layer2(x)
  122. x = self.layer3(x)
  123. x = self.layer4(x)
  124. x = self.avgpool(x)
  125. x = torch.flatten(x, 1)
  126. x = self.fc(x)
  127. return x
  128. def _resnet(arch, block, layers, pretrained, progress, **kwargs):
  129. model = ResNet(block, layers, **kwargs)
  130. return model
  131. def resnet50(pretrained=False, progress=True, **kwargs):
  132. return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,
  133. **kwargs)
  134. def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
  135. """3x3 convolution with padding"""
  136. return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
  137. padding=dilation, groups=groups, bias=False, dilation=dilation)
  138. def conv1x1(in_planes, out_planes, stride=1):
  139. """1x1 convolution"""
  140. return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
  141. class BasicBlock(nn.Module):
  142. expansion = 1
  143. def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
  144. base_width=64, dilation=1, norm_layer=None):
  145. super(BasicBlock, self).__init__()
  146. if norm_layer is None:
  147. norm_layer = nn.BatchNorm2d
  148. if groups != 1 or base_width != 64:
  149. raise ValueError('BasicBlock only supports groups=1 and base_width=64')
  150. if dilation > 1:
  151. raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
  152. # Both self.conv1 and self.downsample layers downsample the input when stride != 1
  153. self.conv1 = conv3x3(inplanes, planes, stride)
  154. self.bn1 = norm_layer(planes)
  155. self.relu = nn.ReLU(inplace=True)
  156. self.conv2 = conv3x3(planes, planes)
  157. self.bn2 = norm_layer(planes)
  158. self.downsample = downsample
  159. self.stride = stride
  160. def forward(self, x):
  161. identity = x
  162. out = self.conv1(x)
  163. out = self.bn1(out)
  164. out = self.relu(out)
  165. out = self.conv2(out)
  166. out = self.bn2(out)
  167. if self.downsample is not None:
  168. identity = self.downsample(x)
  169. out += identity
  170. out = self.relu(out)
  171. return out
  172. class Bottleneck(nn.Module):
  173. expansion = 4
  174. def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
  175. base_width=64, dilation=1, norm_layer=None):
  176. super(Bottleneck, self).__init__()
  177. if norm_layer is None:
  178. norm_layer = nn.BatchNorm2d
  179. width = int(planes * (base_width / 64.)) * groups
  180. # Both self.conv2 and self.downsample layers downsample the input when stride != 1
  181. self.conv1 = conv1x1(inplanes, width)
  182. self.bn1 = norm_layer(width)
  183. self.conv2 = conv3x3(width, width, stride, groups, dilation)
  184. self.bn2 = norm_layer(width)
  185. self.conv3 = conv1x1(width, planes * self.expansion)
  186. self.bn3 = norm_layer(planes * self.expansion)
  187. self.relu = nn.ReLU(inplace=True)
  188. self.downsample = downsample
  189. self.stride = stride
  190. def forward(self, x):
  191. identity = x
  192. out = self.conv1(x)
  193. out = self.bn1(out)
  194. out = self.relu(out)
  195. out = self.conv2(out)
  196. out = self.bn2(out)
  197. out = self.relu(out)
  198. out = self.conv3(out)
  199. out = self.bn3(out)
  200. if self.downsample is not None:
  201. identity = self.downsample(x)
  202. out += identity
  203. out = self.relu(out)
  204. return out
  205. class Deeplab_v3(nn.Module):
  206. # in_channel = 3 fine-tune
  207. def __init__(self, class_number=18):
  208. super().__init__()
  209. encoder = resnet50()
  210. self.start = nn.Sequential(encoder.conv1, encoder.bn1, encoder.relu)
  211. self.maxpool = encoder.maxpool
  212. self.low_feature1 = nn.Sequential(nn.Conv2d(
  213. 64, 32, 1, 1), nn.BatchNorm2d(32), nn.ReLU(inplace=True))
  214. self.low_feature3 = nn.Sequential(nn.Conv2d(
  215. 256, 64, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True))
  216. self.low_feature4 = nn.Sequential(nn.Conv2d(
  217. 512, 128, 1, 1), nn.BatchNorm2d(128), nn.ReLU(inplace=True))
  218. self.layer1 = encoder.layer1 #256
  219. self.layer2 = encoder.layer2 #512
  220. self.layer3 = encoder.layer3 #1024
  221. self.layer4 = encoder.layer4 #2048
  222. self.aspp = ASPP(in_channel=2048, depth=256)
  223. self.conv_cat4 = nn.Sequential(nn.Conv2d(256 + 128, 256, 3, 1, padding=1), nn.BatchNorm2d(256), nn.ReLU(inplace=True))
  224. self.conv_cat3 = nn.Sequential(nn.Conv2d(256 + 64, 256, 3, 1, padding=1), nn.BatchNorm2d(256), nn.ReLU(inplace=True),
  225. nn.Conv2d(256, 64, 3, 1, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True))
  226. self.conv_cat1 = nn.Sequential(nn.Conv2d(64 + 32, 64, 3, 1, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True),
  227. nn.Conv2d(64, 18, 3, 1, padding=1))
  228. def forward(self, x):
  229. size0 = x.shape[2:] # need upsample input size
  230. x1 = self.start(x) # 64, 128*128
  231. x2 = self.maxpool(x1) # 64, 64*64
  232. x3 = self.layer1(x2) # 256, 64*64
  233. x4 = self.layer2(x3) # 512, 32*32
  234. x5 = self.layer3(x4) # 1024,16*16
  235. x = self.layer4(x5) # 2048,8*8
  236. x = self.aspp(x) # 256, 8*8
  237. low_feature1 = self.low_feature1(x1) # 64, 128*128
  238. # low_feature2 = self.low_feature2(x2) # 64, 64*64
  239. low_feature3 = self.low_feature3(x3) # 256, 64*64
  240. low_feature4 = self.low_feature4(x4) # 512, 32*32 -> 128, 32*32
  241. # low_feature5 = self.low_feature5(x5) # 1024,16*16
  242. size1 = low_feature1.shape[2:]
  243. # size2 = low_feature2.shape[2:]
  244. size3 = low_feature3.shape[2:]
  245. size4 = low_feature4.shape[2:]
  246. # size5 = low_feature5.shape[2:]
  247. decoder_feature4 = F.interpolate(x, size=size4, mode='bilinear', align_corners=True)
  248. x = self.conv_cat4(torch.cat([low_feature4, decoder_feature4], dim=1))
  249. decoder_feature3 = F.interpolate(x, size=size3, mode='bilinear', align_corners=True)
  250. x = self.conv_cat3(torch.cat([low_feature3, decoder_feature3], dim=1))
  251. decoder_feature1 = F.interpolate(x, size=size1, mode='bilinear', align_corners=True)
  252. x = self.conv_cat1(torch.cat([low_feature1, decoder_feature1], dim=1))
  253. score = F.interpolate(x,
  254. size=size0,
  255. mode='bilinear',
  256. align_corners=True)
  257. return score
  258. def init_model():
  259. model_path = os.path.join(os.path.dirname(__file__), 'model.pkl')
  260. model = Deeplab_v3()
  261. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  262. model.to(device)
  263. model_state = torch.load(model_path, map_location=device)
  264. new_state_dict = OrderedDict()
  265. for k, v in model_state["model_state_dict"].items():
  266. if k[:7] == "module.":
  267. new_state_dict[k[7:]] = v
  268. else:
  269. new_state_dict[k] = v
  270. model.load_state_dict(new_state_dict)
  271. model.eval()
  272. return model

网络代码复现