docstr: Tests cascade rpn head loss when truth is empty and non-empty.
docstr_tok: ["Tests","cascade","rpn","head","loss","when","truth","is","empty","and","non-empty","."]
code: def test_cascade_rpn_head_loss(self):
      """Tests cascade rpn head loss when truth is empty and non-empty."""
      cascade_rpn_head = CascadeRPNHead(**cascade_rpn_config)
  
      s = 256
      feats = [
          torch.rand(1, 1, s // stride[1], s // stride[0])
          for stride in cascade_rpn_head.stages[
              0
          ].prior_generator.strides
      ]
      img_metas = {
          "img_shape": (s, s),
          "pad_shape": (s, s),
          "scale_factor": 1,
      }
      sample = DetDataSample()
      sample.set_metainfo(img_metas)
  
      # Test that empty ground truth encourages the network to
      # predict background
      gt_instances = InstanceData()
      gt_instances.bboxes = torch.empty((0, 4))
      gt_instances.labels = torch.LongTensor([])
      sample.gt_instances = gt_instances
  
      empty_gt_losses = cascade_rpn_head.loss(feats, [sample])
      for key, loss in empty_gt_losses.items():
          loss = sum(loss)
          if "cls" in key:
              self.assertGreater(
                  loss.item(), 0, "cls loss should be non-zero"
              )
          elif "reg" in key:
              self.assertEqual(
                  loss.item(),
                  0,
                  "there should be no reg loss when no ground true boxes",
              )
  
      # When truth is non-empty then all cls, box loss and centerness loss
      # should be nonzero for random inputs
      gt_instances = InstanceData()
      gt_instances.bboxes = torch.Tensor(
          [[23.6667, 23.8757, 238.6326, 151.8874]]
      )
      gt_instances.labels = torch.LongTensor([0])
      sample.gt_instances = gt_instances
  
      one_gt_losses = cascade_rpn_head.loss(feats, [sample])
      for loss in one_gt_losses.values():
          loss = sum(loss)
          self.assertGreater(
              loss.item(),
              0,
              "cls loss, or box loss, or iou loss should be non-zero",
          )
  
file_path: mmdetection/tests/test_models/test_dense_heads/test_cascade_rpn_head.py
imports: from unittest import TestCase
  import torch
  from mmengine.config import ConfigDict
  from mmengine.structures import InstanceData
  from mmdet.models.dense_heads import CascadeRPNHead
  from mmdet.structures import DetDataSample
label_desc: Use image node_id 1 for calling the TestStageCascadeRPNHead obj's underlying member method code with example usage: obj.test_cascade_rpn_head_loss() without return types