mobilenet_v1.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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 numpy as np
  18. import paddle
  19. from paddle import ParamAttr
  20. import paddle.nn as nn
  21. import paddle.nn.functional as F
  22. from paddle.nn import Conv2D, BatchNorm, Linear, Dropout
  23. from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D
  24. from paddle.nn.initializer import KaimingNormal
  25. import math
  26. __all__ = [
  27. "MobileNetV1_x0_25", "MobileNetV1_x0_5", "MobileNetV1_x0_75", "MobileNetV1"
  28. ]
  29. class ConvBNLayer(nn.Layer):
  30. def __init__(self,
  31. num_channels,
  32. filter_size,
  33. num_filters,
  34. stride,
  35. padding,
  36. channels=None,
  37. num_groups=1,
  38. act='relu',
  39. name=None):
  40. super(ConvBNLayer, self).__init__()
  41. self._conv = Conv2D(
  42. in_channels=num_channels,
  43. out_channels=num_filters,
  44. kernel_size=filter_size,
  45. stride=stride,
  46. padding=padding,
  47. groups=num_groups,
  48. weight_attr=ParamAttr(
  49. initializer=KaimingNormal(), name=name + "_weights"),
  50. bias_attr=False)
  51. self._batch_norm = BatchNorm(
  52. num_filters,
  53. act=act,
  54. param_attr=ParamAttr(name + "_bn_scale"),
  55. bias_attr=ParamAttr(name + "_bn_offset"),
  56. moving_mean_name=name + "_bn_mean",
  57. moving_variance_name=name + "_bn_variance")
  58. def forward(self, inputs):
  59. y = self._conv(inputs)
  60. y = self._batch_norm(y)
  61. return y
  62. class DepthwiseSeparable(nn.Layer):
  63. def __init__(self,
  64. num_channels,
  65. num_filters1,
  66. num_filters2,
  67. num_groups,
  68. stride,
  69. scale,
  70. name=None):
  71. super(DepthwiseSeparable, self).__init__()
  72. self._depthwise_conv = ConvBNLayer(
  73. num_channels=num_channels,
  74. num_filters=int(num_filters1 * scale),
  75. filter_size=3,
  76. stride=stride,
  77. padding=1,
  78. num_groups=int(num_groups * scale),
  79. name=name + "_dw")
  80. self._pointwise_conv = ConvBNLayer(
  81. num_channels=int(num_filters1 * scale),
  82. filter_size=1,
  83. num_filters=int(num_filters2 * scale),
  84. stride=1,
  85. padding=0,
  86. name=name + "_sep")
  87. def forward(self, inputs):
  88. y = self._depthwise_conv(inputs)
  89. y = self._pointwise_conv(y)
  90. return y
  91. class MobileNet(nn.Layer):
  92. def __init__(self, scale=1.0, class_dim=1000):
  93. super(MobileNet, self).__init__()
  94. self.scale = scale
  95. self.block_list = []
  96. self.conv1 = ConvBNLayer(
  97. num_channels=3,
  98. filter_size=3,
  99. channels=3,
  100. num_filters=int(32 * scale),
  101. stride=2,
  102. padding=1,
  103. name="conv1")
  104. conv2_1 = self.add_sublayer(
  105. "conv2_1",
  106. sublayer=DepthwiseSeparable(
  107. num_channels=int(32 * scale),
  108. num_filters1=32,
  109. num_filters2=64,
  110. num_groups=32,
  111. stride=1,
  112. scale=scale,
  113. name="conv2_1"))
  114. self.block_list.append(conv2_1)
  115. conv2_2 = self.add_sublayer(
  116. "conv2_2",
  117. sublayer=DepthwiseSeparable(
  118. num_channels=int(64 * scale),
  119. num_filters1=64,
  120. num_filters2=128,
  121. num_groups=64,
  122. stride=2,
  123. scale=scale,
  124. name="conv2_2"))
  125. self.block_list.append(conv2_2)
  126. conv3_1 = self.add_sublayer(
  127. "conv3_1",
  128. sublayer=DepthwiseSeparable(
  129. num_channels=int(128 * scale),
  130. num_filters1=128,
  131. num_filters2=128,
  132. num_groups=128,
  133. stride=1,
  134. scale=scale,
  135. name="conv3_1"))
  136. self.block_list.append(conv3_1)
  137. conv3_2 = self.add_sublayer(
  138. "conv3_2",
  139. sublayer=DepthwiseSeparable(
  140. num_channels=int(128 * scale),
  141. num_filters1=128,
  142. num_filters2=256,
  143. num_groups=128,
  144. stride=2,
  145. scale=scale,
  146. name="conv3_2"))
  147. self.block_list.append(conv3_2)
  148. conv4_1 = self.add_sublayer(
  149. "conv4_1",
  150. sublayer=DepthwiseSeparable(
  151. num_channels=int(256 * scale),
  152. num_filters1=256,
  153. num_filters2=256,
  154. num_groups=256,
  155. stride=1,
  156. scale=scale,
  157. name="conv4_1"))
  158. self.block_list.append(conv4_1)
  159. conv4_2 = self.add_sublayer(
  160. "conv4_2",
  161. sublayer=DepthwiseSeparable(
  162. num_channels=int(256 * scale),
  163. num_filters1=256,
  164. num_filters2=512,
  165. num_groups=256,
  166. stride=2,
  167. scale=scale,
  168. name="conv4_2"))
  169. self.block_list.append(conv4_2)
  170. for i in range(5):
  171. conv5 = self.add_sublayer(
  172. "conv5_" + str(i + 1),
  173. sublayer=DepthwiseSeparable(
  174. num_channels=int(512 * scale),
  175. num_filters1=512,
  176. num_filters2=512,
  177. num_groups=512,
  178. stride=1,
  179. scale=scale,
  180. name="conv5_" + str(i + 1)))
  181. self.block_list.append(conv5)
  182. conv5_6 = self.add_sublayer(
  183. "conv5_6",
  184. sublayer=DepthwiseSeparable(
  185. num_channels=int(512 * scale),
  186. num_filters1=512,
  187. num_filters2=1024,
  188. num_groups=512,
  189. stride=2,
  190. scale=scale,
  191. name="conv5_6"))
  192. self.block_list.append(conv5_6)
  193. conv6 = self.add_sublayer(
  194. "conv6",
  195. sublayer=DepthwiseSeparable(
  196. num_channels=int(1024 * scale),
  197. num_filters1=1024,
  198. num_filters2=1024,
  199. num_groups=1024,
  200. stride=1,
  201. scale=scale,
  202. name="conv6"))
  203. self.block_list.append(conv6)
  204. self.pool2d_avg = AdaptiveAvgPool2D(1)
  205. self.out = Linear(
  206. int(1024 * scale),
  207. class_dim,
  208. weight_attr=ParamAttr(
  209. initializer=KaimingNormal(), name="fc7_weights"),
  210. bias_attr=ParamAttr(name="fc7_offset"))
  211. def forward(self, inputs):
  212. y = self.conv1(inputs)
  213. for block in self.block_list:
  214. y = block(y)
  215. y = self.pool2d_avg(y)
  216. y = paddle.flatten(y, start_axis=1, stop_axis=-1)
  217. y = self.out(y)
  218. return y
  219. def MobileNetV1_x0_25(**args):
  220. model = MobileNet(scale=0.25, **args)
  221. return model
  222. def MobileNetV1_x0_5(**args):
  223. model = MobileNet(scale=0.5, **args)
  224. return model
  225. def MobileNetV1_x0_75(**args):
  226. model = MobileNet(scale=0.75, **args)
  227. return model
  228. def MobileNetV1(**args):
  229. model = MobileNet(scale=1.0, **args)
  230. return model