lcnet.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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 AdaptiveAvgPool2D, Conv2D
  21. from paddle.regularizer import L2Decay
  22. from paddle.nn.initializer import KaimingNormal
  23. from ppdet.core.workspace import register, serializable
  24. from numbers import Integral
  25. from ..shape_spec import ShapeSpec
  26. __all__ = ['LCNet']
  27. NET_CONFIG = {
  28. "blocks2":
  29. #k, in_c, out_c, s, use_se
  30. [[3, 16, 32, 1, False], ],
  31. "blocks3": [
  32. [3, 32, 64, 2, False],
  33. [3, 64, 64, 1, False],
  34. ],
  35. "blocks4": [
  36. [3, 64, 128, 2, False],
  37. [3, 128, 128, 1, False],
  38. ],
  39. "blocks5": [
  40. [3, 128, 256, 2, False],
  41. [5, 256, 256, 1, False],
  42. [5, 256, 256, 1, False],
  43. [5, 256, 256, 1, False],
  44. [5, 256, 256, 1, False],
  45. [5, 256, 256, 1, False],
  46. ],
  47. "blocks6": [[5, 256, 512, 2, True], [5, 512, 512, 1, True]]
  48. }
  49. def make_divisible(v, divisor=8, min_value=None):
  50. if min_value is None:
  51. min_value = divisor
  52. new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
  53. if new_v < 0.9 * v:
  54. new_v += divisor
  55. return new_v
  56. class ConvBNLayer(nn.Layer):
  57. def __init__(self,
  58. num_channels,
  59. filter_size,
  60. num_filters,
  61. stride,
  62. num_groups=1,
  63. act='hard_swish'):
  64. super().__init__()
  65. self.conv = Conv2D(
  66. in_channels=num_channels,
  67. out_channels=num_filters,
  68. kernel_size=filter_size,
  69. stride=stride,
  70. padding=(filter_size - 1) // 2,
  71. groups=num_groups,
  72. weight_attr=ParamAttr(initializer=KaimingNormal()),
  73. bias_attr=False)
  74. self.bn = nn.BatchNorm2D(
  75. num_filters,
  76. weight_attr=ParamAttr(regularizer=L2Decay(0.0)),
  77. bias_attr=ParamAttr(regularizer=L2Decay(0.0)))
  78. if act == 'hard_swish':
  79. self.act = nn.Hardswish()
  80. elif act == 'relu6':
  81. self.act = nn.ReLU6()
  82. def forward(self, x):
  83. x = self.conv(x)
  84. x = self.bn(x)
  85. x = self.act(x)
  86. return x
  87. class DepthwiseSeparable(nn.Layer):
  88. def __init__(self,
  89. num_channels,
  90. num_filters,
  91. stride,
  92. dw_size=3,
  93. use_se=False,
  94. act='hard_swish'):
  95. super().__init__()
  96. self.use_se = use_se
  97. self.dw_conv = ConvBNLayer(
  98. num_channels=num_channels,
  99. num_filters=num_channels,
  100. filter_size=dw_size,
  101. stride=stride,
  102. num_groups=num_channels,
  103. act=act)
  104. if use_se:
  105. self.se = SEModule(num_channels)
  106. self.pw_conv = ConvBNLayer(
  107. num_channels=num_channels,
  108. filter_size=1,
  109. num_filters=num_filters,
  110. stride=1,
  111. act=act)
  112. def forward(self, x):
  113. x = self.dw_conv(x)
  114. if self.use_se:
  115. x = self.se(x)
  116. x = self.pw_conv(x)
  117. return x
  118. class SEModule(nn.Layer):
  119. def __init__(self, channel, reduction=4):
  120. super().__init__()
  121. self.avg_pool = AdaptiveAvgPool2D(1)
  122. self.conv1 = Conv2D(
  123. in_channels=channel,
  124. out_channels=channel // reduction,
  125. kernel_size=1,
  126. stride=1,
  127. padding=0)
  128. self.relu = nn.ReLU()
  129. self.conv2 = Conv2D(
  130. in_channels=channel // reduction,
  131. out_channels=channel,
  132. kernel_size=1,
  133. stride=1,
  134. padding=0)
  135. self.hardsigmoid = nn.Hardsigmoid()
  136. def forward(self, x):
  137. identity = x
  138. x = self.avg_pool(x)
  139. x = self.conv1(x)
  140. x = self.relu(x)
  141. x = self.conv2(x)
  142. x = self.hardsigmoid(x)
  143. x = paddle.multiply(x=identity, y=x)
  144. return x
  145. @register
  146. @serializable
  147. class LCNet(nn.Layer):
  148. def __init__(self, scale=1.0, feature_maps=[3, 4, 5], act='hard_swish'):
  149. super().__init__()
  150. self.scale = scale
  151. self.feature_maps = feature_maps
  152. out_channels = []
  153. self.conv1 = ConvBNLayer(
  154. num_channels=3,
  155. filter_size=3,
  156. num_filters=make_divisible(16 * scale),
  157. stride=2,
  158. act=act)
  159. self.blocks2 = nn.Sequential(* [
  160. DepthwiseSeparable(
  161. num_channels=make_divisible(in_c * scale),
  162. num_filters=make_divisible(out_c * scale),
  163. dw_size=k,
  164. stride=s,
  165. use_se=se,
  166. act=act)
  167. for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks2"])
  168. ])
  169. self.blocks3 = nn.Sequential(* [
  170. DepthwiseSeparable(
  171. num_channels=make_divisible(in_c * scale),
  172. num_filters=make_divisible(out_c * scale),
  173. dw_size=k,
  174. stride=s,
  175. use_se=se,
  176. act=act)
  177. for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks3"])
  178. ])
  179. out_channels.append(
  180. make_divisible(NET_CONFIG["blocks3"][-1][2] * scale))
  181. self.blocks4 = nn.Sequential(* [
  182. DepthwiseSeparable(
  183. num_channels=make_divisible(in_c * scale),
  184. num_filters=make_divisible(out_c * scale),
  185. dw_size=k,
  186. stride=s,
  187. use_se=se,
  188. act=act)
  189. for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks4"])
  190. ])
  191. out_channels.append(
  192. make_divisible(NET_CONFIG["blocks4"][-1][2] * scale))
  193. self.blocks5 = nn.Sequential(* [
  194. DepthwiseSeparable(
  195. num_channels=make_divisible(in_c * scale),
  196. num_filters=make_divisible(out_c * scale),
  197. dw_size=k,
  198. stride=s,
  199. use_se=se,
  200. act=act)
  201. for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks5"])
  202. ])
  203. out_channels.append(
  204. make_divisible(NET_CONFIG["blocks5"][-1][2] * scale))
  205. self.blocks6 = nn.Sequential(* [
  206. DepthwiseSeparable(
  207. num_channels=make_divisible(in_c * scale),
  208. num_filters=make_divisible(out_c * scale),
  209. dw_size=k,
  210. stride=s,
  211. use_se=se,
  212. act=act)
  213. for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks6"])
  214. ])
  215. out_channels.append(
  216. make_divisible(NET_CONFIG["blocks6"][-1][2] * scale))
  217. self._out_channels = [
  218. ch for idx, ch in enumerate(out_channels) if idx + 2 in feature_maps
  219. ]
  220. def forward(self, inputs):
  221. x = inputs['image']
  222. outs = []
  223. x = self.conv1(x)
  224. x = self.blocks2(x)
  225. x = self.blocks3(x)
  226. outs.append(x)
  227. x = self.blocks4(x)
  228. outs.append(x)
  229. x = self.blocks5(x)
  230. outs.append(x)
  231. x = self.blocks6(x)
  232. outs.append(x)
  233. outs = [o for i, o in enumerate(outs) if i + 2 in self.feature_maps]
  234. return outs
  235. @property
  236. def out_shape(self):
  237. return [ShapeSpec(channels=c) for c in self._out_channels]