mobilenet_v1.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 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(int(64 * scale), len(self.dwsl), feature_maps)
  200. dws22 = self.add_sublayer(
  201. "conv2_2",
  202. sublayer=DepthwiseSeparable(
  203. in_channels=int(64 * scale),
  204. out_channels1=64,
  205. out_channels2=128,
  206. num_groups=64,
  207. stride=2,
  208. scale=scale,
  209. conv_lr=conv_learning_rate,
  210. conv_decay=conv_decay,
  211. norm_decay=norm_decay,
  212. norm_type=norm_type,
  213. name="conv2_2"))
  214. self.dwsl.append(dws22)
  215. self._update_out_channels(int(128 * scale), len(self.dwsl), feature_maps)
  216. # 1/4
  217. dws31 = self.add_sublayer(
  218. "conv3_1",
  219. sublayer=DepthwiseSeparable(
  220. in_channels=int(128 * scale),
  221. out_channels1=128,
  222. out_channels2=128,
  223. num_groups=128,
  224. stride=1,
  225. scale=scale,
  226. conv_lr=conv_learning_rate,
  227. conv_decay=conv_decay,
  228. norm_decay=norm_decay,
  229. norm_type=norm_type,
  230. name="conv3_1"))
  231. self.dwsl.append(dws31)
  232. self._update_out_channels(int(128 * scale), len(self.dwsl), feature_maps)
  233. dws32 = self.add_sublayer(
  234. "conv3_2",
  235. sublayer=DepthwiseSeparable(
  236. in_channels=int(128 * scale),
  237. out_channels1=128,
  238. out_channels2=256,
  239. num_groups=128,
  240. stride=2,
  241. scale=scale,
  242. conv_lr=conv_learning_rate,
  243. conv_decay=conv_decay,
  244. norm_decay=norm_decay,
  245. norm_type=norm_type,
  246. name="conv3_2"))
  247. self.dwsl.append(dws32)
  248. self._update_out_channels(int(256 * scale), len(self.dwsl), feature_maps)
  249. # 1/8
  250. dws41 = self.add_sublayer(
  251. "conv4_1",
  252. sublayer=DepthwiseSeparable(
  253. in_channels=int(256 * scale),
  254. out_channels1=256,
  255. out_channels2=256,
  256. num_groups=256,
  257. stride=1,
  258. scale=scale,
  259. conv_lr=conv_learning_rate,
  260. conv_decay=conv_decay,
  261. norm_decay=norm_decay,
  262. norm_type=norm_type,
  263. name="conv4_1"))
  264. self.dwsl.append(dws41)
  265. self._update_out_channels(int(256 * scale), len(self.dwsl), feature_maps)
  266. dws42 = self.add_sublayer(
  267. "conv4_2",
  268. sublayer=DepthwiseSeparable(
  269. in_channels=int(256 * scale),
  270. out_channels1=256,
  271. out_channels2=512,
  272. num_groups=256,
  273. stride=2,
  274. scale=scale,
  275. conv_lr=conv_learning_rate,
  276. conv_decay=conv_decay,
  277. norm_decay=norm_decay,
  278. norm_type=norm_type,
  279. name="conv4_2"))
  280. self.dwsl.append(dws42)
  281. self._update_out_channels(int(512 * scale), len(self.dwsl), feature_maps)
  282. # 1/16
  283. for i in range(5):
  284. tmp = self.add_sublayer(
  285. "conv5_" + str(i + 1),
  286. sublayer=DepthwiseSeparable(
  287. in_channels=int(512 * scale),
  288. out_channels1=512,
  289. out_channels2=512,
  290. num_groups=512,
  291. stride=1,
  292. scale=scale,
  293. conv_lr=conv_learning_rate,
  294. conv_decay=conv_decay,
  295. norm_decay=norm_decay,
  296. norm_type=norm_type,
  297. name="conv5_" + str(i + 1)))
  298. self.dwsl.append(tmp)
  299. self._update_out_channels(int(512 * scale), len(self.dwsl), feature_maps)
  300. dws56 = self.add_sublayer(
  301. "conv5_6",
  302. sublayer=DepthwiseSeparable(
  303. in_channels=int(512 * scale),
  304. out_channels1=512,
  305. out_channels2=1024,
  306. num_groups=512,
  307. stride=2,
  308. scale=scale,
  309. conv_lr=conv_learning_rate,
  310. conv_decay=conv_decay,
  311. norm_decay=norm_decay,
  312. norm_type=norm_type,
  313. name="conv5_6"))
  314. self.dwsl.append(dws56)
  315. self._update_out_channels(int(1024 * scale), len(self.dwsl), feature_maps)
  316. # 1/32
  317. dws6 = self.add_sublayer(
  318. "conv6",
  319. sublayer=DepthwiseSeparable(
  320. in_channels=int(1024 * scale),
  321. out_channels1=1024,
  322. out_channels2=1024,
  323. num_groups=1024,
  324. stride=1,
  325. scale=scale,
  326. conv_lr=conv_learning_rate,
  327. conv_decay=conv_decay,
  328. norm_decay=norm_decay,
  329. norm_type=norm_type,
  330. name="conv6"))
  331. self.dwsl.append(dws6)
  332. self._update_out_channels(int(1024 * scale), len(self.dwsl), feature_maps)
  333. if self.with_extra_blocks:
  334. self.extra_blocks = []
  335. for i, block_filter in enumerate(self.extra_block_filters):
  336. in_c = 1024 if i == 0 else self.extra_block_filters[i - 1][1]
  337. conv_extra = self.add_sublayer(
  338. "conv7_" + str(i + 1),
  339. sublayer=ExtraBlock(
  340. in_c,
  341. block_filter[0],
  342. block_filter[1],
  343. conv_lr=conv_learning_rate,
  344. conv_decay=conv_decay,
  345. norm_decay=norm_decay,
  346. norm_type=norm_type,
  347. name="conv7_" + str(i + 1)))
  348. self.extra_blocks.append(conv_extra)
  349. self._update_out_channels(
  350. block_filter[1],
  351. len(self.dwsl) + len(self.extra_blocks), feature_maps)
  352. def _update_out_channels(self, channel, feature_idx, feature_maps):
  353. if feature_idx in feature_maps:
  354. self._out_channels.append(channel)
  355. def forward(self, inputs):
  356. outs = []
  357. y = self.conv1(inputs['image'])
  358. for i, block in enumerate(self.dwsl):
  359. y = block(y)
  360. if i + 1 in self.feature_maps:
  361. outs.append(y)
  362. if not self.with_extra_blocks:
  363. return outs
  364. y = outs[-1]
  365. for i, block in enumerate(self.extra_blocks):
  366. idx = i + len(self.dwsl)
  367. y = block(y)
  368. if idx + 1 in self.feature_maps:
  369. outs.append(y)
  370. return outs
  371. @property
  372. def out_shape(self):
  373. return [ShapeSpec(channels=c) for c in self._out_channels]