det_pp_lcnet_v2.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. # copyright (c) 2024 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, division, print_function
  15. import os
  16. import paddle
  17. import paddle.nn as nn
  18. import paddle.nn.functional as F
  19. from paddle import ParamAttr
  20. from paddle.nn import AdaptiveAvgPool2D, BatchNorm2D, Conv2D, Dropout, Linear
  21. from paddle.regularizer import L2Decay
  22. from paddle.nn.initializer import KaimingNormal
  23. from paddle.utils.download import get_path_from_url
  24. MODEL_URLS = {
  25. "PPLCNetV2_small": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNetV2_small_ssld_pretrained.pdparams",
  26. "PPLCNetV2_base": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNetV2_base_ssld_pretrained.pdparams",
  27. "PPLCNetV2_large": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNetV2_large_ssld_pretrained.pdparams",
  28. }
  29. __all__ = list(MODEL_URLS.keys())
  30. NET_CONFIG = {
  31. # in_channels, kernel_size, split_pw, use_rep, use_se, use_shortcut
  32. "stage1": [64, 3, False, False, False, False],
  33. "stage2": [128, 3, False, False, False, False],
  34. "stage3": [256, 5, True, True, True, False],
  35. "stage4": [512, 5, False, True, False, True],
  36. }
  37. def make_divisible(v, divisor=8, min_value=None):
  38. if min_value is None:
  39. min_value = divisor
  40. new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
  41. if new_v < 0.9 * v:
  42. new_v += divisor
  43. return new_v
  44. class ConvBNLayer(nn.Layer):
  45. def __init__(
  46. self, in_channels, out_channels, kernel_size, stride, groups=1, use_act=True
  47. ):
  48. super().__init__()
  49. self.use_act = use_act
  50. self.conv = Conv2D(
  51. in_channels=in_channels,
  52. out_channels=out_channels,
  53. kernel_size=kernel_size,
  54. stride=stride,
  55. padding=(kernel_size - 1) // 2,
  56. groups=groups,
  57. weight_attr=ParamAttr(initializer=KaimingNormal()),
  58. bias_attr=False,
  59. )
  60. self.bn = BatchNorm2D(
  61. out_channels,
  62. weight_attr=ParamAttr(regularizer=L2Decay(0.0)),
  63. bias_attr=ParamAttr(regularizer=L2Decay(0.0)),
  64. )
  65. if self.use_act:
  66. self.act = nn.ReLU()
  67. def forward(self, x):
  68. x = self.conv(x)
  69. x = self.bn(x)
  70. if self.use_act:
  71. x = self.act(x)
  72. return x
  73. class SEModule(nn.Layer):
  74. def __init__(self, channel, reduction=4):
  75. super().__init__()
  76. self.avg_pool = AdaptiveAvgPool2D(1)
  77. self.conv1 = Conv2D(
  78. in_channels=channel,
  79. out_channels=channel // reduction,
  80. kernel_size=1,
  81. stride=1,
  82. padding=0,
  83. )
  84. self.relu = nn.ReLU()
  85. self.conv2 = Conv2D(
  86. in_channels=channel // reduction,
  87. out_channels=channel,
  88. kernel_size=1,
  89. stride=1,
  90. padding=0,
  91. )
  92. self.hardsigmoid = nn.Sigmoid()
  93. def forward(self, x):
  94. identity = x
  95. x = self.avg_pool(x)
  96. x = self.conv1(x)
  97. x = self.relu(x)
  98. x = self.conv2(x)
  99. x = self.hardsigmoid(x)
  100. x = paddle.multiply(x=identity, y=x)
  101. return x
  102. class RepDepthwiseSeparable(nn.Layer):
  103. def __init__(
  104. self,
  105. in_channels,
  106. out_channels,
  107. stride,
  108. dw_size=3,
  109. split_pw=False,
  110. use_rep=False,
  111. use_se=False,
  112. use_shortcut=False,
  113. ):
  114. super().__init__()
  115. self.in_channels = in_channels
  116. self.out_channels = out_channels
  117. self.is_repped = False
  118. self.dw_size = dw_size
  119. self.split_pw = split_pw
  120. self.use_rep = use_rep
  121. self.use_se = use_se
  122. self.use_shortcut = (
  123. True
  124. if use_shortcut and stride == 1 and in_channels == out_channels
  125. else False
  126. )
  127. if self.use_rep:
  128. self.dw_conv_list = nn.LayerList()
  129. for kernel_size in range(self.dw_size, 0, -2):
  130. if kernel_size == 1 and stride != 1:
  131. continue
  132. dw_conv = ConvBNLayer(
  133. in_channels=in_channels,
  134. out_channels=in_channels,
  135. kernel_size=kernel_size,
  136. stride=stride,
  137. groups=in_channels,
  138. use_act=False,
  139. )
  140. self.dw_conv_list.append(dw_conv)
  141. self.dw_conv = nn.Conv2D(
  142. in_channels=in_channels,
  143. out_channels=in_channels,
  144. kernel_size=dw_size,
  145. stride=stride,
  146. padding=(dw_size - 1) // 2,
  147. groups=in_channels,
  148. )
  149. else:
  150. self.dw_conv = ConvBNLayer(
  151. in_channels=in_channels,
  152. out_channels=in_channels,
  153. kernel_size=dw_size,
  154. stride=stride,
  155. groups=in_channels,
  156. )
  157. self.act = nn.ReLU()
  158. if use_se:
  159. self.se = SEModule(in_channels)
  160. if self.split_pw:
  161. pw_ratio = 0.5
  162. self.pw_conv_1 = ConvBNLayer(
  163. in_channels=in_channels,
  164. kernel_size=1,
  165. out_channels=int(out_channels * pw_ratio),
  166. stride=1,
  167. )
  168. self.pw_conv_2 = ConvBNLayer(
  169. in_channels=int(out_channels * pw_ratio),
  170. kernel_size=1,
  171. out_channels=out_channels,
  172. stride=1,
  173. )
  174. else:
  175. self.pw_conv = ConvBNLayer(
  176. in_channels=in_channels,
  177. kernel_size=1,
  178. out_channels=out_channels,
  179. stride=1,
  180. )
  181. def forward(self, x):
  182. if self.use_rep:
  183. input_x = x
  184. if self.is_repped:
  185. x = self.act(self.dw_conv(x))
  186. else:
  187. y = self.dw_conv_list[0](x)
  188. for dw_conv in self.dw_conv_list[1:]:
  189. y += dw_conv(x)
  190. x = self.act(y)
  191. else:
  192. x = self.dw_conv(x)
  193. if self.use_se:
  194. x = self.se(x)
  195. if self.split_pw:
  196. x = self.pw_conv_1(x)
  197. x = self.pw_conv_2(x)
  198. else:
  199. x = self.pw_conv(x)
  200. if self.use_shortcut:
  201. x = x + input_x
  202. return x
  203. def re_parameterize(self):
  204. if self.use_rep:
  205. self.is_repped = True
  206. kernel, bias = self._get_equivalent_kernel_bias()
  207. self.dw_conv.weight.set_value(kernel)
  208. self.dw_conv.bias.set_value(bias)
  209. def _get_equivalent_kernel_bias(self):
  210. kernel_sum = 0
  211. bias_sum = 0
  212. for dw_conv in self.dw_conv_list:
  213. kernel, bias = self._fuse_bn_tensor(dw_conv)
  214. kernel = self._pad_tensor(kernel, to_size=self.dw_size)
  215. kernel_sum += kernel
  216. bias_sum += bias
  217. return kernel_sum, bias_sum
  218. def _fuse_bn_tensor(self, branch):
  219. kernel = branch.conv.weight
  220. running_mean = branch.bn._mean
  221. running_var = branch.bn._variance
  222. gamma = branch.bn.weight
  223. beta = branch.bn.bias
  224. eps = branch.bn._epsilon
  225. std = (running_var + eps).sqrt()
  226. t = (gamma / std).reshape((-1, 1, 1, 1))
  227. return kernel * t, beta - running_mean * gamma / std
  228. def _pad_tensor(self, tensor, to_size):
  229. from_size = tensor.shape[-1]
  230. if from_size == to_size:
  231. return tensor
  232. pad = (to_size - from_size) // 2
  233. return F.pad(tensor, [pad, pad, pad, pad])
  234. class PPLCNetV2(nn.Layer):
  235. def __init__(self, scale, depths, out_indx=[1, 2, 3, 4], **kwargs):
  236. super().__init__(**kwargs)
  237. self.scale = scale
  238. self.out_channels = [
  239. # int(NET_CONFIG["blocks3"][-1][2] * scale),
  240. int(NET_CONFIG["stage1"][0] * scale * 2),
  241. int(NET_CONFIG["stage2"][0] * scale * 2),
  242. int(NET_CONFIG["stage3"][0] * scale * 2),
  243. int(NET_CONFIG["stage4"][0] * scale * 2),
  244. ]
  245. self.stem = nn.Sequential(
  246. *[
  247. ConvBNLayer(
  248. in_channels=3,
  249. kernel_size=3,
  250. out_channels=make_divisible(32 * scale),
  251. stride=2,
  252. ),
  253. RepDepthwiseSeparable(
  254. in_channels=make_divisible(32 * scale),
  255. out_channels=make_divisible(64 * scale),
  256. stride=1,
  257. dw_size=3,
  258. ),
  259. ]
  260. )
  261. self.out_indx = out_indx
  262. # stages
  263. self.stages = nn.LayerList()
  264. for depth_idx, k in enumerate(NET_CONFIG):
  265. (
  266. in_channels,
  267. kernel_size,
  268. split_pw,
  269. use_rep,
  270. use_se,
  271. use_shortcut,
  272. ) = NET_CONFIG[k]
  273. self.stages.append(
  274. nn.Sequential(
  275. *[
  276. RepDepthwiseSeparable(
  277. in_channels=make_divisible(
  278. (in_channels if i == 0 else in_channels * 2) * scale
  279. ),
  280. out_channels=make_divisible(in_channels * 2 * scale),
  281. stride=2 if i == 0 else 1,
  282. dw_size=kernel_size,
  283. split_pw=split_pw,
  284. use_rep=use_rep,
  285. use_se=use_se,
  286. use_shortcut=use_shortcut,
  287. )
  288. for i in range(depths[depth_idx])
  289. ]
  290. )
  291. )
  292. # if pretrained:
  293. self._load_pretrained(MODEL_URLS["PPLCNetV2_base"], use_ssld=True)
  294. def forward(self, x):
  295. x = self.stem(x)
  296. i = 1
  297. outs = []
  298. for stage in self.stages:
  299. x = stage(x)
  300. if i in self.out_indx:
  301. outs.append(x)
  302. i += 1
  303. return outs
  304. def _load_pretrained(self, pretrained_url, use_ssld=False):
  305. print(pretrained_url)
  306. local_weight_path = get_path_from_url(
  307. pretrained_url, os.path.expanduser("~/.paddleclas/weights")
  308. )
  309. param_state_dict = paddle.load(local_weight_path)
  310. self.set_dict(param_state_dict)
  311. print("load pretrain ssd success!")
  312. return
  313. def PPLCNetV2_base(in_channels=3, **kwargs):
  314. """
  315. PPLCNetV2_base
  316. Args:
  317. pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.
  318. If str, means the path of the pretrained model.
  319. use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.
  320. Returns:
  321. model: nn.Layer. Specific `PPLCNetV2_base` model depends on args.
  322. """
  323. model = PPLCNetV2(scale=1.0, depths=[2, 2, 6, 2], **kwargs)
  324. return model