lcnet.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. super().__init__()
  64. self.conv = Conv2D(
  65. in_channels=num_channels,
  66. out_channels=num_filters,
  67. kernel_size=filter_size,
  68. stride=stride,
  69. padding=(filter_size - 1) // 2,
  70. groups=num_groups,
  71. weight_attr=ParamAttr(initializer=KaimingNormal()),
  72. bias_attr=False)
  73. self.bn = nn.BatchNorm2D(
  74. num_filters,
  75. weight_attr=ParamAttr(regularizer=L2Decay(0.0)),
  76. bias_attr=ParamAttr(regularizer=L2Decay(0.0)))
  77. self.hardswish = nn.Hardswish()
  78. def forward(self, x):
  79. x = self.conv(x)
  80. x = self.bn(x)
  81. x = self.hardswish(x)
  82. return x
  83. class DepthwiseSeparable(nn.Layer):
  84. def __init__(self,
  85. num_channels,
  86. num_filters,
  87. stride,
  88. dw_size=3,
  89. use_se=False):
  90. super().__init__()
  91. self.use_se = use_se
  92. self.dw_conv = ConvBNLayer(
  93. num_channels=num_channels,
  94. num_filters=num_channels,
  95. filter_size=dw_size,
  96. stride=stride,
  97. num_groups=num_channels)
  98. if use_se:
  99. self.se = SEModule(num_channels)
  100. self.pw_conv = ConvBNLayer(
  101. num_channels=num_channels,
  102. filter_size=1,
  103. num_filters=num_filters,
  104. stride=1)
  105. def forward(self, x):
  106. x = self.dw_conv(x)
  107. if self.use_se:
  108. x = self.se(x)
  109. x = self.pw_conv(x)
  110. return x
  111. class SEModule(nn.Layer):
  112. def __init__(self, channel, reduction=4):
  113. super().__init__()
  114. self.avg_pool = AdaptiveAvgPool2D(1)
  115. self.conv1 = Conv2D(
  116. in_channels=channel,
  117. out_channels=channel // reduction,
  118. kernel_size=1,
  119. stride=1,
  120. padding=0)
  121. self.relu = nn.ReLU()
  122. self.conv2 = Conv2D(
  123. in_channels=channel // reduction,
  124. out_channels=channel,
  125. kernel_size=1,
  126. stride=1,
  127. padding=0)
  128. self.hardsigmoid = nn.Hardsigmoid()
  129. def forward(self, x):
  130. identity = x
  131. x = self.avg_pool(x)
  132. x = self.conv1(x)
  133. x = self.relu(x)
  134. x = self.conv2(x)
  135. x = self.hardsigmoid(x)
  136. x = paddle.multiply(x=identity, y=x)
  137. return x
  138. @register
  139. @serializable
  140. class LCNet(nn.Layer):
  141. def __init__(self, scale=1.0, feature_maps=[3, 4, 5]):
  142. super().__init__()
  143. self.scale = scale
  144. self.feature_maps = feature_maps
  145. out_channels = []
  146. self.conv1 = ConvBNLayer(
  147. num_channels=3,
  148. filter_size=3,
  149. num_filters=make_divisible(16 * scale),
  150. stride=2)
  151. self.blocks2 = nn.Sequential(* [
  152. DepthwiseSeparable(
  153. num_channels=make_divisible(in_c * scale),
  154. num_filters=make_divisible(out_c * scale),
  155. dw_size=k,
  156. stride=s,
  157. use_se=se)
  158. for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks2"])
  159. ])
  160. self.blocks3 = nn.Sequential(* [
  161. DepthwiseSeparable(
  162. num_channels=make_divisible(in_c * scale),
  163. num_filters=make_divisible(out_c * scale),
  164. dw_size=k,
  165. stride=s,
  166. use_se=se)
  167. for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks3"])
  168. ])
  169. out_channels.append(
  170. make_divisible(NET_CONFIG["blocks3"][-1][2] * scale))
  171. self.blocks4 = nn.Sequential(* [
  172. DepthwiseSeparable(
  173. num_channels=make_divisible(in_c * scale),
  174. num_filters=make_divisible(out_c * scale),
  175. dw_size=k,
  176. stride=s,
  177. use_se=se)
  178. for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks4"])
  179. ])
  180. out_channels.append(
  181. make_divisible(NET_CONFIG["blocks4"][-1][2] * scale))
  182. self.blocks5 = nn.Sequential(* [
  183. DepthwiseSeparable(
  184. num_channels=make_divisible(in_c * scale),
  185. num_filters=make_divisible(out_c * scale),
  186. dw_size=k,
  187. stride=s,
  188. use_se=se)
  189. for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks5"])
  190. ])
  191. out_channels.append(
  192. make_divisible(NET_CONFIG["blocks5"][-1][2] * scale))
  193. self.blocks6 = 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. for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks6"])
  201. ])
  202. out_channels.append(
  203. make_divisible(NET_CONFIG["blocks6"][-1][2] * scale))
  204. self._out_channels = [
  205. ch for idx, ch in enumerate(out_channels) if idx + 2 in feature_maps
  206. ]
  207. def forward(self, inputs):
  208. x = inputs['image']
  209. outs = []
  210. x = self.conv1(x)
  211. x = self.blocks2(x)
  212. x = self.blocks3(x)
  213. outs.append(x)
  214. x = self.blocks4(x)
  215. outs.append(x)
  216. x = self.blocks5(x)
  217. outs.append(x)
  218. x = self.blocks6(x)
  219. outs.append(x)
  220. outs = [o for i, o in enumerate(outs) if i + 2 in self.feature_maps]
  221. return outs
  222. @property
  223. def out_shape(self):
  224. return [ShapeSpec(channels=c) for c in self._out_channels]