rec_resnet_fpn.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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: {"depth": [2, 2, 2, 2], "block_class": BasicBlock},
  27. 34: {"depth": [3, 4, 6, 3], "block_class": BasicBlock},
  28. 50: {"depth": [3, 4, 6, 3], "block_class": BottleneckBlock},
  29. 101: {"depth": [3, 4, 23, 3], "block_class": BottleneckBlock},
  30. 152: {"depth": [3, 8, 36, 3], "block_class": BottleneckBlock},
  31. }
  32. stride_list = [(2, 2), (2, 2), (1, 1), (1, 1)]
  33. num_filters = [64, 128, 256, 512]
  34. self.depth = supported_layers[layers]["depth"]
  35. self.F = []
  36. self.conv = ConvBNLayer(
  37. in_channels=in_channels,
  38. out_channels=64,
  39. kernel_size=7,
  40. stride=2,
  41. act="relu",
  42. name="conv1",
  43. )
  44. self.block_list = []
  45. in_ch = 64
  46. if layers >= 50:
  47. for block in range(len(self.depth)):
  48. for i in range(self.depth[block]):
  49. if layers in [101, 152] and block == 2:
  50. if i == 0:
  51. conv_name = "res" + str(block + 2) + "a"
  52. else:
  53. conv_name = "res" + str(block + 2) + "b" + str(i)
  54. else:
  55. conv_name = "res" + str(block + 2) + chr(97 + i)
  56. block_list = self.add_sublayer(
  57. "bottleneckBlock_{}_{}".format(block, i),
  58. BottleneckBlock(
  59. in_channels=in_ch,
  60. out_channels=num_filters[block],
  61. stride=stride_list[block] if i == 0 else 1,
  62. name=conv_name,
  63. ),
  64. )
  65. in_ch = num_filters[block] * 4
  66. self.block_list.append(block_list)
  67. self.F.append(block_list)
  68. else:
  69. for block in range(len(self.depth)):
  70. for i in range(self.depth[block]):
  71. conv_name = "res" + str(block + 2) + chr(97 + i)
  72. if i == 0 and block != 0:
  73. stride = (2, 1)
  74. else:
  75. stride = (1, 1)
  76. basic_block = self.add_sublayer(
  77. conv_name,
  78. BasicBlock(
  79. in_channels=in_ch,
  80. out_channels=num_filters[block],
  81. stride=stride_list[block] if i == 0 else 1,
  82. is_first=block == i == 0,
  83. name=conv_name,
  84. ),
  85. )
  86. in_ch = basic_block.out_channels
  87. self.block_list.append(basic_block)
  88. out_ch_list = [in_ch // 4, in_ch // 2, in_ch]
  89. self.base_block = []
  90. self.conv_trans = []
  91. self.bn_block = []
  92. for i in [-2, -3]:
  93. in_channels = out_ch_list[i + 1] + out_ch_list[i]
  94. self.base_block.append(
  95. self.add_sublayer(
  96. "F_{}_base_block_0".format(i),
  97. nn.Conv2D(
  98. in_channels=in_channels,
  99. out_channels=out_ch_list[i],
  100. kernel_size=1,
  101. weight_attr=ParamAttr(trainable=True),
  102. bias_attr=ParamAttr(trainable=True),
  103. ),
  104. )
  105. )
  106. self.base_block.append(
  107. self.add_sublayer(
  108. "F_{}_base_block_1".format(i),
  109. nn.Conv2D(
  110. in_channels=out_ch_list[i],
  111. out_channels=out_ch_list[i],
  112. kernel_size=3,
  113. padding=1,
  114. weight_attr=ParamAttr(trainable=True),
  115. bias_attr=ParamAttr(trainable=True),
  116. ),
  117. )
  118. )
  119. self.base_block.append(
  120. self.add_sublayer(
  121. "F_{}_base_block_2".format(i),
  122. nn.BatchNorm(
  123. num_channels=out_ch_list[i],
  124. act="relu",
  125. param_attr=ParamAttr(trainable=True),
  126. bias_attr=ParamAttr(trainable=True),
  127. ),
  128. )
  129. )
  130. self.base_block.append(
  131. self.add_sublayer(
  132. "F_{}_base_block_3".format(i),
  133. nn.Conv2D(
  134. in_channels=out_ch_list[i],
  135. out_channels=512,
  136. kernel_size=1,
  137. bias_attr=ParamAttr(trainable=True),
  138. weight_attr=ParamAttr(trainable=True),
  139. ),
  140. )
  141. )
  142. self.out_channels = 512
  143. def __call__(self, x):
  144. x = self.conv(x)
  145. fpn_list = []
  146. F = []
  147. for i in range(len(self.depth)):
  148. fpn_list.append(np.sum(self.depth[: i + 1]))
  149. for i, block in enumerate(self.block_list):
  150. x = block(x)
  151. for number in fpn_list:
  152. if i + 1 == number:
  153. F.append(x)
  154. base = F[-1]
  155. j = 0
  156. for i, block in enumerate(self.base_block):
  157. if i % 3 == 0 and i < 6:
  158. j = j + 1
  159. b, c, w, h = F[-j - 1].shape
  160. if [w, h] == list(base.shape[2:]):
  161. base = base
  162. else:
  163. base = self.conv_trans[j - 1](base)
  164. base = self.bn_block[j - 1](base)
  165. base = paddle.concat([base, F[-j - 1]], axis=1)
  166. base = block(base)
  167. return base
  168. class ConvBNLayer(nn.Layer):
  169. def __init__(
  170. self,
  171. in_channels,
  172. out_channels,
  173. kernel_size,
  174. stride=1,
  175. groups=1,
  176. act=None,
  177. name=None,
  178. ):
  179. super(ConvBNLayer, self).__init__()
  180. self.conv = nn.Conv2D(
  181. in_channels=in_channels,
  182. out_channels=out_channels,
  183. kernel_size=2 if stride == (1, 1) else kernel_size,
  184. dilation=2 if stride == (1, 1) else 1,
  185. stride=stride,
  186. padding=(kernel_size - 1) // 2,
  187. groups=groups,
  188. weight_attr=ParamAttr(name=name + ".conv2d.output.1.w_0"),
  189. bias_attr=False,
  190. )
  191. if name == "conv1":
  192. bn_name = "bn_" + name
  193. else:
  194. bn_name = "bn" + name[3:]
  195. self.bn = nn.BatchNorm(
  196. num_channels=out_channels,
  197. act=act,
  198. param_attr=ParamAttr(name=name + ".output.1.w_0"),
  199. bias_attr=ParamAttr(name=name + ".output.1.b_0"),
  200. moving_mean_name=bn_name + "_mean",
  201. moving_variance_name=bn_name + "_variance",
  202. )
  203. def __call__(self, x):
  204. x = self.conv(x)
  205. x = self.bn(x)
  206. return x
  207. class ShortCut(nn.Layer):
  208. def __init__(self, in_channels, out_channels, stride, name, is_first=False):
  209. super(ShortCut, self).__init__()
  210. self.use_conv = True
  211. if in_channels != out_channels or stride != 1 or is_first == True:
  212. if stride == (1, 1):
  213. self.conv = ConvBNLayer(in_channels, out_channels, 1, 1, name=name)
  214. else: # stride==(2,2)
  215. self.conv = ConvBNLayer(in_channels, out_channels, 1, stride, name=name)
  216. else:
  217. self.use_conv = False
  218. def forward(self, x):
  219. if self.use_conv:
  220. x = self.conv(x)
  221. return x
  222. class BottleneckBlock(nn.Layer):
  223. def __init__(self, in_channels, out_channels, stride, name):
  224. super(BottleneckBlock, self).__init__()
  225. self.conv0 = ConvBNLayer(
  226. in_channels=in_channels,
  227. out_channels=out_channels,
  228. kernel_size=1,
  229. act="relu",
  230. name=name + "_branch2a",
  231. )
  232. self.conv1 = ConvBNLayer(
  233. in_channels=out_channels,
  234. out_channels=out_channels,
  235. kernel_size=3,
  236. stride=stride,
  237. act="relu",
  238. name=name + "_branch2b",
  239. )
  240. self.conv2 = ConvBNLayer(
  241. in_channels=out_channels,
  242. out_channels=out_channels * 4,
  243. kernel_size=1,
  244. act=None,
  245. name=name + "_branch2c",
  246. )
  247. self.short = ShortCut(
  248. in_channels=in_channels,
  249. out_channels=out_channels * 4,
  250. stride=stride,
  251. is_first=False,
  252. name=name + "_branch1",
  253. )
  254. self.out_channels = out_channels * 4
  255. def forward(self, x):
  256. y = self.conv0(x)
  257. y = self.conv1(y)
  258. y = self.conv2(y)
  259. y = y + self.short(x)
  260. y = F.relu(y)
  261. return y
  262. class BasicBlock(nn.Layer):
  263. def __init__(self, in_channels, out_channels, stride, name, is_first):
  264. super(BasicBlock, self).__init__()
  265. self.conv0 = ConvBNLayer(
  266. in_channels=in_channels,
  267. out_channels=out_channels,
  268. kernel_size=3,
  269. act="relu",
  270. stride=stride,
  271. name=name + "_branch2a",
  272. )
  273. self.conv1 = ConvBNLayer(
  274. in_channels=out_channels,
  275. out_channels=out_channels,
  276. kernel_size=3,
  277. act=None,
  278. name=name + "_branch2b",
  279. )
  280. self.short = ShortCut(
  281. in_channels=in_channels,
  282. out_channels=out_channels,
  283. stride=stride,
  284. is_first=is_first,
  285. name=name + "_branch1",
  286. )
  287. self.out_channels = out_channels
  288. def forward(self, x):
  289. y = self.conv0(x)
  290. y = self.conv1(y)
  291. y = y + self.short(x)
  292. return F.relu(y)