shufflenet_v2.py 8.1 KB

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