pico_head.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  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 math
  18. import numpy as np
  19. import paddle
  20. import paddle.nn as nn
  21. import paddle.nn.functional as F
  22. from paddle import ParamAttr
  23. from paddle.nn.initializer import Normal, Constant
  24. from paddle.fluid.dygraph import parallel_helper
  25. from ppdet.modeling.ops import get_static_shape
  26. from ..initializer import normal_
  27. from ..assigners.utils import generate_anchors_for_grid_cell
  28. from ..bbox_utils import bbox_center, batch_distance2bbox, bbox2distance
  29. from ppdet.core.workspace import register
  30. from ppdet.modeling.layers import ConvNormLayer
  31. from .simota_head import OTAVFLHead
  32. from .gfl_head import Integral, GFLHead
  33. from ppdet.modeling.necks.csp_pan import DPModule
  34. eps = 1e-9
  35. __all__ = ['PicoHead', 'PicoHeadV2', 'PicoFeat']
  36. class PicoSE(nn.Layer):
  37. def __init__(self, feat_channels):
  38. super(PicoSE, self).__init__()
  39. self.fc = nn.Conv2D(feat_channels, feat_channels, 1)
  40. self.conv = ConvNormLayer(feat_channels, feat_channels, 1, 1)
  41. self._init_weights()
  42. def _init_weights(self):
  43. normal_(self.fc.weight, std=0.001)
  44. def forward(self, feat, avg_feat):
  45. weight = F.sigmoid(self.fc(avg_feat))
  46. out = self.conv(feat * weight)
  47. return out
  48. @register
  49. class PicoFeat(nn.Layer):
  50. """
  51. PicoFeat of PicoDet
  52. Args:
  53. feat_in (int): The channel number of input Tensor.
  54. feat_out (int): The channel number of output Tensor.
  55. num_convs (int): The convolution number of the LiteGFLFeat.
  56. norm_type (str): Normalization type, 'bn'/'sync_bn'/'gn'.
  57. share_cls_reg (bool): Whether to share the cls and reg output.
  58. act (str): The act of per layers.
  59. use_se (bool): Whether to use se module.
  60. """
  61. def __init__(self,
  62. feat_in=256,
  63. feat_out=96,
  64. num_fpn_stride=3,
  65. num_convs=2,
  66. norm_type='bn',
  67. share_cls_reg=False,
  68. act='hard_swish',
  69. use_se=False):
  70. super(PicoFeat, self).__init__()
  71. self.num_convs = num_convs
  72. self.norm_type = norm_type
  73. self.share_cls_reg = share_cls_reg
  74. self.act = act
  75. self.use_se = use_se
  76. self.cls_convs = []
  77. self.reg_convs = []
  78. if use_se:
  79. assert share_cls_reg == True, \
  80. 'In the case of using se, share_cls_reg is not supported'
  81. self.se = nn.LayerList()
  82. for stage_idx in range(num_fpn_stride):
  83. cls_subnet_convs = []
  84. reg_subnet_convs = []
  85. for i in range(self.num_convs):
  86. in_c = feat_in if i == 0 else feat_out
  87. cls_conv_dw = self.add_sublayer(
  88. 'cls_conv_dw{}.{}'.format(stage_idx, i),
  89. ConvNormLayer(
  90. ch_in=in_c,
  91. ch_out=feat_out,
  92. filter_size=5,
  93. stride=1,
  94. groups=feat_out,
  95. norm_type=norm_type,
  96. bias_on=False,
  97. lr_scale=2.))
  98. cls_subnet_convs.append(cls_conv_dw)
  99. cls_conv_pw = self.add_sublayer(
  100. 'cls_conv_pw{}.{}'.format(stage_idx, i),
  101. ConvNormLayer(
  102. ch_in=in_c,
  103. ch_out=feat_out,
  104. filter_size=1,
  105. stride=1,
  106. norm_type=norm_type,
  107. bias_on=False,
  108. lr_scale=2.))
  109. cls_subnet_convs.append(cls_conv_pw)
  110. if not self.share_cls_reg:
  111. reg_conv_dw = self.add_sublayer(
  112. 'reg_conv_dw{}.{}'.format(stage_idx, i),
  113. ConvNormLayer(
  114. ch_in=in_c,
  115. ch_out=feat_out,
  116. filter_size=5,
  117. stride=1,
  118. groups=feat_out,
  119. norm_type=norm_type,
  120. bias_on=False,
  121. lr_scale=2.))
  122. reg_subnet_convs.append(reg_conv_dw)
  123. reg_conv_pw = self.add_sublayer(
  124. 'reg_conv_pw{}.{}'.format(stage_idx, i),
  125. ConvNormLayer(
  126. ch_in=in_c,
  127. ch_out=feat_out,
  128. filter_size=1,
  129. stride=1,
  130. norm_type=norm_type,
  131. bias_on=False,
  132. lr_scale=2.))
  133. reg_subnet_convs.append(reg_conv_pw)
  134. self.cls_convs.append(cls_subnet_convs)
  135. self.reg_convs.append(reg_subnet_convs)
  136. if use_se:
  137. self.se.append(PicoSE(feat_out))
  138. def act_func(self, x):
  139. if self.act == "leaky_relu":
  140. x = F.leaky_relu(x)
  141. elif self.act == "hard_swish":
  142. x = F.hardswish(x)
  143. return x
  144. def forward(self, fpn_feat, stage_idx):
  145. assert stage_idx < len(self.cls_convs)
  146. cls_feat = fpn_feat
  147. reg_feat = fpn_feat
  148. for i in range(len(self.cls_convs[stage_idx])):
  149. cls_feat = self.act_func(self.cls_convs[stage_idx][i](cls_feat))
  150. reg_feat = cls_feat
  151. if not self.share_cls_reg:
  152. reg_feat = self.act_func(self.reg_convs[stage_idx][i](reg_feat))
  153. if self.use_se:
  154. avg_feat = F.adaptive_avg_pool2d(cls_feat, (1, 1))
  155. se_feat = self.act_func(self.se[stage_idx](cls_feat, avg_feat))
  156. return cls_feat, se_feat
  157. return cls_feat, reg_feat
  158. @register
  159. class PicoHead(OTAVFLHead):
  160. """
  161. PicoHead
  162. Args:
  163. conv_feat (object): Instance of 'PicoFeat'
  164. num_classes (int): Number of classes
  165. fpn_stride (list): The stride of each FPN Layer
  166. prior_prob (float): Used to set the bias init for the class prediction layer
  167. loss_class (object): Instance of VariFocalLoss.
  168. loss_dfl (object): Instance of DistributionFocalLoss.
  169. loss_bbox (object): Instance of bbox loss.
  170. assigner (object): Instance of label assigner.
  171. reg_max: Max value of integral set :math: `{0, ..., reg_max}`
  172. n QFL setting. Default: 7.
  173. """
  174. __inject__ = [
  175. 'conv_feat', 'dgqp_module', 'loss_class', 'loss_dfl', 'loss_bbox',
  176. 'assigner', 'nms'
  177. ]
  178. __shared__ = ['num_classes', 'eval_size']
  179. def __init__(self,
  180. conv_feat='PicoFeat',
  181. dgqp_module=None,
  182. num_classes=80,
  183. fpn_stride=[8, 16, 32],
  184. prior_prob=0.01,
  185. loss_class='VariFocalLoss',
  186. loss_dfl='DistributionFocalLoss',
  187. loss_bbox='GIoULoss',
  188. assigner='SimOTAAssigner',
  189. reg_max=16,
  190. feat_in_chan=96,
  191. nms=None,
  192. nms_pre=1000,
  193. cell_offset=0,
  194. eval_size=None):
  195. super(PicoHead, self).__init__(
  196. conv_feat=conv_feat,
  197. dgqp_module=dgqp_module,
  198. num_classes=num_classes,
  199. fpn_stride=fpn_stride,
  200. prior_prob=prior_prob,
  201. loss_class=loss_class,
  202. loss_dfl=loss_dfl,
  203. loss_bbox=loss_bbox,
  204. assigner=assigner,
  205. reg_max=reg_max,
  206. feat_in_chan=feat_in_chan,
  207. nms=nms,
  208. nms_pre=nms_pre,
  209. cell_offset=cell_offset)
  210. self.conv_feat = conv_feat
  211. self.num_classes = num_classes
  212. self.fpn_stride = fpn_stride
  213. self.prior_prob = prior_prob
  214. self.loss_vfl = loss_class
  215. self.loss_dfl = loss_dfl
  216. self.loss_bbox = loss_bbox
  217. self.assigner = assigner
  218. self.reg_max = reg_max
  219. self.feat_in_chan = feat_in_chan
  220. self.nms = nms
  221. self.nms_pre = nms_pre
  222. self.cell_offset = cell_offset
  223. self.eval_size = eval_size
  224. self.use_sigmoid = self.loss_vfl.use_sigmoid
  225. if self.use_sigmoid:
  226. self.cls_out_channels = self.num_classes
  227. else:
  228. self.cls_out_channels = self.num_classes + 1
  229. bias_init_value = -math.log((1 - self.prior_prob) / self.prior_prob)
  230. # Clear the super class initialization
  231. self.gfl_head_cls = None
  232. self.gfl_head_reg = None
  233. self.scales_regs = None
  234. self.head_cls_list = []
  235. self.head_reg_list = []
  236. for i in range(len(fpn_stride)):
  237. head_cls = self.add_sublayer(
  238. "head_cls" + str(i),
  239. nn.Conv2D(
  240. in_channels=self.feat_in_chan,
  241. out_channels=self.cls_out_channels + 4 * (self.reg_max + 1)
  242. if self.conv_feat.share_cls_reg else self.cls_out_channels,
  243. kernel_size=1,
  244. stride=1,
  245. padding=0,
  246. weight_attr=ParamAttr(initializer=Normal(
  247. mean=0., std=0.01)),
  248. bias_attr=ParamAttr(
  249. initializer=Constant(value=bias_init_value))))
  250. self.head_cls_list.append(head_cls)
  251. if not self.conv_feat.share_cls_reg:
  252. head_reg = self.add_sublayer(
  253. "head_reg" + str(i),
  254. nn.Conv2D(
  255. in_channels=self.feat_in_chan,
  256. out_channels=4 * (self.reg_max + 1),
  257. kernel_size=1,
  258. stride=1,
  259. padding=0,
  260. weight_attr=ParamAttr(initializer=Normal(
  261. mean=0., std=0.01)),
  262. bias_attr=ParamAttr(initializer=Constant(value=0))))
  263. self.head_reg_list.append(head_reg)
  264. # initialize the anchor points
  265. if self.eval_size:
  266. self.anchor_points, self.stride_tensor = self._generate_anchors()
  267. def forward(self, fpn_feats, export_post_process=True):
  268. assert len(fpn_feats) == len(
  269. self.fpn_stride
  270. ), "The size of fpn_feats is not equal to size of fpn_stride"
  271. if self.training:
  272. return self.forward_train(fpn_feats)
  273. else:
  274. return self.forward_eval(
  275. fpn_feats, export_post_process=export_post_process)
  276. def forward_train(self, fpn_feats):
  277. cls_logits_list, bboxes_reg_list = [], []
  278. for i, fpn_feat in enumerate(fpn_feats):
  279. conv_cls_feat, conv_reg_feat = self.conv_feat(fpn_feat, i)
  280. if self.conv_feat.share_cls_reg:
  281. cls_logits = self.head_cls_list[i](conv_cls_feat)
  282. cls_score, bbox_pred = paddle.split(
  283. cls_logits,
  284. [self.cls_out_channels, 4 * (self.reg_max + 1)],
  285. axis=1)
  286. else:
  287. cls_score = self.head_cls_list[i](conv_cls_feat)
  288. bbox_pred = self.head_reg_list[i](conv_reg_feat)
  289. if self.dgqp_module:
  290. quality_score = self.dgqp_module(bbox_pred)
  291. cls_score = F.sigmoid(cls_score) * quality_score
  292. cls_logits_list.append(cls_score)
  293. bboxes_reg_list.append(bbox_pred)
  294. return (cls_logits_list, bboxes_reg_list)
  295. def forward_eval(self, fpn_feats, export_post_process=True):
  296. if self.eval_size:
  297. anchor_points, stride_tensor = self.anchor_points, self.stride_tensor
  298. else:
  299. anchor_points, stride_tensor = self._generate_anchors(fpn_feats)
  300. cls_logits_list, bboxes_reg_list = [], []
  301. for i, fpn_feat in enumerate(fpn_feats):
  302. conv_cls_feat, conv_reg_feat = self.conv_feat(fpn_feat, i)
  303. if self.conv_feat.share_cls_reg:
  304. cls_logits = self.head_cls_list[i](conv_cls_feat)
  305. cls_score, bbox_pred = paddle.split(
  306. cls_logits,
  307. [self.cls_out_channels, 4 * (self.reg_max + 1)],
  308. axis=1)
  309. else:
  310. cls_score = self.head_cls_list[i](conv_cls_feat)
  311. bbox_pred = self.head_reg_list[i](conv_reg_feat)
  312. if self.dgqp_module:
  313. quality_score = self.dgqp_module(bbox_pred)
  314. cls_score = F.sigmoid(cls_score) * quality_score
  315. if not export_post_process:
  316. # Now only supports batch size = 1 in deploy
  317. # TODO(ygh): support batch size > 1
  318. cls_score_out = F.sigmoid(cls_score).reshape(
  319. [1, self.cls_out_channels, -1]).transpose([0, 2, 1])
  320. bbox_pred = bbox_pred.reshape([1, (self.reg_max + 1) * 4,
  321. -1]).transpose([0, 2, 1])
  322. else:
  323. b, _, h, w = fpn_feat.shape
  324. l = h * w
  325. cls_score_out = F.sigmoid(
  326. cls_score.reshape([b, self.cls_out_channels, l]))
  327. bbox_pred = bbox_pred.transpose([0, 2, 3, 1])
  328. bbox_pred = self.distribution_project(bbox_pred)
  329. bbox_pred = bbox_pred.reshape([b, l, 4])
  330. cls_logits_list.append(cls_score_out)
  331. bboxes_reg_list.append(bbox_pred)
  332. if export_post_process:
  333. cls_logits_list = paddle.concat(cls_logits_list, axis=-1)
  334. bboxes_reg_list = paddle.concat(bboxes_reg_list, axis=1)
  335. bboxes_reg_list = batch_distance2bbox(anchor_points,
  336. bboxes_reg_list)
  337. bboxes_reg_list *= stride_tensor
  338. return (cls_logits_list, bboxes_reg_list)
  339. def _generate_anchors(self, feats=None):
  340. # just use in eval time
  341. anchor_points = []
  342. stride_tensor = []
  343. for i, stride in enumerate(self.fpn_stride):
  344. if feats is not None:
  345. _, _, h, w = feats[i].shape
  346. else:
  347. h = math.ceil(self.eval_size[0] / stride)
  348. w = math.ceil(self.eval_size[1] / stride)
  349. shift_x = paddle.arange(end=w) + self.cell_offset
  350. shift_y = paddle.arange(end=h) + self.cell_offset
  351. shift_y, shift_x = paddle.meshgrid(shift_y, shift_x)
  352. anchor_point = paddle.cast(
  353. paddle.stack(
  354. [shift_x, shift_y], axis=-1), dtype='float32')
  355. anchor_points.append(anchor_point.reshape([-1, 2]))
  356. stride_tensor.append(
  357. paddle.full(
  358. [h * w, 1], stride, dtype='float32'))
  359. anchor_points = paddle.concat(anchor_points)
  360. stride_tensor = paddle.concat(stride_tensor)
  361. return anchor_points, stride_tensor
  362. def post_process(self, head_outs, scale_factor, export_nms=True):
  363. pred_scores, pred_bboxes = head_outs
  364. if not export_nms:
  365. return pred_bboxes, pred_scores
  366. else:
  367. # rescale: [h_scale, w_scale] -> [w_scale, h_scale, w_scale, h_scale]
  368. scale_y, scale_x = paddle.split(scale_factor, 2, axis=-1)
  369. scale_factor = paddle.concat(
  370. [scale_x, scale_y, scale_x, scale_y],
  371. axis=-1).reshape([-1, 1, 4])
  372. # scale bbox to origin image size.
  373. pred_bboxes /= scale_factor
  374. bbox_pred, bbox_num, _ = self.nms(pred_bboxes, pred_scores)
  375. return bbox_pred, bbox_num
  376. @register
  377. class PicoHeadV2(GFLHead):
  378. """
  379. PicoHeadV2
  380. Args:
  381. conv_feat (object): Instance of 'PicoFeat'
  382. num_classes (int): Number of classes
  383. fpn_stride (list): The stride of each FPN Layer
  384. prior_prob (float): Used to set the bias init for the class prediction layer
  385. loss_class (object): Instance of VariFocalLoss.
  386. loss_dfl (object): Instance of DistributionFocalLoss.
  387. loss_bbox (object): Instance of bbox loss.
  388. assigner (object): Instance of label assigner.
  389. reg_max: Max value of integral set :math: `{0, ..., reg_max}`
  390. n QFL setting. Default: 7.
  391. """
  392. __inject__ = [
  393. 'conv_feat', 'dgqp_module', 'loss_class', 'loss_dfl', 'loss_bbox',
  394. 'static_assigner', 'assigner', 'nms'
  395. ]
  396. __shared__ = ['num_classes', 'eval_size']
  397. def __init__(self,
  398. conv_feat='PicoFeatV2',
  399. dgqp_module=None,
  400. num_classes=80,
  401. fpn_stride=[8, 16, 32],
  402. prior_prob=0.01,
  403. use_align_head=True,
  404. loss_class='VariFocalLoss',
  405. loss_dfl='DistributionFocalLoss',
  406. loss_bbox='GIoULoss',
  407. static_assigner_epoch=60,
  408. static_assigner='ATSSAssigner',
  409. assigner='TaskAlignedAssigner',
  410. reg_max=16,
  411. feat_in_chan=96,
  412. nms=None,
  413. nms_pre=1000,
  414. cell_offset=0,
  415. act='hard_swish',
  416. grid_cell_scale=5.0,
  417. eval_size=None):
  418. super(PicoHeadV2, self).__init__(
  419. conv_feat=conv_feat,
  420. dgqp_module=dgqp_module,
  421. num_classes=num_classes,
  422. fpn_stride=fpn_stride,
  423. prior_prob=prior_prob,
  424. loss_class=loss_class,
  425. loss_dfl=loss_dfl,
  426. loss_bbox=loss_bbox,
  427. reg_max=reg_max,
  428. feat_in_chan=feat_in_chan,
  429. nms=nms,
  430. nms_pre=nms_pre,
  431. cell_offset=cell_offset, )
  432. self.conv_feat = conv_feat
  433. self.num_classes = num_classes
  434. self.fpn_stride = fpn_stride
  435. self.prior_prob = prior_prob
  436. self.loss_vfl = loss_class
  437. self.loss_dfl = loss_dfl
  438. self.loss_bbox = loss_bbox
  439. self.static_assigner_epoch = static_assigner_epoch
  440. self.static_assigner = static_assigner
  441. self.assigner = assigner
  442. self.reg_max = reg_max
  443. self.feat_in_chan = feat_in_chan
  444. self.nms = nms
  445. self.nms_pre = nms_pre
  446. self.cell_offset = cell_offset
  447. self.act = act
  448. self.grid_cell_scale = grid_cell_scale
  449. self.use_align_head = use_align_head
  450. self.cls_out_channels = self.num_classes
  451. self.eval_size = eval_size
  452. bias_init_value = -math.log((1 - self.prior_prob) / self.prior_prob)
  453. # Clear the super class initialization
  454. self.gfl_head_cls = None
  455. self.gfl_head_reg = None
  456. self.scales_regs = None
  457. self.head_cls_list = []
  458. self.head_reg_list = []
  459. self.cls_align = nn.LayerList()
  460. for i in range(len(fpn_stride)):
  461. head_cls = self.add_sublayer(
  462. "head_cls" + str(i),
  463. nn.Conv2D(
  464. in_channels=self.feat_in_chan,
  465. out_channels=self.cls_out_channels,
  466. kernel_size=1,
  467. stride=1,
  468. padding=0,
  469. weight_attr=ParamAttr(initializer=Normal(
  470. mean=0., std=0.01)),
  471. bias_attr=ParamAttr(
  472. initializer=Constant(value=bias_init_value))))
  473. self.head_cls_list.append(head_cls)
  474. head_reg = self.add_sublayer(
  475. "head_reg" + str(i),
  476. nn.Conv2D(
  477. in_channels=self.feat_in_chan,
  478. out_channels=4 * (self.reg_max + 1),
  479. kernel_size=1,
  480. stride=1,
  481. padding=0,
  482. weight_attr=ParamAttr(initializer=Normal(
  483. mean=0., std=0.01)),
  484. bias_attr=ParamAttr(initializer=Constant(value=0))))
  485. self.head_reg_list.append(head_reg)
  486. if self.use_align_head:
  487. self.cls_align.append(
  488. DPModule(
  489. self.feat_in_chan,
  490. 1,
  491. 5,
  492. act=self.act,
  493. use_act_in_out=False))
  494. # initialize the anchor points
  495. if self.eval_size:
  496. self.anchor_points, self.stride_tensor = self._generate_anchors()
  497. def forward(self, fpn_feats, export_post_process=True):
  498. assert len(fpn_feats) == len(
  499. self.fpn_stride
  500. ), "The size of fpn_feats is not equal to size of fpn_stride"
  501. if self.training:
  502. return self.forward_train(fpn_feats)
  503. else:
  504. return self.forward_eval(
  505. fpn_feats, export_post_process=export_post_process)
  506. def forward_train(self, fpn_feats):
  507. cls_score_list, reg_list, box_list = [], [], []
  508. for i, (fpn_feat, stride) in enumerate(zip(fpn_feats, self.fpn_stride)):
  509. b, _, h, w = get_static_shape(fpn_feat)
  510. # task decomposition
  511. conv_cls_feat, se_feat = self.conv_feat(fpn_feat, i)
  512. cls_logit = self.head_cls_list[i](se_feat)
  513. reg_pred = self.head_reg_list[i](se_feat)
  514. # cls prediction and alignment
  515. if self.use_align_head:
  516. cls_prob = F.sigmoid(self.cls_align[i](conv_cls_feat))
  517. cls_score = (F.sigmoid(cls_logit) * cls_prob + eps).sqrt()
  518. else:
  519. cls_score = F.sigmoid(cls_logit)
  520. cls_score_out = cls_score.transpose([0, 2, 3, 1])
  521. bbox_pred = reg_pred.transpose([0, 2, 3, 1])
  522. b, cell_h, cell_w, _ = paddle.shape(cls_score_out)
  523. y, x = self.get_single_level_center_point(
  524. [cell_h, cell_w], stride, cell_offset=self.cell_offset)
  525. center_points = paddle.stack([x, y], axis=-1)
  526. cls_score_out = cls_score_out.reshape(
  527. [b, -1, self.cls_out_channels])
  528. bbox_pred = self.distribution_project(bbox_pred) * stride
  529. bbox_pred = bbox_pred.reshape([b, cell_h * cell_w, 4])
  530. bbox_pred = batch_distance2bbox(
  531. center_points, bbox_pred, max_shapes=None)
  532. cls_score_list.append(cls_score.flatten(2).transpose([0, 2, 1]))
  533. reg_list.append(reg_pred.flatten(2).transpose([0, 2, 1]))
  534. box_list.append(bbox_pred / stride)
  535. cls_score_list = paddle.concat(cls_score_list, axis=1)
  536. box_list = paddle.concat(box_list, axis=1)
  537. reg_list = paddle.concat(reg_list, axis=1)
  538. return cls_score_list, reg_list, box_list, fpn_feats
  539. def forward_eval(self, fpn_feats, export_post_process=True):
  540. if self.eval_size:
  541. anchor_points, stride_tensor = self.anchor_points, self.stride_tensor
  542. else:
  543. anchor_points, stride_tensor = self._generate_anchors(fpn_feats)
  544. cls_score_list, box_list = [], []
  545. for i, (fpn_feat, stride) in enumerate(zip(fpn_feats, self.fpn_stride)):
  546. b, _, h, w = fpn_feat.shape
  547. # task decomposition
  548. conv_cls_feat, se_feat = self.conv_feat(fpn_feat, i)
  549. cls_logit = self.head_cls_list[i](se_feat)
  550. reg_pred = self.head_reg_list[i](se_feat)
  551. # cls prediction and alignment
  552. if self.use_align_head:
  553. cls_prob = F.sigmoid(self.cls_align[i](conv_cls_feat))
  554. cls_score = (F.sigmoid(cls_logit) * cls_prob + eps).sqrt()
  555. else:
  556. cls_score = F.sigmoid(cls_logit)
  557. if not export_post_process:
  558. # Now only supports batch size = 1 in deploy
  559. cls_score_list.append(
  560. cls_score.reshape([1, self.cls_out_channels, -1]).transpose(
  561. [0, 2, 1]))
  562. box_list.append(
  563. reg_pred.reshape([1, (self.reg_max + 1) * 4, -1]).transpose(
  564. [0, 2, 1]))
  565. else:
  566. l = h * w
  567. cls_score_out = cls_score.reshape([b, self.cls_out_channels, l])
  568. bbox_pred = reg_pred.transpose([0, 2, 3, 1])
  569. bbox_pred = self.distribution_project(bbox_pred)
  570. bbox_pred = bbox_pred.reshape([b, l, 4])
  571. cls_score_list.append(cls_score_out)
  572. box_list.append(bbox_pred)
  573. if export_post_process:
  574. cls_score_list = paddle.concat(cls_score_list, axis=-1)
  575. box_list = paddle.concat(box_list, axis=1)
  576. box_list = batch_distance2bbox(anchor_points, box_list)
  577. box_list *= stride_tensor
  578. return cls_score_list, box_list
  579. def get_loss(self, head_outs, gt_meta):
  580. pred_scores, pred_regs, pred_bboxes, fpn_feats = head_outs
  581. gt_labels = gt_meta['gt_class']
  582. gt_bboxes = gt_meta['gt_bbox']
  583. gt_scores = gt_meta['gt_score'] if 'gt_score' in gt_meta else None
  584. num_imgs = gt_meta['im_id'].shape[0]
  585. pad_gt_mask = gt_meta['pad_gt_mask']
  586. anchors, _, num_anchors_list, stride_tensor_list = generate_anchors_for_grid_cell(
  587. fpn_feats, self.fpn_stride, self.grid_cell_scale, self.cell_offset)
  588. centers = bbox_center(anchors)
  589. # label assignment
  590. if gt_meta['epoch_id'] < self.static_assigner_epoch:
  591. assigned_labels, assigned_bboxes, assigned_scores = self.static_assigner(
  592. anchors,
  593. num_anchors_list,
  594. gt_labels,
  595. gt_bboxes,
  596. pad_gt_mask,
  597. bg_index=self.num_classes,
  598. gt_scores=gt_scores,
  599. pred_bboxes=pred_bboxes.detach() * stride_tensor_list)
  600. else:
  601. assigned_labels, assigned_bboxes, assigned_scores = self.assigner(
  602. pred_scores.detach(),
  603. pred_bboxes.detach() * stride_tensor_list,
  604. centers,
  605. num_anchors_list,
  606. gt_labels,
  607. gt_bboxes,
  608. pad_gt_mask,
  609. bg_index=self.num_classes,
  610. gt_scores=gt_scores)
  611. assigned_bboxes /= stride_tensor_list
  612. centers_shape = centers.shape
  613. flatten_centers = centers.expand(
  614. [num_imgs, centers_shape[0], centers_shape[1]]).reshape([-1, 2])
  615. flatten_strides = stride_tensor_list.expand(
  616. [num_imgs, centers_shape[0], 1]).reshape([-1, 1])
  617. flatten_cls_preds = pred_scores.reshape([-1, self.num_classes])
  618. flatten_regs = pred_regs.reshape([-1, 4 * (self.reg_max + 1)])
  619. flatten_bboxes = pred_bboxes.reshape([-1, 4])
  620. flatten_bbox_targets = assigned_bboxes.reshape([-1, 4])
  621. flatten_labels = assigned_labels.reshape([-1])
  622. flatten_assigned_scores = assigned_scores.reshape(
  623. [-1, self.num_classes])
  624. pos_inds = paddle.nonzero(
  625. paddle.logical_and((flatten_labels >= 0),
  626. (flatten_labels < self.num_classes)),
  627. as_tuple=False).squeeze(1)
  628. num_total_pos = len(pos_inds)
  629. if num_total_pos > 0:
  630. pos_bbox_targets = paddle.gather(
  631. flatten_bbox_targets, pos_inds, axis=0)
  632. pos_decode_bbox_pred = paddle.gather(
  633. flatten_bboxes, pos_inds, axis=0)
  634. pos_reg = paddle.gather(flatten_regs, pos_inds, axis=0)
  635. pos_strides = paddle.gather(flatten_strides, pos_inds, axis=0)
  636. pos_centers = paddle.gather(
  637. flatten_centers, pos_inds, axis=0) / pos_strides
  638. weight_targets = flatten_assigned_scores.detach()
  639. weight_targets = paddle.gather(
  640. weight_targets.max(axis=1, keepdim=True), pos_inds, axis=0)
  641. pred_corners = pos_reg.reshape([-1, self.reg_max + 1])
  642. target_corners = bbox2distance(pos_centers, pos_bbox_targets,
  643. self.reg_max).reshape([-1])
  644. # regression loss
  645. loss_bbox = paddle.sum(
  646. self.loss_bbox(pos_decode_bbox_pred,
  647. pos_bbox_targets) * weight_targets)
  648. # dfl loss
  649. loss_dfl = self.loss_dfl(
  650. pred_corners,
  651. target_corners,
  652. weight=weight_targets.expand([-1, 4]).reshape([-1]),
  653. avg_factor=4.0)
  654. else:
  655. loss_bbox = paddle.zeros([1])
  656. loss_dfl = paddle.zeros([1])
  657. avg_factor = flatten_assigned_scores.sum()
  658. if paddle.fluid.core.is_compiled_with_dist(
  659. ) and parallel_helper._is_parallel_ctx_initialized():
  660. paddle.distributed.all_reduce(avg_factor)
  661. avg_factor = paddle.clip(
  662. avg_factor / paddle.distributed.get_world_size(), min=1)
  663. loss_vfl = self.loss_vfl(
  664. flatten_cls_preds, flatten_assigned_scores, avg_factor=avg_factor)
  665. loss_bbox = loss_bbox / avg_factor
  666. loss_dfl = loss_dfl / avg_factor
  667. loss_states = dict(
  668. loss_vfl=loss_vfl, loss_bbox=loss_bbox, loss_dfl=loss_dfl)
  669. return loss_states
  670. def _generate_anchors(self, feats=None):
  671. # just use in eval time
  672. anchor_points = []
  673. stride_tensor = []
  674. for i, stride in enumerate(self.fpn_stride):
  675. if feats is not None:
  676. _, _, h, w = feats[i].shape
  677. else:
  678. h = math.ceil(self.eval_size[0] / stride)
  679. w = math.ceil(self.eval_size[1] / stride)
  680. shift_x = paddle.arange(end=w) + self.cell_offset
  681. shift_y = paddle.arange(end=h) + self.cell_offset
  682. shift_y, shift_x = paddle.meshgrid(shift_y, shift_x)
  683. anchor_point = paddle.cast(
  684. paddle.stack(
  685. [shift_x, shift_y], axis=-1), dtype='float32')
  686. anchor_points.append(anchor_point.reshape([-1, 2]))
  687. stride_tensor.append(
  688. paddle.full(
  689. [h * w, 1], stride, dtype='float32'))
  690. anchor_points = paddle.concat(anchor_points)
  691. stride_tensor = paddle.concat(stride_tensor)
  692. return anchor_points, stride_tensor
  693. def post_process(self, head_outs, scale_factor, export_nms=True):
  694. pred_scores, pred_bboxes = head_outs
  695. if not export_nms:
  696. return pred_bboxes, pred_scores
  697. else:
  698. # rescale: [h_scale, w_scale] -> [w_scale, h_scale, w_scale, h_scale]
  699. scale_y, scale_x = paddle.split(scale_factor, 2, axis=-1)
  700. scale_factor = paddle.concat(
  701. [scale_x, scale_y, scale_x, scale_y],
  702. axis=-1).reshape([-1, 1, 4])
  703. # scale bbox to origin image size.
  704. pred_bboxes /= scale_factor
  705. bbox_pred, bbox_num, _ = self.nms(pred_bboxes, pred_scores)
  706. return bbox_pred, bbox_num