test_nasfcos_head.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. from unittest import TestCase
  3. import torch
  4. from mmengine.structures import InstanceData
  5. from mmdet.models.dense_heads import NASFCOSHead
  6. class TestNASFCOSHead(TestCase):
  7. def test_nasfcos_head_loss(self):
  8. """Tests nasfcos head loss when truth is empty and non-empty."""
  9. s = 256
  10. img_metas = [{
  11. 'img_shape': (s, s, 3),
  12. 'pad_shape': (s, s, 3),
  13. 'scale_factor': 1,
  14. }]
  15. nasfcos_head = NASFCOSHead(
  16. num_classes=4,
  17. in_channels=2, # the same as `deform_groups` in dconv3x3_config
  18. feat_channels=2,
  19. norm_cfg=None)
  20. # Nasfcos head expects a multiple levels of features per image
  21. feats = (
  22. torch.rand(1, 2, s // stride[1], s // stride[0]).float()
  23. for stride in nasfcos_head.prior_generator.strides)
  24. cls_scores, bbox_preds, centernesses = nasfcos_head.forward(feats)
  25. # Test that empty ground truth encourages the network to
  26. # predict background
  27. gt_instances = InstanceData()
  28. gt_instances.bboxes = torch.empty((0, 4))
  29. gt_instances.labels = torch.LongTensor([])
  30. empty_gt_losses = nasfcos_head.loss_by_feat(cls_scores, bbox_preds,
  31. centernesses,
  32. [gt_instances], img_metas)
  33. # When there is no truth, the cls loss should be nonzero but
  34. # box loss and centerness loss should be zero
  35. empty_cls_loss = empty_gt_losses['loss_cls'].item()
  36. empty_box_loss = empty_gt_losses['loss_bbox'].item()
  37. empty_ctr_loss = empty_gt_losses['loss_centerness'].item()
  38. self.assertGreater(empty_cls_loss, 0, 'cls loss should be non-zero')
  39. self.assertEqual(
  40. empty_box_loss, 0,
  41. 'there should be no box loss when there are no true boxes')
  42. self.assertEqual(
  43. empty_ctr_loss, 0,
  44. 'there should be no centerness loss when there are no true boxes')
  45. # When truth is non-empty then all cls, box loss and centerness loss
  46. # should be nonzero for random inputs
  47. gt_instances = InstanceData()
  48. gt_instances.bboxes = torch.Tensor(
  49. [[23.6667, 23.8757, 238.6326, 151.8874]])
  50. gt_instances.labels = torch.LongTensor([2])
  51. one_gt_losses = nasfcos_head.loss_by_feat(cls_scores, bbox_preds,
  52. centernesses, [gt_instances],
  53. img_metas)
  54. onegt_cls_loss = one_gt_losses['loss_cls'].item()
  55. onegt_box_loss = one_gt_losses['loss_bbox'].item()
  56. onegt_ctr_loss = one_gt_losses['loss_centerness'].item()
  57. self.assertGreater(onegt_cls_loss, 0, 'cls loss should be non-zero')
  58. self.assertGreater(onegt_box_loss, 0, 'box loss should be non-zero')
  59. self.assertGreater(onegt_ctr_loss, 0,
  60. 'centerness loss should be non-zero')