res2net.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. # copyright (c) 2020 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 paddlex.ppcls.utils.save_load import load_dygraph_pretrain, load_dygraph_pretrain_from_url
  27. MODEL_URLS = {
  28. "Res2Net50_26w_4s":
  29. "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/Res2Net50_26w_4s_pretrained.pdparams",
  30. "Res2Net50_14w_8s":
  31. "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/Res2Net50_14w_8s_pretrained.pdparams",
  32. }
  33. __all__ = list(MODEL_URLS.keys())
  34. class ConvBNLayer(nn.Layer):
  35. def __init__(
  36. self,
  37. num_channels,
  38. num_filters,
  39. filter_size,
  40. stride=1,
  41. groups=1,
  42. act=None,
  43. name=None, ):
  44. super(ConvBNLayer, self).__init__()
  45. self._conv = Conv2D(
  46. in_channels=num_channels,
  47. out_channels=num_filters,
  48. kernel_size=filter_size,
  49. stride=stride,
  50. padding=(filter_size - 1) // 2,
  51. groups=groups,
  52. weight_attr=ParamAttr(name=name + "_weights"),
  53. bias_attr=False)
  54. if name == "conv1":
  55. bn_name = "bn_" + name
  56. else:
  57. bn_name = "bn" + name[3:]
  58. self._batch_norm = BatchNorm(
  59. num_filters,
  60. act=act,
  61. param_attr=ParamAttr(name=bn_name + '_scale'),
  62. bias_attr=ParamAttr(bn_name + '_offset'),
  63. moving_mean_name=bn_name + '_mean',
  64. moving_variance_name=bn_name + '_variance')
  65. def forward(self, inputs):
  66. y = self._conv(inputs)
  67. y = self._batch_norm(y)
  68. return y
  69. class BottleneckBlock(nn.Layer):
  70. def __init__(self,
  71. num_channels1,
  72. num_channels2,
  73. num_filters,
  74. stride,
  75. scales,
  76. shortcut=True,
  77. if_first=False,
  78. name=None):
  79. super(BottleneckBlock, self).__init__()
  80. self.stride = stride
  81. self.scales = scales
  82. self.conv0 = ConvBNLayer(
  83. num_channels=num_channels1,
  84. num_filters=num_filters,
  85. filter_size=1,
  86. act='relu',
  87. name=name + "_branch2a")
  88. self.conv1_list = []
  89. for s in range(scales - 1):
  90. conv1 = self.add_sublayer(
  91. name + '_branch2b_' + str(s + 1),
  92. ConvBNLayer(
  93. num_channels=num_filters // scales,
  94. num_filters=num_filters // scales,
  95. filter_size=3,
  96. stride=stride,
  97. act='relu',
  98. name=name + '_branch2b_' + str(s + 1)))
  99. self.conv1_list.append(conv1)
  100. self.pool2d_avg = AvgPool2D(kernel_size=3, stride=stride, padding=1)
  101. self.conv2 = ConvBNLayer(
  102. num_channels=num_filters,
  103. num_filters=num_channels2,
  104. filter_size=1,
  105. act=None,
  106. name=name + "_branch2c")
  107. if not shortcut:
  108. self.short = ConvBNLayer(
  109. num_channels=num_channels1,
  110. num_filters=num_channels2,
  111. filter_size=1,
  112. stride=stride,
  113. name=name + "_branch1")
  114. self.shortcut = shortcut
  115. def forward(self, inputs):
  116. y = self.conv0(inputs)
  117. xs = paddle.split(y, self.scales, 1)
  118. ys = []
  119. for s, conv1 in enumerate(self.conv1_list):
  120. if s == 0 or self.stride == 2:
  121. ys.append(conv1(xs[s]))
  122. else:
  123. ys.append(conv1(paddle.add(xs[s], ys[-1])))
  124. if self.stride == 1:
  125. ys.append(xs[-1])
  126. else:
  127. ys.append(self.pool2d_avg(xs[-1]))
  128. conv1 = paddle.concat(ys, axis=1)
  129. conv2 = self.conv2(conv1)
  130. if self.shortcut:
  131. short = inputs
  132. else:
  133. short = self.short(inputs)
  134. y = paddle.add(x=short, y=conv2)
  135. y = F.relu(y)
  136. return y
  137. class Res2Net(nn.Layer):
  138. def __init__(self, layers=50, scales=4, width=26, class_num=1000):
  139. super(Res2Net, self).__init__()
  140. self.layers = layers
  141. self.scales = scales
  142. self.width = width
  143. basic_width = self.width * self.scales
  144. supported_layers = [50, 101, 152, 200]
  145. assert layers in supported_layers, \
  146. "supported layers are {} but input layer is {}".format(
  147. supported_layers, layers)
  148. if layers == 50:
  149. depth = [3, 4, 6, 3]
  150. elif layers == 101:
  151. depth = [3, 4, 23, 3]
  152. elif layers == 152:
  153. depth = [3, 8, 36, 3]
  154. elif layers == 200:
  155. depth = [3, 12, 48, 3]
  156. num_channels = [64, 256, 512, 1024]
  157. num_channels2 = [256, 512, 1024, 2048]
  158. num_filters = [basic_width * t for t in [1, 2, 4, 8]]
  159. self.conv1 = ConvBNLayer(
  160. num_channels=3,
  161. num_filters=64,
  162. filter_size=7,
  163. stride=2,
  164. act='relu',
  165. name="conv1")
  166. self.pool2d_max = MaxPool2D(kernel_size=3, stride=2, padding=1)
  167. self.block_list = []
  168. for block in range(len(depth)):
  169. shortcut = False
  170. for i in range(depth[block]):
  171. if layers in [101, 152] and block == 2:
  172. if i == 0:
  173. conv_name = "res" + str(block + 2) + "a"
  174. else:
  175. conv_name = "res" + str(block + 2) + "b" + str(i)
  176. else:
  177. conv_name = "res" + str(block + 2) + chr(97 + i)
  178. bottleneck_block = self.add_sublayer(
  179. 'bb_%d_%d' % (block, i),
  180. BottleneckBlock(
  181. num_channels1=num_channels[block]
  182. if i == 0 else num_channels2[block],
  183. num_channels2=num_channels2[block],
  184. num_filters=num_filters[block],
  185. stride=2 if i == 0 and block != 0 else 1,
  186. scales=scales,
  187. shortcut=shortcut,
  188. if_first=block == i == 0,
  189. name=conv_name))
  190. self.block_list.append(bottleneck_block)
  191. shortcut = True
  192. self.pool2d_avg = AdaptiveAvgPool2D(1)
  193. self.pool2d_avg_channels = num_channels[-1] * 2
  194. stdv = 1.0 / math.sqrt(self.pool2d_avg_channels * 1.0)
  195. self.out = Linear(
  196. self.pool2d_avg_channels,
  197. class_num,
  198. weight_attr=ParamAttr(
  199. initializer=Uniform(-stdv, stdv), name="fc_weights"),
  200. bias_attr=ParamAttr(name="fc_offset"))
  201. def forward(self, inputs):
  202. y = self.conv1(inputs)
  203. y = self.pool2d_max(y)
  204. for block in self.block_list:
  205. y = block(y)
  206. y = self.pool2d_avg(y)
  207. y = paddle.reshape(y, shape=[-1, self.pool2d_avg_channels])
  208. y = self.out(y)
  209. return y
  210. def _load_pretrained(pretrained, model, model_url, use_ssld=False):
  211. if pretrained is False:
  212. pass
  213. elif pretrained is True:
  214. load_dygraph_pretrain_from_url(model, model_url, use_ssld=use_ssld)
  215. elif isinstance(pretrained, str):
  216. load_dygraph_pretrain(model, pretrained)
  217. else:
  218. raise RuntimeError(
  219. "pretrained type is not available. Please use `string` or `boolean` type."
  220. )
  221. def Res2Net50_26w_4s(pretrained=False, use_ssld=False, **kwargs):
  222. model = Res2Net(layers=50, scales=4, width=26, **kwargs)
  223. _load_pretrained(
  224. pretrained, model, MODEL_URLS["Res2Net50_26w_4s"], use_ssld=use_ssld)
  225. return model
  226. def Res2Net50_14w_8s(pretrained=False, use_ssld=False, **kwargs):
  227. model = Res2Net(layers=50, scales=8, width=14, **kwargs)
  228. _load_pretrained(
  229. pretrained, model, MODEL_URLS["Res2Net50_14w_8s"], use_ssld=use_ssld)
  230. return model