์ฝ˜ํ…์ธ ๋กœ ๊ฑด๋„ˆ๋›ฐ๊ธฐ

์ฐธ์กฐ ultralytics/models/utils/ops.py

์ฐธ๊ณ 

์ด ํŒŒ์ผ์€ https://github.com/ultralytics/ ultralytics/blob/main/ ultralytics/models/utils/ops .py์—์„œ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ฌธ์ œ๋ฅผ ๋ฐœ๊ฒฌํ•˜๋ฉด ํ’€ ๋ฆฌํ€˜์ŠคํŠธ (๐Ÿ› ๏ธ) ๋ฅผ ํ†ตํ•ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๋„๋ก ๋„์™€์ฃผ์„ธ์š”. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ™!



ultralytics.models.utils.ops.HungarianMatcher

๋ฒ ์ด์Šค: Module

ํ• ๋‹น ๋ฌธ์ œ๋ฅผ ์ข…๋‹จ ๊ฐ„ ๋ฐฉ์‹์œผ๋กœ ํ•ด๊ฒฐํ•˜๋Š” ์ฐจ๋ณ„ํ™” ๊ฐ€๋Šฅํ•œ ๋ชจ๋“ˆ์ธ ํ—๊ฐ€๋ฆฌ๋งค์ฒ˜๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๋ชจ๋“ˆ์ž…๋‹ˆ๋‹ค. ๋ชจ๋“ˆ์ž…๋‹ˆ๋‹ค.

ํ—๊ฐ€๋ฆฌ๋งค์ฒ˜๋Š” ๋น„์šฉ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์˜ˆ์ธก๋œ ๊ฒฝ๊ณ„ ์ƒ์ž์™€ ๊ธฐ์ค€ ์ง„์‹ค ๊ฒฝ๊ณ„ ์ƒ์ž์— ๋Œ€ํ•ด ์ตœ์ ์˜ ํ• ๋‹น์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค. ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ถ„๋ฅ˜ ์ ์ˆ˜, ๊ฒฝ๊ณ„ ์ƒ์ž ์ขŒํ‘œ, ์„ ํƒ์ ์œผ๋กœ ๋งˆ์Šคํฌ ์˜ˆ์ธก์„ ๊ณ ๋ คํ•ฉ๋‹ˆ๋‹ค.

์†์„ฑ:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช…
cost_gain dict

๋น„์šฉ ๊ณ„์ˆ˜ ์‚ฌ์ „: 'class', 'bbox', 'giou', 'mask', 'dice'.

use_fl bool

๋ถ„๋ฅ˜ ๋น„์šฉ ๊ณ„์‚ฐ์— ์ดˆ์  ์†์‹ค์„ ์‚ฌ์šฉํ• ์ง€ ์—ฌ๋ถ€๋ฅผ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค.

with_mask bool

๋ชจ๋ธ์—์„œ ๋งˆ์Šคํฌ ์˜ˆ์ธก์„ ์ˆ˜ํ–‰ํ• ์ง€ ์—ฌ๋ถ€๋ฅผ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค.

num_sample_points int

๋งˆ์Šคํฌ ๋น„์šฉ ๊ณ„์‚ฐ์— ์‚ฌ์šฉ๋˜๋Š” ์ƒ˜ํ”Œ ํฌ์ธํŠธ ์ˆ˜์ž…๋‹ˆ๋‹ค.

alpha float

์ดˆ์  ์†์‹ค ๊ณ„์‚ฐ์˜ ์•ŒํŒŒ ๊ณ„์ˆ˜์ž…๋‹ˆ๋‹ค.

gamma float

์ดˆ์  ์†์‹ค ๊ณ„์‚ฐ์˜ ๊ฐ๋งˆ ๊ณ„์ˆ˜์ž…๋‹ˆ๋‹ค.

๋ฐฉ๋ฒ•:

์ด๋ฆ„ ์„ค๋ช…
forward

๋ฐฐ์น˜์— ๋Œ€ํ•œ ์˜ˆ์ธก๊ณผ ๊ทผ๊ฑฐ ์ง„์‹ค ๊ฐ„์˜ ์˜ˆ์ธก๊ณผ ๋ฐฐ์น˜์— ๋Œ€ํ•œ ๊ธฐ์ค€ ์ง„์‹ค ๊ฐ„์˜ ํ• ๋‹น์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค.

_cost_mask

๋งˆ์Šคํฌ๊ฐ€ ์˜ˆ์ธก๋˜๋Š” ๊ฒฝ์šฐ ๋งˆ์Šคํฌ ๋น„์šฉ๊ณผ ์ฃผ์‚ฌ์œ„ ๋น„์šฉ์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/models/utils/ops.py
class HungarianMatcher(nn.Module):
    """
    A module implementing the HungarianMatcher, which is a differentiable module to solve the assignment problem in an
    end-to-end fashion.

    HungarianMatcher performs optimal assignment over the predicted and ground truth bounding boxes using a cost
    function that considers classification scores, bounding box coordinates, and optionally, mask predictions.

    Attributes:
        cost_gain (dict): Dictionary of cost coefficients: 'class', 'bbox', 'giou', 'mask', and 'dice'.
        use_fl (bool): Indicates whether to use Focal Loss for the classification cost calculation.
        with_mask (bool): Indicates whether the model makes mask predictions.
        num_sample_points (int): The number of sample points used in mask cost calculation.
        alpha (float): The alpha factor in Focal Loss calculation.
        gamma (float): The gamma factor in Focal Loss calculation.

    Methods:
        forward(pred_bboxes, pred_scores, gt_bboxes, gt_cls, gt_groups, masks=None, gt_mask=None): Computes the
            assignment between predictions and ground truths for a batch.
        _cost_mask(bs, num_gts, masks=None, gt_mask=None): Computes the mask cost and dice cost if masks are predicted.
    """

    def __init__(self, cost_gain=None, use_fl=True, with_mask=False, num_sample_points=12544, alpha=0.25, gamma=2.0):
        """Initializes HungarianMatcher with cost coefficients, Focal Loss, mask prediction, sample points, and alpha
        gamma factors.
        """
        super().__init__()
        if cost_gain is None:
            cost_gain = {"class": 1, "bbox": 5, "giou": 2, "mask": 1, "dice": 1}
        self.cost_gain = cost_gain
        self.use_fl = use_fl
        self.with_mask = with_mask
        self.num_sample_points = num_sample_points
        self.alpha = alpha
        self.gamma = gamma

    def forward(self, pred_bboxes, pred_scores, gt_bboxes, gt_cls, gt_groups, masks=None, gt_mask=None):
        """
        Forward pass for HungarianMatcher. This function computes costs based on prediction and ground truth
        (classification cost, L1 cost between boxes and GIoU cost between boxes) and finds the optimal matching between
        predictions and ground truth based on these costs.

        Args:
            pred_bboxes (Tensor): Predicted bounding boxes with shape [batch_size, num_queries, 4].
            pred_scores (Tensor): Predicted scores with shape [batch_size, num_queries, num_classes].
            gt_cls (torch.Tensor): Ground truth classes with shape [num_gts, ].
            gt_bboxes (torch.Tensor): Ground truth bounding boxes with shape [num_gts, 4].
            gt_groups (List[int]): List of length equal to batch size, containing the number of ground truths for
                each image.
            masks (Tensor, optional): Predicted masks with shape [batch_size, num_queries, height, width].
                Defaults to None.
            gt_mask (List[Tensor], optional): List of ground truth masks, each with shape [num_masks, Height, Width].
                Defaults to None.

        Returns:
            (List[Tuple[Tensor, Tensor]]): A list of size batch_size, each element is a tuple (index_i, index_j), where:
                - index_i is the tensor of indices of the selected predictions (in order)
                - index_j is the tensor of indices of the corresponding selected ground truth targets (in order)
                For each batch element, it holds:
                    len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
        """

        bs, nq, nc = pred_scores.shape

        if sum(gt_groups) == 0:
            return [(torch.tensor([], dtype=torch.long), torch.tensor([], dtype=torch.long)) for _ in range(bs)]

        # We flatten to compute the cost matrices in a batch
        # [batch_size * num_queries, num_classes]
        pred_scores = pred_scores.detach().view(-1, nc)
        pred_scores = F.sigmoid(pred_scores) if self.use_fl else F.softmax(pred_scores, dim=-1)
        # [batch_size * num_queries, 4]
        pred_bboxes = pred_bboxes.detach().view(-1, 4)

        # Compute the classification cost
        pred_scores = pred_scores[:, gt_cls]
        if self.use_fl:
            neg_cost_class = (1 - self.alpha) * (pred_scores**self.gamma) * (-(1 - pred_scores + 1e-8).log())
            pos_cost_class = self.alpha * ((1 - pred_scores) ** self.gamma) * (-(pred_scores + 1e-8).log())
            cost_class = pos_cost_class - neg_cost_class
        else:
            cost_class = -pred_scores

        # Compute the L1 cost between boxes
        cost_bbox = (pred_bboxes.unsqueeze(1) - gt_bboxes.unsqueeze(0)).abs().sum(-1)  # (bs*num_queries, num_gt)

        # Compute the GIoU cost between boxes, (bs*num_queries, num_gt)
        cost_giou = 1.0 - bbox_iou(pred_bboxes.unsqueeze(1), gt_bboxes.unsqueeze(0), xywh=True, GIoU=True).squeeze(-1)

        # Final cost matrix
        C = (
            self.cost_gain["class"] * cost_class
            + self.cost_gain["bbox"] * cost_bbox
            + self.cost_gain["giou"] * cost_giou
        )
        # Compute the mask cost and dice cost
        if self.with_mask:
            C += self._cost_mask(bs, gt_groups, masks, gt_mask)

        # Set invalid values (NaNs and infinities) to 0 (fixes ValueError: matrix contains invalid numeric entries)
        C[C.isnan() | C.isinf()] = 0.0

        C = C.view(bs, nq, -1).cpu()
        indices = [linear_sum_assignment(c[i]) for i, c in enumerate(C.split(gt_groups, -1))]
        gt_groups = torch.as_tensor([0, *gt_groups[:-1]]).cumsum_(0)  # (idx for queries, idx for gt)
        return [
            (torch.tensor(i, dtype=torch.long), torch.tensor(j, dtype=torch.long) + gt_groups[k])
            for k, (i, j) in enumerate(indices)
        ]

__init__(cost_gain=None, use_fl=True, with_mask=False, num_sample_points=12544, alpha=0.25, gamma=2.0)

๋น„์šฉ ๊ณ„์ˆ˜, ์ดˆ์  ์†์‹ค, ๋งˆ์Šคํฌ ์˜ˆ์ธก, ์ƒ˜ํ”Œ ํฌ์ธํŠธ, ์•ŒํŒŒ ๊ฐ๋งˆ ์ธ์ž๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ—๊ฐ€๋ฆฌ๋งค์ฒ˜๋ฅผ ์ดˆ๊ธฐํ™”ํ•ฉ๋‹ˆ๋‹ค. ๊ฐ๋งˆ ์ธ์ž๋กœ ์ดˆ๊ธฐํ™”ํ•ฉ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/models/utils/ops.py
def __init__(self, cost_gain=None, use_fl=True, with_mask=False, num_sample_points=12544, alpha=0.25, gamma=2.0):
    """Initializes HungarianMatcher with cost coefficients, Focal Loss, mask prediction, sample points, and alpha
    gamma factors.
    """
    super().__init__()
    if cost_gain is None:
        cost_gain = {"class": 1, "bbox": 5, "giou": 2, "mask": 1, "dice": 1}
    self.cost_gain = cost_gain
    self.use_fl = use_fl
    self.with_mask = with_mask
    self.num_sample_points = num_sample_points
    self.alpha = alpha
    self.gamma = gamma

forward(pred_bboxes, pred_scores, gt_bboxes, gt_cls, gt_groups, masks=None, gt_mask=None)

ํ—๊ฐ€๋ฆฌ๋งค์ฒ˜์˜ ํฌ์›Œ๋“œ ํŒจ์Šค. ์ด ํ•จ์ˆ˜๋Š” ์˜ˆ์ธก๊ณผ ์‹ค์ธก ๋ฐ์ดํ„ฐ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋น„์šฉ์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค. (๋ถ„๋ฅ˜ ๋น„์šฉ, ๋ฐ•์Šค ๊ฐ„ L1 ๋น„์šฉ, ๋ฐ•์Šค ๊ฐ„ GIoU ๋น„์šฉ)์„ ๊ธฐ๋ฐ˜์œผ๋กœ ๋น„์šฉ์„ ๊ณ„์‚ฐํ•˜๊ณ  ์ด ๋น„์šฉ์„ ๊ธฐ๋ฐ˜์œผ๋กœ ์˜ˆ์ธก๊ณผ ๊ธฐ์ค€๊ฐ’ ๊ฐ„์˜ ์˜ˆ์ธก๊ณผ ๊ธฐ์ค€ ์ง„์‹ค ์‚ฌ์ด์˜ ์ตœ์  ๋งค์นญ์„ ์ฐพ์Šต๋‹ˆ๋‹ค.

๋งค๊ฐœ๋ณ€์ˆ˜:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช… ๊ธฐ๋ณธ๊ฐ’
pred_bboxes Tensor

๋ชจ์–‘์„ ๊ฐ€์ง„ ์˜ˆ์ธก๋œ ๊ฒฝ๊ณ„ ์ƒ์ž [batch_size, num_queries, 4].

ํ•„์ˆ˜
pred_scores Tensor

๋ชจ์–‘ [batch_size, num_queries, num_classes]๋กœ ์˜ˆ์ธก๋œ ์ ์ˆ˜.

ํ•„์ˆ˜
gt_cls Tensor

๋ชจ์–‘์ด ์žˆ๋Š” ๊ทธ๋ผ์šด๋“œ ํŠธ๋ฃจ์Šค ํด๋ž˜์Šค [num_gts, ].

ํ•„์ˆ˜
gt_bboxes Tensor

๋ชจ์–‘์ด ์žˆ๋Š” ๊ธฐ์ค€์  ๊ฒฝ๊ณ„ ์ƒ์ž [num_gts, 4].

ํ•„์ˆ˜
gt_groups List[int]

๋ฐฐ์น˜ ํฌ๊ธฐ์™€ ๋™์ผํ•œ ๊ธธ์ด์˜ ๋ชฉ๋ก์œผ๋กœ, ๊ฐ ์ด๋ฏธ์ง€์˜ ๊ธฐ์ค€๊ฐ’ ์ˆ˜๊ฐ€ ํฌํ•จ๋œ ๋ฅผ ํฌํ•จํ•˜๋Š” ๊ธธ์ด ๋ชฉ๋ก์ž…๋‹ˆ๋‹ค.

ํ•„์ˆ˜
masks Tensor

๋ชจ์–‘ [๋ฐฐ์น˜_ํฌ๊ธฐ, num_์ฟผ๋ฆฌ, ๋†’์ด, ๋„ˆ๋น„]์˜ ์˜ˆ์ƒ ๋งˆ์Šคํฌ์ž…๋‹ˆ๋‹ค. ๊ธฐ๋ณธ๊ฐ’์€ ์—†์Œ์ž…๋‹ˆ๋‹ค.

None
gt_mask List[Tensor]

๊ธฐ์ค€์  ๋งˆ์Šคํฌ์˜ ๋ชฉ๋ก์œผ๋กœ, ๊ฐ๊ฐ [num_masks, ๋†’์ด, ๋„ˆ๋น„] ๋ชจ์–‘์„ ๊ฐ€์ง‘๋‹ˆ๋‹ค. ๊ธฐ๋ณธ๊ฐ’์€ ์—†์Œ์ž…๋‹ˆ๋‹ค.

None

๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค:

์œ ํ˜• ์„ค๋ช…
List[Tuple[Tensor, Tensor]]

batch_size ํฌ๊ธฐ์˜ ๋ชฉ๋ก์œผ๋กœ, ๊ฐ ์š”์†Œ๋Š” ํŠœํ”Œ(index_i, index_j)์ž…๋‹ˆ๋‹ค: - index_i๋Š” ์„ ํƒ๋œ ์˜ˆ์ธก์˜ tensor ์ธ๋ฑ์Šค(์ˆœ์„œ๋Œ€๋กœ)์ž…๋‹ˆ๋‹ค. - index_j๋Š” ์„ ํƒ๋œ ๊ธฐ์ค€๊ฐ’ ๋Œ€์ƒ์˜ ํ•ด๋‹น ์ธ๋ฑ์Šค์˜ tensor (์ˆœ์„œ๋Œ€๋กœ)์ž…๋‹ˆ๋‹ค. ๊ฐ ๋ฐฐ์น˜ ์š”์†Œ์— ๋Œ€ํ•ด ๋‹ค์Œ์„ ๋ณด์œ ํ•ฉ๋‹ˆ๋‹ค: len(index_i) = len(index_j) = min(num_queries, num_target_boxes)

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/models/utils/ops.py
def forward(self, pred_bboxes, pred_scores, gt_bboxes, gt_cls, gt_groups, masks=None, gt_mask=None):
    """
    Forward pass for HungarianMatcher. This function computes costs based on prediction and ground truth
    (classification cost, L1 cost between boxes and GIoU cost between boxes) and finds the optimal matching between
    predictions and ground truth based on these costs.

    Args:
        pred_bboxes (Tensor): Predicted bounding boxes with shape [batch_size, num_queries, 4].
        pred_scores (Tensor): Predicted scores with shape [batch_size, num_queries, num_classes].
        gt_cls (torch.Tensor): Ground truth classes with shape [num_gts, ].
        gt_bboxes (torch.Tensor): Ground truth bounding boxes with shape [num_gts, 4].
        gt_groups (List[int]): List of length equal to batch size, containing the number of ground truths for
            each image.
        masks (Tensor, optional): Predicted masks with shape [batch_size, num_queries, height, width].
            Defaults to None.
        gt_mask (List[Tensor], optional): List of ground truth masks, each with shape [num_masks, Height, Width].
            Defaults to None.

    Returns:
        (List[Tuple[Tensor, Tensor]]): A list of size batch_size, each element is a tuple (index_i, index_j), where:
            - index_i is the tensor of indices of the selected predictions (in order)
            - index_j is the tensor of indices of the corresponding selected ground truth targets (in order)
            For each batch element, it holds:
                len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
    """

    bs, nq, nc = pred_scores.shape

    if sum(gt_groups) == 0:
        return [(torch.tensor([], dtype=torch.long), torch.tensor([], dtype=torch.long)) for _ in range(bs)]

    # We flatten to compute the cost matrices in a batch
    # [batch_size * num_queries, num_classes]
    pred_scores = pred_scores.detach().view(-1, nc)
    pred_scores = F.sigmoid(pred_scores) if self.use_fl else F.softmax(pred_scores, dim=-1)
    # [batch_size * num_queries, 4]
    pred_bboxes = pred_bboxes.detach().view(-1, 4)

    # Compute the classification cost
    pred_scores = pred_scores[:, gt_cls]
    if self.use_fl:
        neg_cost_class = (1 - self.alpha) * (pred_scores**self.gamma) * (-(1 - pred_scores + 1e-8).log())
        pos_cost_class = self.alpha * ((1 - pred_scores) ** self.gamma) * (-(pred_scores + 1e-8).log())
        cost_class = pos_cost_class - neg_cost_class
    else:
        cost_class = -pred_scores

    # Compute the L1 cost between boxes
    cost_bbox = (pred_bboxes.unsqueeze(1) - gt_bboxes.unsqueeze(0)).abs().sum(-1)  # (bs*num_queries, num_gt)

    # Compute the GIoU cost between boxes, (bs*num_queries, num_gt)
    cost_giou = 1.0 - bbox_iou(pred_bboxes.unsqueeze(1), gt_bboxes.unsqueeze(0), xywh=True, GIoU=True).squeeze(-1)

    # Final cost matrix
    C = (
        self.cost_gain["class"] * cost_class
        + self.cost_gain["bbox"] * cost_bbox
        + self.cost_gain["giou"] * cost_giou
    )
    # Compute the mask cost and dice cost
    if self.with_mask:
        C += self._cost_mask(bs, gt_groups, masks, gt_mask)

    # Set invalid values (NaNs and infinities) to 0 (fixes ValueError: matrix contains invalid numeric entries)
    C[C.isnan() | C.isinf()] = 0.0

    C = C.view(bs, nq, -1).cpu()
    indices = [linear_sum_assignment(c[i]) for i, c in enumerate(C.split(gt_groups, -1))]
    gt_groups = torch.as_tensor([0, *gt_groups[:-1]]).cumsum_(0)  # (idx for queries, idx for gt)
    return [
        (torch.tensor(i, dtype=torch.long), torch.tensor(j, dtype=torch.long) + gt_groups[k])
        for k, (i, j) in enumerate(indices)
    ]



ultralytics.models.utils.ops.get_cdn_group(batch, num_classes, num_queries, class_embed, num_dn=100, cls_noise_ratio=0.5, box_noise_scale=1.0, training=False)

๋Œ€๋น„ ๋…ธ์ด์ฆˆ ์ œ๊ฑฐ ํ›ˆ๋ จ ๊ทธ๋ฃน ๊ฐ€์ ธ์˜ค๊ธฐ. ์ด ํ•จ์ˆ˜๋Š” ๊ธฐ์ค€๊ฐ’(GT)์˜ ์–‘์ˆ˜ ์ƒ˜ํ”Œ๊ณผ ์Œ์ˆ˜ ์ƒ˜ํ”Œ๋กœ ๋Œ€์กฐ ๋…ธ์ด์ฆˆ ์ œ๊ฑฐ ํ›ˆ๋ จ ๊ทธ๋ฃน์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. ์–‘์ˆ˜ ์ƒ˜ํ”Œ๊ณผ ๊ธฐ์ค€ ์‹ค์ธก๊ฐ’(GT)์˜ ์Œ์ˆ˜ ์ƒ˜ํ”Œ๋กœ ๋Œ€์กฐ ๋…ธ์ด์ฆˆ ์ œ๊ฑฐ ํ›ˆ๋ จ ๊ทธ๋ฃน์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. ํด๋ž˜์Šค ๋ ˆ์ด๋ธ”๊ณผ ๋ฐ”์šด๋”ฉ ๋ฐ•์Šค ์ขŒํ‘œ์— ๋…ธ์ด์ฆˆ๋ฅผ ์ ์šฉํ•ฉ๋‹ˆ๋‹ค, ๊ทธ๋ฆฌ๊ณ  ์ˆ˜์ •๋œ ๋ ˆ์ด๋ธ”, ๊ฒฝ๊ณ„ ์ƒ์ž, ์ฃผ์˜ ๋งˆ์Šคํฌ ๋ฐ ๋ฉ”ํƒ€ ์ •๋ณด๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

๋งค๊ฐœ๋ณ€์ˆ˜:

์ด๋ฆ„ ์œ ํ˜• ์„ค๋ช… ๊ธฐ๋ณธ๊ฐ’
batch dict

'gt_cls'(torch.Tensor ๋ชจ์–‘ [num_gts, ] ํฌํ•จ), 'gt_bboxes' (torch.Tensor ๋ชจ์–‘ [num_gts, 4]), 'gt_groups' (List(int)) - ๋ฐฐ์น˜ ํฌ๊ธฐ ๊ธธ์ด ๋ชฉ๋ก์œผ๋กœ, ๊ฐ ์ด๋ฏธ์ง€์˜ ๊ฐฏ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๊ฐ ์ด๋ฏธ์ง€์˜ gts ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๋ฐฐ์น˜ ํฌ๊ธฐ ๋ชฉ๋ก์ž…๋‹ˆ๋‹ค.

ํ•„์ˆ˜
num_classes int

์ˆ˜์—… ์ˆ˜.

ํ•„์ˆ˜
num_queries int

์ฟผ๋ฆฌ ์ˆ˜์ž…๋‹ˆ๋‹ค.

ํ•„์ˆ˜
class_embed Tensor

ํด๋ž˜์Šค ๋ ˆ์ด๋ธ”์„ ์ž„๋ฒ ๋”ฉ ๊ณต๊ฐ„์— ๋งคํ•‘ํ•˜๋Š” ์ž„๋ฒ ๋”ฉ ๊ฐ€์ค‘์น˜.

ํ•„์ˆ˜
num_dn int

๋…ธ์ด์ฆˆ ์ œ๊ฑฐ ํšŸ์ˆ˜์ž…๋‹ˆ๋‹ค. ๊ธฐ๋ณธ๊ฐ’์€ 100์ž…๋‹ˆ๋‹ค.

100
cls_noise_ratio float

ํด๋ž˜์Šค ๋ ˆ์ด๋ธ”์˜ ๋…ธ์ด์ฆˆ ๋น„์œจ. ๊ธฐ๋ณธ๊ฐ’์€ 0.5์ž…๋‹ˆ๋‹ค.

0.5
box_noise_scale float

๋ฐ”์šด๋”ฉ ์ƒ์ž ์ขŒํ‘œ์˜ ๋…ธ์ด์ฆˆ ์Šค์ผ€์ผ์ž…๋‹ˆ๋‹ค. ๊ธฐ๋ณธ๊ฐ’์€ 1.0์ž…๋‹ˆ๋‹ค.

1.0
training bool

๊ต์œก ๋ชจ๋“œ์ธ ๊ฒฝ์šฐ. ๊ธฐ๋ณธ๊ฐ’์€ False์ž…๋‹ˆ๋‹ค.

False

๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค:

์œ ํ˜• ์„ค๋ช…
Tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Dict]]

์ˆ˜์ •๋œ ํด๋ž˜์Šค ์ž„๋ฒ ๋”ฉ, ๋ฐ”์šด๋”ฉ ๋ฐ•์Šค, ์ฃผ์˜ ๋งˆ์Šคํฌ ๋ฐ ๋…ธ์ด์ฆˆ ์ œ๊ฑฐ๋ฅผ ์œ„ํ•œ ๋ฉ”ํƒ€ ์ •๋ณด. ํ›ˆ๋ จ ๋ชจ๋“œ๊ฐ€ ์•„๋‹ˆ๊ฑฐ๋‚˜ 'num_dn' ์ด 0๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์œผ๋ฉด, ์ด ํ•จ์ˆ˜๋Š” ํŠœํ”Œ์˜ ๋ชจ๋“  ์š”์†Œ์— ๋Œ€ํ•ด None์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

์˜ ์†Œ์Šค ์ฝ”๋“œ ultralytics/models/utils/ops.py
def get_cdn_group(
    batch, num_classes, num_queries, class_embed, num_dn=100, cls_noise_ratio=0.5, box_noise_scale=1.0, training=False
):
    """
    Get contrastive denoising training group. This function creates a contrastive denoising training group with positive
    and negative samples from the ground truths (gt). It applies noise to the class labels and bounding box coordinates,
    and returns the modified labels, bounding boxes, attention mask and meta information.

    Args:
        batch (dict): A dict that includes 'gt_cls' (torch.Tensor with shape [num_gts, ]), 'gt_bboxes'
            (torch.Tensor with shape [num_gts, 4]), 'gt_groups' (List(int)) which is a list of batch size length
            indicating the number of gts of each image.
        num_classes (int): Number of classes.
        num_queries (int): Number of queries.
        class_embed (torch.Tensor): Embedding weights to map class labels to embedding space.
        num_dn (int, optional): Number of denoising. Defaults to 100.
        cls_noise_ratio (float, optional): Noise ratio for class labels. Defaults to 0.5.
        box_noise_scale (float, optional): Noise scale for bounding box coordinates. Defaults to 1.0.
        training (bool, optional): If it's in training mode. Defaults to False.

    Returns:
        (Tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Dict]]): The modified class embeddings,
            bounding boxes, attention mask and meta information for denoising. If not in training mode or 'num_dn'
            is less than or equal to 0, the function returns None for all elements in the tuple.
    """

    if (not training) or num_dn <= 0:
        return None, None, None, None
    gt_groups = batch["gt_groups"]
    total_num = sum(gt_groups)
    max_nums = max(gt_groups)
    if max_nums == 0:
        return None, None, None, None

    num_group = num_dn // max_nums
    num_group = 1 if num_group == 0 else num_group
    # Pad gt to max_num of a batch
    bs = len(gt_groups)
    gt_cls = batch["cls"]  # (bs*num, )
    gt_bbox = batch["bboxes"]  # bs*num, 4
    b_idx = batch["batch_idx"]

    # Each group has positive and negative queries.
    dn_cls = gt_cls.repeat(2 * num_group)  # (2*num_group*bs*num, )
    dn_bbox = gt_bbox.repeat(2 * num_group, 1)  # 2*num_group*bs*num, 4
    dn_b_idx = b_idx.repeat(2 * num_group).view(-1)  # (2*num_group*bs*num, )

    # Positive and negative mask
    # (bs*num*num_group, ), the second total_num*num_group part as negative samples
    neg_idx = torch.arange(total_num * num_group, dtype=torch.long, device=gt_bbox.device) + num_group * total_num

    if cls_noise_ratio > 0:
        # Half of bbox prob
        mask = torch.rand(dn_cls.shape) < (cls_noise_ratio * 0.5)
        idx = torch.nonzero(mask).squeeze(-1)
        # Randomly put a new one here
        new_label = torch.randint_like(idx, 0, num_classes, dtype=dn_cls.dtype, device=dn_cls.device)
        dn_cls[idx] = new_label

    if box_noise_scale > 0:
        known_bbox = xywh2xyxy(dn_bbox)

        diff = (dn_bbox[..., 2:] * 0.5).repeat(1, 2) * box_noise_scale  # 2*num_group*bs*num, 4

        rand_sign = torch.randint_like(dn_bbox, 0, 2) * 2.0 - 1.0
        rand_part = torch.rand_like(dn_bbox)
        rand_part[neg_idx] += 1.0
        rand_part *= rand_sign
        known_bbox += rand_part * diff
        known_bbox.clip_(min=0.0, max=1.0)
        dn_bbox = xyxy2xywh(known_bbox)
        dn_bbox = torch.logit(dn_bbox, eps=1e-6)  # inverse sigmoid

    num_dn = int(max_nums * 2 * num_group)  # total denoising queries
    # class_embed = torch.cat([class_embed, torch.zeros([1, class_embed.shape[-1]], device=class_embed.device)])
    dn_cls_embed = class_embed[dn_cls]  # bs*num * 2 * num_group, 256
    padding_cls = torch.zeros(bs, num_dn, dn_cls_embed.shape[-1], device=gt_cls.device)
    padding_bbox = torch.zeros(bs, num_dn, 4, device=gt_bbox.device)

    map_indices = torch.cat([torch.tensor(range(num), dtype=torch.long) for num in gt_groups])
    pos_idx = torch.stack([map_indices + max_nums * i for i in range(num_group)], dim=0)

    map_indices = torch.cat([map_indices + max_nums * i for i in range(2 * num_group)])
    padding_cls[(dn_b_idx, map_indices)] = dn_cls_embed
    padding_bbox[(dn_b_idx, map_indices)] = dn_bbox

    tgt_size = num_dn + num_queries
    attn_mask = torch.zeros([tgt_size, tgt_size], dtype=torch.bool)
    # Match query cannot see the reconstruct
    attn_mask[num_dn:, :num_dn] = True
    # Reconstruct cannot see each other
    for i in range(num_group):
        if i == 0:
            attn_mask[max_nums * 2 * i : max_nums * 2 * (i + 1), max_nums * 2 * (i + 1) : num_dn] = True
        if i == num_group - 1:
            attn_mask[max_nums * 2 * i : max_nums * 2 * (i + 1), : max_nums * i * 2] = True
        else:
            attn_mask[max_nums * 2 * i : max_nums * 2 * (i + 1), max_nums * 2 * (i + 1) : num_dn] = True
            attn_mask[max_nums * 2 * i : max_nums * 2 * (i + 1), : max_nums * 2 * i] = True
    dn_meta = {
        "dn_pos_idx": [p.reshape(-1) for p in pos_idx.cpu().split(list(gt_groups), dim=1)],
        "dn_num_group": num_group,
        "dn_num_split": [num_dn, num_queries],
    }

    return (
        padding_cls.to(class_embed.device),
        padding_bbox.to(class_embed.device),
        attn_mask.to(class_embed.device),
        dn_meta,
    )





Created 2023-11-12, Updated 2024-06-02
Authors: glenn-jocher (5), Burhan-Q (1), Laughing-q (1)