resnet.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 os
  18. import math
  19. import paddle
  20. from paddle import ParamAttr
  21. import paddle.nn as nn
  22. import paddle.nn.functional as F
  23. from paddle.nn.initializer import Normal
  24. __all__ = ["ResNet18", "ResNet34", "ResNet50", "ResNet101", "ResNet152"]
  25. class ConvBNLayer(nn.Layer):
  26. def __init__(self,
  27. num_channels,
  28. num_filters,
  29. filter_size,
  30. stride=1,
  31. dilation=1,
  32. groups=1,
  33. act=None,
  34. lr_mult=1.0,
  35. name=None,
  36. data_format="NCHW"):
  37. super(ConvBNLayer, self).__init__()
  38. conv_stdv = filter_size * filter_size * num_filters
  39. self._conv = nn.Conv2D(
  40. in_channels=num_channels,
  41. out_channels=num_filters,
  42. kernel_size=filter_size,
  43. stride=stride,
  44. padding=(filter_size - 1) // 2,
  45. dilation=dilation,
  46. groups=groups,
  47. weight_attr=ParamAttr(
  48. learning_rate=lr_mult,
  49. initializer=Normal(0, math.sqrt(2. / conv_stdv))),
  50. bias_attr=False,
  51. data_format=data_format)
  52. self._batch_norm = nn.BatchNorm2D(num_filters)
  53. self.act = act
  54. def forward(self, inputs):
  55. y = self._conv(inputs)
  56. y = self._batch_norm(y)
  57. if self.act:
  58. y = getattr(F, self.act)(y)
  59. return y
  60. class BottleneckBlock(nn.Layer):
  61. def __init__(self,
  62. num_channels,
  63. num_filters,
  64. stride,
  65. shortcut=True,
  66. name=None,
  67. lr_mult=1.0,
  68. dilation=1,
  69. data_format="NCHW"):
  70. super(BottleneckBlock, self).__init__()
  71. self.conv0 = ConvBNLayer(
  72. num_channels=num_channels,
  73. num_filters=num_filters,
  74. filter_size=1,
  75. dilation=dilation,
  76. act="relu",
  77. lr_mult=lr_mult,
  78. name=name + "_branch2a",
  79. data_format=data_format)
  80. self.conv1 = ConvBNLayer(
  81. num_channels=num_filters,
  82. num_filters=num_filters,
  83. filter_size=3,
  84. dilation=dilation,
  85. stride=stride,
  86. act="relu",
  87. lr_mult=lr_mult,
  88. name=name + "_branch2b",
  89. data_format=data_format)
  90. self.conv2 = ConvBNLayer(
  91. num_channels=num_filters,
  92. num_filters=num_filters * 4,
  93. filter_size=1,
  94. dilation=dilation,
  95. act=None,
  96. lr_mult=lr_mult,
  97. name=name + "_branch2c",
  98. data_format=data_format)
  99. if not shortcut:
  100. self.short = ConvBNLayer(
  101. num_channels=num_channels,
  102. num_filters=num_filters * 4,
  103. filter_size=1,
  104. dilation=dilation,
  105. stride=stride,
  106. lr_mult=lr_mult,
  107. name=name + "_branch1",
  108. data_format=data_format)
  109. self.shortcut = shortcut
  110. self._num_channels_out = num_filters * 4
  111. def forward(self, inputs):
  112. y = self.conv0(inputs)
  113. conv1 = self.conv1(y)
  114. conv2 = self.conv2(conv1)
  115. if self.shortcut:
  116. short = inputs
  117. else:
  118. short = self.short(inputs)
  119. y = paddle.add(x=short, y=conv2)
  120. y = F.relu(y)
  121. return y
  122. class BasicBlock(nn.Layer):
  123. def __init__(self,
  124. num_channels,
  125. num_filters,
  126. stride,
  127. shortcut=True,
  128. name=None,
  129. data_format="NCHW"):
  130. super(BasicBlock, self).__init__()
  131. self.stride = stride
  132. self.conv0 = ConvBNLayer(
  133. num_channels=num_channels,
  134. num_filters=num_filters,
  135. filter_size=3,
  136. stride=stride,
  137. act="relu",
  138. name=name + "_branch2a",
  139. data_format=data_format)
  140. self.conv1 = ConvBNLayer(
  141. num_channels=num_filters,
  142. num_filters=num_filters,
  143. filter_size=3,
  144. act=None,
  145. name=name + "_branch2b",
  146. data_format=data_format)
  147. if not shortcut:
  148. self.short = ConvBNLayer(
  149. num_channels=num_channels,
  150. num_filters=num_filters,
  151. filter_size=1,
  152. stride=stride,
  153. name=name + "_branch1",
  154. data_format=data_format)
  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,
  168. layers=50,
  169. lr_mult=1.0,
  170. last_conv_stride=2,
  171. last_conv_dilation=1):
  172. super(ResNet, self).__init__()
  173. self.layers = layers
  174. self.data_format = "NCHW"
  175. self.input_image_channel = 3
  176. supported_layers = [18, 34, 50, 101, 152]
  177. assert layers in supported_layers, \
  178. "supported layers are {} but input layer is {}".format(
  179. supported_layers, layers)
  180. if layers == 18:
  181. depth = [2, 2, 2, 2]
  182. elif layers == 34 or layers == 50:
  183. depth = [3, 4, 6, 3]
  184. elif layers == 101:
  185. depth = [3, 4, 23, 3]
  186. elif layers == 152:
  187. depth = [3, 8, 36, 3]
  188. num_channels = [64, 256, 512,
  189. 1024] if layers >= 50 else [64, 64, 128, 256]
  190. num_filters = [64, 128, 256, 512]
  191. self.conv = ConvBNLayer(
  192. num_channels=self.input_image_channel,
  193. num_filters=64,
  194. filter_size=7,
  195. stride=2,
  196. act="relu",
  197. lr_mult=lr_mult,
  198. name="conv1",
  199. data_format=self.data_format)
  200. self.pool2d_max = nn.MaxPool2D(
  201. kernel_size=3, stride=2, padding=1, data_format=self.data_format)
  202. self.block_list = []
  203. if layers >= 50:
  204. for block in range(len(depth)):
  205. shortcut = False
  206. for i in range(depth[block]):
  207. if layers in [101, 152] and block == 2:
  208. if i == 0:
  209. conv_name = "res" + str(block + 2) + "a"
  210. else:
  211. conv_name = "res" + str(block + 2) + "b" + str(i)
  212. else:
  213. conv_name = "res" + str(block + 2) + chr(97 + i)
  214. if i != 0 or block == 0:
  215. stride = 1
  216. elif block == len(depth) - 1:
  217. stride = last_conv_stride
  218. else:
  219. stride = 2
  220. bottleneck_block = self.add_sublayer(
  221. conv_name,
  222. BottleneckBlock(
  223. num_channels=num_channels[block]
  224. if i == 0 else num_filters[block] * 4,
  225. num_filters=num_filters[block],
  226. stride=stride,
  227. shortcut=shortcut,
  228. name=conv_name,
  229. lr_mult=lr_mult,
  230. dilation=last_conv_dilation
  231. if block == len(depth) - 1 else 1,
  232. data_format=self.data_format))
  233. self.block_list.append(bottleneck_block)
  234. shortcut = True
  235. else:
  236. for block in range(len(depth)):
  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. conv_name,
  242. BasicBlock(
  243. num_channels=num_channels[block]
  244. if i == 0 else num_filters[block],
  245. num_filters=num_filters[block],
  246. stride=2 if i == 0 and block != 0 else 1,
  247. shortcut=shortcut,
  248. name=conv_name,
  249. data_format=self.data_format))
  250. self.block_list.append(basic_block)
  251. shortcut = True
  252. def forward(self, inputs):
  253. y = self.conv(inputs)
  254. y = self.pool2d_max(y)
  255. for block in self.block_list:
  256. y = block(y)
  257. return y
  258. def ResNet18(**args):
  259. model = ResNet(layers=18, **args)
  260. return model
  261. def ResNet34(**args):
  262. model = ResNet(layers=34, **args)
  263. return model
  264. def ResNet50(pretrained=None, **args):
  265. model = ResNet(layers=50, **args)
  266. if pretrained is not None:
  267. if not (os.path.isdir(pretrained) or
  268. os.path.exists(pretrained + '.pdparams')):
  269. raise ValueError("Model pretrain path {} does not "
  270. "exists.".format(pretrained))
  271. param_state_dict = paddle.load(pretrained + '.pdparams')
  272. model.set_dict(param_state_dict)
  273. return model
  274. def ResNet101(pretrained=None, **args):
  275. model = ResNet(layers=101, **args)
  276. if pretrained is not None:
  277. if not (os.path.isdir(pretrained) or
  278. os.path.exists(pretrained + '.pdparams')):
  279. raise ValueError("Model pretrain path {} does not "
  280. "exists.".format(pretrained))
  281. param_state_dict = paddle.load(pretrained + '.pdparams')
  282. model.set_dict(param_state_dict)
  283. return model
  284. def ResNet152(**args):
  285. model = ResNet(layers=152, **args)
  286. return model