mobilenet_v1.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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.nn as nn
  18. import paddle.nn.functional as F
  19. from paddle import ParamAttr
  20. from paddle.regularizer import L2Decay
  21. from paddle.nn.initializer import KaimingNormal
  22. from paddlex.ppdet.core.workspace import register, serializable
  23. from numbers import Integral
  24. from ..shape_spec import ShapeSpec
  25. __all__ = ['MobileNet']
  26. class ConvBNLayer(nn.Layer):
  27. def __init__(self,
  28. in_channels,
  29. out_channels,
  30. kernel_size,
  31. stride,
  32. padding,
  33. num_groups=1,
  34. act='relu',
  35. conv_lr=1.,
  36. conv_decay=0.,
  37. norm_decay=0.,
  38. norm_type='bn',
  39. name=None):
  40. super(ConvBNLayer, self).__init__()
  41. self.act = act
  42. self._conv = nn.Conv2D(
  43. in_channels,
  44. out_channels,
  45. kernel_size=kernel_size,
  46. stride=stride,
  47. padding=padding,
  48. groups=num_groups,
  49. weight_attr=ParamAttr(
  50. learning_rate=conv_lr,
  51. initializer=KaimingNormal(),
  52. regularizer=L2Decay(conv_decay)),
  53. bias_attr=False)
  54. param_attr = ParamAttr(regularizer=L2Decay(norm_decay))
  55. bias_attr = ParamAttr(regularizer=L2Decay(norm_decay))
  56. if norm_type == 'sync_bn':
  57. self._batch_norm = nn.SyncBatchNorm(
  58. out_channels, weight_attr=param_attr, bias_attr=bias_attr)
  59. else:
  60. self._batch_norm = nn.BatchNorm(
  61. out_channels,
  62. act=None,
  63. param_attr=param_attr,
  64. bias_attr=bias_attr,
  65. use_global_stats=False)
  66. def forward(self, x):
  67. x = self._conv(x)
  68. x = self._batch_norm(x)
  69. if self.act == "relu":
  70. x = F.relu(x)
  71. elif self.act == "relu6":
  72. x = F.relu6(x)
  73. return x
  74. class DepthwiseSeparable(nn.Layer):
  75. def __init__(self,
  76. in_channels,
  77. out_channels1,
  78. out_channels2,
  79. num_groups,
  80. stride,
  81. scale,
  82. conv_lr=1.,
  83. conv_decay=0.,
  84. norm_decay=0.,
  85. norm_type='bn',
  86. name=None):
  87. super(DepthwiseSeparable, self).__init__()
  88. self._depthwise_conv = ConvBNLayer(
  89. in_channels,
  90. int(out_channels1 * scale),
  91. kernel_size=3,
  92. stride=stride,
  93. padding=1,
  94. num_groups=int(num_groups * scale),
  95. conv_lr=conv_lr,
  96. conv_decay=conv_decay,
  97. norm_decay=norm_decay,
  98. norm_type=norm_type,
  99. name=name + "_dw")
  100. self._pointwise_conv = ConvBNLayer(
  101. int(out_channels1 * scale),
  102. int(out_channels2 * scale),
  103. kernel_size=1,
  104. stride=1,
  105. padding=0,
  106. conv_lr=conv_lr,
  107. conv_decay=conv_decay,
  108. norm_decay=norm_decay,
  109. norm_type=norm_type,
  110. name=name + "_sep")
  111. def forward(self, x):
  112. x = self._depthwise_conv(x)
  113. x = self._pointwise_conv(x)
  114. return x
  115. class ExtraBlock(nn.Layer):
  116. def __init__(self,
  117. in_channels,
  118. out_channels1,
  119. out_channels2,
  120. num_groups=1,
  121. stride=2,
  122. conv_lr=1.,
  123. conv_decay=0.,
  124. norm_decay=0.,
  125. norm_type='bn',
  126. name=None):
  127. super(ExtraBlock, self).__init__()
  128. self.pointwise_conv = ConvBNLayer(
  129. in_channels,
  130. int(out_channels1),
  131. kernel_size=1,
  132. stride=1,
  133. padding=0,
  134. num_groups=int(num_groups),
  135. act='relu6',
  136. conv_lr=conv_lr,
  137. conv_decay=conv_decay,
  138. norm_decay=norm_decay,
  139. norm_type=norm_type,
  140. name=name + "_extra1")
  141. self.normal_conv = ConvBNLayer(
  142. int(out_channels1),
  143. int(out_channels2),
  144. kernel_size=3,
  145. stride=stride,
  146. padding=1,
  147. num_groups=int(num_groups),
  148. act='relu6',
  149. conv_lr=conv_lr,
  150. conv_decay=conv_decay,
  151. norm_decay=norm_decay,
  152. norm_type=norm_type,
  153. name=name + "_extra2")
  154. def forward(self, x):
  155. x = self.pointwise_conv(x)
  156. x = self.normal_conv(x)
  157. return x
  158. @register
  159. @serializable
  160. class MobileNet(nn.Layer):
  161. __shared__ = ['norm_type']
  162. def __init__(self,
  163. norm_type='bn',
  164. norm_decay=0.,
  165. conv_decay=0.,
  166. scale=1,
  167. conv_learning_rate=1.0,
  168. feature_maps=[4, 6, 13],
  169. with_extra_blocks=False,
  170. extra_block_filters=[[256, 512], [128, 256], [128, 256],
  171. [64, 128]]):
  172. super(MobileNet, self).__init__()
  173. if isinstance(feature_maps, Integral):
  174. feature_maps = [feature_maps]
  175. self.feature_maps = feature_maps
  176. self.with_extra_blocks = with_extra_blocks
  177. self.extra_block_filters = extra_block_filters
  178. self._out_channels = []
  179. self.conv1 = ConvBNLayer(
  180. in_channels=3,
  181. out_channels=int(32 * scale),
  182. kernel_size=3,
  183. stride=2,
  184. padding=1,
  185. conv_lr=conv_learning_rate,
  186. conv_decay=conv_decay,
  187. norm_decay=norm_decay,
  188. norm_type=norm_type,
  189. name="conv1")
  190. self.dwsl = []
  191. dws21 = self.add_sublayer(
  192. "conv2_1",
  193. sublayer=DepthwiseSeparable(
  194. in_channels=int(32 * scale),
  195. out_channels1=32,
  196. out_channels2=64,
  197. num_groups=32,
  198. stride=1,
  199. scale=scale,
  200. conv_lr=conv_learning_rate,
  201. conv_decay=conv_decay,
  202. norm_decay=norm_decay,
  203. norm_type=norm_type,
  204. name="conv2_1"))
  205. self.dwsl.append(dws21)
  206. self._update_out_channels(
  207. int(64 * scale), len(self.dwsl), feature_maps)
  208. dws22 = self.add_sublayer(
  209. "conv2_2",
  210. sublayer=DepthwiseSeparable(
  211. in_channels=int(64 * scale),
  212. out_channels1=64,
  213. out_channels2=128,
  214. num_groups=64,
  215. stride=2,
  216. scale=scale,
  217. conv_lr=conv_learning_rate,
  218. conv_decay=conv_decay,
  219. norm_decay=norm_decay,
  220. norm_type=norm_type,
  221. name="conv2_2"))
  222. self.dwsl.append(dws22)
  223. self._update_out_channels(
  224. int(128 * scale), len(self.dwsl), feature_maps)
  225. # 1/4
  226. dws31 = self.add_sublayer(
  227. "conv3_1",
  228. sublayer=DepthwiseSeparable(
  229. in_channels=int(128 * scale),
  230. out_channels1=128,
  231. out_channels2=128,
  232. num_groups=128,
  233. stride=1,
  234. scale=scale,
  235. conv_lr=conv_learning_rate,
  236. conv_decay=conv_decay,
  237. norm_decay=norm_decay,
  238. norm_type=norm_type,
  239. name="conv3_1"))
  240. self.dwsl.append(dws31)
  241. self._update_out_channels(
  242. int(128 * scale), len(self.dwsl), feature_maps)
  243. dws32 = self.add_sublayer(
  244. "conv3_2",
  245. sublayer=DepthwiseSeparable(
  246. in_channels=int(128 * scale),
  247. out_channels1=128,
  248. out_channels2=256,
  249. num_groups=128,
  250. stride=2,
  251. scale=scale,
  252. conv_lr=conv_learning_rate,
  253. conv_decay=conv_decay,
  254. norm_decay=norm_decay,
  255. norm_type=norm_type,
  256. name="conv3_2"))
  257. self.dwsl.append(dws32)
  258. self._update_out_channels(
  259. int(256 * scale), len(self.dwsl), feature_maps)
  260. # 1/8
  261. dws41 = self.add_sublayer(
  262. "conv4_1",
  263. sublayer=DepthwiseSeparable(
  264. in_channels=int(256 * scale),
  265. out_channels1=256,
  266. out_channels2=256,
  267. num_groups=256,
  268. stride=1,
  269. scale=scale,
  270. conv_lr=conv_learning_rate,
  271. conv_decay=conv_decay,
  272. norm_decay=norm_decay,
  273. norm_type=norm_type,
  274. name="conv4_1"))
  275. self.dwsl.append(dws41)
  276. self._update_out_channels(
  277. int(256 * scale), len(self.dwsl), feature_maps)
  278. dws42 = self.add_sublayer(
  279. "conv4_2",
  280. sublayer=DepthwiseSeparable(
  281. in_channels=int(256 * scale),
  282. out_channels1=256,
  283. out_channels2=512,
  284. num_groups=256,
  285. stride=2,
  286. scale=scale,
  287. conv_lr=conv_learning_rate,
  288. conv_decay=conv_decay,
  289. norm_decay=norm_decay,
  290. norm_type=norm_type,
  291. name="conv4_2"))
  292. self.dwsl.append(dws42)
  293. self._update_out_channels(
  294. int(512 * scale), len(self.dwsl), feature_maps)
  295. # 1/16
  296. for i in range(5):
  297. tmp = self.add_sublayer(
  298. "conv5_" + str(i + 1),
  299. sublayer=DepthwiseSeparable(
  300. in_channels=int(512 * scale),
  301. out_channels1=512,
  302. out_channels2=512,
  303. num_groups=512,
  304. stride=1,
  305. scale=scale,
  306. conv_lr=conv_learning_rate,
  307. conv_decay=conv_decay,
  308. norm_decay=norm_decay,
  309. norm_type=norm_type,
  310. name="conv5_" + str(i + 1)))
  311. self.dwsl.append(tmp)
  312. self._update_out_channels(
  313. int(512 * scale), len(self.dwsl), feature_maps)
  314. dws56 = self.add_sublayer(
  315. "conv5_6",
  316. sublayer=DepthwiseSeparable(
  317. in_channels=int(512 * scale),
  318. out_channels1=512,
  319. out_channels2=1024,
  320. num_groups=512,
  321. stride=2,
  322. scale=scale,
  323. conv_lr=conv_learning_rate,
  324. conv_decay=conv_decay,
  325. norm_decay=norm_decay,
  326. norm_type=norm_type,
  327. name="conv5_6"))
  328. self.dwsl.append(dws56)
  329. self._update_out_channels(
  330. int(1024 * scale), len(self.dwsl), feature_maps)
  331. # 1/32
  332. dws6 = self.add_sublayer(
  333. "conv6",
  334. sublayer=DepthwiseSeparable(
  335. in_channels=int(1024 * scale),
  336. out_channels1=1024,
  337. out_channels2=1024,
  338. num_groups=1024,
  339. stride=1,
  340. scale=scale,
  341. conv_lr=conv_learning_rate,
  342. conv_decay=conv_decay,
  343. norm_decay=norm_decay,
  344. norm_type=norm_type,
  345. name="conv6"))
  346. self.dwsl.append(dws6)
  347. self._update_out_channels(
  348. int(1024 * scale), len(self.dwsl), feature_maps)
  349. if self.with_extra_blocks:
  350. self.extra_blocks = []
  351. for i, block_filter in enumerate(self.extra_block_filters):
  352. in_c = 1024 if i == 0 else self.extra_block_filters[i - 1][1]
  353. conv_extra = self.add_sublayer(
  354. "conv7_" + str(i + 1),
  355. sublayer=ExtraBlock(
  356. in_c,
  357. block_filter[0],
  358. block_filter[1],
  359. conv_lr=conv_learning_rate,
  360. conv_decay=conv_decay,
  361. norm_decay=norm_decay,
  362. norm_type=norm_type,
  363. name="conv7_" + str(i + 1)))
  364. self.extra_blocks.append(conv_extra)
  365. self._update_out_channels(
  366. block_filter[1],
  367. len(self.dwsl) + len(self.extra_blocks), feature_maps)
  368. def _update_out_channels(self, channel, feature_idx, feature_maps):
  369. if feature_idx in feature_maps:
  370. self._out_channels.append(channel)
  371. def forward(self, inputs):
  372. outs = []
  373. y = self.conv1(inputs['image'])
  374. for i, block in enumerate(self.dwsl):
  375. y = block(y)
  376. if i + 1 in self.feature_maps:
  377. outs.append(y)
  378. if not self.with_extra_blocks:
  379. return outs
  380. y = outs[-1]
  381. for i, block in enumerate(self.extra_blocks):
  382. idx = i + len(self.dwsl)
  383. y = block(y)
  384. if idx + 1 in self.feature_maps:
  385. outs.append(y)
  386. return outs
  387. @property
  388. def out_shape(self):
  389. return [ShapeSpec(channels=c) for c in self._out_channels]