det_mobilenet_v3.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. from torch import nn
  2. from ..common import Activation
  3. def make_divisible(v, divisor=8, min_value=None):
  4. if min_value is None:
  5. min_value = divisor
  6. new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
  7. if new_v < 0.9 * v:
  8. new_v += divisor
  9. return new_v
  10. class ConvBNLayer(nn.Module):
  11. def __init__(
  12. self,
  13. in_channels,
  14. out_channels,
  15. kernel_size,
  16. stride,
  17. padding,
  18. groups=1,
  19. if_act=True,
  20. act=None,
  21. name=None,
  22. ):
  23. super(ConvBNLayer, self).__init__()
  24. self.if_act = if_act
  25. self.conv = nn.Conv2d(
  26. in_channels=in_channels,
  27. out_channels=out_channels,
  28. kernel_size=kernel_size,
  29. stride=stride,
  30. padding=padding,
  31. groups=groups,
  32. bias=False,
  33. )
  34. self.bn = nn.BatchNorm2d(
  35. out_channels,
  36. )
  37. if self.if_act:
  38. self.act = Activation(act_type=act, inplace=True)
  39. def forward(self, x):
  40. x = self.conv(x)
  41. x = self.bn(x)
  42. if self.if_act:
  43. x = self.act(x)
  44. return x
  45. class SEModule(nn.Module):
  46. def __init__(self, in_channels, reduction=4, name=""):
  47. super(SEModule, self).__init__()
  48. self.avg_pool = nn.AdaptiveAvgPool2d(1)
  49. self.conv1 = nn.Conv2d(
  50. in_channels=in_channels,
  51. out_channels=in_channels // reduction,
  52. kernel_size=1,
  53. stride=1,
  54. padding=0,
  55. bias=True,
  56. )
  57. self.relu1 = Activation(act_type="relu", inplace=True)
  58. self.conv2 = nn.Conv2d(
  59. in_channels=in_channels // reduction,
  60. out_channels=in_channels,
  61. kernel_size=1,
  62. stride=1,
  63. padding=0,
  64. bias=True,
  65. )
  66. self.hard_sigmoid = Activation(act_type="hard_sigmoid", inplace=True)
  67. def forward(self, inputs):
  68. outputs = self.avg_pool(inputs)
  69. outputs = self.conv1(outputs)
  70. outputs = self.relu1(outputs)
  71. outputs = self.conv2(outputs)
  72. outputs = self.hard_sigmoid(outputs)
  73. outputs = inputs * outputs
  74. return outputs
  75. class ResidualUnit(nn.Module):
  76. def __init__(
  77. self,
  78. in_channels,
  79. mid_channels,
  80. out_channels,
  81. kernel_size,
  82. stride,
  83. use_se,
  84. act=None,
  85. name="",
  86. ):
  87. super(ResidualUnit, self).__init__()
  88. self.if_shortcut = stride == 1 and in_channels == out_channels
  89. self.if_se = use_se
  90. self.expand_conv = ConvBNLayer(
  91. in_channels=in_channels,
  92. out_channels=mid_channels,
  93. kernel_size=1,
  94. stride=1,
  95. padding=0,
  96. if_act=True,
  97. act=act,
  98. name=name + "_expand",
  99. )
  100. self.bottleneck_conv = ConvBNLayer(
  101. in_channels=mid_channels,
  102. out_channels=mid_channels,
  103. kernel_size=kernel_size,
  104. stride=stride,
  105. padding=int((kernel_size - 1) // 2),
  106. groups=mid_channels,
  107. if_act=True,
  108. act=act,
  109. name=name + "_depthwise",
  110. )
  111. if self.if_se:
  112. self.mid_se = SEModule(mid_channels, name=name + "_se")
  113. self.linear_conv = ConvBNLayer(
  114. in_channels=mid_channels,
  115. out_channels=out_channels,
  116. kernel_size=1,
  117. stride=1,
  118. padding=0,
  119. if_act=False,
  120. act=None,
  121. name=name + "_linear",
  122. )
  123. def forward(self, inputs):
  124. x = self.expand_conv(inputs)
  125. x = self.bottleneck_conv(x)
  126. if self.if_se:
  127. x = self.mid_se(x)
  128. x = self.linear_conv(x)
  129. if self.if_shortcut:
  130. x = inputs + x
  131. return x
  132. class MobileNetV3(nn.Module):
  133. def __init__(
  134. self, in_channels=3, model_name="large", scale=0.5, disable_se=False, **kwargs
  135. ):
  136. """
  137. the MobilenetV3 backbone network for detection module.
  138. Args:
  139. params(dict): the super parameters for build network
  140. """
  141. super(MobileNetV3, self).__init__()
  142. self.disable_se = disable_se
  143. if model_name == "large":
  144. cfg = [
  145. # k, exp, c, se, nl, s,
  146. [3, 16, 16, False, "relu", 1],
  147. [3, 64, 24, False, "relu", 2],
  148. [3, 72, 24, False, "relu", 1],
  149. [5, 72, 40, True, "relu", 2],
  150. [5, 120, 40, True, "relu", 1],
  151. [5, 120, 40, True, "relu", 1],
  152. [3, 240, 80, False, "hard_swish", 2],
  153. [3, 200, 80, False, "hard_swish", 1],
  154. [3, 184, 80, False, "hard_swish", 1],
  155. [3, 184, 80, False, "hard_swish", 1],
  156. [3, 480, 112, True, "hard_swish", 1],
  157. [3, 672, 112, True, "hard_swish", 1],
  158. [5, 672, 160, True, "hard_swish", 2],
  159. [5, 960, 160, True, "hard_swish", 1],
  160. [5, 960, 160, True, "hard_swish", 1],
  161. ]
  162. cls_ch_squeeze = 960
  163. elif model_name == "small":
  164. cfg = [
  165. # k, exp, c, se, nl, s,
  166. [3, 16, 16, True, "relu", 2],
  167. [3, 72, 24, False, "relu", 2],
  168. [3, 88, 24, False, "relu", 1],
  169. [5, 96, 40, True, "hard_swish", 2],
  170. [5, 240, 40, True, "hard_swish", 1],
  171. [5, 240, 40, True, "hard_swish", 1],
  172. [5, 120, 48, True, "hard_swish", 1],
  173. [5, 144, 48, True, "hard_swish", 1],
  174. [5, 288, 96, True, "hard_swish", 2],
  175. [5, 576, 96, True, "hard_swish", 1],
  176. [5, 576, 96, True, "hard_swish", 1],
  177. ]
  178. cls_ch_squeeze = 576
  179. else:
  180. raise NotImplementedError(
  181. "mode[" + model_name + "_model] is not implemented!"
  182. )
  183. supported_scale = [0.35, 0.5, 0.75, 1.0, 1.25]
  184. assert (
  185. scale in supported_scale
  186. ), "supported scale are {} but input scale is {}".format(supported_scale, scale)
  187. inplanes = 16
  188. # conv1
  189. self.conv = ConvBNLayer(
  190. in_channels=in_channels,
  191. out_channels=make_divisible(inplanes * scale),
  192. kernel_size=3,
  193. stride=2,
  194. padding=1,
  195. groups=1,
  196. if_act=True,
  197. act="hard_swish",
  198. name="conv1",
  199. )
  200. self.stages = nn.ModuleList()
  201. self.out_channels = []
  202. block_list = []
  203. i = 0
  204. inplanes = make_divisible(inplanes * scale)
  205. for k, exp, c, se, nl, s in cfg:
  206. se = se and not self.disable_se
  207. if s == 2 and i > 2:
  208. self.out_channels.append(inplanes)
  209. self.stages.append(nn.Sequential(*block_list))
  210. block_list = []
  211. block_list.append(
  212. ResidualUnit(
  213. in_channels=inplanes,
  214. mid_channels=make_divisible(scale * exp),
  215. out_channels=make_divisible(scale * c),
  216. kernel_size=k,
  217. stride=s,
  218. use_se=se,
  219. act=nl,
  220. name="conv" + str(i + 2),
  221. )
  222. )
  223. inplanes = make_divisible(scale * c)
  224. i += 1
  225. block_list.append(
  226. ConvBNLayer(
  227. in_channels=inplanes,
  228. out_channels=make_divisible(scale * cls_ch_squeeze),
  229. kernel_size=1,
  230. stride=1,
  231. padding=0,
  232. groups=1,
  233. if_act=True,
  234. act="hard_swish",
  235. name="conv_last",
  236. )
  237. )
  238. self.stages.append(nn.Sequential(*block_list))
  239. self.out_channels.append(make_divisible(scale * cls_ch_squeeze))
  240. # for i, stage in enumerate(self.stages):
  241. # self.add_sublayer(sublayer=stage, name="stage{}".format(i))
  242. def forward(self, x):
  243. x = self.conv(x)
  244. out_list = []
  245. for stage in self.stages:
  246. x = stage(x)
  247. out_list.append(x)
  248. return out_list