det_mobilenet_v3.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. self.stages = []
  97. self.out_channels = []
  98. block_list = []
  99. i = 0
  100. inplanes = make_divisible(inplanes * scale)
  101. for (k, exp, c, se, nl, s) in cfg:
  102. se = se and not self.disable_se
  103. start_idx = 2 if model_name == 'large' else 0
  104. if s == 2 and i > start_idx:
  105. self.out_channels.append(inplanes)
  106. self.stages.append(nn.Sequential(*block_list))
  107. block_list = []
  108. block_list.append(
  109. ResidualUnit(
  110. in_channels=inplanes,
  111. mid_channels=make_divisible(scale * exp),
  112. out_channels=make_divisible(scale * c),
  113. kernel_size=k,
  114. stride=s,
  115. use_se=se,
  116. act=nl))
  117. inplanes = make_divisible(scale * c)
  118. i += 1
  119. block_list.append(
  120. ConvBNLayer(
  121. in_channels=inplanes,
  122. out_channels=make_divisible(scale * cls_ch_squeeze),
  123. kernel_size=1,
  124. stride=1,
  125. padding=0,
  126. groups=1,
  127. if_act=True,
  128. act='hardswish'))
  129. self.stages.append(nn.Sequential(*block_list))
  130. self.out_channels.append(make_divisible(scale * cls_ch_squeeze))
  131. for i, stage in enumerate(self.stages):
  132. self.add_sublayer(sublayer=stage, name="stage{}".format(i))
  133. def forward(self, x):
  134. x = self.conv(x)
  135. out_list = []
  136. for stage in self.stages:
  137. x = stage(x)
  138. out_list.append(x)
  139. return out_list
  140. class ConvBNLayer(nn.Layer):
  141. def __init__(self,
  142. in_channels,
  143. out_channels,
  144. kernel_size,
  145. stride,
  146. padding,
  147. groups=1,
  148. if_act=True,
  149. act=None):
  150. super(ConvBNLayer, self).__init__()
  151. self.if_act = if_act
  152. self.act = act
  153. self.conv = nn.Conv2D(
  154. in_channels=in_channels,
  155. out_channels=out_channels,
  156. kernel_size=kernel_size,
  157. stride=stride,
  158. padding=padding,
  159. groups=groups,
  160. bias_attr=False)
  161. self.bn = nn.BatchNorm(num_channels=out_channels, act=None)
  162. def forward(self, x):
  163. x = self.conv(x)
  164. x = self.bn(x)
  165. if self.if_act:
  166. if self.act == "relu":
  167. x = F.relu(x)
  168. elif self.act == "hardswish":
  169. x = F.hardswish(x)
  170. else:
  171. print("The activation function({}) is selected incorrectly.".
  172. format(self.act))
  173. exit()
  174. return x
  175. class ResidualUnit(nn.Layer):
  176. def __init__(self,
  177. in_channels,
  178. mid_channels,
  179. out_channels,
  180. kernel_size,
  181. stride,
  182. use_se,
  183. act=None):
  184. super(ResidualUnit, self).__init__()
  185. self.if_shortcut = stride == 1 and in_channels == out_channels
  186. self.if_se = use_se
  187. self.expand_conv = ConvBNLayer(
  188. in_channels=in_channels,
  189. out_channels=mid_channels,
  190. kernel_size=1,
  191. stride=1,
  192. padding=0,
  193. if_act=True,
  194. act=act)
  195. self.bottleneck_conv = ConvBNLayer(
  196. in_channels=mid_channels,
  197. out_channels=mid_channels,
  198. kernel_size=kernel_size,
  199. stride=stride,
  200. padding=int((kernel_size - 1) // 2),
  201. groups=mid_channels,
  202. if_act=True,
  203. act=act)
  204. if self.if_se:
  205. self.mid_se = SEModule(mid_channels)
  206. self.linear_conv = ConvBNLayer(
  207. in_channels=mid_channels,
  208. out_channels=out_channels,
  209. kernel_size=1,
  210. stride=1,
  211. padding=0,
  212. if_act=False,
  213. act=None)
  214. def forward(self, inputs):
  215. x = self.expand_conv(inputs)
  216. x = self.bottleneck_conv(x)
  217. if self.if_se:
  218. x = self.mid_se(x)
  219. x = self.linear_conv(x)
  220. if self.if_shortcut:
  221. x = paddle.add(inputs, x)
  222. return x
  223. class SEModule(nn.Layer):
  224. def __init__(self, in_channels, reduction=4):
  225. super(SEModule, self).__init__()
  226. self.avg_pool = nn.AdaptiveAvgPool2D(1)
  227. self.conv1 = nn.Conv2D(
  228. in_channels=in_channels,
  229. out_channels=in_channels // reduction,
  230. kernel_size=1,
  231. stride=1,
  232. padding=0)
  233. self.conv2 = nn.Conv2D(
  234. in_channels=in_channels // reduction,
  235. out_channels=in_channels,
  236. kernel_size=1,
  237. stride=1,
  238. padding=0)
  239. def forward(self, inputs):
  240. outputs = self.avg_pool(inputs)
  241. outputs = self.conv1(outputs)
  242. outputs = F.relu(outputs)
  243. outputs = self.conv2(outputs)
  244. outputs = F.hardsigmoid(outputs, slope=0.2, offset=0.5)
  245. return inputs * outputs