class_docstr: Simplest RoI head, with only two fc layers for classification and
  regression respectively.
class_docstr_tok: ["Simplest","RoI","head",",","with","only","two","fc","layers","for","classification","and","regression","respectively","."]
docstr: Refine bboxes during training.
  
  Args:
      rois (Tensor): Shape (n*bs, 5), where n is image number per GPU,
          and bs is the sampled RoIs per image. The first column is
          the image id and the next 4 columns are x1, y1, x2, y2.
      labels (Tensor): Shape (n*bs, ).
      bbox_preds (Tensor): Shape (n*bs, 4) or (n*bs, 4*#class).
      pos_is_gts (list[Tensor]): Flags indicating if each positive bbox
          is a gt bbox.
      img_metas (list[dict]): Meta info of each image.
  
  Returns:
      list[Tensor]: Refined bboxes of each image in a mini-batch.
  
  Example:
      >>> # xdoctest: +REQUIRES(module:kwarray)
      >>> import kwarray
      >>> import numpy as np
      >>> from mmdet.core.bbox.demodata import random_boxes
      >>> self = BBoxHead(reg_class_agnostic=True)
      >>> n_roi = 2
      >>> n_img = 4
      >>> scale = 512
      >>> rng = np.random.RandomState(0)
      >>> img_metas = [{'img_shape': (scale, scale)}
      ...              for _ in range(n_img)]
      >>> # Create rois in the expected format
      >>> roi_boxes = random_boxes(n_roi, scale=scale, rng=rng)
      >>> img_ids = torch.randint(0, n_img, (n_roi,))
      >>> img_ids = img_ids.float()
      >>> rois = torch.cat([img_ids[:, None], roi_boxes], dim=1)
      >>> # Create other args
      >>> labels = torch.randint(0, 2, (n_roi,)).long()
      >>> bbox_preds = random_boxes(n_roi, scale=scale, rng=rng)
      >>> # For each image, pretend random positive boxes are gts
      >>> is_label_pos = (labels.numpy() > 0).astype(np.int)
      >>> lbl_per_img = kwarray.group_items(is_label_pos,
      ...                                   img_ids.numpy())
      >>> pos_per_img = [sum(lbl_per_img.get(gid, []))
      ...                for gid in range(n_img)]
      >>> pos_is_gts = [
      >>>     torch.randint(0, 2, (npos,)).byte().sort(
      >>>         descending=True)[0]
      >>>     for npos in pos_per_img
      >>> ]
      >>> bboxes_list = self.refine_bboxes(rois, labels, bbox_preds,
      >>>                    pos_is_gts, img_metas)
      >>> print(bboxes_list)
docstr_tok: ["Refine","bboxes","during","training",".","Args",":","rois","(","Tensor",")",":","Shape","(","n","*","bs",",","5",")",",","where","n","is","image","number","per","GPU",",","and","bs","is","the","sampled","RoIs","per","image",".","The","first","column","is","the","image","id","and","the","next","4","columns","are","x1",",","y1",",","x2",",","y2",".","labels","(","Tensor",")",":","Shape","(","n","*","bs",",",")",".","bbox_preds","(","Tensor",")",":","Shape","(","n","*","bs",",","4",")","or","(","n","*","bs",",","4","*","#","class",")",".","pos_is_gts","(","list","[","Tensor","]",")",":","Flags","indicating","if","each","positive","bbox","is","a","gt","bbox",".","img_metas","(","list","[","dict","]",")",":","Meta","info","of","each","image",".","Returns",":","list","[","Tensor","]",":","Refined","bboxes","of","each","image","in","a","mini-batch",".","Example",":",">",">",">","#","xdoctest",":","+REQUIRES","(","module",":","kwarray",")",">",">",">","import","kwarray",">",">",">","import","numpy","as","np",">",">",">","from","mmdet.core.bbox.demodata","import","random_boxes",">",">",">","self","=","BBoxHead","(","reg_class_agnostic=True",")",">",">",">","n_roi","=","2",">",">",">","n_img","=","4",">",">",">","scale","=","512",">",">",">","rng","=","np.random.RandomState","(","0",")",">",">",">","img_metas","=","[","{","'img_shape","'",":","(","scale",",","scale",")","}","...","for","_","in","range","(","n_img",")","]",">",">",">","#","Create","rois","in","the","expected","format",">",">",">","roi_boxes","=","random_boxes","(","n_roi",",","scale=scale",",","rng=rng",")",">",">",">","img_ids","=","torch.randint","(","0",",","n_img",",","(","n_roi",",",")",")",">",">",">","img_ids","=","img_ids.float","(",")",">",">",">","rois","=","torch.cat","(","[","img_ids","[",":",",","None","]",",","roi_boxes","]",",","dim=1",")",">",">",">","#","Create","other","args",">",">",">","labels","=","torch.randint","(","0",",","2",",","(","n_roi",",",")",")",".long","(",")",">",">",">","bbox_preds","=","random_boxes","(","n_roi",",","scale=scale",",","rng=rng",")",">",">",">","#","For","each","image",",","pretend","random","positive","boxes","are","gts",">",">",">","is_label_pos","=","(","labels.numpy","(",")",">","0",")",".astype","(","np.int",")",">",">",">","lbl_per_img","=","kwarray.group_items","(","is_label_pos",",","...","img_ids.numpy","(",")",")",">",">",">","pos_per_img","=","[","sum","(","lbl_per_img.get","(","gid",",","[","]",")",")","...","for","gid","in","range","(","n_img",")","]",">",">",">","pos_is_gts","=","[",">",">",">","torch.randint","(","0",",","2",",","(","npos",",",")",")",".byte","(",")",".sort","(",">",">",">","descending=True",")","[","0","]",">",">",">","for","npos","in","pos_per_img",">",">",">","]",">",">",">","bboxes_list","=","self.refine_bboxes","(","rois",",","labels",",","bbox_preds",",",">",">",">","pos_is_gts",",","img_metas",")",">",">",">","print","(","bboxes_list",")"]
code: def refine_bboxes(
      self, rois, labels, bbox_preds, pos_is_gts, img_metas
  ):
      """Refine bboxes during training.
  
      Args:
          rois (Tensor): Shape (n*bs, 5), where n is image number per GPU,
              and bs is the sampled RoIs per image. The first column is
              the image id and the next 4 columns are x1, y1, x2, y2.
          labels (Tensor): Shape (n*bs, ).
          bbox_preds (Tensor): Shape (n*bs, 4) or (n*bs, 4*#class).
          pos_is_gts (list[Tensor]): Flags indicating if each positive bbox
              is a gt bbox.
          img_metas (list[dict]): Meta info of each image.
  
      Returns:
          list[Tensor]: Refined bboxes of each image in a mini-batch.
  
      Example:
          >>> # xdoctest: +REQUIRES(module:kwarray)
          >>> import kwarray
          >>> import numpy as np
          >>> from mmdet.core.bbox.demodata import random_boxes
          >>> self = BBoxHead(reg_class_agnostic=True)
          >>> n_roi = 2
          >>> n_img = 4
          >>> scale = 512
          >>> rng = np.random.RandomState(0)
          >>> img_metas = [{'img_shape': (scale, scale)}
          ...              for _ in range(n_img)]
          >>> # Create rois in the expected format
          >>> roi_boxes = random_boxes(n_roi, scale=scale, rng=rng)
          >>> img_ids = torch.randint(0, n_img, (n_roi,))
          >>> img_ids = img_ids.float()
          >>> rois = torch.cat([img_ids[:, None], roi_boxes], dim=1)
          >>> # Create other args
          >>> labels = torch.randint(0, 2, (n_roi,)).long()
          >>> bbox_preds = random_boxes(n_roi, scale=scale, rng=rng)
          >>> # For each image, pretend random positive boxes are gts
          >>> is_label_pos = (labels.numpy() > 0).astype(np.int)
          >>> lbl_per_img = kwarray.group_items(is_label_pos,
          ...                                   img_ids.numpy())
          >>> pos_per_img = [sum(lbl_per_img.get(gid, []))
          ...                for gid in range(n_img)]
          >>> pos_is_gts = [
          >>>     torch.randint(0, 2, (npos,)).byte().sort(
          >>>         descending=True)[0]
          >>>     for npos in pos_per_img
          >>> ]
          >>> bboxes_list = self.refine_bboxes(rois, labels, bbox_preds,
          >>>                    pos_is_gts, img_metas)
          >>> print(bboxes_list)
      """
      img_ids = rois[:, 0].long().unique(sorted=True)
      assert img_ids.numel() <= len(img_metas)
  
      bboxes_list = []
      for i in range(len(img_metas)):
          inds = torch.nonzero(rois[:, 0] == i, as_tuple=False).squeeze(
              dim=1
          )
          num_rois = inds.numel()
  
          bboxes_ = rois[inds, 1:]
          label_ = labels[inds]
          bbox_pred_ = bbox_preds[inds]
          img_meta_ = img_metas[i]
          pos_is_gts_ = pos_is_gts[i]
  
          bboxes = self.regress_by_class(
              bboxes_, label_, bbox_pred_, img_meta_
          )
  
          # filter gt bboxes
          pos_keep = 1 - pos_is_gts_
          keep_inds = pos_is_gts_.new_ones(num_rois)
          keep_inds[: len(pos_is_gts_)] = pos_keep
  
          bboxes_list.append(bboxes[keep_inds.type(torch.bool)])
  
      return bboxes_list
  
file_path: insightface/detection/scrfd/mmdet/models/roi_heads/bbox_heads/bbox_head.py
imports: import torch
  import torch.nn
  import torch.nn.functional
  from mmcv.runner import auto_fp16, force_fp32
  from torch.nn.modules.utils import _pair
  from mmdet.core import build_bbox_coder, multi_apply, multiclass_nms
  from mmdet.models.builder import HEADS, build_loss
  from mmdet.models.losses import accuracy
label_desc: Use image node_id 8 for calling the BBoxHead obj's underlying member method code with example usage: obj.refine_bboxes(rois, labels, bbox_preds, pos_is_gts, img_metas) and returns: bboxes_list