mobilenet_v2.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. from paddle import ParamAttr
  19. import paddle.nn as nn
  20. import paddle.nn.functional as F
  21. from paddle.nn import Conv2D, BatchNorm, Linear, Dropout
  22. from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D
  23. __all__ = ["MobileNetV2"]
  24. class ConvBNLayer(nn.Layer):
  25. def __init__(self,
  26. num_channels,
  27. filter_size,
  28. num_filters,
  29. stride,
  30. padding,
  31. channels=None,
  32. num_groups=1,
  33. name=None,
  34. use_cudnn=True):
  35. super(ConvBNLayer, self).__init__()
  36. self._conv = Conv2D(
  37. in_channels=num_channels,
  38. out_channels=num_filters,
  39. kernel_size=filter_size,
  40. stride=stride,
  41. padding=padding,
  42. groups=num_groups,
  43. weight_attr=ParamAttr(name=name + "_weights"),
  44. bias_attr=False)
  45. self._batch_norm = BatchNorm(
  46. num_filters,
  47. param_attr=ParamAttr(name=name + "_bn_scale"),
  48. bias_attr=ParamAttr(name=name + "_bn_offset"),
  49. moving_mean_name=name + "_bn_mean",
  50. moving_variance_name=name + "_bn_variance")
  51. def forward(self, inputs, if_act=True):
  52. y = self._conv(inputs)
  53. y = self._batch_norm(y)
  54. if if_act:
  55. y = F.relu6(y)
  56. return y
  57. class InvertedResidualUnit(nn.Layer):
  58. def __init__(self, num_channels, num_in_filter, num_filters, stride,
  59. filter_size, padding, expansion_factor, name):
  60. super(InvertedResidualUnit, self).__init__()
  61. num_expfilter = int(round(num_in_filter * expansion_factor))
  62. self._expand_conv = ConvBNLayer(
  63. num_channels=num_channels,
  64. num_filters=num_expfilter,
  65. filter_size=1,
  66. stride=1,
  67. padding=0,
  68. num_groups=1,
  69. name=name + "_expand")
  70. self._bottleneck_conv = ConvBNLayer(
  71. num_channels=num_expfilter,
  72. num_filters=num_expfilter,
  73. filter_size=filter_size,
  74. stride=stride,
  75. padding=padding,
  76. num_groups=num_expfilter,
  77. use_cudnn=False,
  78. name=name + "_dwise")
  79. self._linear_conv = ConvBNLayer(
  80. num_channels=num_expfilter,
  81. num_filters=num_filters,
  82. filter_size=1,
  83. stride=1,
  84. padding=0,
  85. num_groups=1,
  86. name=name + "_linear")
  87. def forward(self, inputs, ifshortcut):
  88. y = self._expand_conv(inputs, if_act=True)
  89. y = self._bottleneck_conv(y, if_act=True)
  90. y = self._linear_conv(y, if_act=False)
  91. if ifshortcut:
  92. y = paddle.add(inputs, y)
  93. return y
  94. class InvresiBlocks(nn.Layer):
  95. def __init__(self, in_c, t, c, n, s, name):
  96. super(InvresiBlocks, self).__init__()
  97. self._first_block = InvertedResidualUnit(
  98. num_channels=in_c,
  99. num_in_filter=in_c,
  100. num_filters=c,
  101. stride=s,
  102. filter_size=3,
  103. padding=1,
  104. expansion_factor=t,
  105. name=name + "_1")
  106. self._block_list = []
  107. for i in range(1, n):
  108. block = self.add_sublayer(
  109. name + "_" + str(i + 1),
  110. sublayer=InvertedResidualUnit(
  111. num_channels=c,
  112. num_in_filter=c,
  113. num_filters=c,
  114. stride=1,
  115. filter_size=3,
  116. padding=1,
  117. expansion_factor=t,
  118. name=name + "_" + str(i + 1)))
  119. self._block_list.append(block)
  120. def forward(self, inputs):
  121. y = self._first_block(inputs, ifshortcut=False)
  122. for block in self._block_list:
  123. y = block(y, ifshortcut=True)
  124. return y
  125. class MobileNet(nn.Layer):
  126. def __init__(self, class_dim=1000, scale=1.0):
  127. super(MobileNet, self).__init__()
  128. self.scale = scale
  129. self.class_dim = class_dim
  130. bottleneck_params_list = [
  131. (1, 16, 1, 1),
  132. (6, 24, 2, 2),
  133. (6, 32, 3, 2),
  134. (6, 64, 4, 2),
  135. (6, 96, 3, 1),
  136. (6, 160, 3, 2),
  137. (6, 320, 1, 1),
  138. ]
  139. self.conv1 = ConvBNLayer(
  140. num_channels=3,
  141. num_filters=int(32 * scale),
  142. filter_size=3,
  143. stride=2,
  144. padding=1,
  145. name="conv1_1")
  146. self.block_list = []
  147. i = 1
  148. in_c = int(32 * scale)
  149. for layer_setting in bottleneck_params_list:
  150. t, c, n, s = layer_setting
  151. i += 1
  152. block = self.add_sublayer(
  153. "conv" + str(i),
  154. sublayer=InvresiBlocks(
  155. in_c=in_c,
  156. t=t,
  157. c=int(c * scale),
  158. n=n,
  159. s=s,
  160. name="conv" + str(i)))
  161. self.block_list.append(block)
  162. in_c = int(c * scale)
  163. self.out_c = int(1280 * scale) if scale > 1.0 else 1280
  164. self.conv9 = ConvBNLayer(
  165. num_channels=in_c,
  166. num_filters=self.out_c,
  167. filter_size=1,
  168. stride=1,
  169. padding=0,
  170. name="conv9")
  171. self.pool2d_avg = AdaptiveAvgPool2D(1)
  172. self.out = Linear(
  173. self.out_c,
  174. class_dim,
  175. weight_attr=ParamAttr(name="fc10_weights"),
  176. bias_attr=ParamAttr(name="fc10_offset"))
  177. def forward(self, inputs):
  178. y = self.conv1(inputs, if_act=True)
  179. for block in self.block_list:
  180. y = block(y)
  181. y = self.conv9(y, if_act=True)
  182. y = self.pool2d_avg(y)
  183. y = paddle.flatten(y, start_axis=1, stop_axis=-1)
  184. y = self.out(y)
  185. return y
  186. def MobileNetV2(scale=1.0, **args):
  187. model = MobileNet(scale=scale, **args)
  188. return model