code: def test_loss_with_ignore_index(
      use_sigmoid, reduction, avg_non_ignore
  ):
      # Test cross_entropy loss
      loss_class = CrossEntropyLoss(
          use_sigmoid=use_sigmoid,
          use_mask=False,
          ignore_index=255,
          avg_non_ignore=avg_non_ignore,
      )
      pred = torch.rand((10, 5))
      target = torch.randint(0, 5, (10,))
  
      ignored_indices = torch.randint(0, 10, (2,), dtype=torch.long)
      target[ignored_indices] = 255
  
      # Test loss forward with default ignore
      loss_with_ignore = loss_class(
          pred, target, reduction_override=reduction
      )
      assert isinstance(loss_with_ignore, torch.Tensor)
  
      # Test loss forward with forward ignore
      target[ignored_indices] = 255
      loss_with_forward_ignore = loss_class(
          pred, target, ignore_index=255, reduction_override=reduction
      )
      assert isinstance(loss_with_forward_ignore, torch.Tensor)
  
      # Verify correctness
      if avg_non_ignore:
          # manually remove the ignored elements
          not_ignored_indices = target != 255
          pred = pred[not_ignored_indices]
          target = target[not_ignored_indices]
      loss = loss_class(pred, target, reduction_override=reduction)
  
      assert torch.allclose(loss, loss_with_ignore)
      assert torch.allclose(loss, loss_with_forward_ignore)
  
      # test ignore all target
      pred = torch.rand((10, 5))
      target = torch.ones((10,), dtype=torch.long) * 255
      loss = loss_class(pred, target, reduction_override=reduction)
      assert loss == 0
  
file_path: mmdetection/tests/test_models/test_losses/test_loss.py
imports: import json
  import pytest
  import torch
  import torch.nn.functional
  from mmengine.utils import digit_version
  from mmdet.models.losses import BalancedL1Loss, CrossEntropyLoss, DDQAuxLoss, DiceLoss, DistributionFocalLoss, EQLV2Loss, FocalLoss, GaussianFocalLoss, KnowledgeDistillationKLDivLoss, L1Loss, MarginL2Loss, MSELoss, QualityFocalLoss, SeesawLoss, SmoothL1Loss, VarifocalLoss
  from mmdet.models.losses.ghm_loss import GHMC, GHMR
  from mmdet.models.losses.iou_loss import BoundedIoULoss, CIoULoss, DIoULoss, EIoULoss, GIoULoss, IoULoss, SIoULoss
label_desc: Use image node_id 8 for calling a global function with example usage: test_loss_with_ignore_index(use_sigmoid, reduction, avg_non_ignore) without return types