det_resnet.py 7.7 KB

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