mobilenet_v1.py 13 KB

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