det_mobilenet_v3.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 paddle
  18. from paddle import nn
  19. import paddle.nn.functional as F
  20. from paddle import ParamAttr
  21. __all__ = ['MobileNetV3']
  22. def make_divisible(v, divisor=8, min_value=None):
  23. if min_value is None:
  24. min_value = divisor
  25. new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
  26. if new_v < 0.9 * v:
  27. new_v += divisor
  28. return new_v
  29. class MobileNetV3(nn.Layer):
  30. def __init__(self,
  31. in_channels=3,
  32. model_name='large',
  33. scale=0.5,
  34. disable_se=False,
  35. **kwargs):
  36. """
  37. the MobilenetV3 backbone network for detection module.
  38. Args:
  39. params(dict): the super parameters for build network
  40. """
  41. super(MobileNetV3, self).__init__()
  42. self.disable_se = disable_se
  43. if model_name == "large":
  44. cfg = [
  45. # k, exp, c, se, nl, s,
  46. [3, 16, 16, False, 'relu', 1],
  47. [3, 64, 24, False, 'relu', 2],
  48. [3, 72, 24, False, 'relu', 1],
  49. [5, 72, 40, True, 'relu', 2],
  50. [5, 120, 40, True, 'relu', 1],
  51. [5, 120, 40, True, 'relu', 1],
  52. [3, 240, 80, False, 'hardswish', 2],
  53. [3, 200, 80, False, 'hardswish', 1],
  54. [3, 184, 80, False, 'hardswish', 1],
  55. [3, 184, 80, False, 'hardswish', 1],
  56. [3, 480, 112, True, 'hardswish', 1],
  57. [3, 672, 112, True, 'hardswish', 1],
  58. [5, 672, 160, True, 'hardswish', 2],
  59. [5, 960, 160, True, 'hardswish', 1],
  60. [5, 960, 160, True, 'hardswish', 1],
  61. ]
  62. cls_ch_squeeze = 960
  63. elif model_name == "small":
  64. cfg = [
  65. # k, exp, c, se, nl, s,
  66. [3, 16, 16, True, 'relu', 2],
  67. [3, 72, 24, False, 'relu', 2],
  68. [3, 88, 24, False, 'relu', 1],
  69. [5, 96, 40, True, 'hardswish', 2],
  70. [5, 240, 40, True, 'hardswish', 1],
  71. [5, 240, 40, True, 'hardswish', 1],
  72. [5, 120, 48, True, 'hardswish', 1],
  73. [5, 144, 48, True, 'hardswish', 1],
  74. [5, 288, 96, True, 'hardswish', 2],
  75. [5, 576, 96, True, 'hardswish', 1],
  76. [5, 576, 96, True, 'hardswish', 1],
  77. ]
  78. cls_ch_squeeze = 576
  79. else:
  80. raise NotImplementedError("mode[" + model_name +
  81. "_model] is not implemented!")
  82. supported_scale = [0.35, 0.5, 0.75, 1.0, 1.25]
  83. assert scale in supported_scale, \
  84. "supported scale are {} but input scale is {}".format(supported_scale, scale)
  85. inplanes = 16
  86. # conv1
  87. self.conv = ConvBNLayer(
  88. in_channels=in_channels,
  89. out_channels=make_divisible(inplanes * scale),
  90. kernel_size=3,
  91. stride=2,
  92. padding=1,
  93. groups=1,
  94. if_act=True,
  95. act='hardswish',
  96. name='conv1')
  97. self.stages = []
  98. self.out_channels = []
  99. block_list = []
  100. i = 0
  101. inplanes = make_divisible(inplanes * scale)
  102. for (k, exp, c, se, nl, s) in cfg:
  103. se = se and not self.disable_se
  104. start_idx = 2 if model_name == 'large' else 0
  105. if s == 2 and i > start_idx:
  106. self.out_channels.append(inplanes)
  107. self.stages.append(nn.Sequential(*block_list))
  108. block_list = []
  109. block_list.append(
  110. ResidualUnit(
  111. in_channels=inplanes,
  112. mid_channels=make_divisible(scale * exp),
  113. out_channels=make_divisible(scale * c),
  114. kernel_size=k,
  115. stride=s,
  116. use_se=se,
  117. act=nl,
  118. name="conv" + str(i + 2)))
  119. inplanes = make_divisible(scale * c)
  120. i += 1
  121. block_list.append(
  122. ConvBNLayer(
  123. in_channels=inplanes,
  124. out_channels=make_divisible(scale * cls_ch_squeeze),
  125. kernel_size=1,
  126. stride=1,
  127. padding=0,
  128. groups=1,
  129. if_act=True,
  130. act='hardswish',
  131. name='conv_last'))
  132. self.stages.append(nn.Sequential(*block_list))
  133. self.out_channels.append(make_divisible(scale * cls_ch_squeeze))
  134. for i, stage in enumerate(self.stages):
  135. self.add_sublayer(sublayer=stage, name="stage{}".format(i))
  136. def forward(self, x):
  137. x = self.conv(x)
  138. out_list = []
  139. for stage in self.stages:
  140. x = stage(x)
  141. out_list.append(x)
  142. return out_list
  143. class ConvBNLayer(nn.Layer):
  144. def __init__(self,
  145. in_channels,
  146. out_channels,
  147. kernel_size,
  148. stride,
  149. padding,
  150. groups=1,
  151. if_act=True,
  152. act=None,
  153. name=None):
  154. super(ConvBNLayer, self).__init__()
  155. self.if_act = if_act
  156. self.act = act
  157. self.conv = nn.Conv2D(
  158. in_channels=in_channels,
  159. out_channels=out_channels,
  160. kernel_size=kernel_size,
  161. stride=stride,
  162. padding=padding,
  163. groups=groups,
  164. weight_attr=ParamAttr(name=name + '_weights'),
  165. bias_attr=False)
  166. self.bn = nn.BatchNorm(
  167. num_channels=out_channels,
  168. act=None,
  169. param_attr=ParamAttr(name=name + "_bn_scale"),
  170. bias_attr=ParamAttr(name=name + "_bn_offset"),
  171. moving_mean_name=name + "_bn_mean",
  172. moving_variance_name=name + "_bn_variance")
  173. def forward(self, x):
  174. x = self.conv(x)
  175. x = self.bn(x)
  176. if self.if_act:
  177. if self.act == "relu":
  178. x = F.relu(x)
  179. elif self.act == "hardswish":
  180. x = F.hardswish(x)
  181. else:
  182. print("The activation function({}) is selected incorrectly.".
  183. format(self.act))
  184. exit()
  185. return x
  186. class ResidualUnit(nn.Layer):
  187. def __init__(self,
  188. in_channels,
  189. mid_channels,
  190. out_channels,
  191. kernel_size,
  192. stride,
  193. use_se,
  194. act=None,
  195. name=''):
  196. super(ResidualUnit, self).__init__()
  197. self.if_shortcut = stride == 1 and in_channels == out_channels
  198. self.if_se = use_se
  199. self.expand_conv = ConvBNLayer(
  200. in_channels=in_channels,
  201. out_channels=mid_channels,
  202. kernel_size=1,
  203. stride=1,
  204. padding=0,
  205. if_act=True,
  206. act=act,
  207. name=name + "_expand")
  208. self.bottleneck_conv = ConvBNLayer(
  209. in_channels=mid_channels,
  210. out_channels=mid_channels,
  211. kernel_size=kernel_size,
  212. stride=stride,
  213. padding=int((kernel_size - 1) // 2),
  214. groups=mid_channels,
  215. if_act=True,
  216. act=act,
  217. name=name + "_depthwise")
  218. if self.if_se:
  219. self.mid_se = SEModule(mid_channels, name=name + "_se")
  220. self.linear_conv = ConvBNLayer(
  221. in_channels=mid_channels,
  222. out_channels=out_channels,
  223. kernel_size=1,
  224. stride=1,
  225. padding=0,
  226. if_act=False,
  227. act=None,
  228. name=name + "_linear")
  229. def forward(self, inputs):
  230. x = self.expand_conv(inputs)
  231. x = self.bottleneck_conv(x)
  232. if self.if_se:
  233. x = self.mid_se(x)
  234. x = self.linear_conv(x)
  235. if self.if_shortcut:
  236. x = paddle.add(inputs, x)
  237. return x
  238. class SEModule(nn.Layer):
  239. def __init__(self, in_channels, reduction=4, name=""):
  240. super(SEModule, self).__init__()
  241. self.avg_pool = nn.AdaptiveAvgPool2D(1)
  242. self.conv1 = nn.Conv2D(
  243. in_channels=in_channels,
  244. out_channels=in_channels // reduction,
  245. kernel_size=1,
  246. stride=1,
  247. padding=0,
  248. weight_attr=ParamAttr(name=name + "_1_weights"),
  249. bias_attr=ParamAttr(name=name + "_1_offset"))
  250. self.conv2 = nn.Conv2D(
  251. in_channels=in_channels // reduction,
  252. out_channels=in_channels,
  253. kernel_size=1,
  254. stride=1,
  255. padding=0,
  256. weight_attr=ParamAttr(name + "_2_weights"),
  257. bias_attr=ParamAttr(name=name + "_2_offset"))
  258. def forward(self, inputs):
  259. outputs = self.avg_pool(inputs)
  260. outputs = self.conv1(outputs)
  261. outputs = F.relu(outputs)
  262. outputs = self.conv2(outputs)
  263. outputs = F.hardsigmoid(outputs, slope=0.2, offset=0.5)
  264. return inputs * outputs