det_resnet_vd.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. import paddle
  18. from paddle import ParamAttr
  19. import paddle.nn as nn
  20. import paddle.nn.functional as F
  21. from paddle.vision.ops import DeformConv2D
  22. from paddle.regularizer import L2Decay
  23. from paddle.nn.initializer import Normal, Constant, XavierUniform
  24. __all__ = ["ResNet_vd", "ConvBNLayer", "DeformableConvV2"]
  25. class DeformableConvV2(nn.Layer):
  26. def __init__(self,
  27. in_channels,
  28. out_channels,
  29. kernel_size,
  30. stride=1,
  31. padding=0,
  32. dilation=1,
  33. groups=1,
  34. weight_attr=None,
  35. bias_attr=None,
  36. lr_scale=1,
  37. regularizer=None,
  38. skip_quant=False,
  39. dcn_bias_regularizer=L2Decay(0.),
  40. dcn_bias_lr_scale=2.):
  41. super(DeformableConvV2, self).__init__()
  42. self.offset_channel = 2 * kernel_size**2 * groups
  43. self.mask_channel = kernel_size**2 * groups
  44. if bias_attr:
  45. # in FCOS-DCN head, specifically need learning_rate and regularizer
  46. dcn_bias_attr = ParamAttr(
  47. initializer=Constant(value=0),
  48. regularizer=dcn_bias_regularizer,
  49. learning_rate=dcn_bias_lr_scale)
  50. else:
  51. # in ResNet backbone, do not need bias
  52. dcn_bias_attr = False
  53. self.conv_dcn = DeformConv2D(
  54. in_channels,
  55. out_channels,
  56. kernel_size,
  57. stride=stride,
  58. padding=(kernel_size - 1) // 2 * dilation,
  59. dilation=dilation,
  60. deformable_groups=groups,
  61. weight_attr=weight_attr,
  62. bias_attr=dcn_bias_attr)
  63. if lr_scale == 1 and regularizer is None:
  64. offset_bias_attr = ParamAttr(initializer=Constant(0.))
  65. else:
  66. offset_bias_attr = ParamAttr(
  67. initializer=Constant(0.),
  68. learning_rate=lr_scale,
  69. regularizer=regularizer)
  70. self.conv_offset = nn.Conv2D(
  71. in_channels,
  72. groups * 3 * kernel_size**2,
  73. kernel_size,
  74. stride=stride,
  75. padding=(kernel_size - 1) // 2,
  76. weight_attr=ParamAttr(initializer=Constant(0.0)),
  77. bias_attr=offset_bias_attr)
  78. if skip_quant:
  79. self.conv_offset.skip_quant = True
  80. def forward(self, x):
  81. offset_mask = self.conv_offset(x)
  82. offset, mask = paddle.split(
  83. offset_mask,
  84. num_or_sections=[self.offset_channel, self.mask_channel],
  85. axis=1)
  86. mask = F.sigmoid(mask)
  87. y = self.conv_dcn(x, offset, mask=mask)
  88. return y
  89. class ConvBNLayer(nn.Layer):
  90. def __init__(self,
  91. in_channels,
  92. out_channels,
  93. kernel_size,
  94. stride=1,
  95. groups=1,
  96. dcn_groups=1,
  97. is_vd_mode=False,
  98. act=None,
  99. is_dcn=False):
  100. super(ConvBNLayer, self).__init__()
  101. self.is_vd_mode = is_vd_mode
  102. self._pool2d_avg = nn.AvgPool2D(
  103. kernel_size=2, stride=2, padding=0, ceil_mode=True)
  104. if not is_dcn:
  105. self._conv = nn.Conv2D(
  106. in_channels=in_channels,
  107. out_channels=out_channels,
  108. kernel_size=kernel_size,
  109. stride=stride,
  110. padding=(kernel_size - 1) // 2,
  111. groups=groups,
  112. bias_attr=False)
  113. else:
  114. self._conv = DeformableConvV2(
  115. in_channels=in_channels,
  116. out_channels=out_channels,
  117. kernel_size=kernel_size,
  118. stride=stride,
  119. padding=(kernel_size - 1) // 2,
  120. groups=dcn_groups, #groups,
  121. bias_attr=False)
  122. self._batch_norm = nn.BatchNorm(out_channels, act=act)
  123. def forward(self, inputs):
  124. if self.is_vd_mode:
  125. inputs = self._pool2d_avg(inputs)
  126. y = self._conv(inputs)
  127. y = self._batch_norm(y)
  128. return y
  129. class BottleneckBlock(nn.Layer):
  130. def __init__(
  131. self,
  132. in_channels,
  133. out_channels,
  134. stride,
  135. shortcut=True,
  136. if_first=False,
  137. is_dcn=False, ):
  138. super(BottleneckBlock, self).__init__()
  139. self.conv0 = ConvBNLayer(
  140. in_channels=in_channels,
  141. out_channels=out_channels,
  142. kernel_size=1,
  143. act='relu')
  144. self.conv1 = ConvBNLayer(
  145. in_channels=out_channels,
  146. out_channels=out_channels,
  147. kernel_size=3,
  148. stride=stride,
  149. act='relu',
  150. is_dcn=is_dcn,
  151. dcn_groups=2)
  152. self.conv2 = ConvBNLayer(
  153. in_channels=out_channels,
  154. out_channels=out_channels * 4,
  155. kernel_size=1,
  156. act=None)
  157. if not shortcut:
  158. self.short = ConvBNLayer(
  159. in_channels=in_channels,
  160. out_channels=out_channels * 4,
  161. kernel_size=1,
  162. stride=1,
  163. is_vd_mode=False if if_first else True)
  164. self.shortcut = shortcut
  165. def forward(self, inputs):
  166. y = self.conv0(inputs)
  167. conv1 = self.conv1(y)
  168. conv2 = self.conv2(conv1)
  169. if self.shortcut:
  170. short = inputs
  171. else:
  172. short = self.short(inputs)
  173. y = paddle.add(x=short, y=conv2)
  174. y = F.relu(y)
  175. return y
  176. class BasicBlock(nn.Layer):
  177. def __init__(
  178. self,
  179. in_channels,
  180. out_channels,
  181. stride,
  182. shortcut=True,
  183. if_first=False, ):
  184. super(BasicBlock, self).__init__()
  185. self.stride = stride
  186. self.conv0 = ConvBNLayer(
  187. in_channels=in_channels,
  188. out_channels=out_channels,
  189. kernel_size=3,
  190. stride=stride,
  191. act='relu')
  192. self.conv1 = ConvBNLayer(
  193. in_channels=out_channels,
  194. out_channels=out_channels,
  195. kernel_size=3,
  196. act=None)
  197. if not shortcut:
  198. self.short = ConvBNLayer(
  199. in_channels=in_channels,
  200. out_channels=out_channels,
  201. kernel_size=1,
  202. stride=1,
  203. is_vd_mode=False if if_first else True)
  204. self.shortcut = shortcut
  205. def forward(self, inputs):
  206. y = self.conv0(inputs)
  207. conv1 = self.conv1(y)
  208. if self.shortcut:
  209. short = inputs
  210. else:
  211. short = self.short(inputs)
  212. y = paddle.add(x=short, y=conv1)
  213. y = F.relu(y)
  214. return y
  215. class ResNet_vd(nn.Layer):
  216. def __init__(self,
  217. in_channels=3,
  218. layers=50,
  219. dcn_stage=None,
  220. out_indices=None,
  221. **kwargs):
  222. super(ResNet_vd, self).__init__()
  223. self.layers = layers
  224. supported_layers = [18, 34, 50, 101, 152, 200]
  225. assert layers in supported_layers, \
  226. "supported layers are {} but input layer is {}".format(
  227. supported_layers, layers)
  228. if layers == 18:
  229. depth = [2, 2, 2, 2]
  230. elif layers == 34 or layers == 50:
  231. depth = [3, 4, 6, 3]
  232. elif layers == 101:
  233. depth = [3, 4, 23, 3]
  234. elif layers == 152:
  235. depth = [3, 8, 36, 3]
  236. elif layers == 200:
  237. depth = [3, 12, 48, 3]
  238. num_channels = [64, 256, 512,
  239. 1024] if layers >= 50 else [64, 64, 128, 256]
  240. num_filters = [64, 128, 256, 512]
  241. self.dcn_stage = dcn_stage if dcn_stage is not None else [
  242. False, False, False, False
  243. ]
  244. self.out_indices = out_indices if out_indices is not None else [
  245. 0, 1, 2, 3
  246. ]
  247. self.conv1_1 = ConvBNLayer(
  248. in_channels=in_channels,
  249. out_channels=32,
  250. kernel_size=3,
  251. stride=2,
  252. act='relu')
  253. self.conv1_2 = ConvBNLayer(
  254. in_channels=32,
  255. out_channels=32,
  256. kernel_size=3,
  257. stride=1,
  258. act='relu')
  259. self.conv1_3 = ConvBNLayer(
  260. in_channels=32,
  261. out_channels=64,
  262. kernel_size=3,
  263. stride=1,
  264. act='relu')
  265. self.pool2d_max = nn.MaxPool2D(kernel_size=3, stride=2, padding=1)
  266. self.stages = []
  267. self.out_channels = []
  268. if layers >= 50:
  269. for block in range(len(depth)):
  270. block_list = []
  271. shortcut = False
  272. is_dcn = self.dcn_stage[block]
  273. for i in range(depth[block]):
  274. bottleneck_block = self.add_sublayer(
  275. 'bb_%d_%d' % (block, i),
  276. BottleneckBlock(
  277. in_channels=num_channels[block]
  278. if i == 0 else num_filters[block] * 4,
  279. out_channels=num_filters[block],
  280. stride=2 if i == 0 and block != 0 else 1,
  281. shortcut=shortcut,
  282. if_first=block == i == 0,
  283. is_dcn=is_dcn))
  284. shortcut = True
  285. block_list.append(bottleneck_block)
  286. if block in self.out_indices:
  287. self.out_channels.append(num_filters[block] * 4)
  288. self.stages.append(nn.Sequential(*block_list))
  289. else:
  290. for block in range(len(depth)):
  291. block_list = []
  292. shortcut = False
  293. for i in range(depth[block]):
  294. basic_block = self.add_sublayer(
  295. 'bb_%d_%d' % (block, i),
  296. BasicBlock(
  297. in_channels=num_channels[block]
  298. if i == 0 else num_filters[block],
  299. out_channels=num_filters[block],
  300. stride=2 if i == 0 and block != 0 else 1,
  301. shortcut=shortcut,
  302. if_first=block == i == 0))
  303. shortcut = True
  304. block_list.append(basic_block)
  305. if block in self.out_indices:
  306. self.out_channels.append(num_filters[block])
  307. self.stages.append(nn.Sequential(*block_list))
  308. def forward(self, inputs):
  309. y = self.conv1_1(inputs)
  310. y = self.conv1_2(y)
  311. y = self.conv1_3(y)
  312. y = self.pool2d_max(y)
  313. out = []
  314. for i, block in enumerate(self.stages):
  315. y = block(y)
  316. if i in self.out_indices:
  317. out.append(y)
  318. return out