det_mobilenet_v3.py 8.9 KB

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