rec_resnet_fpn.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. #copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. #Licensed under the Apache License, Version 2.0 (the "License");
  4. #you may not use this file except in compliance with the License.
  5. #You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. #Unless required by applicable law or agreed to in writing, software
  10. #distributed under the License is distributed on an "AS IS" BASIS,
  11. #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. #See the License for the specific language governing permissions and
  13. #limitations under the License.
  14. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. from paddle import nn, ParamAttr
  18. from paddle.nn import functional as F
  19. import paddle
  20. import numpy as np
  21. __all__ = ["ResNetFPN"]
  22. class ResNetFPN(nn.Layer):
  23. def __init__(self, in_channels=1, layers=50, **kwargs):
  24. super(ResNetFPN, self).__init__()
  25. supported_layers = {
  26. 18: {
  27. 'depth': [2, 2, 2, 2],
  28. 'block_class': BasicBlock
  29. },
  30. 34: {
  31. 'depth': [3, 4, 6, 3],
  32. 'block_class': BasicBlock
  33. },
  34. 50: {
  35. 'depth': [3, 4, 6, 3],
  36. 'block_class': BottleneckBlock
  37. },
  38. 101: {
  39. 'depth': [3, 4, 23, 3],
  40. 'block_class': BottleneckBlock
  41. },
  42. 152: {
  43. 'depth': [3, 8, 36, 3],
  44. 'block_class': BottleneckBlock
  45. }
  46. }
  47. stride_list = [(2, 2), (2, 2), (1, 1), (1, 1)]
  48. num_filters = [64, 128, 256, 512]
  49. self.depth = supported_layers[layers]['depth']
  50. self.F = []
  51. self.conv = ConvBNLayer(
  52. in_channels=in_channels,
  53. out_channels=64,
  54. kernel_size=7,
  55. stride=2,
  56. act="relu",
  57. name="conv1")
  58. self.block_list = []
  59. in_ch = 64
  60. if layers >= 50:
  61. for block in range(len(self.depth)):
  62. for i in range(self.depth[block]):
  63. if layers in [101, 152] and block == 2:
  64. if i == 0:
  65. conv_name = "res" + str(block + 2) + "a"
  66. else:
  67. conv_name = "res" + str(block + 2) + "b" + str(i)
  68. else:
  69. conv_name = "res" + str(block + 2) + chr(97 + i)
  70. block_list = self.add_sublayer(
  71. "bottleneckBlock_{}_{}".format(block, i),
  72. BottleneckBlock(
  73. in_channels=in_ch,
  74. out_channels=num_filters[block],
  75. stride=stride_list[block] if i == 0 else 1,
  76. name=conv_name))
  77. in_ch = num_filters[block] * 4
  78. self.block_list.append(block_list)
  79. self.F.append(block_list)
  80. else:
  81. for block in range(len(self.depth)):
  82. for i in range(self.depth[block]):
  83. conv_name = "res" + str(block + 2) + chr(97 + i)
  84. if i == 0 and block != 0:
  85. stride = (2, 1)
  86. else:
  87. stride = (1, 1)
  88. basic_block = self.add_sublayer(
  89. conv_name,
  90. BasicBlock(
  91. in_channels=in_ch,
  92. out_channels=num_filters[block],
  93. stride=stride_list[block] if i == 0 else 1,
  94. is_first=block == i == 0,
  95. name=conv_name))
  96. in_ch = basic_block.out_channels
  97. self.block_list.append(basic_block)
  98. out_ch_list = [in_ch // 4, in_ch // 2, in_ch]
  99. self.base_block = []
  100. self.conv_trans = []
  101. self.bn_block = []
  102. for i in [-2, -3]:
  103. in_channels = out_ch_list[i + 1] + out_ch_list[i]
  104. self.base_block.append(
  105. self.add_sublayer(
  106. "F_{}_base_block_0".format(i),
  107. nn.Conv2D(
  108. in_channels=in_channels,
  109. out_channels=out_ch_list[i],
  110. kernel_size=1,
  111. weight_attr=ParamAttr(trainable=True),
  112. bias_attr=ParamAttr(trainable=True))))
  113. self.base_block.append(
  114. self.add_sublayer(
  115. "F_{}_base_block_1".format(i),
  116. nn.Conv2D(
  117. in_channels=out_ch_list[i],
  118. out_channels=out_ch_list[i],
  119. kernel_size=3,
  120. padding=1,
  121. weight_attr=ParamAttr(trainable=True),
  122. bias_attr=ParamAttr(trainable=True))))
  123. self.base_block.append(
  124. self.add_sublayer(
  125. "F_{}_base_block_2".format(i),
  126. nn.BatchNorm(
  127. num_channels=out_ch_list[i],
  128. act="relu",
  129. param_attr=ParamAttr(trainable=True),
  130. bias_attr=ParamAttr(trainable=True))))
  131. self.base_block.append(
  132. self.add_sublayer(
  133. "F_{}_base_block_3".format(i),
  134. nn.Conv2D(
  135. in_channels=out_ch_list[i],
  136. out_channels=512,
  137. kernel_size=1,
  138. bias_attr=ParamAttr(trainable=True),
  139. weight_attr=ParamAttr(trainable=True))))
  140. self.out_channels = 512
  141. def __call__(self, x):
  142. x = self.conv(x)
  143. fpn_list = []
  144. F = []
  145. for i in range(len(self.depth)):
  146. fpn_list.append(np.sum(self.depth[:i + 1]))
  147. for i, block in enumerate(self.block_list):
  148. x = block(x)
  149. for number in fpn_list:
  150. if i + 1 == number:
  151. F.append(x)
  152. base = F[-1]
  153. j = 0
  154. for i, block in enumerate(self.base_block):
  155. if i % 3 == 0 and i < 6:
  156. j = j + 1
  157. b, c, w, h = F[-j - 1].shape
  158. if [w, h] == list(base.shape[2:]):
  159. base = base
  160. else:
  161. base = self.conv_trans[j - 1](base)
  162. base = self.bn_block[j - 1](base)
  163. base = paddle.concat([base, F[-j - 1]], axis=1)
  164. base = block(base)
  165. return base
  166. class ConvBNLayer(nn.Layer):
  167. def __init__(self,
  168. in_channels,
  169. out_channels,
  170. kernel_size,
  171. stride=1,
  172. groups=1,
  173. act=None,
  174. name=None):
  175. super(ConvBNLayer, self).__init__()
  176. self.conv = nn.Conv2D(
  177. in_channels=in_channels,
  178. out_channels=out_channels,
  179. kernel_size=2 if stride == (1, 1) else kernel_size,
  180. dilation=2 if stride == (1, 1) else 1,
  181. stride=stride,
  182. padding=(kernel_size - 1) // 2,
  183. groups=groups,
  184. weight_attr=ParamAttr(name=name + '.conv2d.output.1.w_0'),
  185. bias_attr=False, )
  186. if name == "conv1":
  187. bn_name = "bn_" + name
  188. else:
  189. bn_name = "bn" + name[3:]
  190. self.bn = nn.BatchNorm(
  191. num_channels=out_channels,
  192. act=act,
  193. param_attr=ParamAttr(name=name + '.output.1.w_0'),
  194. bias_attr=ParamAttr(name=name + '.output.1.b_0'),
  195. moving_mean_name=bn_name + "_mean",
  196. moving_variance_name=bn_name + "_variance")
  197. def __call__(self, x):
  198. x = self.conv(x)
  199. x = self.bn(x)
  200. return x
  201. class ShortCut(nn.Layer):
  202. def __init__(self, in_channels, out_channels, stride, name, is_first=False):
  203. super(ShortCut, self).__init__()
  204. self.use_conv = True
  205. if in_channels != out_channels or stride != 1 or is_first == True:
  206. if stride == (1, 1):
  207. self.conv = ConvBNLayer(
  208. in_channels, out_channels, 1, 1, name=name)
  209. else: # stride==(2,2)
  210. self.conv = ConvBNLayer(
  211. in_channels, out_channels, 1, stride, name=name)
  212. else:
  213. self.use_conv = False
  214. def forward(self, x):
  215. if self.use_conv:
  216. x = self.conv(x)
  217. return x
  218. class BottleneckBlock(nn.Layer):
  219. def __init__(self, in_channels, out_channels, stride, name):
  220. super(BottleneckBlock, self).__init__()
  221. self.conv0 = ConvBNLayer(
  222. in_channels=in_channels,
  223. out_channels=out_channels,
  224. kernel_size=1,
  225. act='relu',
  226. name=name + "_branch2a")
  227. self.conv1 = ConvBNLayer(
  228. in_channels=out_channels,
  229. out_channels=out_channels,
  230. kernel_size=3,
  231. stride=stride,
  232. act='relu',
  233. name=name + "_branch2b")
  234. self.conv2 = ConvBNLayer(
  235. in_channels=out_channels,
  236. out_channels=out_channels * 4,
  237. kernel_size=1,
  238. act=None,
  239. name=name + "_branch2c")
  240. self.short = ShortCut(
  241. in_channels=in_channels,
  242. out_channels=out_channels * 4,
  243. stride=stride,
  244. is_first=False,
  245. name=name + "_branch1")
  246. self.out_channels = out_channels * 4
  247. def forward(self, x):
  248. y = self.conv0(x)
  249. y = self.conv1(y)
  250. y = self.conv2(y)
  251. y = y + self.short(x)
  252. y = F.relu(y)
  253. return y
  254. class BasicBlock(nn.Layer):
  255. def __init__(self, in_channels, out_channels, stride, name, is_first):
  256. super(BasicBlock, self).__init__()
  257. self.conv0 = ConvBNLayer(
  258. in_channels=in_channels,
  259. out_channels=out_channels,
  260. kernel_size=3,
  261. act='relu',
  262. stride=stride,
  263. name=name + "_branch2a")
  264. self.conv1 = ConvBNLayer(
  265. in_channels=out_channels,
  266. out_channels=out_channels,
  267. kernel_size=3,
  268. act=None,
  269. name=name + "_branch2b")
  270. self.short = ShortCut(
  271. in_channels=in_channels,
  272. out_channels=out_channels,
  273. stride=stride,
  274. is_first=is_first,
  275. name=name + "_branch1")
  276. self.out_channels = out_channels
  277. def forward(self, x):
  278. y = self.conv0(x)
  279. y = self.conv1(y)
  280. y = y + self.short(x)
  281. return F.relu(y)