class_docstr: Generalized Focal Loss: Learning Qualified and Distributed Bounding
  Boxes for Dense Object Detection.
  
  GFL head structure is similar with ATSS, however GFL uses
  1) joint representation for classification and localization quality, and
  2) flexible General distribution for bounding box locations,
  which are supervised by
  Quality Focal Loss (QFL) and Distribution Focal Loss (DFL), respectively
  
  https://arxiv.org/abs/2006.04388
  
  Args:
      num_classes (int): Number of categories excluding the background
          category.
      in_channels (int): Number of channels in the input feature map.
      stacked_convs (int): Number of conv layers in cls and reg tower.
          Default: 4.
      conv_cfg (dict): dictionary to construct and config conv layer.
          Default: None.
      norm_cfg (dict): dictionary to construct and config norm layer.
          Default: dict(type='GN', num_groups=32, requires_grad=True).
      loss_qfl (dict): Config of Quality Focal Loss (QFL).
      reg_max (int): Max value of integral set :math: `{0, ..., reg_max}`
          in QFL setting. Default: 16.
  Example:
      >>> self = GFLHead(11, 7)
      >>> feats = [torch.rand(1, 7, s, s) for s in [4, 8, 16, 32, 64]]
      >>> cls_quality_score, bbox_pred = self.forward(feats)
      >>> assert len(cls_quality_score) == len(self.scales)
class_docstr_tok: ["Generalized","Focal","Loss",":","Learning","Qualified","and","Distributed","Bounding","Boxes","for","Dense","Object","Detection",".","GFL","head","structure","is","similar","with","ATSS",",","however","GFL","uses","1",")","joint","representation","for","classification","and","localization","quality",",","and","2",")","flexible","General","distribution","for","bounding","box","locations",",","which","are","supervised","by","Quality","Focal","Loss","(","QFL",")","and","Distribution","Focal","Loss","(","DFL",")",",","respectively","https",":","\/\/arxiv.org\/abs\/2006.04388","Args",":","num_classes","(","int",")",":","Number","of","categories","excluding","the","background","category",".","in_channels","(","int",")",":","Number","of","channels","in","the","input","feature","map",".","stacked_convs","(","int",")",":","Number","of","conv","layers","in","cls","and","reg","tower",".","Default",":","4.","conv_cfg","(","dict",")",":","dictionary","to","construct","and","config","conv","layer",".","Default",":","None",".","norm_cfg","(","dict",")",":","dictionary","to","construct","and","config","norm","layer",".","Default",":","dict","(","type='GN","'",",","num_groups=32",",","requires_grad=True",")",".","loss_qfl","(","dict",")",":","Config","of","Quality","Focal","Loss","(","QFL",")",".","reg_max","(","int",")",":","Max","value","of","integral","set",":","math",":","`","{","0",",","...",",","reg_max","}","`","in","QFL","setting",".","Default",":","16",".","Example",":",">",">",">","self","=","GFLHead","(","11",",","7",")",">",">",">","feats","=","[","torch.rand","(","1",",","7",",","s",",","s",")","for","s","in","[","4",",","8",",","16",",","32",",","64","]","]",">",">",">","cls_quality_score",",","bbox_pred","=","self.forward","(","feats",")",">",">",">","assert","len","(","cls_quality_score",")","==","len","(","self.scales",")"]
docstr: Compute loss of a single scale level.
  
  Args:
      anchors (Tensor): Box reference for each scale level with shape
          (N, num_total_anchors, 4).
      cls_score (Tensor): Cls and quality joint scores for each scale
          level has shape (N, num_classes, H, W).
      bbox_pred (Tensor): Box distribution logits for each scale
          level with shape (N, 4*(n+1), H, W), n is max value of integral
          set.
      labels (Tensor): Labels of each anchors with shape
          (N, num_total_anchors).
      label_weights (Tensor): Label weights of each anchor with shape
          (N, num_total_anchors)
      bbox_targets (Tensor): BBox regression targets of each anchor wight
          shape (N, num_total_anchors, 4).
      stride (tuple): Stride in this scale level.
      num_total_samples (int): Number of positive samples that is
          reduced over all GPUs.
  
  Returns:
      dict[str, Tensor]: A dictionary of loss components.
docstr_tok: ["Compute","loss","of","a","single","scale","level",".","Args",":","anchors","(","Tensor",")",":","Box","reference","for","each","scale","level","with","shape","(","N",",","num_total_anchors",",","4",")",".","cls_score","(","Tensor",")",":","Cls","and","quality","joint","scores","for","each","scale","level","has","shape","(","N",",","num_classes",",","H",",","W",")",".","bbox_pred","(","Tensor",")",":","Box","distribution","logits","for","each","scale","level","with","shape","(","N",",","4","*","(","n+1",")",",","H",",","W",")",",","n","is","max","value","of","integral","set",".","labels","(","Tensor",")",":","Labels","of","each","anchors","with","shape","(","N",",","num_total_anchors",")",".","label_weights","(","Tensor",")",":","Label","weights","of","each","anchor","with","shape","(","N",",","num_total_anchors",")","bbox_targets","(","Tensor",")",":","BBox","regression","targets","of","each","anchor","wight","shape","(","N",",","num_total_anchors",",","4",")",".","stride","(","tuple",")",":","Stride","in","this","scale","level",".","num_total_samples","(","int",")",":","Number","of","positive","samples","that","is","reduced","over","all","GPUs",".","Returns",":","dict","[","str",",","Tensor","]",":","A","dictionary","of","loss","components","."]
code: def loss_single(
      self,
      anchors,
      cls_score,
      bbox_pred,
      kps_pred,
      labels,
      label_weights,
      bbox_targets,
      kps_targets,
      kps_weights,
      stride,
      num_total_samples,
  ):
      """Compute loss of a single scale level.
  
      Args:
          anchors (Tensor): Box reference for each scale level with shape
              (N, num_total_anchors, 4).
          cls_score (Tensor): Cls and quality joint scores for each scale
              level has shape (N, num_classes, H, W).
          bbox_pred (Tensor): Box distribution logits for each scale
              level with shape (N, 4*(n+1), H, W), n is max value of integral
              set.
          labels (Tensor): Labels of each anchors with shape
              (N, num_total_anchors).
          label_weights (Tensor): Label weights of each anchor with shape
              (N, num_total_anchors)
          bbox_targets (Tensor): BBox regression targets of each anchor wight
              shape (N, num_total_anchors, 4).
          stride (tuple): Stride in this scale level.
          num_total_samples (int): Number of positive samples that is
              reduced over all GPUs.
  
      Returns:
          dict[str, Tensor]: A dictionary of loss components.
      """
      assert (
          stride[0] == stride[1]
      ), "h stride is not equal to w stride!"
      use_qscore = True
      anchors = anchors.reshape(-1, 4)
      cls_score = cls_score.permute(0, 2, 3, 1).reshape(
          -1, self.cls_out_channels
      )
      if not self.use_dfl:
          bbox_pred = bbox_pred.permute(0, 2, 3, 1).reshape(-1, 4)
      else:
          bbox_pred = bbox_pred.permute(0, 2, 3, 1).reshape(
              -1, 4 * (self.reg_max + 1)
          )
      bbox_targets = bbox_targets.reshape(-1, 4)
      labels = labels.reshape(-1)
      label_weights = label_weights.reshape(-1)
  
      if self.use_kps:
          kps_pred = kps_pred.permute(0, 2, 3, 1).reshape(
              -1, self.NK * 2
          )
          kps_targets = kps_targets.reshape((-1, self.NK * 2))
          kps_weights = kps_weights.reshape((-1, self.NK * 2))
          # print('AAA000', kps_targets.shape, kps_weights.shape)
  
      # FG cat_id: [0, num_classes -1], BG cat_id: num_classes
      bg_class_ind = self.num_classes
      pos_inds = (
          ((labels >= 0) & (labels < bg_class_ind)).nonzero().squeeze(1)
      )
      score = label_weights.new_zeros(labels.shape)
  
      if len(pos_inds) > 0:
          pos_bbox_targets = bbox_targets[pos_inds]
          pos_bbox_pred = bbox_pred[pos_inds]
          pos_anchors = anchors[pos_inds]
          pos_anchor_centers = (
              self.anchor_center(pos_anchors) / stride[0]
          )
  
          weight_targets = cls_score.detach().sigmoid()
          weight_targets = weight_targets.max(dim=1)[0][pos_inds]
          pos_decode_bbox_targets = pos_bbox_targets / stride[0]
  
          if self.use_dfl:
              pos_bbox_pred_corners = self.integral(pos_bbox_pred)
              pos_decode_bbox_pred = distance2bbox(
                  pos_anchor_centers, pos_bbox_pred_corners
              )
          else:
              pos_decode_bbox_pred = distance2bbox(
                  pos_anchor_centers, pos_bbox_pred
              )
          if self.use_kps:
              pos_kps_targets = kps_targets[pos_inds]
              pos_kps_pred = kps_pred[pos_inds]
              # print('CCC000', kps_weights.shape)
              pos_kps_weights = (
                  kps_weights.max(dim=1)[0][pos_inds] * weight_targets
              )
              # pos_kps_weights = kps_weights.max(dim=1)[0][pos_inds]
              pos_kps_weights = pos_kps_weights.reshape((-1, 1))
              # pos_kps_weights = kps_weights.max(dim=1, keepdims=True)[0][pos_inds]
              # print('SSS', pos_kps_weights.sum())
  
              # pos_decode_kps_targets = pos_kps_targets / stride[0]
              # pos_decode_kps_pred = distance2kps(pos_anchor_centers, pos_kps_pred)
  
              pos_decode_kps_targets = kps2distance(
                  pos_anchor_centers, pos_kps_targets / stride[0]
              )
              pos_decode_kps_pred = pos_kps_pred
              # print('ZZZ', pos_decode_kps_targets.shape, pos_decode_kps_pred.shape)
              # print(pos_kps_weights[0,:].detach().cpu().numpy())
              # print(pos_decode_kps_targets[0,:].detach().cpu().numpy())
              # print(pos_decode_kps_pred[0,:].detach().cpu().numpy())
  
              # print('CCC111', weight_targets.shape, pos_bbox_pred.shape, pos_decode_bbox_pred.shape, pos_kps_pred.shape, pos_decode_kps_pred.shape, pos_kps_weights.shape)
  
          if use_qscore:
              score[pos_inds] = bbox_overlaps(
                  pos_decode_bbox_pred.detach(),
                  pos_decode_bbox_targets,
                  is_aligned=True,
              )
          else:
              score[pos_inds] = 1.0
  
          # regression loss
          loss_bbox = self.loss_bbox(
              pos_decode_bbox_pred,
              pos_decode_bbox_targets,
              weight=weight_targets,
              avg_factor=1.0,
          )
  
          if self.use_kps:
              loss_kps = self.loss_kps(
                  pos_decode_kps_pred * self.loss_kps_std,
                  pos_decode_kps_targets * self.loss_kps_std,
                  weight=pos_kps_weights,
                  avg_factor=1.0,
              )
          else:
              loss_kps = kps_pred.sum() * 0
  
          # dfl loss
          if self.use_dfl:
              pred_corners = pos_bbox_pred.reshape(-1, self.reg_max + 1)
              target_corners = bbox2distance(
                  pos_anchor_centers,
                  pos_decode_bbox_targets,
                  self.reg_max,
              ).reshape(-1)
              loss_dfl = self.loss_dfl(
                  pred_corners,
                  target_corners,
                  weight=weight_targets[:, None]
                  .expand(-1, 4)
                  .reshape(-1),
                  avg_factor=4.0,
              )
          else:
              loss_dfl = bbox_pred.sum() * 0
      else:
          loss_bbox = bbox_pred.sum() * 0
          loss_dfl = bbox_pred.sum() * 0
          loss_kps = kps_pred.sum() * 0
          weight_targets = torch.tensor(0).cuda()
  
      loss_cls = self.loss_cls(
          cls_score,
          (labels, score),
          weight=label_weights,
          avg_factor=num_total_samples,
      )
  
      return (
          loss_cls,
          loss_bbox,
          loss_dfl,
          loss_kps,
          weight_targets.sum(),
      )
  
imports: import numpy
  import torch
  import torch.nn
  import torch.nn.functional
  from mmcv.cnn import ConvModule, Scale, bias_init_with_prob, normal_init, DepthwiseSeparableConvModule
  from mmcv.cnn import constant_init, kaiming_init
  from mmcv.runner import force_fp32
  from mmdet.core import anchor_inside_flags, bbox2distance, bbox_overlaps, build_assigner, build_sampler, distance2bbox, distance2kps, kps2distance, images_to_levels, multi_apply, multiclass_nms, reduce_mean, unmap
  from ..builder import HEADS, build_loss
  from .anchor_head import AnchorHead
  from .base_dense_head import BaseDenseHead
  from .dense_test_mixins import BBoxTestMixin
label_desc: Use image node_id 10 for calling the SCRFDHead obj's underlying member method code with example usage: obj.loss_single(anchors, cls_score, bbox_pred, kps_pred, labels, label_weights, bbox_targets, kps_targets, kps_weights, stride, num_total_samples) and returns: loss_cls,  loss_bbox,  loss_dfl,  loss_kps,  weight_targets