mobilenet_v3.py 16 KB

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