e2e_resnet_vd_pg.py 8.9 KB

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