det_resnet.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. # copyright (c) 2022 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 numpy as np
  18. import paddle
  19. from paddle import ParamAttr
  20. import paddle.nn as nn
  21. import paddle.nn.functional as F
  22. from paddle.nn import Conv2D, BatchNorm, Linear, Dropout
  23. from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D
  24. from paddle.nn.initializer import Uniform
  25. import math
  26. from paddle.vision.ops import DeformConv2D
  27. from paddle.regularizer import L2Decay
  28. from paddle.nn.initializer import Normal, Constant, XavierUniform
  29. from .det_resnet_vd import DeformableConvV2, ConvBNLayer
  30. class BottleneckBlock(nn.Layer):
  31. def __init__(self,
  32. num_channels,
  33. num_filters,
  34. stride,
  35. shortcut=True,
  36. is_dcn=False):
  37. super(BottleneckBlock, self).__init__()
  38. self.conv0 = ConvBNLayer(
  39. in_channels=num_channels,
  40. out_channels=num_filters,
  41. kernel_size=1,
  42. act="relu", )
  43. self.conv1 = ConvBNLayer(
  44. in_channels=num_filters,
  45. out_channels=num_filters,
  46. kernel_size=3,
  47. stride=stride,
  48. act="relu",
  49. is_dcn=is_dcn,
  50. dcn_groups=1, )
  51. self.conv2 = ConvBNLayer(
  52. in_channels=num_filters,
  53. out_channels=num_filters * 4,
  54. kernel_size=1,
  55. act=None, )
  56. if not shortcut:
  57. self.short = ConvBNLayer(
  58. in_channels=num_channels,
  59. out_channels=num_filters * 4,
  60. kernel_size=1,
  61. stride=stride, )
  62. self.shortcut = shortcut
  63. self._num_channels_out = num_filters * 4
  64. def forward(self, inputs):
  65. y = self.conv0(inputs)
  66. conv1 = self.conv1(y)
  67. conv2 = self.conv2(conv1)
  68. if self.shortcut:
  69. short = inputs
  70. else:
  71. short = self.short(inputs)
  72. y = paddle.add(x=short, y=conv2)
  73. y = F.relu(y)
  74. return y
  75. class BasicBlock(nn.Layer):
  76. def __init__(self,
  77. num_channels,
  78. num_filters,
  79. stride,
  80. shortcut=True,
  81. name=None):
  82. super(BasicBlock, self).__init__()
  83. self.stride = stride
  84. self.conv0 = ConvBNLayer(
  85. in_channels=num_channels,
  86. out_channels=num_filters,
  87. kernel_size=3,
  88. stride=stride,
  89. act="relu")
  90. self.conv1 = ConvBNLayer(
  91. in_channels=num_filters,
  92. out_channels=num_filters,
  93. kernel_size=3,
  94. act=None)
  95. if not shortcut:
  96. self.short = ConvBNLayer(
  97. in_channels=num_channels,
  98. out_channels=num_filters,
  99. kernel_size=1,
  100. stride=stride)
  101. self.shortcut = shortcut
  102. def forward(self, inputs):
  103. y = self.conv0(inputs)
  104. conv1 = self.conv1(y)
  105. if self.shortcut:
  106. short = inputs
  107. else:
  108. short = self.short(inputs)
  109. y = paddle.add(x=short, y=conv1)
  110. y = F.relu(y)
  111. return y
  112. class ResNet(nn.Layer):
  113. def __init__(self,
  114. in_channels=3,
  115. layers=50,
  116. out_indices=None,
  117. dcn_stage=None):
  118. super(ResNet, self).__init__()
  119. self.layers = layers
  120. self.input_image_channel = in_channels
  121. supported_layers = [18, 34, 50, 101, 152]
  122. assert layers in supported_layers, \
  123. "supported layers are {} but input layer is {}".format(
  124. supported_layers, layers)
  125. if layers == 18:
  126. depth = [2, 2, 2, 2]
  127. elif layers == 34 or layers == 50:
  128. depth = [3, 4, 6, 3]
  129. elif layers == 101:
  130. depth = [3, 4, 23, 3]
  131. elif layers == 152:
  132. depth = [3, 8, 36, 3]
  133. num_channels = [64, 256, 512,
  134. 1024] if layers >= 50 else [64, 64, 128, 256]
  135. num_filters = [64, 128, 256, 512]
  136. self.dcn_stage = dcn_stage if dcn_stage is not None else [
  137. False, False, False, False
  138. ]
  139. self.out_indices = out_indices if out_indices is not None else [
  140. 0, 1, 2, 3
  141. ]
  142. self.conv = ConvBNLayer(
  143. in_channels=self.input_image_channel,
  144. out_channels=64,
  145. kernel_size=7,
  146. stride=2,
  147. act="relu", )
  148. self.pool2d_max = MaxPool2D(
  149. kernel_size=3,
  150. stride=2,
  151. padding=1, )
  152. self.stages = []
  153. self.out_channels = []
  154. if layers >= 50:
  155. for block in range(len(depth)):
  156. shortcut = False
  157. block_list = []
  158. is_dcn = self.dcn_stage[block]
  159. for i in range(depth[block]):
  160. if layers in [101, 152] and block == 2:
  161. if i == 0:
  162. conv_name = "res" + str(block + 2) + "a"
  163. else:
  164. conv_name = "res" + str(block + 2) + "b" + str(i)
  165. else:
  166. conv_name = "res" + str(block + 2) + chr(97 + i)
  167. bottleneck_block = self.add_sublayer(
  168. conv_name,
  169. BottleneckBlock(
  170. num_channels=num_channels[block]
  171. if i == 0 else num_filters[block] * 4,
  172. num_filters=num_filters[block],
  173. stride=2 if i == 0 and block != 0 else 1,
  174. shortcut=shortcut,
  175. is_dcn=is_dcn))
  176. block_list.append(bottleneck_block)
  177. shortcut = True
  178. if block in self.out_indices:
  179. self.out_channels.append(num_filters[block] * 4)
  180. self.stages.append(nn.Sequential(*block_list))
  181. else:
  182. for block in range(len(depth)):
  183. shortcut = False
  184. block_list = []
  185. for i in range(depth[block]):
  186. conv_name = "res" + str(block + 2) + chr(97 + i)
  187. basic_block = self.add_sublayer(
  188. conv_name,
  189. BasicBlock(
  190. num_channels=num_channels[block]
  191. if i == 0 else num_filters[block],
  192. num_filters=num_filters[block],
  193. stride=2 if i == 0 and block != 0 else 1,
  194. shortcut=shortcut))
  195. block_list.append(basic_block)
  196. shortcut = True
  197. if block in self.out_indices:
  198. self.out_channels.append(num_filters[block])
  199. self.stages.append(nn.Sequential(*block_list))
  200. def forward(self, inputs):
  201. y = self.conv(inputs)
  202. y = self.pool2d_max(y)
  203. out = []
  204. for i, block in enumerate(self.stages):
  205. y = block(y)
  206. if i in self.out_indices:
  207. out.append(y)
  208. return out