e2e_resnet_vd_pg.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. # copyright (c) 2021 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. __all__ = ["ResNet"]
  22. class ConvBNLayer(nn.Layer):
  23. def __init__(
  24. self,
  25. in_channels,
  26. out_channels,
  27. kernel_size,
  28. stride=1,
  29. groups=1,
  30. is_vd_mode=False,
  31. act=None,
  32. name=None, ):
  33. super(ConvBNLayer, self).__init__()
  34. self.is_vd_mode = is_vd_mode
  35. self._pool2d_avg = nn.AvgPool2D(
  36. kernel_size=2, stride=2, padding=0, ceil_mode=True)
  37. self._conv = nn.Conv2D(
  38. in_channels=in_channels,
  39. out_channels=out_channels,
  40. kernel_size=kernel_size,
  41. stride=stride,
  42. padding=(kernel_size - 1) // 2,
  43. groups=groups,
  44. weight_attr=ParamAttr(name=name + "_weights"),
  45. bias_attr=False)
  46. if name == "conv1":
  47. bn_name = "bn_" + name
  48. else:
  49. bn_name = "bn" + name[3:]
  50. self._batch_norm = nn.BatchNorm(
  51. out_channels,
  52. act=act,
  53. param_attr=ParamAttr(name=bn_name + '_scale'),
  54. bias_attr=ParamAttr(bn_name + '_offset'),
  55. moving_mean_name=bn_name + '_mean',
  56. moving_variance_name=bn_name + '_variance')
  57. def forward(self, inputs):
  58. y = self._conv(inputs)
  59. y = self._batch_norm(y)
  60. return y
  61. class BottleneckBlock(nn.Layer):
  62. def __init__(self,
  63. in_channels,
  64. out_channels,
  65. stride,
  66. shortcut=True,
  67. if_first=False,
  68. name=None):
  69. super(BottleneckBlock, self).__init__()
  70. self.conv0 = ConvBNLayer(
  71. in_channels=in_channels,
  72. out_channels=out_channels,
  73. kernel_size=1,
  74. act='relu',
  75. name=name + "_branch2a")
  76. self.conv1 = ConvBNLayer(
  77. in_channels=out_channels,
  78. out_channels=out_channels,
  79. kernel_size=3,
  80. stride=stride,
  81. act='relu',
  82. name=name + "_branch2b")
  83. self.conv2 = ConvBNLayer(
  84. in_channels=out_channels,
  85. out_channels=out_channels * 4,
  86. kernel_size=1,
  87. act=None,
  88. name=name + "_branch2c")
  89. if not shortcut:
  90. self.short = ConvBNLayer(
  91. in_channels=in_channels,
  92. out_channels=out_channels * 4,
  93. kernel_size=1,
  94. stride=stride,
  95. is_vd_mode=False if if_first else True,
  96. name=name + "_branch1")
  97. self.shortcut = shortcut
  98. def forward(self, inputs):
  99. y = self.conv0(inputs)
  100. conv1 = self.conv1(y)
  101. conv2 = self.conv2(conv1)
  102. if self.shortcut:
  103. short = inputs
  104. else:
  105. short = self.short(inputs)
  106. y = paddle.add(x=short, y=conv2)
  107. y = F.relu(y)
  108. return y
  109. class BasicBlock(nn.Layer):
  110. def __init__(self,
  111. in_channels,
  112. out_channels,
  113. stride,
  114. shortcut=True,
  115. if_first=False,
  116. name=None):
  117. super(BasicBlock, self).__init__()
  118. self.stride = stride
  119. self.conv0 = ConvBNLayer(
  120. in_channels=in_channels,
  121. out_channels=out_channels,
  122. kernel_size=3,
  123. stride=stride,
  124. act='relu',
  125. name=name + "_branch2a")
  126. self.conv1 = ConvBNLayer(
  127. in_channels=out_channels,
  128. out_channels=out_channels,
  129. kernel_size=3,
  130. act=None,
  131. name=name + "_branch2b")
  132. if not shortcut:
  133. self.short = ConvBNLayer(
  134. in_channels=in_channels,
  135. out_channels=out_channels,
  136. kernel_size=1,
  137. stride=1,
  138. is_vd_mode=False if if_first else True,
  139. name=name + "_branch1")
  140. self.shortcut = shortcut
  141. def forward(self, inputs):
  142. y = self.conv0(inputs)
  143. conv1 = self.conv1(y)
  144. if self.shortcut:
  145. short = inputs
  146. else:
  147. short = self.short(inputs)
  148. y = paddle.add(x=short, y=conv1)
  149. y = F.relu(y)
  150. return y
  151. class ResNet(nn.Layer):
  152. def __init__(self, in_channels=3, layers=50, **kwargs):
  153. super(ResNet, self).__init__()
  154. self.layers = layers
  155. supported_layers = [18, 34, 50, 101, 152, 200]
  156. assert layers in supported_layers, \
  157. "supported layers are {} but input layer is {}".format(
  158. supported_layers, layers)
  159. if layers == 18:
  160. depth = [2, 2, 2, 2]
  161. elif layers == 34 or layers == 50:
  162. # depth = [3, 4, 6, 3]
  163. depth = [3, 4, 6, 3, 3]
  164. elif layers == 101:
  165. depth = [3, 4, 23, 3]
  166. elif layers == 152:
  167. depth = [3, 8, 36, 3]
  168. elif layers == 200:
  169. depth = [3, 12, 48, 3]
  170. num_channels = [64, 256, 512, 1024,
  171. 2048] if layers >= 50 else [64, 64, 128, 256]
  172. num_filters = [64, 128, 256, 512, 512]
  173. self.conv1_1 = ConvBNLayer(
  174. in_channels=in_channels,
  175. out_channels=64,
  176. kernel_size=7,
  177. stride=2,
  178. act='relu',
  179. name="conv1_1")
  180. self.pool2d_max = nn.MaxPool2D(kernel_size=3, stride=2, padding=1)
  181. self.stages = []
  182. self.out_channels = [3, 64]
  183. # num_filters = [64, 128, 256, 512, 512]
  184. if layers >= 50:
  185. for block in range(len(depth)):
  186. block_list = []
  187. shortcut = False
  188. for i in range(depth[block]):
  189. if layers in [101, 152] and block == 2:
  190. if i == 0:
  191. conv_name = "res" + str(block + 2) + "a"
  192. else:
  193. conv_name = "res" + str(block + 2) + "b" + str(i)
  194. else:
  195. conv_name = "res" + str(block + 2) + chr(97 + i)
  196. bottleneck_block = self.add_sublayer(
  197. 'bb_%d_%d' % (block, i),
  198. BottleneckBlock(
  199. in_channels=num_channels[block]
  200. if i == 0 else num_filters[block] * 4,
  201. out_channels=num_filters[block],
  202. stride=2 if i == 0 and block != 0 else 1,
  203. shortcut=shortcut,
  204. if_first=block == i == 0,
  205. name=conv_name))
  206. shortcut = True
  207. block_list.append(bottleneck_block)
  208. self.out_channels.append(num_filters[block] * 4)
  209. self.stages.append(nn.Sequential(*block_list))
  210. else:
  211. for block in range(len(depth)):
  212. block_list = []
  213. shortcut = False
  214. for i in range(depth[block]):
  215. conv_name = "res" + str(block + 2) + chr(97 + i)
  216. basic_block = self.add_sublayer(
  217. 'bb_%d_%d' % (block, i),
  218. BasicBlock(
  219. in_channels=num_channels[block]
  220. if i == 0 else num_filters[block],
  221. out_channels=num_filters[block],
  222. stride=2 if i == 0 and block != 0 else 1,
  223. shortcut=shortcut,
  224. if_first=block == i == 0,
  225. name=conv_name))
  226. shortcut = True
  227. block_list.append(basic_block)
  228. self.out_channels.append(num_filters[block])
  229. self.stages.append(nn.Sequential(*block_list))
  230. def forward(self, inputs):
  231. out = [inputs]
  232. y = self.conv1_1(inputs)
  233. out.append(y)
  234. y = self.pool2d_max(y)
  235. for block in self.stages:
  236. y = block(y)
  237. out.append(y)
  238. return out