shufflenet_v2.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. # copyright (c) 2021 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. from paddle import ParamAttr
  20. import paddle.nn.functional as F
  21. from paddle.nn import Conv2D, MaxPool2D, AdaptiveAvgPool2D, BatchNorm2D
  22. from paddle.nn.initializer import KaimingNormal
  23. from paddle.regularizer import L2Decay
  24. from ppdet.core.workspace import register, serializable
  25. from numbers import Integral
  26. from ..shape_spec import ShapeSpec
  27. from ppdet.modeling.ops import channel_shuffle
  28. __all__ = ['ShuffleNetV2']
  29. class ConvBNLayer(nn.Layer):
  30. def __init__(self,
  31. in_channels,
  32. out_channels,
  33. kernel_size,
  34. stride,
  35. padding,
  36. groups=1,
  37. act=None):
  38. super(ConvBNLayer, self).__init__()
  39. self._conv = Conv2D(
  40. in_channels=in_channels,
  41. out_channels=out_channels,
  42. kernel_size=kernel_size,
  43. stride=stride,
  44. padding=padding,
  45. groups=groups,
  46. weight_attr=ParamAttr(initializer=KaimingNormal()),
  47. bias_attr=False)
  48. self._batch_norm = BatchNorm2D(
  49. out_channels,
  50. weight_attr=ParamAttr(regularizer=L2Decay(0.0)),
  51. bias_attr=ParamAttr(regularizer=L2Decay(0.0)))
  52. if act == "hard_swish":
  53. act = 'hardswish'
  54. self.act = act
  55. def forward(self, inputs):
  56. y = self._conv(inputs)
  57. y = self._batch_norm(y)
  58. if self.act:
  59. y = getattr(F, self.act)(y)
  60. return y
  61. class InvertedResidual(nn.Layer):
  62. def __init__(self, in_channels, out_channels, stride, act="relu"):
  63. super(InvertedResidual, self).__init__()
  64. self._conv_pw = ConvBNLayer(
  65. in_channels=in_channels // 2,
  66. out_channels=out_channels // 2,
  67. kernel_size=1,
  68. stride=1,
  69. padding=0,
  70. groups=1,
  71. act=act)
  72. self._conv_dw = ConvBNLayer(
  73. in_channels=out_channels // 2,
  74. out_channels=out_channels // 2,
  75. kernel_size=3,
  76. stride=stride,
  77. padding=1,
  78. groups=out_channels // 2,
  79. act=None)
  80. self._conv_linear = ConvBNLayer(
  81. in_channels=out_channels // 2,
  82. out_channels=out_channels // 2,
  83. kernel_size=1,
  84. stride=1,
  85. padding=0,
  86. groups=1,
  87. act=act)
  88. def forward(self, inputs):
  89. x1, x2 = paddle.split(
  90. inputs,
  91. num_or_sections=[inputs.shape[1] // 2, inputs.shape[1] // 2],
  92. axis=1)
  93. x2 = self._conv_pw(x2)
  94. x2 = self._conv_dw(x2)
  95. x2 = self._conv_linear(x2)
  96. out = paddle.concat([x1, x2], axis=1)
  97. return channel_shuffle(out, 2)
  98. class InvertedResidualDS(nn.Layer):
  99. def __init__(self, in_channels, out_channels, stride, act="relu"):
  100. super(InvertedResidualDS, self).__init__()
  101. # branch1
  102. self._conv_dw_1 = ConvBNLayer(
  103. in_channels=in_channels,
  104. out_channels=in_channels,
  105. kernel_size=3,
  106. stride=stride,
  107. padding=1,
  108. groups=in_channels,
  109. act=None)
  110. self._conv_linear_1 = ConvBNLayer(
  111. in_channels=in_channels,
  112. out_channels=out_channels // 2,
  113. kernel_size=1,
  114. stride=1,
  115. padding=0,
  116. groups=1,
  117. act=act)
  118. # branch2
  119. self._conv_pw_2 = ConvBNLayer(
  120. in_channels=in_channels,
  121. out_channels=out_channels // 2,
  122. kernel_size=1,
  123. stride=1,
  124. padding=0,
  125. groups=1,
  126. act=act)
  127. self._conv_dw_2 = ConvBNLayer(
  128. in_channels=out_channels // 2,
  129. out_channels=out_channels // 2,
  130. kernel_size=3,
  131. stride=stride,
  132. padding=1,
  133. groups=out_channels // 2,
  134. act=None)
  135. self._conv_linear_2 = ConvBNLayer(
  136. in_channels=out_channels // 2,
  137. out_channels=out_channels // 2,
  138. kernel_size=1,
  139. stride=1,
  140. padding=0,
  141. groups=1,
  142. act=act)
  143. def forward(self, inputs):
  144. x1 = self._conv_dw_1(inputs)
  145. x1 = self._conv_linear_1(x1)
  146. x2 = self._conv_pw_2(inputs)
  147. x2 = self._conv_dw_2(x2)
  148. x2 = self._conv_linear_2(x2)
  149. out = paddle.concat([x1, x2], axis=1)
  150. return channel_shuffle(out, 2)
  151. @register
  152. @serializable
  153. class ShuffleNetV2(nn.Layer):
  154. def __init__(self, scale=1.0, act="relu", feature_maps=[5, 13, 17]):
  155. super(ShuffleNetV2, self).__init__()
  156. self.scale = scale
  157. if isinstance(feature_maps, Integral):
  158. feature_maps = [feature_maps]
  159. self.feature_maps = feature_maps
  160. stage_repeats = [4, 8, 4]
  161. if scale == 0.25:
  162. stage_out_channels = [-1, 24, 24, 48, 96, 512]
  163. elif scale == 0.33:
  164. stage_out_channels = [-1, 24, 32, 64, 128, 512]
  165. elif scale == 0.5:
  166. stage_out_channels = [-1, 24, 48, 96, 192, 1024]
  167. elif scale == 1.0:
  168. stage_out_channels = [-1, 24, 116, 232, 464, 1024]
  169. elif scale == 1.5:
  170. stage_out_channels = [-1, 24, 176, 352, 704, 1024]
  171. elif scale == 2.0:
  172. stage_out_channels = [-1, 24, 224, 488, 976, 2048]
  173. else:
  174. raise NotImplementedError("This scale size:[" + str(scale) +
  175. "] is not implemented!")
  176. self._out_channels = []
  177. self._feature_idx = 0
  178. # 1. conv1
  179. self._conv1 = ConvBNLayer(
  180. in_channels=3,
  181. out_channels=stage_out_channels[1],
  182. kernel_size=3,
  183. stride=2,
  184. padding=1,
  185. act=act)
  186. self._max_pool = MaxPool2D(kernel_size=3, stride=2, padding=1)
  187. self._feature_idx += 1
  188. # 2. bottleneck sequences
  189. self._block_list = []
  190. for stage_id, num_repeat in enumerate(stage_repeats):
  191. for i in range(num_repeat):
  192. if i == 0:
  193. block = self.add_sublayer(
  194. name=str(stage_id + 2) + '_' + str(i + 1),
  195. sublayer=InvertedResidualDS(
  196. in_channels=stage_out_channels[stage_id + 1],
  197. out_channels=stage_out_channels[stage_id + 2],
  198. stride=2,
  199. act=act))
  200. else:
  201. block = self.add_sublayer(
  202. name=str(stage_id + 2) + '_' + str(i + 1),
  203. sublayer=InvertedResidual(
  204. in_channels=stage_out_channels[stage_id + 2],
  205. out_channels=stage_out_channels[stage_id + 2],
  206. stride=1,
  207. act=act))
  208. self._block_list.append(block)
  209. self._feature_idx += 1
  210. self._update_out_channels(stage_out_channels[stage_id + 2],
  211. self._feature_idx, self.feature_maps)
  212. def _update_out_channels(self, channel, feature_idx, feature_maps):
  213. if feature_idx in feature_maps:
  214. self._out_channels.append(channel)
  215. def forward(self, inputs):
  216. y = self._conv1(inputs['image'])
  217. y = self._max_pool(y)
  218. outs = []
  219. for i, inv in enumerate(self._block_list):
  220. y = inv(y)
  221. if i + 2 in self.feature_maps:
  222. outs.append(y)
  223. return outs
  224. @property
  225. def out_shape(self):
  226. return [ShapeSpec(channels=c) for c in self._out_channels]