mv3.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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 numpy as np
  18. import paddle
  19. from paddle import ParamAttr
  20. import paddle.nn as nn
  21. import paddle.nn.functional as F
  22. from paddle.nn.functional import hardswish, hardsigmoid
  23. from paddle.nn import Conv2D, BatchNorm, Linear, Dropout
  24. from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D
  25. from paddle.regularizer import L2Decay
  26. import math
  27. from paddle.utils.cpp_extension import load
  28. # jit compile custom op
  29. custom_ops = load(
  30. name="custom_jit_ops",
  31. sources=["./custom_op/custom_relu_op.cc", "./custom_op/custom_relu_op.cu"],
  32. )
  33. def make_divisible(v, divisor=8, min_value=None):
  34. if min_value is None:
  35. min_value = divisor
  36. new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
  37. if new_v < 0.9 * v:
  38. new_v += divisor
  39. return new_v
  40. class MobileNetV3(nn.Layer):
  41. def __init__(
  42. self,
  43. scale=1.0,
  44. model_name="small",
  45. dropout_prob=0.2,
  46. class_dim=1000,
  47. use_custom_relu=False,
  48. ):
  49. super(MobileNetV3, self).__init__()
  50. self.use_custom_relu = use_custom_relu
  51. inplanes = 16
  52. if model_name == "large":
  53. self.cfg = [
  54. # k, exp, c, se, nl, s,
  55. [3, 16, 16, False, "relu", 1],
  56. [3, 64, 24, False, "relu", 2],
  57. [3, 72, 24, False, "relu", 1],
  58. [5, 72, 40, True, "relu", 2],
  59. [5, 120, 40, True, "relu", 1],
  60. [5, 120, 40, True, "relu", 1],
  61. [3, 240, 80, False, "hardswish", 2],
  62. [3, 200, 80, False, "hardswish", 1],
  63. [3, 184, 80, False, "hardswish", 1],
  64. [3, 184, 80, False, "hardswish", 1],
  65. [3, 480, 112, True, "hardswish", 1],
  66. [3, 672, 112, True, "hardswish", 1],
  67. [5, 672, 160, True, "hardswish", 2],
  68. [5, 960, 160, True, "hardswish", 1],
  69. [5, 960, 160, True, "hardswish", 1],
  70. ]
  71. self.cls_ch_squeeze = 960
  72. self.cls_ch_expand = 1280
  73. elif model_name == "small":
  74. self.cfg = [
  75. # k, exp, c, se, nl, s,
  76. [3, 16, 16, True, "relu", 2],
  77. [3, 72, 24, False, "relu", 2],
  78. [3, 88, 24, False, "relu", 1],
  79. [5, 96, 40, True, "hardswish", 2],
  80. [5, 240, 40, True, "hardswish", 1],
  81. [5, 240, 40, True, "hardswish", 1],
  82. [5, 120, 48, True, "hardswish", 1],
  83. [5, 144, 48, True, "hardswish", 1],
  84. [5, 288, 96, True, "hardswish", 2],
  85. [5, 576, 96, True, "hardswish", 1],
  86. [5, 576, 96, True, "hardswish", 1],
  87. ]
  88. self.cls_ch_squeeze = 576
  89. self.cls_ch_expand = 1280
  90. else:
  91. raise NotImplementedError(
  92. "mode[{}_model] is not implemented!".format(model_name)
  93. )
  94. self.conv1 = ConvBNLayer(
  95. in_c=3,
  96. out_c=make_divisible(inplanes * scale),
  97. filter_size=3,
  98. stride=2,
  99. padding=1,
  100. num_groups=1,
  101. if_act=True,
  102. act="hardswish",
  103. name="conv1",
  104. use_custom_relu=self.use_custom_relu,
  105. )
  106. self.block_list = []
  107. i = 0
  108. inplanes = make_divisible(inplanes * scale)
  109. for k, exp, c, se, nl, s in self.cfg:
  110. block = self.add_sublayer(
  111. "conv" + str(i + 2),
  112. ResidualUnit(
  113. in_c=inplanes,
  114. mid_c=make_divisible(scale * exp),
  115. out_c=make_divisible(scale * c),
  116. filter_size=k,
  117. stride=s,
  118. use_se=se,
  119. act=nl,
  120. name="conv" + str(i + 2),
  121. use_custom_relu=self.use_custom_relu,
  122. ),
  123. )
  124. self.block_list.append(block)
  125. inplanes = make_divisible(scale * c)
  126. i += 1
  127. self.last_second_conv = ConvBNLayer(
  128. in_c=inplanes,
  129. out_c=make_divisible(scale * self.cls_ch_squeeze),
  130. filter_size=1,
  131. stride=1,
  132. padding=0,
  133. num_groups=1,
  134. if_act=True,
  135. act="hardswish",
  136. name="conv_last",
  137. use_custom_relu=self.use_custom_relu,
  138. )
  139. self.pool = AdaptiveAvgPool2D(1)
  140. self.last_conv = Conv2D(
  141. in_channels=make_divisible(scale * self.cls_ch_squeeze),
  142. out_channels=self.cls_ch_expand,
  143. kernel_size=1,
  144. stride=1,
  145. padding=0,
  146. weight_attr=ParamAttr(),
  147. bias_attr=False,
  148. )
  149. self.dropout = Dropout(p=dropout_prob, mode="downscale_in_infer")
  150. self.out = Linear(
  151. self.cls_ch_expand,
  152. class_dim,
  153. weight_attr=ParamAttr(),
  154. bias_attr=ParamAttr(),
  155. )
  156. def forward(self, inputs, label=None):
  157. x = self.conv1(inputs)
  158. for block in self.block_list:
  159. x = block(x)
  160. x = self.last_second_conv(x)
  161. x = self.pool(x)
  162. x = self.last_conv(x)
  163. x = hardswish(x)
  164. x = self.dropout(x)
  165. x = paddle.flatten(x, start_axis=1, stop_axis=-1)
  166. x = self.out(x)
  167. return x
  168. class ConvBNLayer(nn.Layer):
  169. def __init__(
  170. self,
  171. in_c,
  172. out_c,
  173. filter_size,
  174. stride,
  175. padding,
  176. num_groups=1,
  177. if_act=True,
  178. act=None,
  179. use_cudnn=True,
  180. name="",
  181. use_custom_relu=False,
  182. ):
  183. super(ConvBNLayer, self).__init__()
  184. self.if_act = if_act
  185. self.act = act
  186. self.conv = Conv2D(
  187. in_channels=in_c,
  188. out_channels=out_c,
  189. kernel_size=filter_size,
  190. stride=stride,
  191. padding=padding,
  192. groups=num_groups,
  193. weight_attr=ParamAttr(),
  194. bias_attr=False,
  195. )
  196. self.bn = BatchNorm(
  197. num_channels=out_c,
  198. act=None,
  199. param_attr=ParamAttr(regularizer=L2Decay(0.0)),
  200. bias_attr=ParamAttr(regularizer=L2Decay(0.0)),
  201. )
  202. # moving_mean_name=name + "_bn_mean",
  203. # moving_variance_name=name + "_bn_variance")
  204. self.use_custom_relu = use_custom_relu
  205. def forward(self, x):
  206. x = self.conv(x)
  207. x = self.bn(x)
  208. if self.if_act:
  209. if self.act == "relu":
  210. if self.use_custom_relu:
  211. x = custom_ops.custom_relu(x)
  212. else:
  213. x = F.relu(x)
  214. elif self.act == "hardswish":
  215. x = hardswish(x)
  216. else:
  217. print("The activation function is selected incorrectly.")
  218. exit()
  219. return x
  220. class ResidualUnit(nn.Layer):
  221. def __init__(
  222. self,
  223. in_c,
  224. mid_c,
  225. out_c,
  226. filter_size,
  227. stride,
  228. use_se,
  229. act=None,
  230. name="",
  231. use_custom_relu=False,
  232. ):
  233. super(ResidualUnit, self).__init__()
  234. self.if_shortcut = stride == 1 and in_c == out_c
  235. self.if_se = use_se
  236. self.use_custom_relu = use_custom_relu
  237. self.expand_conv = ConvBNLayer(
  238. in_c=in_c,
  239. out_c=mid_c,
  240. filter_size=1,
  241. stride=1,
  242. padding=0,
  243. if_act=True,
  244. act=act,
  245. name=name + "_expand",
  246. use_custom_relu=self.use_custom_relu,
  247. )
  248. self.bottleneck_conv = ConvBNLayer(
  249. in_c=mid_c,
  250. out_c=mid_c,
  251. filter_size=filter_size,
  252. stride=stride,
  253. padding=int((filter_size - 1) // 2),
  254. num_groups=mid_c,
  255. if_act=True,
  256. act=act,
  257. name=name + "_depthwise",
  258. use_custom_relu=self.use_custom_relu,
  259. )
  260. if self.if_se:
  261. self.mid_se = SEModule(mid_c, name=name + "_se")
  262. self.linear_conv = ConvBNLayer(
  263. in_c=mid_c,
  264. out_c=out_c,
  265. filter_size=1,
  266. stride=1,
  267. padding=0,
  268. if_act=False,
  269. act=None,
  270. name=name + "_linear",
  271. use_custom_relu=self.use_custom_relu,
  272. )
  273. def forward(self, inputs):
  274. x = self.expand_conv(inputs)
  275. x = self.bottleneck_conv(x)
  276. if self.if_se:
  277. x = self.mid_se(x)
  278. x = self.linear_conv(x)
  279. if self.if_shortcut:
  280. x = paddle.add(inputs, x)
  281. return x
  282. class SEModule(nn.Layer):
  283. def __init__(self, channel, reduction=4, name=""):
  284. super(SEModule, self).__init__()
  285. self.avg_pool = AdaptiveAvgPool2D(1)
  286. self.conv1 = Conv2D(
  287. in_channels=channel,
  288. out_channels=channel // reduction,
  289. kernel_size=1,
  290. stride=1,
  291. padding=0,
  292. weight_attr=ParamAttr(),
  293. bias_attr=ParamAttr(),
  294. )
  295. self.conv2 = Conv2D(
  296. in_channels=channel // reduction,
  297. out_channels=channel,
  298. kernel_size=1,
  299. stride=1,
  300. padding=0,
  301. weight_attr=ParamAttr(),
  302. bias_attr=ParamAttr(),
  303. )
  304. def forward(self, inputs):
  305. outputs = self.avg_pool(inputs)
  306. outputs = self.conv1(outputs)
  307. outputs = F.relu(outputs)
  308. outputs = self.conv2(outputs)
  309. outputs = hardsigmoid(outputs, slope=0.2, offset=0.5)
  310. return paddle.multiply(x=inputs, y=outputs)
  311. def MobileNetV3_small_x0_35(**args):
  312. model = MobileNetV3(model_name="small", scale=0.35, **args)
  313. return model
  314. def MobileNetV3_small_x0_5(**args):
  315. model = MobileNetV3(model_name="small", scale=0.5, **args)
  316. return model
  317. def MobileNetV3_small_x0_75(**args):
  318. model = MobileNetV3(model_name="small", scale=0.75, **args)
  319. return model
  320. def MobileNetV3_small_x1_0(**args):
  321. model = MobileNetV3(model_name="small", scale=1.0, **args)
  322. return model
  323. def MobileNetV3_small_x1_25(**args):
  324. model = MobileNetV3(model_name="small", scale=1.25, **args)
  325. return model
  326. def MobileNetV3_large_x0_35(**args):
  327. model = MobileNetV3(model_name="large", scale=0.35, **args)
  328. return model
  329. def MobileNetV3_large_x0_5(**args):
  330. model = MobileNetV3(model_name="large", scale=0.5, **args)
  331. return model
  332. def MobileNetV3_large_x0_75(**args):
  333. model = MobileNetV3(model_name="large", scale=0.75, **args)
  334. return model
  335. def MobileNetV3_large_x1_0(**args):
  336. model = MobileNetV3(model_name="large", scale=1.0, **args)
  337. return model
  338. def MobileNetV3_large_x1_25(**args):
  339. model = MobileNetV3(model_name="large", scale=1.25, **args)
  340. return
  341. class DistillMV3(nn.Layer):
  342. def __init__(
  343. self,
  344. scale=1.0,
  345. model_name="small",
  346. dropout_prob=0.2,
  347. class_dim=1000,
  348. args=None,
  349. use_custom_relu=False,
  350. ):
  351. super(DistillMV3, self).__init__()
  352. self.student = MobileNetV3(
  353. model_name=model_name,
  354. scale=scale,
  355. class_dim=class_dim,
  356. use_custom_relu=use_custom_relu,
  357. )
  358. self.student1 = MobileNetV3(
  359. model_name=model_name,
  360. scale=scale,
  361. class_dim=class_dim,
  362. use_custom_relu=use_custom_relu,
  363. )
  364. def forward(self, inputs, label=None):
  365. predicts = dict()
  366. predicts["student"] = self.student(inputs, label)
  367. predicts["student1"] = self.student1(inputs, label)
  368. return predicts
  369. def distillmv3_large_x0_5(**args):
  370. model = DistillMV3(model_name="large", scale=0.5, **args)
  371. return model
  372. class SiameseMV3(nn.Layer):
  373. def __init__(
  374. self,
  375. scale=1.0,
  376. model_name="small",
  377. dropout_prob=0.2,
  378. class_dim=1000,
  379. args=None,
  380. use_custom_relu=False,
  381. ):
  382. super(SiameseMV3, self).__init__()
  383. self.net = MobileNetV3(
  384. model_name=model_name,
  385. scale=scale,
  386. class_dim=class_dim,
  387. use_custom_relu=use_custom_relu,
  388. )
  389. self.net1 = MobileNetV3(
  390. model_name=model_name,
  391. scale=scale,
  392. class_dim=class_dim,
  393. use_custom_relu=use_custom_relu,
  394. )
  395. def forward(self, inputs, label=None):
  396. # net
  397. x = self.net.conv1(inputs)
  398. for block in self.net.block_list:
  399. x = block(x)
  400. # net1
  401. x1 = self.net1.conv1(inputs)
  402. for block in self.net1.block_list:
  403. x1 = block(x1)
  404. # add
  405. x = x + x1
  406. x = self.net.last_second_conv(x)
  407. x = self.net.pool(x)
  408. x = self.net.last_conv(x)
  409. x = hardswish(x)
  410. x = self.net.dropout(x)
  411. x = paddle.flatten(x, start_axis=1, stop_axis=-1)
  412. x = self.net.out(x)
  413. return x
  414. def siamese_mv3(class_dim, use_custom_relu):
  415. model = SiameseMV3(
  416. scale=0.5,
  417. model_name="large",
  418. class_dim=class_dim,
  419. use_custom_relu=use_custom_relu,
  420. )
  421. return model
  422. def build_model(config):
  423. model_type = config["model_type"]
  424. if model_type == "cls":
  425. class_dim = config["MODEL"]["class_dim"]
  426. use_custom_relu = config["MODEL"]["use_custom_relu"]
  427. if "siamese" in config["MODEL"] and config["MODEL"]["siamese"] is True:
  428. model = siamese_mv3(class_dim=class_dim, use_custom_relu=use_custom_relu)
  429. else:
  430. model = MobileNetV3_large_x0_5(
  431. class_dim=class_dim, use_custom_relu=use_custom_relu
  432. )
  433. elif model_type == "cls_distill":
  434. class_dim = config["MODEL"]["class_dim"]
  435. use_custom_relu = config["MODEL"]["use_custom_relu"]
  436. model = distillmv3_large_x0_5(
  437. class_dim=class_dim, use_custom_relu=use_custom_relu
  438. )
  439. elif model_type == "cls_distill_multiopt":
  440. class_dim = config["MODEL"]["class_dim"]
  441. use_custom_relu = config["MODEL"]["use_custom_relu"]
  442. model = distillmv3_large_x0_5(class_dim=100, use_custom_relu=use_custom_relu)
  443. else:
  444. raise ValueError("model_type should be one of ['']")
  445. return model