id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
34,217
import torch import torch.nn.functional as F from scipy.optimize import linear_sum_assignment from torch import nn from torch.cuda.amp import autocast import numpy as np def linear_sum_assignment_with_nan(cost_matrix): cost_matrix = np.asarray(cost_matrix) nan = np.isnan(cost_matrix).any() nan_all = np.isn...
null
34,218
import torch import torch.nn.functional as F from scipy.optimize import linear_sum_assignment from torch import nn from torch.cuda.amp import autocast import numpy as np The provided code snippet includes necessary dependencies for implementing the `batch_dice_loss` function. Write a Python function `def batch_dice_lo...
Compute the DICE loss, similar to generalized IOU for masks Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class).
34,219
import torch import torch.nn.functional as F from scipy.optimize import linear_sum_assignment from torch import nn from torch.cuda.amp import autocast import numpy as np The provided code snippet includes necessary dependencies for implementing the `batch_sigmoid_ce_loss` function. Write a Python function `def batch_s...
Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class). Returns: Loss tensor
34,220
import logging import numpy as np from typing import Callable, Dict, List, Optional, Tuple, Union import fvcore.nn.weight_init as weight_init import torch from torch import nn from torch.nn import functional as F from torch.nn.init import xavier_uniform_, constant_, uniform_, normal_ from torch.cuda.amp import autocast...
Build a pixel decoder from `cfg.MODEL.MASK_FORMER.PIXEL_DECODER_NAME`.
34,221
from __future__ import absolute_import from __future__ import print_function from __future__ import division import warnings import math import torch from torch import nn import torch.nn.functional as F from torch.nn.init import xavier_uniform_, constant_ from ..functions.ms_deform_attn_func import ms_deform_attn_core_...
null
34,222
import os import glob import torch from torch.utils.cpp_extension import CUDA_HOME from torch.utils.cpp_extension import CppExtension from torch.utils.cpp_extension import CUDAExtension from setuptools import find_packages from setuptools import setup def get_extensions(): this_dir = os.path.dirname(os.path.abspat...
null
34,223
from __future__ import absolute_import from __future__ import print_function from __future__ import division import torch import torch.nn.functional as F from torch.autograd import Function from torch.autograd.function import once_differentiable def ms_deform_attn_core_pytorch(value, value_spatial_shapes, sampling_loc...
null
34,224
from annotator.oneformer.detectron2.config import CfgNode as CN The provided code snippet includes necessary dependencies for implementing the `add_common_config` function. Write a Python function `def add_common_config(cfg)` to solve the following problem: Add config for common configuration Here is the function: d...
Add config for common configuration
34,225
from annotator.oneformer.detectron2.config import CfgNode as CN The provided code snippet includes necessary dependencies for implementing the `add_oneformer_config` function. Write a Python function `def add_oneformer_config(cfg)` to solve the following problem: Add config for ONE_FORMER. Here is the function: def ...
Add config for ONE_FORMER.
34,226
from annotator.oneformer.detectron2.config import CfgNode as CN The provided code snippet includes necessary dependencies for implementing the `add_swin_config` function. Write a Python function `def add_swin_config(cfg)` to solve the following problem: Add config forSWIN Backbone. Here is the function: def add_swin...
Add config forSWIN Backbone.
34,227
from annotator.oneformer.detectron2.config import CfgNode as CN The provided code snippet includes necessary dependencies for implementing the `add_dinat_config` function. Write a Python function `def add_dinat_config(cfg)` to solve the following problem: Add config for NAT Backbone. Here is the function: def add_di...
Add config for NAT Backbone.
34,228
from annotator.oneformer.detectron2.config import CfgNode as CN The provided code snippet includes necessary dependencies for implementing the `add_convnext_config` function. Write a Python function `def add_convnext_config(cfg)` to solve the following problem: Add config for ConvNeXt Backbone. Here is the function: ...
Add config for ConvNeXt Backbone.
34,229
from annotator.oneformer.detectron2.config import CfgNode as CN The provided code snippet includes necessary dependencies for implementing the `add_beit_adapter_config` function. Write a Python function `def add_beit_adapter_config(cfg)` to solve the following problem: Add config for BEiT Adapter Backbone. Here is th...
Add config for BEiT Adapter Backbone.
34,231
import contextlib import copy import io import itertools import json import logging import numpy as np import os import pickle from collections import OrderedDict import annotator.oneformer.pycocotools.mask as mask_util import torch from annotator.oneformer.pycocotools.coco import COCO from annotator.oneformer.pycocoto...
Dump an "Instances" object to a COCO-format json that's used for evaluation. Args: instances (Instances): img_id (int): the image id Returns: list[dict]: list of json annotations in COCO format.
34,232
import contextlib import copy import io import itertools import json import logging import numpy as np import os import pickle from collections import OrderedDict import annotator.oneformer.pycocotools.mask as mask_util import torch from annotator.oneformer.pycocotools.coco import COCO from annotator.oneformer.pycocoto...
Evaluate the coco results using COCOEval API.
34,235
import contextlib import copy import io import itertools import json import logging import numpy as np import os import pickle from collections import OrderedDict import annotator.oneformer.pycocotools.mask as mask_util import torch from annotator.oneformer.pycocotools.coco import COCO from annotator.oneformer.pycocoto...
Evaluate the coco results using COCOEval API.
34,236
import numpy as np import random random.seed(0) _COLORS = [] def gen_color(): color = tuple(np.round(np.random.choice(range(256), size=3)/255, 3)) if color not in _COLORS and np.mean(color) != 0.0: _COLORS.append(color) else: gen_color()
null
34,237
import numpy as np import random _COLORS = [] The provided code snippet includes necessary dependencies for implementing the `colormap` function. Write a Python function `def colormap(rgb=False, maximum=255)` to solve the following problem: Args: rgb (bool): whether to return RGB colors or BGR colors. maximum (int): e...
Args: rgb (bool): whether to return RGB colors or BGR colors. maximum (int): either 255 or 1 Returns: ndarray: a float32 array of Nx3 colors, in range [0, 255] or [0, 1]
34,238
import numpy as np import random random.seed(0) _COLORS = [] The provided code snippet includes necessary dependencies for implementing the `random_color` function. Write a Python function `def random_color(rgb=False, maximum=255)` to solve the following problem: Args: rgb (bool): whether to return RGB colors or BGR c...
Args: rgb (bool): whether to return RGB colors or BGR colors. maximum (int): either 255 or 1 Returns: ndarray: a vector of 3 numbers
34,239
import numpy as np import random random.seed(0) _COLORS = [] The provided code snippet includes necessary dependencies for implementing the `random_colors` function. Write a Python function `def random_colors(N, rgb=False, maximum=255)` to solve the following problem: Args: N (int): number of unique colors needed rgb ...
Args: N (int): number of unique colors needed rgb (bool): whether to return RGB colors or BGR colors. maximum (int): either 255 or 1 Returns: ndarray: a list of random_color
34,240
import colorsys import logging import math import numpy as np from enum import Enum, unique import cv2 import matplotlib as mpl import matplotlib.colors as mplc import matplotlib.figure as mplfigure import annotator.oneformer.pycocotools.mask as mask_util import torch from matplotlib.backends.backend_agg import FigureC...
Args: rgb (bool): whether to return RGB colors or BGR colors. maximum (int): either 255 or 1 Returns: ndarray: a vector of 3 numbers
34,241
import colorsys import logging import math import numpy as np from enum import Enum, unique import cv2 import matplotlib as mpl import matplotlib.colors as mplc import matplotlib.figure as mplfigure import annotator.oneformer.pycocotools.mask as mask_util import torch from matplotlib.backends.backend_agg import FigureC...
Args: classes (list[int] or None): scores (list[float] or None): class_names (list[str] or None): is_crowd (list[bool] or None): Returns: list[str] or None
34,242
import os import wandb from annotator.oneformer.detectron2.utils import comm from annotator.oneformer.detectron2.utils.events import EventWriter, get_event_storage import os os.environ['IGNORE_CMD_ARGS_ERRORS'] = 'True' def setup_wandb(cfg, args): if comm.is_main_process(): init_args = { k...
null
34,243
import torch, os from torchvision.ops.boxes import box_area try: import torch except ImportError: __all__ = [ 'Config', 'ConfigDict', 'DictAction', 'is_str', 'iter_cast', 'list_cast', 'tuple_cast', 'is_seq_of', 'is_list_of', 'is_tuple_of', 'slice_list', 'concat_list', 'check_prerequisit...
null
34,244
import torch, os from torchvision.ops.boxes import box_area try: import torch except ImportError: __all__ = [ 'Config', 'ConfigDict', 'DictAction', 'is_str', 'iter_cast', 'list_cast', 'tuple_cast', 'is_seq_of', 'is_list_of', 'is_tuple_of', 'slice_list', 'concat_list', 'check_prerequisit...
null
34,245
import torch, os from torchvision.ops.boxes import box_area def box_iou(boxes1, boxes2): area1 = box_area(boxes1) area2 = box_area(boxes2) # import ipdb; ipdb.set_trace() lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2] rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2] w...
Generalized IoU from https://giou.stanford.edu/ The boxes should be in [x0, y0, x1, y1] format Returns a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2)
34,246
import torch, os from torchvision.ops.boxes import box_area def box_iou_pairwise(boxes1, boxes2): area1 = box_area(boxes1) area2 = box_area(boxes2) lt = torch.max(boxes1[:, :2], boxes2[:, :2]) # [N,2] rb = torch.min(boxes1[:, 2:], boxes2[:, 2:]) # [N,2] wh = (rb - lt).clamp(min=0) # [N,2] int...
Generalized IoU from https://giou.stanford.edu/ Input: - boxes1, boxes2: N,4 Output: - giou: N, 4
34,247
import torch, os from torchvision.ops.boxes import box_area try: import torch except ImportError: __all__ = [ 'Config', 'ConfigDict', 'DictAction', 'is_str', 'iter_cast', 'list_cast', 'tuple_cast', 'is_seq_of', 'is_list_of', 'is_tuple_of', 'slice_list', 'concat_list', 'check_prerequisit...
Compute the bounding boxes around the provided masks The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions. Returns a [N, 4] tensors, with the boxes in xyxy format
34,248
from typing import Tuple import numpy as np import torch def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): assert embed_dim % 2 == 0 # use half of dimensions to encode grid_h emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) emb_w = get_1d_sincos_pos_embed_from_grid(...
grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
34,249
from typing import Tuple import numpy as np import torch try: import torch except ImportError: __all__ = [ 'Config', 'ConfigDict', 'DictAction', 'is_str', 'iter_cast', 'list_cast', 'tuple_cast', 'is_seq_of', 'is_list_of', 'is_tuple_of', 'slice_list', 'concat_list', 'check_prerequisites'...
null
34,250
from typing import Tuple import numpy as np import torch try: import torch except ImportError: __all__ = [ 'Config', 'ConfigDict', 'DictAction', 'is_str', 'iter_cast', 'list_cast', 'tuple_cast', 'is_seq_of', 'is_list_of', 'is_tuple_of', 'slice_list', 'concat_list', 'check_prerequisites'...
null
34,251
from typing import List, Optional import torch import torch.distributed as dist import torchvision from torch import Tensor import warnings import torch.nn.functional as F import math try: import torch except ImportError: __all__ = [ 'Config', 'ConfigDict', 'DictAction', 'is_str', 'iter_cast', ...
null
34,252
from typing import List, Optional import torch import torch.distributed as dist import torchvision from torch import Tensor import warnings import torch.nn.functional as F import math def _no_grad_trunc_normal_(tensor, mean, std, a, b): # Cut & paste from PyTorch official master until it's in a few official release...
r"""Fills the input Tensor with values drawn from a truncated normal distribution. The values are effectively drawn from the normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` with values outside :math:`[a, b]` redrawn until they are within the bounds. The method used for generating the random values wo...
34,253
from typing import List, Optional import torch import torch.distributed as dist import torchvision from torch import Tensor import warnings import torch.nn.functional as F import math try: import torch except ImportError: __all__ = [ 'Config', 'ConfigDict', 'DictAction', 'is_str', 'iter_cast', ...
null
34,254
from typing import List, Optional import torch import torch.distributed as dist import torchvision from torch import Tensor import warnings import torch.nn.functional as F import math def _max_by_axis(the_list): # type: (List[List[int]]) -> List[int] maxes = the_list[0] for sublist in the_list[1:]: ...
null
34,255
from typing import List, Optional import torch import torch.distributed as dist import torchvision from torch import Tensor import warnings import torch.nn.functional as F import math def is_dist_avail_and_initialized(): if not dist.is_available(): return False if not dist.is_initialized(): ret...
null
34,256
import random import warnings import numpy as np import torch from annotator.mmpkg.mmcv.parallel import MMDataParallel, MMDistributedDataParallel from annotator.mmpkg.mmcv.runner import build_optimizer, build_runner from annotator.mmpkg.mmseg.core import DistEvalHook, EvalHook from annotator.mmpkg.mmseg.datasets import...
Set random seed. Args: seed (int): Seed to be used. deterministic (bool): Whether to set the deterministic option for CUDNN backend, i.e., set `torch.backends.cudnn.deterministic` to True and `torch.backends.cudnn.benchmark` to False. Default: False.
34,257
import random import warnings import numpy as np import torch from annotator.mmpkg.mmcv.parallel import MMDataParallel, MMDistributedDataParallel from annotator.mmpkg.mmcv.runner import build_optimizer, build_runner from annotator.mmpkg.mmseg.core import DistEvalHook, EvalHook from annotator.mmpkg.mmseg.datasets import...
Launch segmentor training.
34,258
import matplotlib.pyplot as plt import annotator.mmpkg.mmcv as mmcv import torch from annotator.mmpkg.mmcv.parallel import collate, scatter from annotator.mmpkg.mmcv.runner import load_checkpoint from annotator.mmpkg.mmseg.datasets.pipelines import Compose from annotator.mmpkg.mmseg.models import build_segmentor from m...
Initialize a segmentor from config file. Args: config (str or :obj:`mmcv.Config`): Config file path or the config object. checkpoint (str, optional): Checkpoint path. If left as None, the model will not load any weights. device (str, optional) CPU/CUDA device option. Default 'cuda:0'. Use 'cpu' for loading model on CPU...
34,259
import matplotlib.pyplot as plt import annotator.mmpkg.mmcv as mmcv import torch from annotator.mmpkg.mmcv.parallel import collate, scatter from annotator.mmpkg.mmcv.runner import load_checkpoint from annotator.mmpkg.mmseg.datasets.pipelines import Compose from annotator.mmpkg.mmseg.models import build_segmentor from m...
Inference image(s) with the segmentor. Args: model (nn.Module): The loaded segmentor. imgs (str/ndarray or list[str/ndarray]): Either image files or loaded images. Returns: (list[Tensor]): The segmentation result.
34,260
import matplotlib.pyplot as plt import annotator.mmpkg.mmcv as mmcv import torch from annotator.mmpkg.mmcv.parallel import collate, scatter from annotator.mmpkg.mmcv.runner import load_checkpoint from annotator.mmpkg.mmseg.datasets.pipelines import Compose from annotator.mmpkg.mmseg.models import build_segmentor from m...
Visualize the segmentation results on the image. Args: model (nn.Module): The loaded segmentor. img (str or np.ndarray): Image filename or loaded image. result (list): The segmentation result. palette (list[list[int]]] | None): The palette of segmentation map. If None is given, random palette will be generated. Default...
34,261
import annotator.mmpkg.mmcv as mmcv The provided code snippet includes necessary dependencies for implementing the `cityscapes_classes` function. Write a Python function `def cityscapes_classes()` to solve the following problem: Cityscapes class names for external use. Here is the function: def cityscapes_classes():...
Cityscapes class names for external use.
34,262
import annotator.mmpkg.mmcv as mmcv The provided code snippet includes necessary dependencies for implementing the `ade_classes` function. Write a Python function `def ade_classes()` to solve the following problem: ADE20K class names for external use. Here is the function: def ade_classes(): """ADE20K class name...
ADE20K class names for external use.
34,263
import annotator.mmpkg.mmcv as mmcv The provided code snippet includes necessary dependencies for implementing the `voc_classes` function. Write a Python function `def voc_classes()` to solve the following problem: Pascal VOC class names for external use. Here is the function: def voc_classes(): """Pascal VOC cl...
Pascal VOC class names for external use.
34,264
import annotator.mmpkg.mmcv as mmcv The provided code snippet includes necessary dependencies for implementing the `cityscapes_palette` function. Write a Python function `def cityscapes_palette()` to solve the following problem: Cityscapes palette for external use. Here is the function: def cityscapes_palette(): ...
Cityscapes palette for external use.
34,265
import annotator.mmpkg.mmcv as mmcv The provided code snippet includes necessary dependencies for implementing the `ade_palette` function. Write a Python function `def ade_palette()` to solve the following problem: ADE20K palette for external use. Here is the function: def ade_palette(): """ADE20K palette for ex...
ADE20K palette for external use.
34,266
import annotator.mmpkg.mmcv as mmcv The provided code snippet includes necessary dependencies for implementing the `voc_palette` function. Write a Python function `def voc_palette()` to solve the following problem: Pascal VOC palette for external use. Here is the function: def voc_palette(): """Pascal VOC palett...
Pascal VOC palette for external use.
34,267
import annotator.mmpkg.mmcv as mmcv dataset_aliases = { 'cityscapes': ['cityscapes'], 'ade': ['ade', 'ade20k'], 'voc': ['voc', 'pascal_voc', 'voc12', 'voc12aug'] } The provided code snippet includes necessary dependencies for implementing the `get_classes` function. Write a Python function `def get_classes...
Get class names of a dataset.
34,268
import annotator.mmpkg.mmcv as mmcv dataset_aliases = { 'cityscapes': ['cityscapes'], 'ade': ['ade', 'ade20k'], 'voc': ['voc', 'pascal_voc', 'voc12', 'voc12aug'] } The provided code snippet includes necessary dependencies for implementing the `get_palette` function. Write a Python function `def get_palette...
Get class palette (RGB) of a dataset.
34,269
from collections import OrderedDict import annotator.mmpkg.mmcv as mmcv import numpy as np import torch def eval_metrics(results, gt_seg_maps, num_classes, ignore_index, metrics=['mIoU'], nan_to_num=None, label_map=dic...
Calculate Mean Intersection and Union (mIoU) Args: results (list[ndarray] | list[str]): List of prediction segmentation maps or list of prediction result filenames. gt_seg_maps (list[ndarray] | list[str]): list of ground truth segmentation maps or list of label filenames. num_classes (int): Number of categories. ignore...
34,270
from collections import OrderedDict import annotator.mmpkg.mmcv as mmcv import numpy as np import torch def eval_metrics(results, gt_seg_maps, num_classes, ignore_index, metrics=['mIoU'], nan_to_num=None, label_map=dic...
Calculate Mean Dice (mDice) Args: results (list[ndarray] | list[str]): List of prediction segmentation maps or list of prediction result filenames. gt_seg_maps (list[ndarray] | list[str]): list of ground truth segmentation maps or list of label filenames. num_classes (int): Number of categories. ignore_index (int): Ind...
34,271
from collections import OrderedDict import annotator.mmpkg.mmcv as mmcv import numpy as np import torch def eval_metrics(results, gt_seg_maps, num_classes, ignore_index, metrics=['mIoU'], nan_to_num=None, label_map=dic...
Calculate Mean Intersection and Union (mIoU) Args: results (list[ndarray] | list[str]): List of prediction segmentation maps or list of prediction result filenames. gt_seg_maps (list[ndarray] | list[str]): list of ground truth segmentation maps or list of label filenames. num_classes (int): Number of categories. ignore...
34,272
from annotator.mmpkg.mmcv.utils import Registry, build_from_cfg PIXEL_SAMPLERS = Registry('pixel sampler') The provided code snippet includes necessary dependencies for implementing the `build_pixel_sampler` function. Write a Python function `def build_pixel_sampler(cfg, **default_args)` to solve the following problem...
Build pixel sampler for segmentation map.
34,275
from collections.abc import Sequence import annotator.mmpkg.mmcv as mmcv import numpy as np import torch from annotator.mmpkg.mmcv.parallel import DataContainer as DC from ..builder import PIPELINES The provided code snippet includes necessary dependencies for implementing the `to_tensor` function. Write a Python func...
Convert objects of various python types to :obj:`torch.Tensor`. Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`, :class:`Sequence`, :class:`int` and :class:`float`. Args: data (torch.Tensor | numpy.ndarray | Sequence | int | float): Data to be converted.
34,276
import copy import platform import random from functools import partial import numpy as np from annotator.mmpkg.mmcv.parallel import collate from annotator.mmpkg.mmcv.runner import get_dist_info from annotator.mmpkg.mmcv.utils import Registry, build_from_cfg from annotator.mmpkg.mmcv.utils.parrots_wrapper import DataLo...
Build PyTorch DataLoader. In distributed training, each GPU/process has a dataloader. In non-distributed training, there is only one dataloader for all GPUs. Args: dataset (Dataset): A PyTorch dataset. samples_per_gpu (int): Number of training samples on each GPU, i.e., batch size of each GPU. workers_per_gpu (int): Ho...
34,277
import annotator.mmpkg.mmcv as mmcv import torch import torch.nn as nn import torch.nn.functional as F from ..builder import LOSSES from .utils import get_class_weight, weight_reduce_loss def flatten_binary_logits(logits, labels, ignore_index=None): """Flattens predictions in the batch (binary case) Remove labels e...
Binary Lovasz hinge loss. Args: logits (torch.Tensor): [B, H, W], logits at each pixel (between -infty and +infty). labels (torch.Tensor): [B, H, W], binary ground truth masks (0 or 1). classes (str | list[int], optional): Placeholder, to be consistent with other loss. Default: None. per_image (bool, optional): If per_...
34,278
import annotator.mmpkg.mmcv as mmcv import torch import torch.nn as nn import torch.nn.functional as F from ..builder import LOSSES from .utils import get_class_weight, weight_reduce_loss def flatten_probs(probs, labels, ignore_index=None): """Flattens predictions in the batch.""" if probs.dim() == 3: #...
Multi-class Lovasz-Softmax loss. Args: probs (torch.Tensor): [B, C, H, W], class probabilities at each prediction (between 0 and 1). labels (torch.Tensor): [B, H, W], ground truth labels (between 0 and C - 1). classes (str | list[int], optional): Classes chosen to calculate loss. 'all' for all classes, 'present' for cl...
34,279
import functools import annotator.mmpkg.mmcv as mmcv import numpy as np import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `get_class_weight` function. Write a Python function `def get_class_weight(class_weight)` to solve the following problem: Get class weig...
Get class weight for loss function. Args: class_weight (list[float] | str | None): If class_weight is a str, take it as a file name and read from it.
34,280
import functools import annotator.mmpkg.mmcv as mmcv import numpy as np import torch.nn.functional as F def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wis...
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...
34,286
import warnings from annotator.mmpkg.mmcv.cnn import MODELS as MMCV_MODELS from annotator.mmpkg.mmcv.utils import Registry BACKBONES = MODELS The provided code snippet includes necessary dependencies for implementing the `build_backbone` function. Write a Python function `def build_backbone(cfg)` to solve the followin...
Build backbone.
34,287
import warnings from annotator.mmpkg.mmcv.cnn import MODELS as MMCV_MODELS from annotator.mmpkg.mmcv.utils import Registry NECKS = MODELS The provided code snippet includes necessary dependencies for implementing the `build_neck` function. Write a Python function `def build_neck(cfg)` to solve the following problem: B...
Build neck.
34,288
import warnings from annotator.mmpkg.mmcv.cnn import MODELS as MMCV_MODELS from annotator.mmpkg.mmcv.utils import Registry HEADS = MODELS The provided code snippet includes necessary dependencies for implementing the `build_head` function. Write a Python function `def build_head(cfg)` to solve the following problem: B...
Build head.
34,289
import warnings from annotator.mmpkg.mmcv.cnn import MODELS as MMCV_MODELS from annotator.mmpkg.mmcv.utils import Registry LOSSES = MODELS The provided code snippet includes necessary dependencies for implementing the `build_loss` function. Write a Python function `def build_loss(cfg)` to solve the following problem: ...
Build loss.
34,290
import warnings from annotator.mmpkg.mmcv.cnn import MODELS as MMCV_MODELS from annotator.mmpkg.mmcv.utils import Registry SEGMENTORS = MODELS The provided code snippet includes necessary dependencies for implementing the `build_segmentor` function. Write a Python function `def build_segmentor(cfg, train_cfg=None, tes...
Build segmentor.
34,291
import torch import torch.nn as nn from annotator.mmpkg.mmseg.models.builder import HEADS from annotator.mmpkg.mmseg.ops import resize from ..losses import accuracy from .cascade_decode_head import BaseCascadeDecodeHead The provided code snippet includes necessary dependencies for implementing the `calculate_uncertain...
Estimate uncertainty based on seg logits. For each location of the prediction ``seg_logits`` we estimate uncertainty as the difference between top first and top second predicted logits. Args: seg_logits (Tensor): Semantic segmentation logits, shape (batch_size, num_classes, height, width). Returns: scores (Tensor): T u...
34,292
import math import torch import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F from annotator.mmpkg.mmcv.cnn import ConvModule from ..builder import HEADS from .decode_head import BaseDecodeHead The provided code snippet includes necessary dependencies for implementing the `reduce_mean...
Reduce mean when distributed training.
34,295
from annotator.mmpkg.mmcv.utils import collect_env as collect_base_env from annotator.mmpkg.mmcv.utils import get_git_hash import annotator.mmpkg.mmseg as mmseg The provided code snippet includes necessary dependencies for implementing the `collect_env` function. Write a Python function `def collect_env()` to solve th...
Collect the information of the running environments.
34,296
import logging from annotator.mmpkg.mmcv.utils import get_logger import logging The provided code snippet includes necessary dependencies for implementing the `get_root_logger` function. Write a Python function `def get_root_logger(log_file=None, log_level=logging.INFO)` to solve the following problem: Get the root l...
Get the root logger. The logger will be initialized if it has not been initialized. By default a StreamHandler will be added. If `log_file` is specified, a FileHandler will also be added. The name of the root logger is the top-level package name, e.g., "mmseg". Args: log_file (str | None): The log filename. If specifie...
34,306
import copy import warnings import torch import torch.nn as nn from annotator.mmpkg.mmcv import ConfigDict, deprecated_api_warning from annotator.mmpkg.mmcv.cnn import Linear, build_activation_layer, build_norm_layer from annotator.mmpkg.mmcv.runner.base_module import BaseModule, ModuleList, Sequential from annotator.m...
Builder for Position Encoding.
34,307
import copy import warnings import torch import torch.nn as nn from annotator.mmpkg.mmcv import ConfigDict, deprecated_api_warning from annotator.mmpkg.mmcv.cnn import Linear, build_activation_layer, build_norm_layer from annotator.mmpkg.mmcv.runner.base_module import BaseModule, ModuleList, Sequential from annotator.m...
Builder for attention.
34,308
import copy import warnings import torch import torch.nn as nn from annotator.mmpkg.mmcv import ConfigDict, deprecated_api_warning from annotator.mmpkg.mmcv.cnn import Linear, build_activation_layer, build_norm_layer from annotator.mmpkg.mmcv.runner.base_module import BaseModule, ModuleList, Sequential from annotator.m...
Builder for feed-forward network (FFN).
34,309
import copy import warnings import torch import torch.nn as nn from annotator.mmpkg.mmcv import ConfigDict, deprecated_api_warning from annotator.mmpkg.mmcv.cnn import Linear, build_activation_layer, build_norm_layer from annotator.mmpkg.mmcv.runner.base_module import BaseModule, ModuleList, Sequential from annotator.m...
Builder for transformer layer.
34,310
import copy import warnings import torch import torch.nn as nn from annotator.mmpkg.mmcv import ConfigDict, deprecated_api_warning from annotator.mmpkg.mmcv.cnn import Linear, build_activation_layer, build_norm_layer from annotator.mmpkg.mmcv.runner.base_module import BaseModule, ModuleList, Sequential from annotator.m...
Builder for transformer encoder and transformer decoder.
34,315
import torch import torch.nn as nn from annotator.mmpkg.mmcv import build_from_cfg from .registry import DROPOUT_LAYERS The provided code snippet includes necessary dependencies for implementing the `drop_path` function. Write a Python function `def drop_path(x, drop_prob=0., training=False)` to solve the following pr...
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). We follow the implementation https://github.com/rwightman/pytorch-image-models/blob/a2727c1bf78ba0d7b5727f5f95e37fb7f8866b1f/timm/models/layers/drop.py # noqa: E501
34,316
import torch import torch.nn as nn from annotator.mmpkg.mmcv import build_from_cfg from .registry import DROPOUT_LAYERS DROPOUT_LAYERS = Registry('drop out layers') The provided code snippet includes necessary dependencies for implementing the `build_dropout` function. Write a Python function `def build_dropout(cfg, ...
Builder for drop out layers.
34,317
import inspect import torch.nn as nn from annotator.mmpkg.mmcv.utils import is_tuple_of from annotator.mmpkg.mmcv.utils.parrots_wrapper import SyncBatchNorm, _BatchNorm, _InstanceNorm from .registry import NORM_LAYERS NORM_LAYERS.register_module('BN', module=nn.BatchNorm2d) NORM_LAYERS.register_module('BN1d', module=nn...
Build normalization layer. Args: cfg (dict): The norm layer config, which should contain: - type (str): Layer type. - layer args: Args needed to instantiate a norm layer. - requires_grad (bool, optional): Whether stop gradient updates. num_features (int): Number of input channels. postfix (int | str): The postfix to be...
34,318
import inspect import torch.nn as nn from annotator.mmpkg.mmcv.utils import is_tuple_of from annotator.mmpkg.mmcv.utils.parrots_wrapper import SyncBatchNorm, _BatchNorm, _InstanceNorm from .registry import NORM_LAYERS _BatchNorm, _InstanceNorm, SyncBatchNorm_ = _get_norm() The provided code snippet includes necessary...
Check if a layer is a normalization layer. Args: layer (nn.Module): The layer to be checked. exclude (type | tuple[type]): Types to be excluded. Returns: bool: Whether the layer is a norm layer.
34,320
import torch import torch.nn as nn import torch.nn.functional as F from annotator.mmpkg.mmcv.utils import TORCH_VERSION, build_from_cfg, digit_version from .registry import ACTIVATION_LAYERS ACTIVATION_LAYERS = Registry('activation layer') The provided code snippet includes necessary dependencies for implementing the...
Build activation layer. Args: cfg (dict): The activation layer config, which should contain: - type (str): Layer type. - layer args: Args needed to instantiate an activation layer. Returns: nn.Module: Created activation layer.
34,326
import torch import annotator.mmpkg.mmcv as mmcv class _BatchNormXd(torch.nn.modules.batchnorm._BatchNorm): """A general BatchNorm layer without input dimension check. Reproduced from @kapily's work: (https://github.com/pytorch/pytorch/issues/41081#issuecomment-783961547) The only difference between Bat...
Helper function to convert all `SyncBatchNorm` (SyncBN) and `mmcv.ops.sync_bn.SyncBatchNorm`(MMSyncBN) layers in the model to `BatchNormXd` layers. Adapted from @kapily's work: (https://github.com/pytorch/pytorch/issues/41081#issuecomment-783961547) Args: module (nn.Module): The module containing `SyncBatchNorm` layers...
34,328
import copy import math import warnings import numpy as np import torch import torch.nn as nn from torch import Tensor from annotator.mmpkg.mmcv.utils import Registry, build_from_cfg, get_logger, print_log The provided code snippet includes necessary dependencies for implementing the `update_init_info` function. Write...
Update the `_params_init_info` in the module if the value of parameters are changed. Args: module (obj:`nn.Module`): The module of PyTorch with a user-defined attribute `_params_init_info` which records the initialization information. init_info (str): The string that describes the initialization.
34,329
import copy import math import warnings import numpy as np import torch import torch.nn as nn from torch import Tensor from annotator.mmpkg.mmcv.utils import Registry, build_from_cfg, get_logger, print_log def constant_init(module, val, bias=0): if hasattr(module, 'weight') and module.weight is not None: n...
null
34,330
import copy import math import warnings import numpy as np import torch import torch.nn as nn from torch import Tensor from annotator.mmpkg.mmcv.utils import Registry, build_from_cfg, get_logger, print_log def xavier_init(module, gain=1, bias=0, distribution='normal'): assert distribution in ['uniform', 'normal'] ...
null
34,331
import copy import math import warnings import numpy as np import torch import torch.nn as nn from torch import Tensor from annotator.mmpkg.mmcv.utils import Registry, build_from_cfg, get_logger, print_log def normal_init(module, mean=0, std=1, bias=0): if hasattr(module, 'weight') and module.weight is not None: ...
null
34,332
import copy import math import warnings import numpy as np import torch import torch.nn as nn from torch import Tensor from annotator.mmpkg.mmcv.utils import Registry, build_from_cfg, get_logger, print_log def trunc_normal_(tensor: Tensor, mean: float = 0., std: float = 1., ...
null
34,333
import copy import math import warnings import numpy as np import torch import torch.nn as nn from torch import Tensor from annotator.mmpkg.mmcv.utils import Registry, build_from_cfg, get_logger, print_log def uniform_init(module, a=0, b=1, bias=0): if hasattr(module, 'weight') and module.weight is not None: ...
null
34,334
import copy import math import warnings import numpy as np import torch import torch.nn as nn from torch import Tensor from annotator.mmpkg.mmcv.utils import Registry, build_from_cfg, get_logger, print_log def kaiming_init(module, a=0, mode='fan_out', nonlinearity='rel...
null
34,335
import copy import math import warnings import numpy as np import torch import torch.nn as nn from torch import Tensor from annotator.mmpkg.mmcv.utils import Registry, build_from_cfg, get_logger, print_log The provided code snippet includes necessary dependencies for implementing the `bias_init_with_prob` function. Wr...
initialize conv/fc bias value according to a given probability value.
34,336
import copy import math import warnings import numpy as np import torch import torch.nn as nn from torch import Tensor from annotator.mmpkg.mmcv.utils import Registry, build_from_cfg, get_logger, print_log def _get_bases_name(m): return [b.__name__ for b in m.__class__.__bases__]
null
34,337
import copy import math import warnings import numpy as np import torch import torch.nn as nn from torch import Tensor from annotator.mmpkg.mmcv.utils import Registry, build_from_cfg, get_logger, print_log def _initialize(module, cfg, wholemodule=False): func = build_from_cfg(cfg, INITIALIZERS) # wholemodule fl...
Initialize a module. Args: module (``torch.nn.Module``): the module will be initialized. init_cfg (dict | list[dict]): initialization configuration dict to define initializer. OpenMMLab has implemented 6 initializers including ``Constant``, ``Xavier``, ``Normal``, ``Uniform``, ``Kaiming``, and ``Pretrained``. Example: ...
34,338
import sys from functools import partial import numpy as np import torch import torch.nn as nn import annotator.mmpkg.mmcv as mmcv def flops_to_string(flops, units='GFLOPs', precision=2): """Convert FLOPs number into a string. Note that Here we take a multiply-add counts as one FLOP. Args: flops (fl...
Get complexity information of a model. This method can calculate FLOPs and parameter counts of a model with corresponding input shape. It can also print complexity information for each layer in a model. Supported layers are listed as below: - Convolutions: ``nn.Conv1d``, ``nn.Conv2d``, ``nn.Conv3d``. - Activations: ``n...
34,339
import sys from functools import partial import numpy as np import torch import torch.nn as nn import annotator.mmpkg.mmcv as mmcv def empty_flops_counter_hook(module, input, output): module.__flops__ += 0
null
34,379
import numpy as np import annotator.mmpkg.mmcv as mmcv try: import torch except ImportError: torch = None The provided code snippet includes necessary dependencies for implementing the `tensor2imgs` function. Write a Python function `def tensor2imgs(tensor, mean=(0, 0, 0), std=(1, 1, 1), to_rgb=True)` to solve...
Convert tensor to 3-channel images. Args: tensor (torch.Tensor): Tensor that contains multiple images, shape ( N, C, H, W). mean (tuple[float], optional): Mean of images. Defaults to (0, 0, 0). std (tuple[float], optional): Standard deviation of images. Defaults to (1, 1, 1). to_rgb (bool, optional): Whether the tensor...
34,380
import io import os.path as osp from pathlib import Path import cv2 import numpy as np from cv2 import (IMREAD_COLOR, IMREAD_GRAYSCALE, IMREAD_IGNORE_ORIENTATION, IMREAD_UNCHANGED) from annotator.mmpkg.mmcv.utils import check_file_exist, is_str, mkdir_or_exist try: import tifffile except ImportErro...
Select a backend for image decoding. Args: backend (str): The image decoding backend type. Options are `cv2`, `pillow`, `turbojpeg` (see https://github.com/lilohuang/PyTurboJPEG) and `tifffile`. `turbojpeg` is faster but it only supports `.jpeg` file format.
34,381
import io import os.path as osp from pathlib import Path import cv2 import numpy as np from cv2 import (IMREAD_COLOR, IMREAD_GRAYSCALE, IMREAD_IGNORE_ORIENTATION, IMREAD_UNCHANGED) from annotator.mmpkg.mmcv.utils import check_file_exist, is_str, mkdir_or_exist try: import tifffile except ImportErro...
Read an image. Args: img_or_path (ndarray or str or Path): Either a numpy array or str or pathlib.Path. If it is a numpy array (loaded image), then it will be returned as is. flag (str): Flags specifying the color type of a loaded image, candidates are `color`, `grayscale`, `unchanged`, `color_ignore_orientation` and `...
34,382
import io import os.path as osp from pathlib import Path import cv2 import numpy as np from cv2 import (IMREAD_COLOR, IMREAD_GRAYSCALE, IMREAD_IGNORE_ORIENTATION, IMREAD_UNCHANGED) from annotator.mmpkg.mmcv.utils import check_file_exist, is_str, mkdir_or_exist jpeg = None supported_backends = ['cv2', '...
Read an image from bytes. Args: content (bytes): Image bytes got from files or other streams. flag (str): Same as :func:`imread`. backend (str | None): The image decoding backend type. Options are `cv2`, `pillow`, `turbojpeg`, `None`. If backend is None, the global imread_backend specified by ``mmcv.use_backend()`` wil...
34,383
import io import os.path as osp from pathlib import Path import cv2 import numpy as np from cv2 import (IMREAD_COLOR, IMREAD_GRAYSCALE, IMREAD_IGNORE_ORIENTATION, IMREAD_UNCHANGED) from annotator.mmpkg.mmcv.utils import check_file_exist, is_str, mkdir_or_exist The provided code snippet includes necess...
Write image to file. Args: img (ndarray): Image array to be written. file_path (str): Image file path. params (None or list): Same as opencv :func:`imwrite` interface. auto_mkdir (bool): If the parent folder of `file_path` does not exist, whether to create it automatically. Returns: bool: Successful or not.
34,384
import cv2 import numpy as np from annotator.mmpkg.mmcv.image import imread, imwrite from .color import color_val def imshow(img, win_name='', wait_time=0): """Show an image. Args: img (str or ndarray): The image to be displayed. win_name (str): The window name. wait_time (int): Value of...
Draw bboxes on an image. Args: img (str or ndarray): The image to be displayed. bboxes (list or ndarray): A list of ndarray of shape (k, 4). colors (list[str or tuple or Color]): A list of colors. top_k (int): Plot the first k bboxes only if set positive. thickness (int): Thickness of lines. show (bool): Whether to sho...
34,385
import cv2 import numpy as np from annotator.mmpkg.mmcv.image import imread, imwrite from .color import color_val def imshow(img, win_name='', wait_time=0): """Show an image. Args: img (str or ndarray): The image to be displayed. win_name (str): The window name. wait_time (int): Value of...
Draw bboxes and class labels (with scores) on an image. Args: img (str or ndarray): The image to be displayed. bboxes (ndarray): Bounding boxes (with scores), shaped (n, 4) or (n, 5). labels (ndarray): Labels of bboxes. class_names (list[str]): Names of each classes. score_thr (float): Minimum score of bboxes to be sho...
34,386
from __future__ import division import numpy as np from annotator.mmpkg.mmcv.image import rgb2bgr from annotator.mmpkg.mmcv.video import flowread from .image import imshow def flow2rgb(flow, color_wheel=None, unknown_thr=1e6): """Convert flow map to RGB image. Args: flow (ndarray): Array of optical flow...
Show optical flow. Args: flow (ndarray or str): The optical flow to be displayed. win_name (str): The window name. wait_time (int): Value of waitKey param.
34,388
import torch import torch.nn as nn import torch.nn.functional as F from annotator.mmpkg.mmcv.cnn import PLUGIN_LAYERS, Scale The provided code snippet includes necessary dependencies for implementing the `NEG_INF_DIAG` function. Write a Python function `def NEG_INF_DIAG(n, device)` to solve the following problem: Retu...
Returns a diagonal matrix of size [n, n]. The diagonal are all "-inf". This is for avoiding calculating the overlapped element in the Criss-Cross twice.