mobilenet_v1.py 13 KB

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