mobilenet_v3.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. import paddle.nn as nn
  19. import paddle.nn.functional as F
  20. from paddle import ParamAttr
  21. from paddle.regularizer import L2Decay
  22. from paddlex.ppdet.core.workspace import register, serializable
  23. from numbers import Integral
  24. from ..shape_spec import ShapeSpec
  25. __all__ = ['MobileNetV3']
  26. def make_divisible(v, divisor=8, min_value=None):
  27. if min_value is None:
  28. min_value = divisor
  29. new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
  30. if new_v < 0.9 * v:
  31. new_v += divisor
  32. return new_v
  33. class ConvBNLayer(nn.Layer):
  34. def __init__(self,
  35. in_c,
  36. out_c,
  37. filter_size,
  38. stride,
  39. padding,
  40. num_groups=1,
  41. act=None,
  42. lr_mult=1.,
  43. conv_decay=0.,
  44. norm_type='bn',
  45. norm_decay=0.,
  46. freeze_norm=False,
  47. name=""):
  48. super(ConvBNLayer, self).__init__()
  49. self.act = act
  50. self.conv = nn.Conv2D(
  51. in_channels=in_c,
  52. out_channels=out_c,
  53. kernel_size=filter_size,
  54. stride=stride,
  55. padding=padding,
  56. groups=num_groups,
  57. weight_attr=ParamAttr(
  58. learning_rate=lr_mult, regularizer=L2Decay(conv_decay)),
  59. bias_attr=False)
  60. norm_lr = 0. if freeze_norm else lr_mult
  61. param_attr = ParamAttr(
  62. learning_rate=norm_lr,
  63. regularizer=L2Decay(norm_decay),
  64. trainable=False if freeze_norm else True)
  65. bias_attr = ParamAttr(
  66. learning_rate=norm_lr,
  67. regularizer=L2Decay(norm_decay),
  68. trainable=False if freeze_norm else True)
  69. global_stats = True if freeze_norm else False
  70. if norm_type == 'sync_bn':
  71. self.bn = nn.SyncBatchNorm(
  72. out_c, weight_attr=param_attr, bias_attr=bias_attr)
  73. else:
  74. self.bn = nn.BatchNorm(
  75. out_c,
  76. act=None,
  77. param_attr=param_attr,
  78. bias_attr=bias_attr,
  79. use_global_stats=global_stats)
  80. norm_params = self.bn.parameters()
  81. if freeze_norm:
  82. for param in norm_params:
  83. param.stop_gradient = True
  84. def forward(self, x):
  85. x = self.conv(x)
  86. x = self.bn(x)
  87. if self.act is not None:
  88. if self.act == "relu":
  89. x = F.relu(x)
  90. elif self.act == "relu6":
  91. x = F.relu6(x)
  92. elif self.act == "hard_swish":
  93. x = F.hardswish(x)
  94. else:
  95. raise NotImplementedError(
  96. "The activation function is selected incorrectly.")
  97. return x
  98. class ResidualUnit(nn.Layer):
  99. def __init__(self,
  100. in_c,
  101. mid_c,
  102. out_c,
  103. filter_size,
  104. stride,
  105. use_se,
  106. lr_mult,
  107. conv_decay=0.,
  108. norm_type='bn',
  109. norm_decay=0.,
  110. freeze_norm=False,
  111. act=None,
  112. return_list=False,
  113. name=''):
  114. super(ResidualUnit, self).__init__()
  115. self.if_shortcut = stride == 1 and in_c == out_c
  116. self.use_se = use_se
  117. self.return_list = return_list
  118. self.expand_conv = ConvBNLayer(
  119. in_c=in_c,
  120. out_c=mid_c,
  121. filter_size=1,
  122. stride=1,
  123. padding=0,
  124. act=act,
  125. lr_mult=lr_mult,
  126. conv_decay=conv_decay,
  127. norm_type=norm_type,
  128. norm_decay=norm_decay,
  129. freeze_norm=freeze_norm,
  130. name=name + "_expand")
  131. self.bottleneck_conv = ConvBNLayer(
  132. in_c=mid_c,
  133. out_c=mid_c,
  134. filter_size=filter_size,
  135. stride=stride,
  136. padding=int((filter_size - 1) // 2),
  137. num_groups=mid_c,
  138. act=act,
  139. lr_mult=lr_mult,
  140. conv_decay=conv_decay,
  141. norm_type=norm_type,
  142. norm_decay=norm_decay,
  143. freeze_norm=freeze_norm,
  144. name=name + "_depthwise")
  145. if self.use_se:
  146. self.mid_se = SEModule(
  147. mid_c, lr_mult, conv_decay, name=name + "_se")
  148. self.linear_conv = ConvBNLayer(
  149. in_c=mid_c,
  150. out_c=out_c,
  151. filter_size=1,
  152. stride=1,
  153. padding=0,
  154. act=None,
  155. lr_mult=lr_mult,
  156. conv_decay=conv_decay,
  157. norm_type=norm_type,
  158. norm_decay=norm_decay,
  159. freeze_norm=freeze_norm,
  160. name=name + "_linear")
  161. def forward(self, inputs):
  162. y = self.expand_conv(inputs)
  163. x = self.bottleneck_conv(y)
  164. if self.use_se:
  165. x = self.mid_se(x)
  166. x = self.linear_conv(x)
  167. if self.if_shortcut:
  168. x = paddle.add(inputs, x)
  169. if self.return_list:
  170. return [y, x]
  171. else:
  172. return x
  173. class SEModule(nn.Layer):
  174. def __init__(self, channel, lr_mult, conv_decay, reduction=4, name=""):
  175. super(SEModule, self).__init__()
  176. self.avg_pool = nn.AdaptiveAvgPool2D(1)
  177. mid_channels = int(channel // reduction)
  178. self.conv1 = nn.Conv2D(
  179. in_channels=channel,
  180. out_channels=mid_channels,
  181. kernel_size=1,
  182. stride=1,
  183. padding=0,
  184. weight_attr=ParamAttr(
  185. learning_rate=lr_mult, regularizer=L2Decay(conv_decay)),
  186. bias_attr=ParamAttr(
  187. learning_rate=lr_mult, regularizer=L2Decay(conv_decay)))
  188. self.conv2 = nn.Conv2D(
  189. in_channels=mid_channels,
  190. out_channels=channel,
  191. kernel_size=1,
  192. stride=1,
  193. padding=0,
  194. weight_attr=ParamAttr(
  195. learning_rate=lr_mult, regularizer=L2Decay(conv_decay)),
  196. bias_attr=ParamAttr(
  197. learning_rate=lr_mult, regularizer=L2Decay(conv_decay)))
  198. def forward(self, inputs):
  199. outputs = self.avg_pool(inputs)
  200. outputs = self.conv1(outputs)
  201. outputs = F.relu(outputs)
  202. outputs = self.conv2(outputs)
  203. outputs = F.hardsigmoid(outputs, slope=0.2, offset=0.5)
  204. return paddle.multiply(x=inputs, y=outputs)
  205. class ExtraBlockDW(nn.Layer):
  206. def __init__(self,
  207. in_c,
  208. ch_1,
  209. ch_2,
  210. stride,
  211. lr_mult,
  212. conv_decay=0.,
  213. norm_type='bn',
  214. norm_decay=0.,
  215. freeze_norm=False,
  216. name=None):
  217. super(ExtraBlockDW, self).__init__()
  218. self.pointwise_conv = ConvBNLayer(
  219. in_c=in_c,
  220. out_c=ch_1,
  221. filter_size=1,
  222. stride=1,
  223. padding='SAME',
  224. act='relu6',
  225. lr_mult=lr_mult,
  226. conv_decay=conv_decay,
  227. norm_type=norm_type,
  228. norm_decay=norm_decay,
  229. freeze_norm=freeze_norm,
  230. name=name + "_extra1")
  231. self.depthwise_conv = ConvBNLayer(
  232. in_c=ch_1,
  233. out_c=ch_2,
  234. filter_size=3,
  235. stride=stride,
  236. padding='SAME',
  237. num_groups=int(ch_1),
  238. act='relu6',
  239. lr_mult=lr_mult,
  240. conv_decay=conv_decay,
  241. norm_type=norm_type,
  242. norm_decay=norm_decay,
  243. freeze_norm=freeze_norm,
  244. name=name + "_extra2_dw")
  245. self.normal_conv = ConvBNLayer(
  246. in_c=ch_2,
  247. out_c=ch_2,
  248. filter_size=1,
  249. stride=1,
  250. padding='SAME',
  251. act='relu6',
  252. lr_mult=lr_mult,
  253. conv_decay=conv_decay,
  254. norm_type=norm_type,
  255. norm_decay=norm_decay,
  256. freeze_norm=freeze_norm,
  257. name=name + "_extra2_sep")
  258. def forward(self, inputs):
  259. x = self.pointwise_conv(inputs)
  260. x = self.depthwise_conv(x)
  261. x = self.normal_conv(x)
  262. return x
  263. @register
  264. @serializable
  265. class MobileNetV3(nn.Layer):
  266. __shared__ = ['norm_type']
  267. def __init__(self,
  268. scale=1.0,
  269. model_name="large",
  270. feature_maps=[6, 12, 15],
  271. with_extra_blocks=False,
  272. extra_block_filters=[[256, 512], [128, 256], [128, 256],
  273. [64, 128]],
  274. lr_mult_list=[1.0, 1.0, 1.0, 1.0, 1.0],
  275. conv_decay=0.0,
  276. multiplier=1.0,
  277. norm_type='bn',
  278. norm_decay=0.0,
  279. freeze_norm=False):
  280. super(MobileNetV3, self).__init__()
  281. if isinstance(feature_maps, Integral):
  282. feature_maps = [feature_maps]
  283. if norm_type == 'sync_bn' and freeze_norm:
  284. raise ValueError(
  285. "The norm_type should not be sync_bn when freeze_norm is True")
  286. self.feature_maps = feature_maps
  287. self.with_extra_blocks = with_extra_blocks
  288. self.extra_block_filters = extra_block_filters
  289. inplanes = 16
  290. if model_name == "large":
  291. self.cfg = [
  292. # k, exp, c, se, nl, s,
  293. [3, 16, 16, False, "relu", 1],
  294. [3, 64, 24, False, "relu", 2],
  295. [3, 72, 24, False, "relu", 1],
  296. [5, 72, 40, True, "relu", 2], # RCNN output
  297. [5, 120, 40, True, "relu", 1],
  298. [5, 120, 40, True, "relu", 1], # YOLOv3 output
  299. [3, 240, 80, False, "hard_swish", 2], # RCNN output
  300. [3, 200, 80, False, "hard_swish", 1],
  301. [3, 184, 80, False, "hard_swish", 1],
  302. [3, 184, 80, False, "hard_swish", 1],
  303. [3, 480, 112, True, "hard_swish", 1],
  304. [3, 672, 112, True, "hard_swish", 1], # YOLOv3 output
  305. [5, 672, 160, True, "hard_swish",
  306. 2], # SSD/SSDLite/RCNN output
  307. [5, 960, 160, True, "hard_swish", 1],
  308. [5, 960, 160, True, "hard_swish", 1], # YOLOv3 output
  309. ]
  310. elif model_name == "small":
  311. self.cfg = [
  312. # k, exp, c, se, nl, s,
  313. [3, 16, 16, True, "relu", 2],
  314. [3, 72, 24, False, "relu", 2], # RCNN output
  315. [3, 88, 24, False, "relu", 1], # YOLOv3 output
  316. [5, 96, 40, True, "hard_swish", 2], # RCNN output
  317. [5, 240, 40, True, "hard_swish", 1],
  318. [5, 240, 40, True, "hard_swish", 1],
  319. [5, 120, 48, True, "hard_swish", 1],
  320. [5, 144, 48, True, "hard_swish", 1], # YOLOv3 output
  321. [5, 288, 96, True, "hard_swish", 2], # SSD/SSDLite/RCNN output
  322. [5, 576, 96, True, "hard_swish", 1],
  323. [5, 576, 96, True, "hard_swish", 1], # YOLOv3 output
  324. ]
  325. else:
  326. raise NotImplementedError(
  327. "mode[{}_model] is not implemented!".format(model_name))
  328. if multiplier != 1.0:
  329. self.cfg[-3][2] = int(self.cfg[-3][2] * multiplier)
  330. self.cfg[-2][1] = int(self.cfg[-2][1] * multiplier)
  331. self.cfg[-2][2] = int(self.cfg[-2][2] * multiplier)
  332. self.cfg[-1][1] = int(self.cfg[-1][1] * multiplier)
  333. self.cfg[-1][2] = int(self.cfg[-1][2] * multiplier)
  334. self.conv1 = ConvBNLayer(
  335. in_c=3,
  336. out_c=make_divisible(inplanes * scale),
  337. filter_size=3,
  338. stride=2,
  339. padding=1,
  340. num_groups=1,
  341. act="hard_swish",
  342. lr_mult=lr_mult_list[0],
  343. conv_decay=conv_decay,
  344. norm_type=norm_type,
  345. norm_decay=norm_decay,
  346. freeze_norm=freeze_norm,
  347. name="conv1")
  348. self._out_channels = []
  349. self.block_list = []
  350. i = 0
  351. inplanes = make_divisible(inplanes * scale)
  352. for (k, exp, c, se, nl, s) in self.cfg:
  353. lr_idx = min(i // 3, len(lr_mult_list) - 1)
  354. lr_mult = lr_mult_list[lr_idx]
  355. # for SSD/SSDLite, first head input is after ResidualUnit expand_conv
  356. return_list = self.with_extra_blocks and i + 2 in self.feature_maps
  357. block = self.add_sublayer(
  358. "conv" + str(i + 2),
  359. sublayer=ResidualUnit(
  360. in_c=inplanes,
  361. mid_c=make_divisible(scale * exp),
  362. out_c=make_divisible(scale * c),
  363. filter_size=k,
  364. stride=s,
  365. use_se=se,
  366. act=nl,
  367. lr_mult=lr_mult,
  368. conv_decay=conv_decay,
  369. norm_type=norm_type,
  370. norm_decay=norm_decay,
  371. freeze_norm=freeze_norm,
  372. return_list=return_list,
  373. name="conv" + str(i + 2)))
  374. self.block_list.append(block)
  375. inplanes = make_divisible(scale * c)
  376. i += 1
  377. self._update_out_channels(
  378. make_divisible(scale * exp)
  379. if return_list else inplanes, i + 1, feature_maps)
  380. if self.with_extra_blocks:
  381. self.extra_block_list = []
  382. extra_out_c = make_divisible(scale * self.cfg[-1][1])
  383. lr_idx = min(i // 3, len(lr_mult_list) - 1)
  384. lr_mult = lr_mult_list[lr_idx]
  385. conv_extra = self.add_sublayer(
  386. "conv" + str(i + 2),
  387. sublayer=ConvBNLayer(
  388. in_c=inplanes,
  389. out_c=extra_out_c,
  390. filter_size=1,
  391. stride=1,
  392. padding=0,
  393. num_groups=1,
  394. act="hard_swish",
  395. lr_mult=lr_mult,
  396. conv_decay=conv_decay,
  397. norm_type=norm_type,
  398. norm_decay=norm_decay,
  399. freeze_norm=freeze_norm,
  400. name="conv" + str(i + 2)))
  401. self.extra_block_list.append(conv_extra)
  402. i += 1
  403. self._update_out_channels(extra_out_c, i + 1, feature_maps)
  404. for j, block_filter in enumerate(self.extra_block_filters):
  405. in_c = extra_out_c if j == 0 else self.extra_block_filters[
  406. j - 1][1]
  407. conv_extra = self.add_sublayer(
  408. "conv" + str(i + 2),
  409. sublayer=ExtraBlockDW(
  410. in_c,
  411. block_filter[0],
  412. block_filter[1],
  413. stride=2,
  414. lr_mult=lr_mult,
  415. conv_decay=conv_decay,
  416. norm_type=norm_type,
  417. norm_decay=norm_decay,
  418. freeze_norm=freeze_norm,
  419. name='conv' + str(i + 2)))
  420. self.extra_block_list.append(conv_extra)
  421. i += 1
  422. self._update_out_channels(block_filter[1], i + 1, feature_maps)
  423. def _update_out_channels(self, channel, feature_idx, feature_maps):
  424. if feature_idx in feature_maps:
  425. self._out_channels.append(channel)
  426. def forward(self, inputs):
  427. x = self.conv1(inputs['image'])
  428. outs = []
  429. for idx, block in enumerate(self.block_list):
  430. x = block(x)
  431. if idx + 2 in self.feature_maps:
  432. if isinstance(x, list):
  433. outs.append(x[0])
  434. x = x[1]
  435. else:
  436. outs.append(x)
  437. if not self.with_extra_blocks:
  438. return outs
  439. for i, block in enumerate(self.extra_block_list):
  440. idx = i + len(self.block_list)
  441. x = block(x)
  442. if idx + 2 in self.feature_maps:
  443. outs.append(x)
  444. return outs
  445. @property
  446. def out_shape(self):
  447. return [ShapeSpec(channels=c) for c in self._out_channels]