id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
14,756
from mmengine.utils import is_str The provided code snippet includes necessary dependencies for implementing the `imagenet_det_classes` function. Write a Python function `def imagenet_det_classes() -> list` to solve the following problem: Class names of ImageNet Det. Here is the function: def imagenet_det_classes() ...
Class names of ImageNet Det.
14,757
from mmengine.utils import is_str The provided code snippet includes necessary dependencies for implementing the `imagenet_vid_classes` function. Write a Python function `def imagenet_vid_classes() -> list` to solve the following problem: Class names of ImageNet VID. Here is the function: def imagenet_vid_classes() ...
Class names of ImageNet VID.
14,758
from mmengine.utils import is_str The provided code snippet includes necessary dependencies for implementing the `coco_classes` function. Write a Python function `def coco_classes() -> list` to solve the following problem: Class names of COCO. Here is the function: def coco_classes() -> list: """Class names of C...
Class names of COCO.
14,759
from mmengine.utils import is_str The provided code snippet includes necessary dependencies for implementing the `cityscapes_classes` function. Write a Python function `def cityscapes_classes() -> list` to solve the following problem: Class names of Cityscapes. Here is the function: def cityscapes_classes() -> list:...
Class names of Cityscapes.
14,760
from mmengine.utils import is_str The provided code snippet includes necessary dependencies for implementing the `oid_challenge_classes` function. Write a Python function `def oid_challenge_classes() -> list` to solve the following problem: Class names of Open Images Challenge. Here is the function: def oid_challeng...
Class names of Open Images Challenge.
14,761
from mmengine.utils import is_str The provided code snippet includes necessary dependencies for implementing the `oid_v6_classes` function. Write a Python function `def oid_v6_classes() -> list` to solve the following problem: Class names of Open Images V6. Here is the function: def oid_v6_classes() -> list: """...
Class names of Open Images V6.
14,762
from mmengine.utils import is_str The provided code snippet includes necessary dependencies for implementing the `objects365v1_classes` function. Write a Python function `def objects365v1_classes() -> list` to solve the following problem: Class names of Objects365 V1. Here is the function: def objects365v1_classes()...
Class names of Objects365 V1.
14,763
from mmengine.utils import is_str The provided code snippet includes necessary dependencies for implementing the `objects365v2_classes` function. Write a Python function `def objects365v2_classes() -> list` to solve the following problem: Class names of Objects365 V2. Here is the function: def objects365v2_classes()...
Class names of Objects365 V2.
14,764
from multiprocessing import Pool import numpy as np from mmengine.logging import print_log from mmengine.utils import is_str from terminaltables import AsciiTable from .bbox_overlaps import bbox_overlaps from .class_names import get_classes def average_precision(recalls, precisions, mode='area'): """Calculate avera...
Evaluate mAP of a dataset. Args: det_results (list[list]): [[cls1_det, cls2_det, ...], ...]. The outer list indicates images, and the inner list indicates per-class detected bboxes. annotations (list[dict]): Ground truth annotations where each item of the list indicates an image. Keys of annotations are: - `bboxes`: nu...
14,765
from collections.abc import Sequence import numpy as np from mmengine.logging import print_log from terminaltables import AsciiTable from .bbox_overlaps import bbox_overlaps def _recalls(all_ious, proposal_nums, thrs): img_num = all_ious.shape[0] total_gt_num = sum([ious.shape[0] for ious in all_ious]) _iou...
Calculate recalls. Args: gts (list[ndarray]): a list of arrays of shape (n, 4) proposals (list[ndarray]): a list of arrays of shape (k, 4) or (k, 5) proposal_nums (int | Sequence[int]): Top N proposals to be evaluated. iou_thrs (float | Sequence[float]): IoU thresholds. Default: 0.5. logger (logging.Logger | str | None...
14,766
from collections.abc import Sequence import numpy as np from mmengine.logging import print_log from terminaltables import AsciiTable from .bbox_overlaps import bbox_overlaps def _recalls(all_ious, proposal_nums, thrs): img_num = all_ious.shape[0] total_gt_num = sum([ious.shape[0] for ious in all_ious]) _iou...
Plot Proposal_num-Recalls curve. Args: recalls(ndarray or list): shape (k,) proposal_nums(ndarray or list): same shape as `recalls`
14,767
from collections.abc import Sequence import numpy as np from mmengine.logging import print_log from terminaltables import AsciiTable from .bbox_overlaps import bbox_overlaps def _recalls(all_ious, proposal_nums, thrs): img_num = all_ious.shape[0] total_gt_num = sum([ious.shape[0] for ious in all_ious]) _iou...
Plot IoU-Recalls curve. Args: recalls(ndarray or list): shape (k,) iou_thrs(ndarray or list): same shape as `recalls`
14,768
import multiprocessing import os import mmcv import numpy as np from mmengine.fileio import FileClient def pq_compute_single_core(proc_id, annotation_set, gt_folder, pred_folder, categories, ...
Evaluate the metrics of Panoptic Segmentation with multithreading. Same as the function with the same name in `panopticapi`. Args: matched_annotations_list (list): The matched annotation list. Each element is a tuple of annotations of the same image with the format (gt_anns, pred_anns). gt_folder (str): The path of the...
14,769
import json from typing import List import torch.nn as nn from mmengine.dist import get_dist_info from mmengine.logging import MMLogger from mmengine.optim import DefaultOptimWrapperConstructor from mmdet.registry import OPTIM_WRAPPER_CONSTRUCTORS The provided code snippet includes necessary dependencies for implement...
Get the layer id to set the different learning rates in ``layer_wise`` decay_type. Args: var_name (str): The key of the model. max_layer_id (int): Maximum layer id. Returns: int: The id number corresponding to different learning rate in ``LearningRateDecayOptimizerConstructor``.
14,770
import json from typing import List import torch.nn as nn from mmengine.dist import get_dist_info from mmengine.logging import MMLogger from mmengine.optim import DefaultOptimWrapperConstructor from mmdet.registry import OPTIM_WRAPPER_CONSTRUCTORS The provided code snippet includes necessary dependencies for implement...
Get the stage id to set the different learning rates in ``stage_wise`` decay_type. Args: var_name (str): The key of the model. max_stage_id (int): Maximum stage id. Returns: int: The id number corresponding to different learning rate in ``LearningRateDecayOptimizerConstructor``.
14,771
def trigger_visualization_hook(cfg, args): default_hooks = cfg.default_hooks if 'visualization' in default_hooks: visualization_hook = default_hooks['visualization'] # Turn on visualization visualization_hook['draw'] = True if args.show: visualization_hook['show'] =...
null
14,772
from collections import OrderedDict from mmengine.dist import get_dist_info from mmengine.hooks import Hook from torch import nn from mmdet.registry import HOOKS from mmdet.utils import all_reduce_dict The provided code snippet includes necessary dependencies for implementing the `get_norm_states` function. Write a Py...
Get the state_dict of batch norms in the module.
14,773
from mmcv.transforms import LoadImageFromFile from mmdet.datasets.transforms import LoadAnnotations, LoadPanopticAnnotations from mmdet.registry import TRANSFORMS The provided code snippet includes necessary dependencies for implementing the `get_loading_pipeline` function. Write a Python function `def get_loading_pip...
Only keep loading image and annotations related configuration. Args: pipeline (list[dict]): Data pipeline configs. Returns: list[dict]: The new pipeline list with only keep loading image and annotations related configuration. Examples: >>> pipelines = [ ... dict(type='LoadImageFromFile'), ... dict(type='LoadAnnotations...
14,774
from typing import List, Optional, Union import numpy as np from mmcv.transforms import RandomChoice from mmcv.transforms.utils import cache_randomness from mmengine.config import ConfigDict from mmdet.registry import TRANSFORMS AUTOAUG_POLICIES_V0 = [ [('Equalize', 0.8, 1), ('ShearY', 0.8, 4)], [('Color', 0.4,...
Autoaugment policies that was used in AutoAugment Paper.
14,775
from typing import List, Optional, Union import numpy as np from mmcv.transforms import RandomChoice from mmcv.transforms.utils import cache_randomness from mmengine.config import ConfigDict from mmdet.registry import TRANSFORMS _MAX_LEVEL = 10 The provided code snippet includes necessary dependencies for implementing...
Map from level to magnitude.
14,776
from typing import Optional import torch import torch.nn as nn from torch import Tensor from mmdet.registry import MODELS from .utils import weighted_loss The provided code snippet includes necessary dependencies for implementing the `smooth_l1_loss` function. Write a Python function `def smooth_l1_loss(pred: Tensor, ...
Smooth L1 loss. Args: pred (Tensor): The prediction. target (Tensor): The learning target of the prediction. beta (float, optional): The threshold in the piecewise function. Defaults to 1.0. Returns: Tensor: Calculated loss
14,777
from typing import Optional import torch import torch.nn as nn from torch import Tensor from mmdet.registry import MODELS from .utils import weighted_loss The provided code snippet includes necessary dependencies for implementing the `l1_loss` function. Write a Python function `def l1_loss(pred: Tensor, target: Tensor...
L1 loss. Args: pred (Tensor): The prediction. target (Tensor): The learning target of the prediction. Returns: Tensor: Calculated loss
14,778
import functools from typing import Callable, Optional import torch import torch.nn.functional as F from torch import Tensor def weight_reduce_loss(loss: Tensor, weight: Optional[Tensor] = None, reduction: str = 'mean', avg_factor: Optional[float] = N...
Create a weighted version of a given loss function. To use this decorator, the loss function must have the signature like `loss_func(pred, target, **kwargs)`. The function only needs to compute element-wise loss without any reduction. This decorator will add weight and reduction arguments to the function. The decorated...
14,779
import torch import torch.nn as nn import torch.nn.functional as F from mmdet.registry import MODELS The provided code snippet includes necessary dependencies for implementing the `ae_loss_per_image` function. Write a Python function `def ae_loss_per_image(tl_preds, br_preds, match)` to solve the following problem: As...
Associative Embedding Loss in one image. Associative Embedding Loss including two parts: pull loss and push loss. Pull loss makes embedding vectors from same object closer to each other. Push loss distinguish embedding vector from different objects, and makes the gap between them is large enough. During computing, usua...
14,780
from typing import Optional import torch.nn as nn import torch.nn.functional as F from torch import Tensor from mmdet.registry import MODELS from .utils import weighted_loss The provided code snippet includes necessary dependencies for implementing the `mse_loss` function. Write a Python function `def mse_loss(pred: T...
A Wrapper of MSE loss. Args: pred (Tensor): The prediction. target (Tensor): The learning target of the prediction. Returns: Tensor: loss Tensor
14,781
from typing import List, Optional, Tuple import torch import torch.nn as nn from torch import Tensor from mmdet.structures.bbox import bbox_overlaps from ..task_modules.coders import BaseBBoxCoder from ..task_modules.samplers import SamplingResult The provided code snippet includes necessary dependencies for implement...
Importance-based Sample Reweighting (ISR_P), positive part. Args: cls_score (Tensor): Predicted classification scores. bbox_pred (Tensor): Predicted bbox deltas. bbox_targets (tuple[Tensor]): A tuple of bbox targets, the are labels, label_weights, bbox_targets, bbox_weights, respectively. rois (Tensor): Anchors (single...
14,782
from typing import List, Optional, Tuple import torch import torch.nn as nn from torch import Tensor from mmdet.structures.bbox import bbox_overlaps from ..task_modules.coders import BaseBBoxCoder from ..task_modules.samplers import SamplingResult The provided code snippet includes necessary dependencies for implement...
Classification-Aware Regression Loss (CARL). Args: cls_score (Tensor): Predicted classification scores. labels (Tensor): Targets of classification. bbox_pred (Tensor): Predicted bbox deltas. bbox_targets (Tensor): Target of bbox regression. loss_bbox (func): Regression loss func of the head. bbox_coder (obj): BBox code...
14,783
import torch import torch.nn as nn import torch.nn.functional as F from mmcv.ops import sigmoid_focal_loss as _sigmoid_focal_loss from mmdet.registry import MODELS from .utils import weight_reduce_loss def weight_reduce_loss(loss: Tensor, weight: Optional[Tensor] = None, r...
PyTorch version of `Focal Loss <https://arxiv.org/abs/1708.02002>`_. Args: pred (torch.Tensor): The prediction with shape (N, C), C is the number of classes target (torch.Tensor): The learning label of the prediction. weight (torch.Tensor, optional): Sample-wise loss weight. gamma (float, optional): The gamma for calcu...
14,784
import torch import torch.nn as nn import torch.nn.functional as F from mmcv.ops import sigmoid_focal_loss as _sigmoid_focal_loss from mmdet.registry import MODELS from .utils import weight_reduce_loss def weight_reduce_loss(loss: Tensor, weight: Optional[Tensor] = None, r...
PyTorch version of `Focal Loss <https://arxiv.org/abs/1708.02002>`_. Different from `py_sigmoid_focal_loss`, this function accepts probability as input. Args: pred (torch.Tensor): The prediction probability with shape (N, C), C is the number of classes. target (torch.Tensor): The learning label of the prediction. The t...
14,785
import torch import torch.nn as nn import torch.nn.functional as F from mmcv.ops import sigmoid_focal_loss as _sigmoid_focal_loss from mmdet.registry import MODELS from .utils import weight_reduce_loss def weight_reduce_loss(loss: Tensor, weight: Optional[Tensor] = None, r...
r"""A wrapper of cuda version `Focal Loss <https://arxiv.org/abs/1708.02002>`_. Args: pred (torch.Tensor): The prediction with shape (N, C), C is the number of classes. target (torch.Tensor): The learning label of the prediction. weight (torch.Tensor, optional): Sample-wise loss weight. gamma (float, optional): The gam...
14,786
from functools import partial import torch import torch.nn as nn import torch.nn.functional as F from mmdet.models.losses.utils import weighted_loss from mmdet.registry import MODELS The provided code snippet includes necessary dependencies for implementing the `quality_focal_loss` function. Write a Python function `d...
r"""Quality Focal Loss (QFL) is from `Generalized Focal Loss: Learning Qualified and Distributed Bounding Boxes for Dense Object Detection <https://arxiv.org/abs/2006.04388>`_. Args: pred (torch.Tensor): Predicted joint representation of classification and quality (IoU) estimation with shape (N, C), C is the number of ...
14,787
from functools import partial import torch import torch.nn as nn import torch.nn.functional as F from mmdet.models.losses.utils import weighted_loss from mmdet.registry import MODELS The provided code snippet includes necessary dependencies for implementing the `quality_focal_loss_tensor_target` function. Write a Pyth...
`QualityFocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: pred (torch.Tensor): The prediction with shape (N, C), C is the number of classes target (torch.Tensor): The learning target of the iou-aware classification score with shape (N, C), C is the number of classes. beta (float): The beta parameter for calculating...
14,788
from functools import partial import torch import torch.nn as nn import torch.nn.functional as F from mmdet.models.losses.utils import weighted_loss from mmdet.registry import MODELS The provided code snippet includes necessary dependencies for implementing the `quality_focal_loss_with_prob` function. Write a Python f...
r"""Quality Focal Loss (QFL) is from `Generalized Focal Loss: Learning Qualified and Distributed Bounding Boxes for Dense Object Detection <https://arxiv.org/abs/2006.04388>`_. Different from `quality_focal_loss`, this function accepts probability as input. Args: pred (torch.Tensor): Predicted joint representation of c...
14,789
from functools import partial import torch import torch.nn as nn import torch.nn.functional as F from mmdet.models.losses.utils import weighted_loss from mmdet.registry import MODELS The provided code snippet includes necessary dependencies for implementing the `distribution_focal_loss` function. Write a Python functi...
r"""Distribution Focal Loss (DFL) is from `Generalized Focal Loss: Learning Qualified and Distributed Bounding Boxes for Dense Object Detection <https://arxiv.org/abs/2006.04388>`_. Args: pred (torch.Tensor): Predicted general distribution of bounding boxes (before softmax) with shape (N, n+1), n is the max value of th...
14,790
from typing import Optional import torch.nn as nn import torch.nn.functional as F from torch import Tensor from mmdet.registry import MODELS from .utils import weight_reduce_loss def weight_reduce_loss(loss: Tensor, weight: Optional[Tensor] = None, reduction: str = 'mean',...
`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: pred (Tensor): The prediction with shape (N, C), C is the number of classes. target (Tensor): The learning target of the iou-aware classification score with shape (N, C), C is the number of classes. weight (Tensor, optional): The weight of loss for each predict...
14,791
from typing import Optional import torch.nn as nn import torch.nn.functional as F from torch import Tensor from mmdet.registry import MODELS from .utils import weighted_loss The provided code snippet includes necessary dependencies for implementing the `knowledge_distillation_kl_div_loss` function. Write a Python func...
r"""Loss function for knowledge distilling using KL divergence. Args: pred (Tensor): Predicted logits with shape (N, n + 1). soft_label (Tensor): Target logits with shape (N, N + 1). T (int): Temperature for distillation. detach_target (bool): Remove soft_label from automatic differentiation Returns: Tensor: Loss tenso...
14,792
import torch import torch.nn as nn import torch.nn.functional as F from mmdet.registry import MODELS from .utils import weight_reduce_loss def _expand_onehot_labels(labels, label_weights, label_channels): bin_labels = labels.new_full((labels.size(0), label_channels), 0) inds = torch.nonzero( (labels >=...
null
14,793
import numpy as np import torch import torch.nn as nn from mmdet.registry import MODELS from .utils import weighted_loss The provided code snippet includes necessary dependencies for implementing the `balanced_l1_loss` function. Write a Python function `def balanced_l1_loss(pred, target, ...
Calculate balanced L1 loss. Please see the `Libra R-CNN <https://arxiv.org/pdf/1904.02701.pdf>`_ Args: pred (torch.Tensor): The prediction with shape (N, 4). target (torch.Tensor): The learning target of the prediction with shape (N, 4). beta (float): The loss is a piecewise function of prediction and target and ``beta...
14,794
import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `accuracy` function. Write a Python function `def accuracy(pred, target, topk=1, thresh=None)` to solve the following problem: Calculate accuracy according to the prediction and target. Args: pred (torch.Tensor): The m...
Calculate accuracy according to the prediction and target. Args: pred (torch.Tensor): The model prediction, shape (N, num_class) target (torch.Tensor): The target of each prediction, shape (N, ) topk (int | tuple[int], optional): If the predictions in ``topk`` matches the target, the predictions will be regarded as cor...
14,795
from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor from mmdet.registry import MODELS from .accuracy import accuracy from .cross_entropy_loss import cross_entropy from .utils import weight_reduce_loss def cross_entropy(pred, ...
Calculate the Seesaw CrossEntropy loss. Args: cls_score (Tensor): The prediction with shape (N, C), C is the number of classes. labels (Tensor): The learning label of the prediction. label_weights (Tensor): Sample-wise loss weight. cum_samples (Tensor): Cumulative samples for each category. num_classes (int): The numbe...
14,796
import math import warnings from typing import Optional import torch import torch.nn as nn from torch import Tensor from mmdet.registry import MODELS from mmdet.structures.bbox import bbox_overlaps from .utils import weighted_loss The provided code snippet includes necessary dependencies for implementing the `iou_loss...
IoU loss. Computing the IoU loss between a set of predicted bboxes and target bboxes. The loss is calculated as negative log of IoU. Args: pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2), shape (n, 4). target (Tensor): Corresponding gt bboxes, shape (n, 4). linear (bool, optional): If True, use linear scale ...
14,797
import math import warnings from typing import Optional import torch import torch.nn as nn from torch import Tensor from mmdet.registry import MODELS from mmdet.structures.bbox import bbox_overlaps from .utils import weighted_loss The provided code snippet includes necessary dependencies for implementing the `bounded_...
BIoULoss. This is an implementation of paper `Improving Object Localization with Fitness NMS and Bounded IoU Loss. <https://arxiv.org/abs/1711.00164>`_. Args: pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2), shape (n, 4). target (Tensor): Corresponding gt bboxes, shape (n, 4). beta (float, optional): Beta pa...
14,798
import math import warnings from typing import Optional import torch import torch.nn as nn from torch import Tensor from mmdet.registry import MODELS from mmdet.structures.bbox import bbox_overlaps from .utils import weighted_loss The provided code snippet includes necessary dependencies for implementing the `giou_los...
r"""`Generalized Intersection over Union: A Metric and A Loss for Bounding Box Regression <https://arxiv.org/abs/1902.09630>`_. Args: pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2), shape (n, 4). target (Tensor): Corresponding gt bboxes, shape (n, 4). eps (float): Epsilon to avoid log(0). Return: Tensor: Lo...
14,799
import math import warnings from typing import Optional import torch import torch.nn as nn from torch import Tensor from mmdet.registry import MODELS from mmdet.structures.bbox import bbox_overlaps from .utils import weighted_loss The provided code snippet includes necessary dependencies for implementing the `diou_los...
r"""Implementation of `Distance-IoU Loss: Faster and Better Learning for Bounding Box Regression https://arxiv.org/abs/1911.08287`_. Code is modified from https://github.com/Zzh-tju/DIoU. Args: pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2), shape (n, 4). target (Tensor): Corresponding gt bboxes, shape (n, ...
14,800
import math import warnings from typing import Optional import torch import torch.nn as nn from torch import Tensor from mmdet.registry import MODELS from mmdet.structures.bbox import bbox_overlaps from .utils import weighted_loss The provided code snippet includes necessary dependencies for implementing the `ciou_los...
r"""`Implementation of paper `Enhancing Geometric Factors into Model Learning and Inference for Object Detection and Instance Segmentation <https://arxiv.org/abs/2005.03572>`_. Code is modified from https://github.com/Zzh-tju/CIoU. Args: pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2), shape (n, 4). target (...
14,801
import math import warnings from typing import Optional import torch import torch.nn as nn from torch import Tensor from mmdet.registry import MODELS from mmdet.structures.bbox import bbox_overlaps from .utils import weighted_loss The provided code snippet includes necessary dependencies for implementing the `eiou_los...
r"""Implementation of paper `Extended-IoU Loss: A Systematic IoU-Related Method: Beyond Simplified Regression for Better Localization <https://ieeexplore.ieee.org/abstract/document/9429909>`_ Code is modified from https://github.com//ShiqiYu/libfacedetection.train. Args: pred (Tensor): Predicted bboxes of format (x1, y...
14,802
import torch import torch.nn as nn from mmdet.registry import MODELS from .utils import weight_reduce_loss def weight_reduce_loss(loss: Tensor, weight: Optional[Tensor] = None, reduction: str = 'mean', avg_factor: Optional[float] = None) -> Tensor: ...
Calculate dice loss, there are two forms of dice loss is supported: - the one proposed in `V-Net: Fully Convolutional Neural Networks for Volumetric Medical Image Segmentation <https://arxiv.org/abs/1606.04797>`_. - the dice loss in which the power of the number in the denominator is the first power instead of the seco...
14,803
import warnings import torch import torch.nn as nn import torch.nn.functional as F from mmdet.registry import MODELS from .utils import weight_reduce_loss def _expand_onehot_labels(labels, label_weights, label_channels, ignore_index): """Expand onehot labels to match the size of prediction.""" bin_labels = labe...
Calculate the binary CrossEntropy loss. Args: pred (torch.Tensor): The prediction with shape (N, 1) or (N, ). When the shape of pred is (N, 1), label will be expanded to one-hot format, and when the shape of pred is (N, ), label will not be expanded to one-hot format. label (torch.Tensor): The learning label of the pre...
14,804
import warnings import torch import torch.nn as nn import torch.nn.functional as F from mmdet.registry import MODELS from .utils import weight_reduce_loss The provided code snippet includes necessary dependencies for implementing the `mask_cross_entropy` function. Write a Python function `def mask_cross_entropy(pred, ...
Calculate the CrossEntropy loss for masks. Args: pred (torch.Tensor): The prediction with shape (N, C, *), C is the number of classes. The trailing * indicates arbitrary shape. target (torch.Tensor): The learning label of the prediction. label (torch.Tensor): ``label`` indicates the class label of the mask correspondin...
14,805
from typing import Optional, Union import torch.nn as nn from torch import Tensor from mmdet.registry import MODELS from .utils import weight_reduce_loss, weighted_loss The provided code snippet includes necessary dependencies for implementing the `gaussian_focal_loss` function. Write a Python function `def gaussian_f...
`Focal Loss <https://arxiv.org/abs/1708.02002>`_ for targets in gaussian distribution. Args: pred (torch.Tensor): The prediction. gaussian_target (torch.Tensor): The learning target of the prediction in gaussian distribution. alpha (float, optional): A balanced form for Focal Loss. Defaults to 2.0. gamma (float, option...
14,806
from typing import Optional, Union import torch.nn as nn from torch import Tensor from mmdet.registry import MODELS from .utils import weight_reduce_loss, weighted_loss def weight_reduce_loss(loss: Tensor, weight: Optional[Tensor] = None, reduction: str = 'mean', ...
`Focal Loss <https://arxiv.org/abs/1708.02002>`_ for targets in gaussian distribution. Note: The index with a value of 1 in ``gaussian_target`` in the ``gaussian_focal_loss`` function is a positive sample, but in ``gaussian_focal_loss_with_pos_inds`` the positive sample is passed in through the ``pos_inds`` parameter. ...
14,807
from typing import Optional, Tuple, Union import torch from mmcv.ops.nms import batched_nms from torch import Tensor from mmdet.structures.bbox import bbox_overlaps from mmdet.utils import ConfigType The provided code snippet includes necessary dependencies for implementing the `multiclass_nms` function. Write a Pytho...
NMS for multi-class bboxes. Args: multi_bboxes (Tensor): shape (n, #class*4) or (n, 4) multi_scores (Tensor): shape (n, #class), where the last column contains scores of the background class, but this will be ignored. score_thr (float): bbox threshold, bboxes with scores lower than it will not be considered. nms_cfg (U...
14,808
from typing import Optional, Tuple, Union import torch from mmcv.ops.nms import batched_nms from torch import Tensor from mmdet.structures.bbox import bbox_overlaps from mmdet.utils import ConfigType The provided code snippet includes necessary dependencies for implementing the `fast_nms` function. Write a Python func...
Fast NMS in `YOLACT <https://arxiv.org/abs/1904.02689>`_. Fast NMS allows already-removed detections to suppress other detections so that every instance can be decided to be kept or discarded in parallel, which is not possible in traditional NMS. This relaxation allows us to implement Fast NMS entirely in standard GPU-...
14,809
import torch The provided code snippet includes necessary dependencies for implementing the `mask_matrix_nms` function. Write a Python function `def mask_matrix_nms(masks, labels, scores, filter_thr=-1, nms_pre=-1, max_...
Matrix NMS for multi-class masks. Args: masks (Tensor): Has shape (num_instances, h, w) labels (Tensor): Labels of corresponding masks, has shape (num_instances,). scores (Tensor): Mask scores of corresponding masks, has shape (num_instances). filter_thr (float): Score threshold to filter the masks after matrix nms. De...
14,810
import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn.bricks.wrappers import NewEmptyTensorOp, obsolete_torch_version The provided code snippet includes necessary dependencies for implementing the `adaptive_avg_pool2d` function. Write a Python function `def adaptive_avg_pool2d(input, output_...
Handle empty batch dimension to adaptive_avg_pool2d. Args: input (tensor): 4D tensor. output_size (int, tuple[int,int]): the target output size.
14,811
import math import warnings from typing import Optional, Sequence, Tuple, Union import torch import torch.nn.functional as F from mmcv.cnn import (Linear, build_activation_layer, build_conv_layer, build_norm_layer) from mmcv.cnn.bricks.drop import Dropout from mmengine.model import BaseModule, Mod...
Convert [N, L, C] shape tensor to [N, C, H, W] shape tensor. Args: x (Tensor): The input tensor of shape [N, L, C] before conversion. hw_shape (Sequence[int]): The height and width of output feature map. Returns: Tensor: The output tensor of shape [N, C, H, W] after conversion.
14,812
import math import warnings from typing import Optional, Sequence, Tuple, Union import torch import torch.nn.functional as F from mmcv.cnn import (Linear, build_activation_layer, build_conv_layer, build_norm_layer) from mmcv.cnn.bricks.drop import Dropout from mmengine.model import BaseModule, Mod...
Flatten [N, C, H, W] shape tensor to [N, L, C] shape tensor. Args: x (Tensor): The input tensor of shape [N, C, H, W] before conversion. Returns: Tensor: The output tensor of shape [N, L, C] after conversion.
14,813
import math import warnings from typing import Optional, Sequence, Tuple, Union import torch import torch.nn.functional as F from mmcv.cnn import (Linear, build_activation_layer, build_conv_layer, build_norm_layer) from mmcv.cnn.bricks.drop import Dropout from mmengine.model import BaseModule, Mod...
Convert coordinate tensor to positional encoding. Args: coord_tensor (Tensor): Coordinate tensor to be converted to positional encoding. With the last dimension as 2 or 4. num_feats (int, optional): The feature dimension for each position along x-axis or y-axis. Note the final returned dimension for each position is 2 ...
14,814
import math import warnings from typing import Optional, Sequence, Tuple, Union import torch import torch.nn.functional as F from mmcv.cnn import (Linear, build_activation_layer, build_conv_layer, build_norm_layer) from mmcv.cnn.bricks.drop import Dropout from mmengine.model import BaseModule, Mod...
Inverse function of sigmoid. Args: x (Tensor): The tensor to do the inverse. eps (float): EPS avoid numerical overflow. Defaults 1e-5. Returns: Tensor: The x has passed the inverse function of sigmoid, has the same shape with input.
14,815
from typing import Dict, List, Optional, Sequence, Tuple import torch import torch.nn as nn from mmcv.cnn import Scale from mmengine.structures import InstanceData from torch import Tensor from mmdet.registry import MODELS from mmdet.structures.bbox import bbox2distance from mmdet.utils import (ConfigType, InstanceList...
This function is used to transpose image first tensors to level first ones.
14,816
import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from timm.models.registry import register_model from timm.models.vision_transformer import _cfg from mmdet.vtpack.layers import DynamicGrainedEncoder from mm...
convert patch embedding weight from manual patchify + linear proj to conv
14,817
import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from timm.models.registry import register_model from timm.models.vision_transformer import _cfg from mmdet.vtpack.layers import DynamicGrainedEncoder from mm...
null
14,818
import time import warnings from collections import OrderedDict from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as cp from mmcv.cnn import build_norm_layer from mmengine.model.weight_init import (constant_init, trunc_normal_, ...
null
14,819
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as cp from mmcv.cnn import build_conv_layer, build_norm_layer from mmengine.model import BaseModule from torch.nn.modules.utils import _pair from mmdet.models.backbones.resnet import Bottleneck, ResNet from mmdet.registry i...
Build Trident Res Layers.
14,820
import copy import math from functools import partial import torch import torch.nn as nn import torch.utils.checkpoint as cp from mmcv.cnn.bricks import ConvModule, DropPath from mmengine.model import BaseModule, Sequential from mmdet.registry import MODELS from ..layers import InvertedResidual, SELayer from ..utils im...
Scaling operation to the layer's parameters according to the arch_setting.
14,821
import warnings from collections import OrderedDict from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as cp from mmcv.cnn import build_norm_layer from mmcv.cnn.bricks.transformer import FFN, build_dropout from mmengine.logging import MMLogger from...
null
14,822
import math import warnings from collections import OrderedDict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import Conv2d, build_activation_layer, build_norm_layer from mmcv.cnn.bricks.drop import build_dropout from mmcv.cnn.bricks.transformer import MultiheadAtte...
null
14,823
import time import warnings from collections import OrderedDict from copy import deepcopy from typing import Any, Callable, List, Optional, Type, Union from torch import Tensor import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as cp from mmcv.cnn import build_norm_layer fr...
3x3 convolution with padding
14,824
import time import warnings from collections import OrderedDict from copy import deepcopy from typing import Any, Callable, List, Optional, Type, Union from torch import Tensor import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as cp from mmcv.cnn import build_norm_layer fr...
1x1 convolution
14,825
from typing import Optional, Tuple import torch from mmengine.structures import InstanceData from torch import Tensor from mmdet.registry import TASK_UTILS from mmdet.utils import ConfigType from .assign_result import AssignResult from .base_assigner import BaseAssigner The provided code snippet includes necessary dep...
Expand an array of boxes by a given scale. Args: bboxes (Tensor): Shape (m, 4) scale (float): The scale factor of bboxes Returns: Tensor: Shape (m, 4). Scaled bboxes
14,826
from typing import Optional, Tuple import torch from mmengine.structures import InstanceData from torch import Tensor from mmdet.registry import TASK_UTILS from mmdet.utils import ConfigType from .assign_result import AssignResult from .base_assigner import BaseAssigner The provided code snippet includes necessary dep...
Are points located in bboxes. Args: points (Tensor): Points, shape: (m, 2). bboxes (Tensor): Bounding boxes, shape: (n, 4). Return: Tensor: Flags indicating if points are located in bboxes, shape: (m, n).
14,827
from typing import Optional, Tuple import torch from mmengine.structures import InstanceData from torch import Tensor from mmdet.registry import TASK_UTILS from mmdet.utils import ConfigType from .assign_result import AssignResult from .base_assigner import BaseAssigner The provided code snippet includes necessary dep...
Compute the area of an array of bboxes. Args: bboxes (Tensor): The coordinates ox bboxes. Shape: (m, 4) Returns: Tensor: Area of the bboxes. Shape: (m, )
14,828
import warnings from typing import List, Optional import torch from mmengine.structures import InstanceData from torch import Tensor from mmdet.registry import TASK_UTILS from mmdet.utils import ConfigType from .assign_result import AssignResult from .base_assigner import BaseAssigner The provided code snippet include...
Compute the center distance between bboxes and priors. Args: bboxes (Tensor): Shape (n, 4) for , "xyxy" format. priors (Tensor): Shape (n, 4) for priors, "xyxy" format. Returns: Tensor: Center distances between bboxes and priors.
14,829
from typing import Optional, Tuple import torch import torch.nn.functional as F from mmengine.structures import InstanceData from torch import Tensor from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import BaseBoxes from mmdet.utils import ConfigType from .assign_result import AssignResult from .base_as...
Compute the masks center of mass. Args: masks: Mask tensor, has shape (num_masks, H, W). eps: a small number to avoid normalizer to be zero. Defaults to 1e-7. Returns: Tensor: The masks center of mass. Has shape (num_masks, 2).
14,830
from typing import List, Optional, Tuple import torch from mmengine.structures import InstanceData from torch import Tensor from mmdet.registry import TASK_UTILS from ..prior_generators import anchor_inside_flags from .assign_result import AssignResult from .base_assigner import BaseAssigner The provided code snippet ...
Calculate region of the box defined by the ratio, the ratio is from the center of the box to every edge.
14,831
from typing import List, Optional, Tuple import torch from mmengine.structures import InstanceData from torch import Tensor from mmdet.registry import TASK_UTILS from ..prior_generators import anchor_inside_flags from .assign_result import AssignResult from .base_assigner import BaseAssigner The provided code snippet ...
Get the flag indicate whether anchor centers are inside regions.
14,832
import torch from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import bbox_overlaps, get_box_tensor def cast_tensor_type(x, scale=1., dtype=None): if dtype == 'fp16': # scale is for preventing overflows x = (x / scale).half() return x
null
14,833
from typing import Optional, Tuple import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes The provided code snippet includes necessary dependencies for implementing the `anchor_inside_flags` function. Write a Python function `def anchor_inside_flags(flat_anchors: Tensor, ...
Check whether the anchors are inside the border. Args: flat_anchors (torch.Tensor): Flatten anchors, shape (n, 4). valid_flags (torch.Tensor): An existing valid flags of anchors. img_shape (tuple(int)): Shape of current image. allowed_border (int): The border to allow the valid anchor. Defaults to 0. Returns: torch.Ten...
14,834
from typing import Optional, Tuple import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes The provided code snippet includes necessary dependencies for implementing the `calc_region` function. Write a Python function `def calc_region(bbox: Tensor, ratio: float, ...
Calculate a proportional bbox region. The bbox center are fixed and the new h' and w' is h * ratio and w * ratio. Args: bbox (Tensor): Bboxes to calculate regions, shape (n, 4). ratio (float): Ratio of the output region. featmap_size (tuple, Optional): Feature map size in (height, width) order used for clipping the bou...
14,835
import warnings import numpy as np import torch from torch import Tensor from mmdet.structures.bbox import BaseBoxes, cat_boxes from mmdet.utils import util_mixins from mmdet.utils.util_random import ensure_rng from ..assigners import AssignResult The provided code snippet includes necessary dependencies for implement...
Simple version of ``kwimage.Boxes.random`` Returns: Tensor: shape (n, 4) in x1, y1, x2, y2 format. References: https://gitlab.kitware.com/computer-vision/kwimage/blob/master/kwimage/structs/boxes.py#L1390 Example: >>> num = 3 >>> scale = 512 >>> rng = 0 >>> boxes = random_boxes(num, scale, rng) >>> print(boxes) tensor(...
14,836
import numpy as np import torch import torch.nn.functional as F from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import HorizontalBoxes, bbox_rescale, get_box_tensor from .base_bbox_coder import BaseBBoxCoder def generat_buckets(proposals, num_buckets, scale_factor=1.0): """Generate buckets w.r.t bu...
Generate buckets estimation and fine regression targets. Args: proposals (Tensor): Shape (n, 4) gt (Tensor): Shape (n, 4) num_buckets (int): Number of buckets. scale_factor (float): Scale factor to rescale proposals. offset_topk (int): Topk buckets are used to generate bucket fine regression targets. Defaults to 2. off...
14,837
import numpy as np import torch import torch.nn.functional as F from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import HorizontalBoxes, bbox_rescale, get_box_tensor from .base_bbox_coder import BaseBBoxCoder The provided code snippet includes necessary dependencies for implementing the `bucket2bbox` f...
Apply bucketing estimation (cls preds) and fine regression (offset preds) to generate det bboxes. Args: proposals (Tensor): Boxes to be transformed. Shape (n, 4) cls_preds (Tensor): bucketing estimation. Shape (n, num_buckets*2). offset_preds (Tensor): fine regression. Shape (n, num_buckets*2). num_buckets (int): Numbe...
14,838
import warnings import numpy as np import torch from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import HorizontalBoxes, get_box_tensor from .base_bbox_coder import BaseBBoxCoder The provided code snippet includes necessary dependencies for implementing the `bbox2delta` function. Write a Python functio...
Compute deltas of proposals w.r.t. gt. We usually compute the deltas of x, y, w, h of proposals w.r.t ground truth bboxes to get regression target. This is the inverse function of :func:`delta2bbox`. Args: proposals (Tensor): Boxes to be transformed, shape (N, ..., 4) gt (Tensor): Gt bboxes to be used as base, shape (N...
14,839
import warnings import numpy as np import torch from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import HorizontalBoxes, get_box_tensor from .base_bbox_coder import BaseBBoxCoder The provided code snippet includes necessary dependencies for implementing the `delta2bbox` function. Write a Python functio...
Apply deltas to shift/scale base boxes. Typically the rois are anchor or proposed bounding boxes and the deltas are network outputs used to shift/scale those boxes. This is the inverse function of :func:`bbox2delta`. Args: rois (Tensor): Boxes to be transformed. Has shape (N, 4). deltas (Tensor): Encoded offsets relati...
14,840
import warnings import numpy as np import torch from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import HorizontalBoxes, get_box_tensor from .base_bbox_coder import BaseBBoxCoder The provided code snippet includes necessary dependencies for implementing the `onnx_delta2bbox` function. Write a Python fu...
Apply deltas to shift/scale base boxes. Typically the rois are anchor or proposed bounding boxes and the deltas are network outputs used to shift/scale those boxes. This is the inverse function of :func:`bbox2delta`. Args: rois (Tensor): Boxes to be transformed. Has shape (N, 4) or (B, N, 4) deltas (Tensor): Encoded of...
14,841
import torch from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import HorizontalBoxes, get_box_tensor from .base_bbox_coder import BaseBBoxCoder The provided code snippet includes necessary dependencies for implementing the `bboxes2tblr` function. Write a Python function `def bboxes2tblr(priors, gts, no...
Encode ground truth boxes to tblr coordinate. It first convert the gt coordinate to tblr format, (top, bottom, left, right), relative to prior box centers. The tblr coordinate may be normalized by the side length of prior bboxes if `normalize_by_wh` is specified as True, and it is then normalized by the `normalizer` fa...
14,842
import torch from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import HorizontalBoxes, get_box_tensor from .base_bbox_coder import BaseBBoxCoder The provided code snippet includes necessary dependencies for implementing the `tblr2bboxes` function. Write a Python function `def tblr2bboxes(priors, ...
Decode tblr outputs to prediction boxes. The process includes 3 steps: 1) De-normalize tblr coordinates by multiplying it with `normalizer`; 2) De-normalize tblr coordinates by the prior bbox width and height if `normalize_by_wh` is `True`; 3) Convert tblr (top, bottom, left, right) pair relative to the center of prior...
14,843
import numpy as np import torch from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import HorizontalBoxes, get_box_tensor from .base_bbox_coder import BaseBBoxCoder The provided code snippet includes necessary dependencies for implementing the `legacy_bbox2delta` function. Write a Python function `def le...
Compute deltas of proposals w.r.t. gt in the MMDet V1.x manner. We usually compute the deltas of x, y, w, h of proposals w.r.t ground truth bboxes to get regression target. This is the inverse function of `delta2bbox()` Args: proposals (Tensor): Boxes to be transformed, shape (N, ..., 4) gt (Tensor): Gt bboxes to be us...
14,844
import numpy as np import torch from mmdet.registry import TASK_UTILS from mmdet.structures.bbox import HorizontalBoxes, get_box_tensor from .base_bbox_coder import BaseBBoxCoder The provided code snippet includes necessary dependencies for implementing the `legacy_delta2bbox` function. Write a Python function `def le...
Apply deltas to shift/scale base boxes in the MMDet V1.x manner. Typically the rois are anchor or proposed bounding boxes and the deltas are network outputs used to shift/scale those boxes. This is the inverse function of `bbox2delta()` Args: rois (Tensor): Boxes to be transformed. Has shape (N, 4) deltas (Tensor): Enc...
14,845
import warnings from mmdet.registry import TASK_UTILS The provided code snippet includes necessary dependencies for implementing the `build_bbox_coder` function. Write a Python function `def build_bbox_coder(cfg, **default_args)` to solve the following problem: Builder of box coder. Here is the function: def build_b...
Builder of box coder.
14,846
import warnings from mmdet.registry import TASK_UTILS The provided code snippet includes necessary dependencies for implementing the `build_iou_calculator` function. Write a Python function `def build_iou_calculator(cfg, default_args=None)` to solve the following problem: Builder of IoU calculator. Here is the functi...
Builder of IoU calculator.
14,847
import warnings from mmdet.registry import TASK_UTILS The provided code snippet includes necessary dependencies for implementing the `build_match_cost` function. Write a Python function `def build_match_cost(cfg, default_args=None)` to solve the following problem: Builder of IoU calculator. Here is the function: def...
Builder of IoU calculator.
14,848
import warnings from mmdet.registry import TASK_UTILS The provided code snippet includes necessary dependencies for implementing the `build_assigner` function. Write a Python function `def build_assigner(cfg, **default_args)` to solve the following problem: Builder of box assigner. Here is the function: def build_as...
Builder of box assigner.
14,849
import warnings from mmdet.registry import TASK_UTILS The provided code snippet includes necessary dependencies for implementing the `build_sampler` function. Write a Python function `def build_sampler(cfg, **default_args)` to solve the following problem: Builder of box sampler. Here is the function: def build_sampl...
Builder of box sampler.
14,850
import warnings from mmdet.registry import TASK_UTILS def build_prior_generator(cfg, default_args=None): warnings.warn( '``build_prior_generator`` would be deprecated soon, please use ' '``mmdet.registry.TASK_UTILS.build()`` ') return TASK_UTILS.build(cfg, default_args=default_args)
null
14,851
import warnings from mmdet.registry import TASK_UTILS def build_anchor_generator(cfg, default_args=None): warnings.warn( '``build_anchor_generator`` would be deprecated soon, please use ' '``mmdet.registry.TASK_UTILS.build()`` ') return TASK_UTILS.build(cfg, default_args=default_args)
null
14,852
from typing import List, Tuple import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule, build_conv_layer, build_upsample_layer from mmcv.ops.carafe import CARAFEPack from mmengine.config import ConfigDict from mmengine.model import BaseModule, ModuleList fro...
Paste instance masks according to boxes. This implementation is modified from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N, 1, H, W boxes (Tensor): N, 4 img_h (int): Height of the image to be pasted. img_w (int): Width of the image to be pasted. skip_empty (bool): Only paste masks within the ...
14,853
from typing import Union from mmengine.config import ConfigDict from mmengine.structures import InstanceData from torch import Tensor from mmdet.registry import MODELS from mmdet.structures import SampleList from mmdet.structures.bbox import BaseBoxes from mmdet.structures.mask import BitmapMasks, PolygonMasks from mmd...
Convert the key and value of mmengine.ConfigDict into a list. Args: cfg (ConfigDict): The detectron2 model config. config_list (list): A list contains the key and value of ConfigDict. Defaults to []. father_name (str): The father name add before the key. Defaults to "MODEL". Returns: tuple: - config_list: A list contai...
14,854
from typing import Union from mmengine.config import ConfigDict from mmengine.structures import InstanceData from torch import Tensor from mmdet.registry import MODELS from mmdet.structures import SampleList from mmdet.structures.bbox import BaseBoxes from mmdet.structures.mask import BitmapMasks, PolygonMasks from mmd...
Convert the Detectron2's result to DetDataSample. Args: data_samples (list[:obj:`DetDataSample`]): The batch data samples. It usually includes information such as `gt_instance` or `gt_panoptic_seg` or `gt_sem_seg`. d2_results_list (list): The list of the results of Detectron2's model. Returns: list[:obj:`DetDataSample`...
14,855
from functools import partial from typing import List, Sequence, Tuple, Union import numpy as np import torch from mmengine.structures import InstanceData from mmengine.utils import digit_version from six.moves import map, zip from torch import Tensor from torch.autograd import Function from torch.nn import functional ...
Interpolate the `source` to the shape of the `target`. The `source` must be a Tensor, but the `target` can be a Tensor or a np.ndarray with the shape (..., target_h, target_w). Args: source (Tensor): A 3D/4D Tensor with the shape (N, H, W) or (N, C, H, W). target (Tensor | np.ndarray): The interpolation target with the...