s2anet_head.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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. #
  15. # The code is based on https://github.com/csuhan/s2anet/blob/master/mmdet/models/anchor_heads_rotated/s2anet_head.py
  16. import paddle
  17. from paddle import ParamAttr
  18. import paddle.nn as nn
  19. import paddle.nn.functional as F
  20. from paddle.nn.initializer import Normal, Constant
  21. from paddlex.ppdet.core.workspace import register
  22. from paddlex.ppdet.modeling import ops
  23. from paddlex.ppdet.modeling import bbox_utils
  24. from paddlex.ppdet.modeling.proposal_generator.target_layer import RBoxAssigner
  25. import numpy as np
  26. class S2ANetAnchorGenerator(nn.Layer):
  27. """
  28. AnchorGenerator by paddle
  29. """
  30. def __init__(self, base_size, scales, ratios, scale_major=True, ctr=None):
  31. super(S2ANetAnchorGenerator, self).__init__()
  32. self.base_size = base_size
  33. self.scales = paddle.to_tensor(scales)
  34. self.ratios = paddle.to_tensor(ratios)
  35. self.scale_major = scale_major
  36. self.ctr = ctr
  37. self.base_anchors = self.gen_base_anchors()
  38. @property
  39. def num_base_anchors(self):
  40. return self.base_anchors.shape[0]
  41. def gen_base_anchors(self):
  42. w = self.base_size
  43. h = self.base_size
  44. if self.ctr is None:
  45. x_ctr = 0.5 * (w - 1)
  46. y_ctr = 0.5 * (h - 1)
  47. else:
  48. x_ctr, y_ctr = self.ctr
  49. h_ratios = paddle.sqrt(self.ratios)
  50. w_ratios = 1 / h_ratios
  51. if self.scale_major:
  52. ws = (w * w_ratios[:] * self.scales[:]).reshape([-1])
  53. hs = (h * h_ratios[:] * self.scales[:]).reshape([-1])
  54. else:
  55. ws = (w * self.scales[:] * w_ratios[:]).reshape([-1])
  56. hs = (h * self.scales[:] * h_ratios[:]).reshape([-1])
  57. base_anchors = paddle.stack(
  58. [
  59. x_ctr - 0.5 * (ws - 1), y_ctr - 0.5 * (hs - 1),
  60. x_ctr + 0.5 * (ws - 1), y_ctr + 0.5 * (hs - 1)
  61. ],
  62. axis=-1)
  63. base_anchors = paddle.round(base_anchors)
  64. return base_anchors
  65. def _meshgrid(self, x, y, row_major=True):
  66. yy, xx = paddle.meshgrid(y, x)
  67. yy = yy.reshape([-1])
  68. xx = xx.reshape([-1])
  69. if row_major:
  70. return xx, yy
  71. else:
  72. return yy, xx
  73. def forward(self, featmap_size, stride=16):
  74. # featmap_size*stride project it to original area
  75. feat_h = featmap_size[0]
  76. feat_w = featmap_size[1]
  77. shift_x = paddle.arange(0, feat_w, 1, 'int32') * stride
  78. shift_y = paddle.arange(0, feat_h, 1, 'int32') * stride
  79. shift_xx, shift_yy = self._meshgrid(shift_x, shift_y)
  80. shifts = paddle.stack(
  81. [shift_xx, shift_yy, shift_xx, shift_yy], axis=-1)
  82. all_anchors = self.base_anchors[:, :] + shifts[:, :]
  83. all_anchors = all_anchors.reshape([feat_h * feat_w, 4])
  84. return all_anchors
  85. def valid_flags(self, featmap_size, valid_size):
  86. feat_h, feat_w = featmap_size
  87. valid_h, valid_w = valid_size
  88. assert valid_h <= feat_h and valid_w <= feat_w
  89. valid_x = paddle.zeros([feat_w], dtype='int32')
  90. valid_y = paddle.zeros([feat_h], dtype='int32')
  91. valid_x[:valid_w] = 1
  92. valid_y[:valid_h] = 1
  93. valid_xx, valid_yy = self._meshgrid(valid_x, valid_y)
  94. valid = valid_xx & valid_yy
  95. valid = paddle.reshape(valid, [-1, 1])
  96. valid = paddle.expand(valid, [-1, self.num_base_anchors]).reshape([-1])
  97. return valid
  98. class AlignConv(nn.Layer):
  99. def __init__(self, in_channels, out_channels, kernel_size=3, groups=1):
  100. super(AlignConv, self).__init__()
  101. self.kernel_size = kernel_size
  102. self.align_conv = paddle.vision.ops.DeformConv2D(
  103. in_channels,
  104. out_channels,
  105. kernel_size=self.kernel_size,
  106. padding=(self.kernel_size - 1) // 2,
  107. groups=groups,
  108. weight_attr=ParamAttr(initializer=Normal(0, 0.01)),
  109. bias_attr=None)
  110. @paddle.no_grad()
  111. def get_offset(self, anchors, featmap_size, stride):
  112. """
  113. Args:
  114. anchors: [M,5] xc,yc,w,h,angle
  115. featmap_size: (feat_h, feat_w)
  116. stride: 8
  117. Returns:
  118. """
  119. anchors = paddle.reshape(anchors, [-1, 5]) # (NA,5)
  120. dtype = anchors.dtype
  121. feat_h = featmap_size[0]
  122. feat_w = featmap_size[1]
  123. pad = (self.kernel_size - 1) // 2
  124. idx = paddle.arange(-pad, pad + 1, dtype=dtype)
  125. yy, xx = paddle.meshgrid(idx, idx)
  126. xx = paddle.reshape(xx, [-1])
  127. yy = paddle.reshape(yy, [-1])
  128. # get sampling locations of default conv
  129. xc = paddle.arange(0, feat_w, dtype=dtype)
  130. yc = paddle.arange(0, feat_h, dtype=dtype)
  131. yc, xc = paddle.meshgrid(yc, xc)
  132. xc = paddle.reshape(xc, [-1, 1])
  133. yc = paddle.reshape(yc, [-1, 1])
  134. x_conv = xc + xx
  135. y_conv = yc + yy
  136. # get sampling locations of anchors
  137. # x_ctr, y_ctr, w, h, a = np.unbind(anchors, dim=1)
  138. x_ctr = anchors[:, 0]
  139. y_ctr = anchors[:, 1]
  140. w = anchors[:, 2]
  141. h = anchors[:, 3]
  142. a = anchors[:, 4]
  143. x_ctr = paddle.reshape(x_ctr, [-1, 1])
  144. y_ctr = paddle.reshape(y_ctr, [-1, 1])
  145. w = paddle.reshape(w, [-1, 1])
  146. h = paddle.reshape(h, [-1, 1])
  147. a = paddle.reshape(a, [-1, 1])
  148. x_ctr = x_ctr / stride
  149. y_ctr = y_ctr / stride
  150. w_s = w / stride
  151. h_s = h / stride
  152. cos, sin = paddle.cos(a), paddle.sin(a)
  153. dw, dh = w_s / self.kernel_size, h_s / self.kernel_size
  154. x, y = dw * xx, dh * yy
  155. xr = cos * x - sin * y
  156. yr = sin * x + cos * y
  157. x_anchor, y_anchor = xr + x_ctr, yr + y_ctr
  158. # get offset filed
  159. offset_x = x_anchor - x_conv
  160. offset_y = y_anchor - y_conv
  161. offset = paddle.stack([offset_y, offset_x], axis=-1)
  162. offset = paddle.reshape(
  163. offset,
  164. [feat_h * feat_w, self.kernel_size * self.kernel_size * 2])
  165. offset = paddle.transpose(offset, [1, 0])
  166. offset = paddle.reshape(
  167. offset,
  168. [1, self.kernel_size * self.kernel_size * 2, feat_h, feat_w])
  169. return offset
  170. def forward(self, x, refine_anchors, featmap_size, stride):
  171. offset = self.get_offset(refine_anchors, featmap_size, stride)
  172. x = F.relu(self.align_conv(x, offset))
  173. return x
  174. @register
  175. class S2ANetHead(nn.Layer):
  176. """
  177. S2Anet head
  178. Args:
  179. stacked_convs (int): number of stacked_convs
  180. feat_in (int): input channels of feat
  181. feat_out (int): output channels of feat
  182. num_classes (int): num_classes
  183. anchor_strides (list): stride of anchors
  184. anchor_scales (list): scale of anchors
  185. anchor_ratios (list): ratios of anchors
  186. target_means (list): target_means
  187. target_stds (list): target_stds
  188. align_conv_type (str): align_conv_type ['Conv', 'AlignConv']
  189. align_conv_size (int): kernel size of align_conv
  190. use_sigmoid_cls (bool): use sigmoid_cls or not
  191. reg_loss_weight (list): loss weight for regression
  192. """
  193. __shared__ = ['num_classes']
  194. __inject__ = ['anchor_assign']
  195. def __init__(self,
  196. stacked_convs=2,
  197. feat_in=256,
  198. feat_out=256,
  199. num_classes=15,
  200. anchor_strides=[8, 16, 32, 64, 128],
  201. anchor_scales=[4],
  202. anchor_ratios=[1.0],
  203. target_means=0.0,
  204. target_stds=1.0,
  205. align_conv_type='AlignConv',
  206. align_conv_size=3,
  207. use_sigmoid_cls=True,
  208. anchor_assign=RBoxAssigner().__dict__,
  209. reg_loss_weight=[1.0, 1.0, 1.0, 1.0, 1.1],
  210. cls_loss_weight=[1.1, 1.05],
  211. reg_loss_type='l1'):
  212. super(S2ANetHead, self).__init__()
  213. self.stacked_convs = stacked_convs
  214. self.feat_in = feat_in
  215. self.feat_out = feat_out
  216. self.anchor_list = None
  217. self.anchor_scales = anchor_scales
  218. self.anchor_ratios = anchor_ratios
  219. self.anchor_strides = anchor_strides
  220. self.anchor_strides = paddle.to_tensor(anchor_strides)
  221. self.anchor_base_sizes = list(anchor_strides)
  222. self.means = paddle.ones(shape=[5]) * target_means
  223. self.stds = paddle.ones(shape=[5]) * target_stds
  224. assert align_conv_type in ['AlignConv', 'Conv', 'DCN']
  225. self.align_conv_type = align_conv_type
  226. self.align_conv_size = align_conv_size
  227. self.use_sigmoid_cls = use_sigmoid_cls
  228. self.cls_out_channels = num_classes if self.use_sigmoid_cls else 1
  229. self.sampling = False
  230. self.anchor_assign = anchor_assign
  231. self.reg_loss_weight = reg_loss_weight
  232. self.cls_loss_weight = cls_loss_weight
  233. self.alpha = 1.0
  234. self.beta = 1.0
  235. self.reg_loss_type = reg_loss_type
  236. self.s2anet_head_out = None
  237. # anchor
  238. self.anchor_generators = []
  239. for anchor_base in self.anchor_base_sizes:
  240. self.anchor_generators.append(
  241. S2ANetAnchorGenerator(anchor_base, anchor_scales,
  242. anchor_ratios))
  243. self.anchor_generators = nn.LayerList(self.anchor_generators)
  244. self.fam_cls_convs = nn.Sequential()
  245. self.fam_reg_convs = nn.Sequential()
  246. for i in range(self.stacked_convs):
  247. chan_in = self.feat_in if i == 0 else self.feat_out
  248. self.fam_cls_convs.add_sublayer(
  249. 'fam_cls_conv_{}'.format(i),
  250. nn.Conv2D(
  251. in_channels=chan_in,
  252. out_channels=self.feat_out,
  253. kernel_size=3,
  254. padding=1,
  255. weight_attr=ParamAttr(initializer=Normal(0.0, 0.01)),
  256. bias_attr=ParamAttr(initializer=Constant(0))))
  257. self.fam_cls_convs.add_sublayer('fam_cls_conv_{}_act'.format(i),
  258. nn.ReLU())
  259. self.fam_reg_convs.add_sublayer(
  260. 'fam_reg_conv_{}'.format(i),
  261. nn.Conv2D(
  262. in_channels=chan_in,
  263. out_channels=self.feat_out,
  264. kernel_size=3,
  265. padding=1,
  266. weight_attr=ParamAttr(initializer=Normal(0.0, 0.01)),
  267. bias_attr=ParamAttr(initializer=Constant(0))))
  268. self.fam_reg_convs.add_sublayer('fam_reg_conv_{}_act'.format(i),
  269. nn.ReLU())
  270. self.fam_reg = nn.Conv2D(
  271. self.feat_out,
  272. 5,
  273. 1,
  274. weight_attr=ParamAttr(initializer=Normal(0.0, 0.01)),
  275. bias_attr=ParamAttr(initializer=Constant(0)))
  276. prior_prob = 0.01
  277. bias_init = float(-np.log((1 - prior_prob) / prior_prob))
  278. self.fam_cls = nn.Conv2D(
  279. self.feat_out,
  280. self.cls_out_channels,
  281. 1,
  282. weight_attr=ParamAttr(initializer=Normal(0.0, 0.01)),
  283. bias_attr=ParamAttr(initializer=Constant(bias_init)))
  284. if self.align_conv_type == "AlignConv":
  285. self.align_conv = AlignConv(self.feat_out, self.feat_out,
  286. self.align_conv_size)
  287. elif self.align_conv_type == "Conv":
  288. self.align_conv = nn.Conv2D(
  289. self.feat_out,
  290. self.feat_out,
  291. self.align_conv_size,
  292. padding=(self.align_conv_size - 1) // 2,
  293. bias_attr=ParamAttr(initializer=Constant(0)))
  294. elif self.align_conv_type == "DCN":
  295. self.align_conv_offset = nn.Conv2D(
  296. self.feat_out,
  297. 2 * self.align_conv_size**2,
  298. 1,
  299. weight_attr=ParamAttr(initializer=Normal(0.0, 0.01)),
  300. bias_attr=ParamAttr(initializer=Constant(0)))
  301. self.align_conv = paddle.vision.ops.DeformConv2D(
  302. self.feat_out,
  303. self.feat_out,
  304. self.align_conv_size,
  305. padding=(self.align_conv_size - 1) // 2,
  306. weight_attr=ParamAttr(initializer=Normal(0.0, 0.01)),
  307. bias_attr=False)
  308. self.or_conv = nn.Conv2D(
  309. self.feat_out,
  310. self.feat_out,
  311. kernel_size=3,
  312. padding=1,
  313. weight_attr=ParamAttr(initializer=Normal(0.0, 0.01)),
  314. bias_attr=ParamAttr(initializer=Constant(0)))
  315. # ODM
  316. self.odm_cls_convs = nn.Sequential()
  317. self.odm_reg_convs = nn.Sequential()
  318. for i in range(self.stacked_convs):
  319. ch_in = self.feat_out
  320. # ch_in = int(self.feat_out / 8) if i == 0 else self.feat_out
  321. self.odm_cls_convs.add_sublayer(
  322. 'odm_cls_conv_{}'.format(i),
  323. nn.Conv2D(
  324. in_channels=ch_in,
  325. out_channels=self.feat_out,
  326. kernel_size=3,
  327. stride=1,
  328. padding=1,
  329. weight_attr=ParamAttr(initializer=Normal(0.0, 0.01)),
  330. bias_attr=ParamAttr(initializer=Constant(0))))
  331. self.odm_cls_convs.add_sublayer('odm_cls_conv_{}_act'.format(i),
  332. nn.ReLU())
  333. self.odm_reg_convs.add_sublayer(
  334. 'odm_reg_conv_{}'.format(i),
  335. nn.Conv2D(
  336. in_channels=self.feat_out,
  337. out_channels=self.feat_out,
  338. kernel_size=3,
  339. stride=1,
  340. padding=1,
  341. weight_attr=ParamAttr(initializer=Normal(0.0, 0.01)),
  342. bias_attr=ParamAttr(initializer=Constant(0))))
  343. self.odm_reg_convs.add_sublayer('odm_reg_conv_{}_act'.format(i),
  344. nn.ReLU())
  345. self.odm_cls = nn.Conv2D(
  346. self.feat_out,
  347. self.cls_out_channels,
  348. 3,
  349. padding=1,
  350. weight_attr=ParamAttr(initializer=Normal(0.0, 0.01)),
  351. bias_attr=ParamAttr(initializer=Constant(bias_init)))
  352. self.odm_reg = nn.Conv2D(
  353. self.feat_out,
  354. 5,
  355. 3,
  356. padding=1,
  357. weight_attr=ParamAttr(initializer=Normal(0.0, 0.01)),
  358. bias_attr=ParamAttr(initializer=Constant(0)))
  359. self.featmap_sizes = []
  360. self.base_anchors_list = []
  361. self.refine_anchor_list = []
  362. def forward(self, feats):
  363. fam_reg_branch_list = []
  364. fam_cls_branch_list = []
  365. odm_reg_branch_list = []
  366. odm_cls_branch_list = []
  367. self.featmap_sizes_list = []
  368. self.base_anchors_list = []
  369. self.refine_anchor_list = []
  370. for feat_idx in range(len(feats)):
  371. feat = feats[feat_idx]
  372. fam_cls_feat = self.fam_cls_convs(feat)
  373. fam_cls = self.fam_cls(fam_cls_feat)
  374. # [N, CLS, H, W] --> [N, H, W, CLS]
  375. fam_cls = fam_cls.transpose([0, 2, 3, 1])
  376. fam_cls_reshape = paddle.reshape(
  377. fam_cls, [fam_cls.shape[0], -1, self.cls_out_channels])
  378. fam_cls_branch_list.append(fam_cls_reshape)
  379. fam_reg_feat = self.fam_reg_convs(feat)
  380. fam_reg = self.fam_reg(fam_reg_feat)
  381. # [N, 5, H, W] --> [N, H, W, 5]
  382. fam_reg = fam_reg.transpose([0, 2, 3, 1])
  383. fam_reg_reshape = paddle.reshape(fam_reg,
  384. [fam_reg.shape[0], -1, 5])
  385. fam_reg_branch_list.append(fam_reg_reshape)
  386. # prepare anchor
  387. featmap_size = (paddle.shape(feat)[2], paddle.shape(feat)[3])
  388. self.featmap_sizes_list.append(featmap_size)
  389. init_anchors = self.anchor_generators[feat_idx](
  390. featmap_size, self.anchor_strides[feat_idx])
  391. init_anchors = paddle.to_tensor(init_anchors, dtype='float32')
  392. NA = featmap_size[0] * featmap_size[1]
  393. init_anchors = paddle.reshape(init_anchors, [NA, 4])
  394. init_anchors = self.rect2rbox(init_anchors)
  395. self.base_anchors_list.append(init_anchors)
  396. if self.training:
  397. refine_anchor = self.bbox_decode(fam_reg.detach(),
  398. init_anchors)
  399. else:
  400. refine_anchor = self.bbox_decode(fam_reg, init_anchors)
  401. self.refine_anchor_list.append(refine_anchor)
  402. if self.align_conv_type == 'AlignConv':
  403. align_feat = self.align_conv(feat,
  404. refine_anchor.clone(),
  405. featmap_size,
  406. self.anchor_strides[feat_idx])
  407. elif self.align_conv_type == 'DCN':
  408. align_offset = self.align_conv_offset(feat)
  409. align_feat = self.align_conv(feat, align_offset)
  410. elif self.align_conv_type == 'Conv':
  411. align_feat = self.align_conv(feat)
  412. or_feat = self.or_conv(align_feat)
  413. odm_reg_feat = or_feat
  414. odm_cls_feat = or_feat
  415. odm_reg_feat = self.odm_reg_convs(odm_reg_feat)
  416. odm_cls_feat = self.odm_cls_convs(odm_cls_feat)
  417. odm_cls_score = self.odm_cls(odm_cls_feat)
  418. # [N, CLS, H, W] --> [N, H, W, CLS]
  419. odm_cls_score = odm_cls_score.transpose([0, 2, 3, 1])
  420. odm_cls_score_shape = odm_cls_score.shape
  421. odm_cls_score_reshape = paddle.reshape(odm_cls_score, [
  422. odm_cls_score_shape[0], odm_cls_score_shape[1] *
  423. odm_cls_score_shape[2], self.cls_out_channels
  424. ])
  425. odm_cls_branch_list.append(odm_cls_score_reshape)
  426. odm_bbox_pred = self.odm_reg(odm_reg_feat)
  427. # [N, 5, H, W] --> [N, H, W, 5]
  428. odm_bbox_pred = odm_bbox_pred.transpose([0, 2, 3, 1])
  429. odm_bbox_pred_reshape = paddle.reshape(odm_bbox_pred, [-1, 5])
  430. odm_bbox_pred_reshape = paddle.unsqueeze(
  431. odm_bbox_pred_reshape, axis=0)
  432. odm_reg_branch_list.append(odm_bbox_pred_reshape)
  433. self.s2anet_head_out = (fam_cls_branch_list, fam_reg_branch_list,
  434. odm_cls_branch_list, odm_reg_branch_list)
  435. return self.s2anet_head_out
  436. def get_prediction(self, nms_pre=2000):
  437. refine_anchors = self.refine_anchor_list
  438. fam_cls_branch_list = self.s2anet_head_out[0]
  439. fam_reg_branch_list = self.s2anet_head_out[1]
  440. odm_cls_branch_list = self.s2anet_head_out[2]
  441. odm_reg_branch_list = self.s2anet_head_out[3]
  442. pred_scores, pred_bboxes = self.get_bboxes(
  443. odm_cls_branch_list, odm_reg_branch_list, refine_anchors, nms_pre,
  444. self.cls_out_channels, self.use_sigmoid_cls)
  445. return pred_scores, pred_bboxes
  446. def smooth_l1_loss(self, pred, label, delta=1.0 / 9.0):
  447. """
  448. Args:
  449. pred: pred score
  450. label: label
  451. delta: delta
  452. Returns: loss
  453. """
  454. assert pred.shape == label.shape and label.numel() > 0
  455. assert delta > 0
  456. diff = paddle.abs(pred - label)
  457. loss = paddle.where(diff < delta, 0.5 * diff * diff / delta,
  458. diff - 0.5 * delta)
  459. return loss
  460. def get_fam_loss(self, fam_target, s2anet_head_out, reg_loss_type='gwd'):
  461. (labels, label_weights, bbox_targets, bbox_weights, bbox_gt_bboxes,
  462. pos_inds, neg_inds) = fam_target
  463. fam_cls_branch_list, fam_reg_branch_list, odm_cls_branch_list, odm_reg_branch_list = s2anet_head_out
  464. fam_cls_losses = []
  465. fam_bbox_losses = []
  466. st_idx = 0
  467. num_total_samples = len(pos_inds) + len(
  468. neg_inds) if self.sampling else len(pos_inds)
  469. num_total_samples = max(1, num_total_samples)
  470. for idx, feat_size in enumerate(self.featmap_sizes_list):
  471. feat_anchor_num = feat_size[0] * feat_size[1]
  472. # step1: get data
  473. feat_labels = labels[st_idx:st_idx + feat_anchor_num]
  474. feat_label_weights = label_weights[st_idx:st_idx + feat_anchor_num]
  475. feat_bbox_targets = bbox_targets[st_idx:st_idx +
  476. feat_anchor_num, :]
  477. feat_bbox_weights = bbox_weights[st_idx:st_idx +
  478. feat_anchor_num, :]
  479. # step2: calc cls loss
  480. feat_labels = feat_labels.reshape(-1)
  481. feat_label_weights = feat_label_weights.reshape(-1)
  482. fam_cls_score = fam_cls_branch_list[idx]
  483. fam_cls_score = paddle.squeeze(fam_cls_score, axis=0)
  484. fam_cls_score1 = fam_cls_score
  485. feat_labels = paddle.to_tensor(feat_labels)
  486. feat_labels_one_hot = paddle.nn.functional.one_hot(
  487. feat_labels, self.cls_out_channels + 1)
  488. feat_labels_one_hot = feat_labels_one_hot[:, 1:]
  489. feat_labels_one_hot.stop_gradient = True
  490. num_total_samples = paddle.to_tensor(
  491. num_total_samples, dtype='float32', stop_gradient=True)
  492. fam_cls = F.sigmoid_focal_loss(
  493. fam_cls_score1,
  494. feat_labels_one_hot,
  495. normalizer=num_total_samples,
  496. reduction='none')
  497. feat_label_weights = feat_label_weights.reshape(
  498. feat_label_weights.shape[0], 1)
  499. feat_label_weights = np.repeat(
  500. feat_label_weights, self.cls_out_channels, axis=1)
  501. feat_label_weights = paddle.to_tensor(
  502. feat_label_weights, stop_gradient=True)
  503. fam_cls = fam_cls * feat_label_weights
  504. fam_cls_total = paddle.sum(fam_cls)
  505. fam_cls_losses.append(fam_cls_total)
  506. # step3: regression loss
  507. feat_bbox_targets = paddle.to_tensor(
  508. feat_bbox_targets, dtype='float32', stop_gradient=True)
  509. feat_bbox_targets = paddle.reshape(feat_bbox_targets, [-1, 5])
  510. fam_bbox_pred = fam_reg_branch_list[idx]
  511. fam_bbox_pred = paddle.squeeze(fam_bbox_pred, axis=0)
  512. fam_bbox_pred = paddle.reshape(fam_bbox_pred, [-1, 5])
  513. fam_bbox = self.smooth_l1_loss(fam_bbox_pred, feat_bbox_targets)
  514. loss_weight = paddle.to_tensor(
  515. self.reg_loss_weight, dtype='float32', stop_gradient=True)
  516. fam_bbox = paddle.multiply(fam_bbox, loss_weight)
  517. feat_bbox_weights = paddle.to_tensor(
  518. feat_bbox_weights, stop_gradient=True)
  519. if reg_loss_type == 'l1':
  520. fam_bbox = fam_bbox * feat_bbox_weights
  521. fam_bbox_total = paddle.sum(fam_bbox) / num_total_samples
  522. elif reg_loss_type == 'iou' or reg_loss_type == 'gwd':
  523. fam_bbox = paddle.sum(fam_bbox, axis=-1)
  524. feat_bbox_weights = paddle.sum(feat_bbox_weights, axis=-1)
  525. try:
  526. from rbox_iou_ops import rbox_iou
  527. except Exception as e:
  528. print("import custom_ops error, try install rbox_iou_ops " \
  529. "following ppdet/ext_op/README.md", e)
  530. sys.stdout.flush()
  531. sys.exit(-1)
  532. # calc iou
  533. fam_bbox_decode = self.delta2rbox(self.base_anchors_list[idx],
  534. fam_bbox_pred)
  535. bbox_gt_bboxes = paddle.to_tensor(
  536. bbox_gt_bboxes,
  537. dtype=fam_bbox_decode.dtype,
  538. place=fam_bbox_decode.place)
  539. bbox_gt_bboxes.stop_gradient = True
  540. iou = rbox_iou(fam_bbox_decode, bbox_gt_bboxes)
  541. iou = paddle.diag(iou)
  542. if reg_loss_type == 'gwd':
  543. bbox_gt_bboxes_level = bbox_gt_bboxes[st_idx:st_idx +
  544. feat_anchor_num, :]
  545. fam_bbox_total = self.gwd_loss(fam_bbox_decode,
  546. bbox_gt_bboxes_level)
  547. fam_bbox_total = fam_bbox_total * feat_bbox_weights
  548. fam_bbox_total = paddle.sum(
  549. fam_bbox_total) / num_total_samples
  550. fam_bbox_losses.append(fam_bbox_total)
  551. st_idx += feat_anchor_num
  552. fam_cls_loss = paddle.add_n(fam_cls_losses)
  553. fam_cls_loss_weight = paddle.to_tensor(
  554. self.cls_loss_weight[0], dtype='float32', stop_gradient=True)
  555. fam_cls_loss = fam_cls_loss * fam_cls_loss_weight
  556. fam_reg_loss = paddle.add_n(fam_bbox_losses)
  557. return fam_cls_loss, fam_reg_loss
  558. def get_odm_loss(self, odm_target, s2anet_head_out, reg_loss_type='gwd'):
  559. (labels, label_weights, bbox_targets, bbox_weights, bbox_gt_bboxes,
  560. pos_inds, neg_inds) = odm_target
  561. fam_cls_branch_list, fam_reg_branch_list, odm_cls_branch_list, odm_reg_branch_list = s2anet_head_out
  562. odm_cls_losses = []
  563. odm_bbox_losses = []
  564. st_idx = 0
  565. num_total_samples = len(pos_inds) + len(
  566. neg_inds) if self.sampling else len(pos_inds)
  567. num_total_samples = max(1, num_total_samples)
  568. for idx, feat_size in enumerate(self.featmap_sizes_list):
  569. feat_anchor_num = feat_size[0] * feat_size[1]
  570. # step1: get data
  571. feat_labels = labels[st_idx:st_idx + feat_anchor_num]
  572. feat_label_weights = label_weights[st_idx:st_idx + feat_anchor_num]
  573. feat_bbox_targets = bbox_targets[st_idx:st_idx +
  574. feat_anchor_num, :]
  575. feat_bbox_weights = bbox_weights[st_idx:st_idx +
  576. feat_anchor_num, :]
  577. # step2: calc cls loss
  578. feat_labels = feat_labels.reshape(-1)
  579. feat_label_weights = feat_label_weights.reshape(-1)
  580. odm_cls_score = odm_cls_branch_list[idx]
  581. odm_cls_score = paddle.squeeze(odm_cls_score, axis=0)
  582. odm_cls_score1 = odm_cls_score
  583. feat_labels = paddle.to_tensor(feat_labels)
  584. feat_labels_one_hot = paddle.nn.functional.one_hot(
  585. feat_labels, self.cls_out_channels + 1)
  586. feat_labels_one_hot = feat_labels_one_hot[:, 1:]
  587. feat_labels_one_hot.stop_gradient = True
  588. num_total_samples = paddle.to_tensor(
  589. num_total_samples, dtype='float32', stop_gradient=True)
  590. odm_cls = F.sigmoid_focal_loss(
  591. odm_cls_score1,
  592. feat_labels_one_hot,
  593. normalizer=num_total_samples,
  594. reduction='none')
  595. feat_label_weights = feat_label_weights.reshape(
  596. feat_label_weights.shape[0], 1)
  597. feat_label_weights = np.repeat(
  598. feat_label_weights, self.cls_out_channels, axis=1)
  599. feat_label_weights = paddle.to_tensor(feat_label_weights)
  600. feat_label_weights.stop_gradient = True
  601. odm_cls = odm_cls * feat_label_weights
  602. odm_cls_total = paddle.sum(odm_cls)
  603. odm_cls_losses.append(odm_cls_total)
  604. # # step3: regression loss
  605. feat_bbox_targets = paddle.to_tensor(
  606. feat_bbox_targets, dtype='float32')
  607. feat_bbox_targets = paddle.reshape(feat_bbox_targets, [-1, 5])
  608. feat_bbox_targets.stop_gradient = True
  609. odm_bbox_pred = odm_reg_branch_list[idx]
  610. odm_bbox_pred = paddle.squeeze(odm_bbox_pred, axis=0)
  611. odm_bbox_pred = paddle.reshape(odm_bbox_pred, [-1, 5])
  612. odm_bbox = self.smooth_l1_loss(odm_bbox_pred, feat_bbox_targets)
  613. loss_weight = paddle.to_tensor(
  614. self.reg_loss_weight, dtype='float32', stop_gradient=True)
  615. odm_bbox = paddle.multiply(odm_bbox, loss_weight)
  616. feat_bbox_weights = paddle.to_tensor(
  617. feat_bbox_weights, stop_gradient=True)
  618. if reg_loss_type == 'l1':
  619. odm_bbox = odm_bbox * feat_bbox_weights
  620. odm_bbox_total = paddle.sum(odm_bbox) / num_total_samples
  621. elif reg_loss_type == 'iou' or reg_loss_type == 'gwd':
  622. odm_bbox = paddle.sum(odm_bbox, axis=-1)
  623. feat_bbox_weights = paddle.sum(feat_bbox_weights, axis=-1)
  624. try:
  625. from rbox_iou_ops import rbox_iou
  626. except Exception as e:
  627. print("import custom_ops error, try install rbox_iou_ops " \
  628. "following ppdet/ext_op/README.md", e)
  629. sys.stdout.flush()
  630. sys.exit(-1)
  631. # calc iou
  632. odm_bbox_decode = self.delta2rbox(self.refine_anchor_list[idx],
  633. odm_bbox_pred)
  634. bbox_gt_bboxes = paddle.to_tensor(
  635. bbox_gt_bboxes,
  636. dtype=odm_bbox_decode.dtype,
  637. place=odm_bbox_decode.place)
  638. bbox_gt_bboxes.stop_gradient = True
  639. iou = rbox_iou(odm_bbox_decode, bbox_gt_bboxes)
  640. iou = paddle.diag(iou)
  641. if reg_loss_type == 'gwd':
  642. bbox_gt_bboxes_level = bbox_gt_bboxes[st_idx:st_idx +
  643. feat_anchor_num, :]
  644. odm_bbox_total = self.gwd_loss(odm_bbox_decode,
  645. bbox_gt_bboxes_level)
  646. odm_bbox_total = odm_bbox_total * feat_bbox_weights
  647. odm_bbox_total = paddle.sum(
  648. odm_bbox_total) / num_total_samples
  649. odm_bbox_losses.append(odm_bbox_total)
  650. st_idx += feat_anchor_num
  651. odm_cls_loss = paddle.add_n(odm_cls_losses)
  652. odm_cls_loss_weight = paddle.to_tensor(
  653. self.cls_loss_weight[1], dtype='float32', stop_gradient=True)
  654. odm_cls_loss = odm_cls_loss * odm_cls_loss_weight
  655. odm_reg_loss = paddle.add_n(odm_bbox_losses)
  656. return odm_cls_loss, odm_reg_loss
  657. def get_loss(self, inputs):
  658. # inputs: im_id image im_shape scale_factor gt_bbox gt_class is_crowd
  659. # compute loss
  660. fam_cls_loss_lst = []
  661. fam_reg_loss_lst = []
  662. odm_cls_loss_lst = []
  663. odm_reg_loss_lst = []
  664. im_shape = inputs['im_shape']
  665. for im_id in range(im_shape.shape[0]):
  666. np_im_shape = inputs['im_shape'][im_id].numpy()
  667. np_scale_factor = inputs['scale_factor'][im_id].numpy()
  668. # data_format: (xc, yc, w, h, theta)
  669. gt_bboxes = inputs['gt_rbox'][im_id].numpy()
  670. gt_labels = inputs['gt_class'][im_id].numpy()
  671. is_crowd = inputs['is_crowd'][im_id].numpy()
  672. gt_labels = gt_labels + 1
  673. # featmap_sizes
  674. anchors_list_all = np.concatenate(self.base_anchors_list)
  675. # get im_feat
  676. fam_cls_feats_list = [e[im_id] for e in self.s2anet_head_out[0]]
  677. fam_reg_feats_list = [e[im_id] for e in self.s2anet_head_out[1]]
  678. odm_cls_feats_list = [e[im_id] for e in self.s2anet_head_out[2]]
  679. odm_reg_feats_list = [e[im_id] for e in self.s2anet_head_out[3]]
  680. im_s2anet_head_out = (fam_cls_feats_list, fam_reg_feats_list,
  681. odm_cls_feats_list, odm_reg_feats_list)
  682. # FAM
  683. im_fam_target = self.anchor_assign(anchors_list_all, gt_bboxes,
  684. gt_labels, is_crowd)
  685. if im_fam_target is not None:
  686. im_fam_cls_loss, im_fam_reg_loss = self.get_fam_loss(
  687. im_fam_target, im_s2anet_head_out, self.reg_loss_type)
  688. fam_cls_loss_lst.append(im_fam_cls_loss)
  689. fam_reg_loss_lst.append(im_fam_reg_loss)
  690. # ODM
  691. np_refine_anchors_list = paddle.concat(
  692. self.refine_anchor_list).numpy()
  693. np_refine_anchors_list = np.concatenate(np_refine_anchors_list)
  694. np_refine_anchors_list = np_refine_anchors_list.reshape(-1, 5)
  695. im_odm_target = self.anchor_assign(np_refine_anchors_list,
  696. gt_bboxes, gt_labels, is_crowd)
  697. if im_odm_target is not None:
  698. im_odm_cls_loss, im_odm_reg_loss = self.get_odm_loss(
  699. im_odm_target, im_s2anet_head_out, self.reg_loss_type)
  700. odm_cls_loss_lst.append(im_odm_cls_loss)
  701. odm_reg_loss_lst.append(im_odm_reg_loss)
  702. fam_cls_loss = paddle.add_n(fam_cls_loss_lst)
  703. fam_reg_loss = paddle.add_n(fam_reg_loss_lst)
  704. odm_cls_loss = paddle.add_n(odm_cls_loss_lst)
  705. odm_reg_loss = paddle.add_n(odm_reg_loss_lst)
  706. return {
  707. 'fam_cls_loss': fam_cls_loss,
  708. 'fam_reg_loss': fam_reg_loss,
  709. 'odm_cls_loss': odm_cls_loss,
  710. 'odm_reg_loss': odm_reg_loss
  711. }
  712. def get_bboxes(self, cls_score_list, bbox_pred_list, mlvl_anchors, nms_pre,
  713. cls_out_channels, use_sigmoid_cls):
  714. assert len(cls_score_list) == len(bbox_pred_list) == len(mlvl_anchors)
  715. mlvl_bboxes = []
  716. mlvl_scores = []
  717. idx = 0
  718. for cls_score, bbox_pred, anchors in zip(cls_score_list,
  719. bbox_pred_list, mlvl_anchors):
  720. cls_score = paddle.reshape(cls_score, [-1, cls_out_channels])
  721. if use_sigmoid_cls:
  722. scores = F.sigmoid(cls_score)
  723. else:
  724. scores = F.softmax(cls_score, axis=-1)
  725. # bbox_pred = bbox_pred.permute(1, 2, 0).reshape(-1, 5)
  726. bbox_pred = paddle.transpose(bbox_pred, [1, 2, 0])
  727. bbox_pred = paddle.reshape(bbox_pred, [-1, 5])
  728. anchors = paddle.reshape(anchors, [-1, 5])
  729. if scores.shape[0] > nms_pre:
  730. # Get maximum scores for foreground classes.
  731. if use_sigmoid_cls:
  732. max_scores = paddle.max(scores, axis=1)
  733. else:
  734. max_scores = paddle.max(scores[:, 1:], axis=1)
  735. topk_val, topk_inds = paddle.topk(max_scores, nms_pre)
  736. anchors = paddle.gather(anchors, topk_inds)
  737. bbox_pred = paddle.gather(bbox_pred, topk_inds)
  738. scores = paddle.gather(scores, topk_inds)
  739. bbox_delta = paddle.reshape(bbox_pred, [-1, 5])
  740. bboxes = self.delta2rbox(anchors, bbox_delta)
  741. mlvl_bboxes.append(bboxes)
  742. mlvl_scores.append(scores)
  743. idx += 1
  744. mlvl_bboxes = paddle.concat(mlvl_bboxes, axis=0)
  745. mlvl_scores = paddle.concat(mlvl_scores)
  746. return mlvl_scores, mlvl_bboxes
  747. def rect2rbox(self, bboxes):
  748. """
  749. :param bboxes: shape (n, 4) (xmin, ymin, xmax, ymax)
  750. :return: dbboxes: shape (n, 5) (x_ctr, y_ctr, w, h, angle)
  751. """
  752. bboxes = paddle.reshape(bboxes, [-1, 4])
  753. num_boxes = paddle.shape(bboxes)[0]
  754. x_ctr = (bboxes[:, 2] + bboxes[:, 0]) / 2.0
  755. y_ctr = (bboxes[:, 3] + bboxes[:, 1]) / 2.0
  756. edges1 = paddle.abs(bboxes[:, 2] - bboxes[:, 0])
  757. edges2 = paddle.abs(bboxes[:, 3] - bboxes[:, 1])
  758. rbox_w = paddle.maximum(edges1, edges2)
  759. rbox_h = paddle.minimum(edges1, edges2)
  760. # set angle
  761. inds = edges1 < edges2
  762. inds = paddle.cast(inds, 'int32')
  763. rboxes_angle = inds * np.pi / 2.0
  764. rboxes = paddle.stack(
  765. (x_ctr, y_ctr, rbox_w, rbox_h, rboxes_angle), axis=1)
  766. return rboxes
  767. # deltas to rbox
  768. def delta2rbox(self, rrois, deltas, wh_ratio_clip=1e-6):
  769. """
  770. :param rrois: (cx, cy, w, h, theta)
  771. :param deltas: (dx, dy, dw, dh, dtheta)
  772. :param means: means of anchor
  773. :param stds: stds of anchor
  774. :param wh_ratio_clip: clip threshold of wh_ratio
  775. :return:
  776. """
  777. deltas = paddle.reshape(deltas, [-1, 5])
  778. rrois = paddle.reshape(rrois, [-1, 5])
  779. # fix dy2st bug denorm_deltas = deltas * self.stds + self.means
  780. denorm_deltas = paddle.add(
  781. paddle.multiply(deltas, self.stds), self.means)
  782. dx = denorm_deltas[:, 0]
  783. dy = denorm_deltas[:, 1]
  784. dw = denorm_deltas[:, 2]
  785. dh = denorm_deltas[:, 3]
  786. dangle = denorm_deltas[:, 4]
  787. max_ratio = np.abs(np.log(wh_ratio_clip))
  788. dw = paddle.clip(dw, min=-max_ratio, max=max_ratio)
  789. dh = paddle.clip(dh, min=-max_ratio, max=max_ratio)
  790. rroi_x = rrois[:, 0]
  791. rroi_y = rrois[:, 1]
  792. rroi_w = rrois[:, 2]
  793. rroi_h = rrois[:, 3]
  794. rroi_angle = rrois[:, 4]
  795. gx = dx * rroi_w * paddle.cos(rroi_angle) - dy * rroi_h * paddle.sin(
  796. rroi_angle) + rroi_x
  797. gy = dx * rroi_w * paddle.sin(rroi_angle) + dy * rroi_h * paddle.cos(
  798. rroi_angle) + rroi_y
  799. gw = rroi_w * dw.exp()
  800. gh = rroi_h * dh.exp()
  801. ga = np.pi * dangle + rroi_angle
  802. ga = (ga + np.pi / 4) % np.pi - np.pi / 4
  803. ga = paddle.to_tensor(ga)
  804. gw = paddle.to_tensor(gw, dtype='float32')
  805. gh = paddle.to_tensor(gh, dtype='float32')
  806. bboxes = paddle.stack([gx, gy, gw, gh, ga], axis=-1)
  807. return bboxes
  808. def bbox_decode(self, bbox_preds, anchors):
  809. """decode bbox from deltas
  810. Args:
  811. bbox_preds: [N,H,W,5]
  812. anchors: [H*W,5]
  813. return:
  814. bboxes: [N,H,W,5]
  815. """
  816. num_imgs, H, W, _ = bbox_preds.shape
  817. bbox_delta = paddle.reshape(bbox_preds, [-1, 5])
  818. bboxes = self.delta2rbox(anchors, bbox_delta)
  819. return bboxes
  820. def trace(self, A):
  821. tr = paddle.diagonal(A, axis1=-2, axis2=-1)
  822. tr = paddle.sum(tr, axis=-1)
  823. return tr
  824. def sqrt_newton_schulz_autograd(self, A, numIters):
  825. A_shape = A.shape
  826. batchSize = A_shape[0]
  827. dim = A_shape[1]
  828. normA = A * A
  829. normA = paddle.sum(normA, axis=1)
  830. normA = paddle.sum(normA, axis=1)
  831. normA = paddle.sqrt(normA)
  832. normA1 = normA.reshape([batchSize, 1, 1])
  833. Y = paddle.divide(A, paddle.expand_as(normA1, A))
  834. I = paddle.eye(dim, dim).reshape([1, dim, dim])
  835. l0 = []
  836. for i in range(batchSize):
  837. l0.append(I)
  838. I = paddle.concat(l0, axis=0)
  839. I.stop_gradient = False
  840. Z = paddle.eye(dim, dim).reshape([1, dim, dim])
  841. l1 = []
  842. for i in range(batchSize):
  843. l1.append(Z)
  844. Z = paddle.concat(l1, axis=0)
  845. Z.stop_gradient = False
  846. for i in range(numIters):
  847. T = 0.5 * (3.0 * I - Z.bmm(Y))
  848. Y = Y.bmm(T)
  849. Z = T.bmm(Z)
  850. sA = Y * paddle.sqrt(normA1).reshape([batchSize, 1, 1])
  851. sA = paddle.expand_as(sA, A)
  852. return sA
  853. def wasserstein_distance_sigma(sigma1, sigma2):
  854. wasserstein_distance_item2 = paddle.matmul(
  855. sigma1, sigma1) + paddle.matmul(
  856. sigma2, sigma2) - 2 * self.sqrt_newton_schulz_autograd(
  857. paddle.matmul(
  858. paddle.matmul(sigma1, paddle.matmul(sigma2, sigma2)),
  859. sigma1), 10)
  860. wasserstein_distance_item2 = self.trace(wasserstein_distance_item2)
  861. return wasserstein_distance_item2
  862. def xywhr2xyrs(self, xywhr):
  863. xywhr = paddle.reshape(xywhr, [-1, 5])
  864. xy = xywhr[:, :2]
  865. wh = paddle.clip(xywhr[:, 2:4], min=1e-7, max=1e7)
  866. r = xywhr[:, 4]
  867. cos_r = paddle.cos(r)
  868. sin_r = paddle.sin(r)
  869. R = paddle.stack(
  870. (cos_r, -sin_r, sin_r, cos_r), axis=-1).reshape([-1, 2, 2])
  871. S = 0.5 * paddle.nn.functional.diag_embed(wh)
  872. return xy, R, S
  873. def gwd_loss(self,
  874. pred,
  875. target,
  876. fun='log',
  877. tau=1.0,
  878. alpha=1.0,
  879. normalize=False):
  880. xy_p, R_p, S_p = self.xywhr2xyrs(pred)
  881. xy_t, R_t, S_t = self.xywhr2xyrs(target)
  882. xy_distance = (xy_p - xy_t).square().sum(axis=-1)
  883. Sigma_p = R_p.matmul(S_p.square()).matmul(R_p.transpose([0, 2, 1]))
  884. Sigma_t = R_t.matmul(S_t.square()).matmul(R_t.transpose([0, 2, 1]))
  885. whr_distance = paddle.diagonal(
  886. S_p, axis1=-2, axis2=-1).square().sum(axis=-1)
  887. whr_distance = whr_distance + paddle.diagonal(
  888. S_t, axis1=-2, axis2=-1).square().sum(axis=-1)
  889. _t = Sigma_p.matmul(Sigma_t)
  890. _t_tr = paddle.diagonal(_t, axis1=-2, axis2=-1).sum(axis=-1)
  891. _t_det_sqrt = paddle.diagonal(S_p, axis1=-2, axis2=-1).prod(axis=-1)
  892. _t_det_sqrt = _t_det_sqrt * paddle.diagonal(
  893. S_t, axis1=-2, axis2=-1).prod(axis=-1)
  894. whr_distance = whr_distance + (-2) * (
  895. (_t_tr + 2 * _t_det_sqrt).clip(0).sqrt())
  896. distance = (xy_distance + alpha * alpha * whr_distance).clip(0)
  897. if normalize:
  898. wh_p = pred[..., 2:4].clip(min=1e-7, max=1e7)
  899. wh_t = target[..., 2:4].clip(min=1e-7, max=1e7)
  900. scale = ((wh_p.log() + wh_t.log()).sum(dim=-1) / 4).exp()
  901. distance = distance / scale
  902. if fun == 'log':
  903. distance = paddle.log1p(distance)
  904. if tau >= 1.0:
  905. return 1 - 1 / (tau + distance)
  906. return distance