rec_hgnet.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. # copyright (c) 2022 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. import paddle
  15. import paddle.nn as nn
  16. import paddle.nn.functional as F
  17. from paddle.nn.initializer import KaimingNormal, Constant
  18. from paddle.nn import Conv2D, BatchNorm2D, ReLU, AdaptiveAvgPool2D, MaxPool2D
  19. from paddle.regularizer import L2Decay
  20. from paddle import ParamAttr
  21. kaiming_normal_ = KaimingNormal()
  22. zeros_ = Constant(value=0.0)
  23. ones_ = Constant(value=1.0)
  24. class MeanPool2D(nn.Layer):
  25. def __init__(self, w, h):
  26. super().__init__()
  27. self.w = w
  28. self.h = h
  29. def forward(self, feat):
  30. batch_size, channels, _, _ = feat.shape
  31. feat_flat = paddle.reshape(feat, [batch_size, channels, -1])
  32. feat_mean = paddle.mean(feat_flat, axis=2)
  33. feat_mean = paddle.reshape(feat_mean, [batch_size, channels, self.w, self.h])
  34. return feat_mean
  35. class ConvBNAct(nn.Layer):
  36. def __init__(
  37. self, in_channels, out_channels, kernel_size, stride, groups=1, use_act=True
  38. ):
  39. super().__init__()
  40. self.use_act = use_act
  41. self.conv = Conv2D(
  42. in_channels,
  43. out_channels,
  44. kernel_size,
  45. stride,
  46. padding=(kernel_size - 1) // 2,
  47. groups=groups,
  48. bias_attr=False,
  49. )
  50. self.bn = BatchNorm2D(
  51. out_channels,
  52. weight_attr=ParamAttr(regularizer=L2Decay(0.0)),
  53. bias_attr=ParamAttr(regularizer=L2Decay(0.0)),
  54. )
  55. if self.use_act:
  56. self.act = ReLU()
  57. def forward(self, x):
  58. x = self.conv(x)
  59. x = self.bn(x)
  60. if self.use_act:
  61. x = self.act(x)
  62. return x
  63. class ESEModule(nn.Layer):
  64. def __init__(self, channels):
  65. super().__init__()
  66. if "npu" in paddle.device.get_device():
  67. self.avg_pool = MeanPool2D(1, 1)
  68. else:
  69. self.avg_pool = AdaptiveAvgPool2D(1)
  70. self.conv = Conv2D(
  71. in_channels=channels,
  72. out_channels=channels,
  73. kernel_size=1,
  74. stride=1,
  75. padding=0,
  76. )
  77. self.sigmoid = nn.Sigmoid()
  78. def forward(self, x):
  79. identity = x
  80. x = self.avg_pool(x)
  81. x = self.conv(x)
  82. x = self.sigmoid(x)
  83. return paddle.multiply(x=identity, y=x)
  84. class HG_Block(nn.Layer):
  85. def __init__(
  86. self,
  87. in_channels,
  88. mid_channels,
  89. out_channels,
  90. layer_num,
  91. identity=False,
  92. ):
  93. super().__init__()
  94. self.identity = identity
  95. self.layers = nn.LayerList()
  96. self.layers.append(
  97. ConvBNAct(
  98. in_channels=in_channels,
  99. out_channels=mid_channels,
  100. kernel_size=3,
  101. stride=1,
  102. )
  103. )
  104. for _ in range(layer_num - 1):
  105. self.layers.append(
  106. ConvBNAct(
  107. in_channels=mid_channels,
  108. out_channels=mid_channels,
  109. kernel_size=3,
  110. stride=1,
  111. )
  112. )
  113. # feature aggregation
  114. total_channels = in_channels + layer_num * mid_channels
  115. self.aggregation_conv = ConvBNAct(
  116. in_channels=total_channels,
  117. out_channels=out_channels,
  118. kernel_size=1,
  119. stride=1,
  120. )
  121. self.att = ESEModule(out_channels)
  122. def forward(self, x):
  123. identity = x
  124. output = []
  125. output.append(x)
  126. for layer in self.layers:
  127. x = layer(x)
  128. output.append(x)
  129. x = paddle.concat(output, axis=1)
  130. x = self.aggregation_conv(x)
  131. x = self.att(x)
  132. if self.identity:
  133. x += identity
  134. return x
  135. class HG_Stage(nn.Layer):
  136. def __init__(
  137. self,
  138. in_channels,
  139. mid_channels,
  140. out_channels,
  141. block_num,
  142. layer_num,
  143. downsample=True,
  144. stride=[2, 1],
  145. ):
  146. super().__init__()
  147. self.downsample = downsample
  148. if downsample:
  149. self.downsample = ConvBNAct(
  150. in_channels=in_channels,
  151. out_channels=in_channels,
  152. kernel_size=3,
  153. stride=stride,
  154. groups=in_channels,
  155. use_act=False,
  156. )
  157. blocks_list = []
  158. blocks_list.append(
  159. HG_Block(in_channels, mid_channels, out_channels, layer_num, identity=False)
  160. )
  161. for _ in range(block_num - 1):
  162. blocks_list.append(
  163. HG_Block(
  164. out_channels, mid_channels, out_channels, layer_num, identity=True
  165. )
  166. )
  167. self.blocks = nn.Sequential(*blocks_list)
  168. def forward(self, x):
  169. if self.downsample:
  170. x = self.downsample(x)
  171. x = self.blocks(x)
  172. return x
  173. class PPHGNet(nn.Layer):
  174. """
  175. PPHGNet
  176. Args:
  177. stem_channels: list. Stem channel list of PPHGNet.
  178. stage_config: dict. The configuration of each stage of PPHGNet. such as the number of channels, stride, etc.
  179. layer_num: int. Number of layers of HG_Block.
  180. use_last_conv: boolean. Whether to use a 1x1 convolutional layer before the classification layer.
  181. class_expand: int=2048. Number of channels for the last 1x1 convolutional layer.
  182. dropout_prob: float. Parameters of dropout, 0.0 means dropout is not used.
  183. class_num: int=1000. The number of classes.
  184. Returns:
  185. model: nn.Layer. Specific PPHGNet model depends on args.
  186. """
  187. def __init__(
  188. self,
  189. stem_channels,
  190. stage_config,
  191. layer_num,
  192. in_channels=3,
  193. det=False,
  194. out_indices=None,
  195. ):
  196. super().__init__()
  197. self.det = det
  198. self.out_indices = out_indices if out_indices is not None else [0, 1, 2, 3]
  199. # stem
  200. stem_channels.insert(0, in_channels)
  201. self.stem = nn.Sequential(
  202. *[
  203. ConvBNAct(
  204. in_channels=stem_channels[i],
  205. out_channels=stem_channels[i + 1],
  206. kernel_size=3,
  207. stride=2 if i == 0 else 1,
  208. )
  209. for i in range(len(stem_channels) - 1)
  210. ]
  211. )
  212. if self.det:
  213. self.pool = nn.MaxPool2D(kernel_size=3, stride=2, padding=1)
  214. # stages
  215. self.stages = nn.LayerList()
  216. self.out_channels = []
  217. for block_id, k in enumerate(stage_config):
  218. (
  219. in_channels,
  220. mid_channels,
  221. out_channels,
  222. block_num,
  223. downsample,
  224. stride,
  225. ) = stage_config[k]
  226. self.stages.append(
  227. HG_Stage(
  228. in_channels,
  229. mid_channels,
  230. out_channels,
  231. block_num,
  232. layer_num,
  233. downsample,
  234. stride,
  235. )
  236. )
  237. if block_id in self.out_indices:
  238. self.out_channels.append(out_channels)
  239. if not self.det:
  240. self.out_channels = stage_config["stage4"][2]
  241. self._init_weights()
  242. def _init_weights(self):
  243. for m in self.sublayers():
  244. if isinstance(m, nn.Conv2D):
  245. kaiming_normal_(m.weight)
  246. elif isinstance(m, (nn.BatchNorm2D)):
  247. ones_(m.weight)
  248. zeros_(m.bias)
  249. elif isinstance(m, nn.Linear):
  250. zeros_(m.bias)
  251. def forward(self, x):
  252. x = self.stem(x)
  253. if self.det:
  254. x = self.pool(x)
  255. out = []
  256. for i, stage in enumerate(self.stages):
  257. x = stage(x)
  258. if self.det and i in self.out_indices:
  259. out.append(x)
  260. if self.det:
  261. return out
  262. if self.training:
  263. x = F.adaptive_avg_pool2d(x, [1, 40])
  264. else:
  265. x = F.avg_pool2d(x, [3, 2])
  266. return x
  267. def PPHGNet_tiny(pretrained=False, use_ssld=False, **kwargs):
  268. """
  269. PPHGNet_tiny
  270. Args:
  271. pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.
  272. If str, means the path of the pretrained model.
  273. use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.
  274. Returns:
  275. model: nn.Layer. Specific `PPHGNet_tiny` model depends on args.
  276. """
  277. stage_config = {
  278. # in_channels, mid_channels, out_channels, blocks, downsample
  279. "stage1": [96, 96, 224, 1, False, [2, 1]],
  280. "stage2": [224, 128, 448, 1, True, [1, 2]],
  281. "stage3": [448, 160, 512, 2, True, [2, 1]],
  282. "stage4": [512, 192, 768, 1, True, [2, 1]],
  283. }
  284. model = PPHGNet(
  285. stem_channels=[48, 48, 96], stage_config=stage_config, layer_num=5, **kwargs
  286. )
  287. return model
  288. def PPHGNet_small(pretrained=False, use_ssld=False, det=False, **kwargs):
  289. """
  290. PPHGNet_small
  291. Args:
  292. pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.
  293. If str, means the path of the pretrained model.
  294. use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.
  295. Returns:
  296. model: nn.Layer. Specific `PPHGNet_small` model depends on args.
  297. """
  298. stage_config_det = {
  299. # in_channels, mid_channels, out_channels, blocks, downsample
  300. "stage1": [128, 128, 256, 1, False, 2],
  301. "stage2": [256, 160, 512, 1, True, 2],
  302. "stage3": [512, 192, 768, 2, True, 2],
  303. "stage4": [768, 224, 1024, 1, True, 2],
  304. }
  305. stage_config_rec = {
  306. # in_channels, mid_channels, out_channels, blocks, downsample
  307. "stage1": [128, 128, 256, 1, True, [2, 1]],
  308. "stage2": [256, 160, 512, 1, True, [1, 2]],
  309. "stage3": [512, 192, 768, 2, True, [2, 1]],
  310. "stage4": [768, 224, 1024, 1, True, [2, 1]],
  311. }
  312. model = PPHGNet(
  313. stem_channels=[64, 64, 128],
  314. stage_config=stage_config_det if det else stage_config_rec,
  315. layer_num=6,
  316. det=det,
  317. **kwargs,
  318. )
  319. return model
  320. def PPHGNet_base(pretrained=False, use_ssld=True, **kwargs):
  321. """
  322. PPHGNet_base
  323. Args:
  324. pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.
  325. If str, means the path of the pretrained model.
  326. use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.
  327. Returns:
  328. model: nn.Layer. Specific `PPHGNet_base` model depends on args.
  329. """
  330. stage_config = {
  331. # in_channels, mid_channels, out_channels, blocks, downsample
  332. "stage1": [160, 192, 320, 1, False, [2, 1]],
  333. "stage2": [320, 224, 640, 2, True, [1, 2]],
  334. "stage3": [640, 256, 960, 3, True, [2, 1]],
  335. "stage4": [960, 288, 1280, 2, True, [2, 1]],
  336. }
  337. model = PPHGNet(
  338. stem_channels=[96, 96, 160],
  339. stage_config=stage_config,
  340. layer_num=7,
  341. dropout_prob=0.2,
  342. **kwargs,
  343. )
  344. return model