id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
9,366
from share import * import config import cv2 import einops import gradio as gr import numpy as np import torch import random from pytorch_lightning import seed_everything from annotator.util import resize_image, HWC3 from annotator.openpose import OpenposeDetector from cldm.model import create_model, load_state_dict fr...
null
9,367
from share import * import config import cv2 import einops import gradio as gr import numpy as np import torch import random from pytorch_lightning import seed_everything from annotator.util import resize_image, HWC3 from annotator.midas import MidasDetector from cldm.model import create_model, load_state_dict from cld...
null
9,368
import os import torch from share import * from cldm.model import load_state_dict def get_node_name(name, parent_name): if len(name) <= len(parent_name): return False, '' p = name[:len(parent_name)] if p != parent_name: return False, '' return True, name[len(parent_name):]
null
9,369
from share import * import config import cv2 import einops import gradio as gr import numpy as np import torch import random from pytorch_lightning import seed_everything from annotator.util import resize_image, HWC3 from cldm.model import create_model, load_state_dict from cldm.ddim_hacked import DDIMSampler model = c...
null
9,370
import sys import os assert len(sys.argv) == 3, 'Args are wrong.' import torch from share import * from cldm.model import create_model def get_node_name(name, parent_name): if len(name) <= len(parent_name): return False, '' p = name[:len(parent_name)] if p != parent_name: return False, '' ...
null
9,371
from share import * import config import cv2 import einops import gradio as gr import numpy as np import torch import random from pytorch_lightning import seed_everything from annotator.util import resize_image, HWC3 from annotator.mlsd import MLSDdetector from cldm.model import create_model, load_state_dict from cldm....
null
9,372
from share import * import config import cv2 import einops import gradio as gr import numpy as np import torch import random from pytorch_lightning import seed_everything from annotator.util import resize_image, HWC3 from annotator.hed import HEDdetector from cldm.model import create_model, load_state_dict from cldm.dd...
null
9,373
import os import torch from omegaconf import OmegaConf from ldm.util import instantiate_from_config def get_state_dict(d): return d.get('state_dict', d) def load_state_dict(ckpt_path, location='cpu'): _, extension = os.path.splitext(ckpt_path) if extension.lower() == ".safetensors": import safetens...
null
9,374
import os import torch from omegaconf import OmegaConf from ldm.util import instantiate_from_config def instantiate_from_config(config): if not "target" in config: if config == '__is_first_stage__': return None elif config == "__is_unconditional__": return None raise...
null
9,375
import torch import einops import ldm.modules.encoders.modules import ldm.modules.attention from transformers import logging from ldm.modules.attention import default def _hacked_sliced_attentin_forward(self, x, context=None, mask=None): h = self.heads q = self.to_q(x) context = default(context, x) k = ...
null
9,376
import torch import einops import ldm.modules.encoders.modules import ldm.modules.attention from transformers import logging from ldm.modules.attention import default def disable_verbosity(): logging.set_verbosity_error() print('logging improved.') return def _hacked_clip_forward(self, text): PAD = self...
null
9,378
from share import * import config import cv2 import einops import gradio as gr import numpy as np import torch import random from pytorch_lightning import seed_everything from annotator.util import resize_image, HWC3 from annotator.midas import MidasDetector from cldm.model import create_model, load_state_dict from cld...
null
9,379
from share import * import config import cv2 import einops import gradio as gr import numpy as np import torch import random from pytorch_lightning import seed_everything from annotator.util import resize_image, HWC3 from annotator.uniformer import UniformerDetector from cldm.model import create_model, load_state_dict ...
null
9,380
import cv2 import os import torch import torch.nn as nn from torchvision.transforms import Compose from .midas.dpt_depth import DPTDepthModel from .midas.midas_net import MidasNet from .midas.midas_net_custom import MidasNet_small from .midas.transforms import Resize, NormalizeImage, PrepareForNet from annotator.util i...
Overwrite model.train with this function to make sure train/eval mode does not change anymore.
9,381
import cv2 import os import torch import torch.nn as nn from torchvision.transforms import Compose from .midas.dpt_depth import DPTDepthModel from .midas.midas_net import MidasNet from .midas.midas_net_custom import MidasNet_small from .midas.transforms import Resize, NormalizeImage, PrepareForNet from annotator.util i...
null
9,382
import cv2 import os import torch import torch.nn as nn from torchvision.transforms import Compose from .midas.dpt_depth import DPTDepthModel from .midas.midas_net import MidasNet from .midas.midas_net_custom import MidasNet_small from .midas.transforms import Resize, NormalizeImage, PrepareForNet from annotator.util i...
null
9,383
import sys import re import numpy as np import cv2 import torch The provided code snippet includes necessary dependencies for implementing the `read_pfm` function. Write a Python function `def read_pfm(path)` to solve the following problem: Read pfm file. Args: path (str): path to file Returns: tuple: (data, scale) H...
Read pfm file. Args: path (str): path to file Returns: tuple: (data, scale)
9,384
import sys import re import numpy as np import cv2 import torch The provided code snippet includes necessary dependencies for implementing the `read_image` function. Write a Python function `def read_image(path)` to solve the following problem: Read image and output RGB image (0-1). Args: path (str): path to file Retu...
Read image and output RGB image (0-1). Args: path (str): path to file Returns: array: RGB image (0-1)
9,385
import sys import re import numpy as np import cv2 import torch The provided code snippet includes necessary dependencies for implementing the `resize_image` function. Write a Python function `def resize_image(img)` to solve the following problem: Resize image and make it fit for network. Args: img (array): image Retu...
Resize image and make it fit for network. Args: img (array): image Returns: tensor: data ready for network
9,386
import sys import re import numpy as np import cv2 import torch The provided code snippet includes necessary dependencies for implementing the `resize_depth` function. Write a Python function `def resize_depth(depth, width, height)` to solve the following problem: Resize depth map and bring to CPU (numpy). Args: depth...
Resize depth map and bring to CPU (numpy). Args: depth (tensor): depth width (int): image width height (int): image height Returns: array: processed depth
9,387
import sys import re import numpy as np import cv2 import torch def write_pfm(path, image, scale=1): """Write pfm file. Args: path (str): pathto file image (array): data scale (int, optional): Scale. Defaults to 1. """ with open(path, "wb") as file: color = None i...
Write depth map to pfm and png file. Args: path (str): filepath without extension depth (array): depth
9,389
import torch import torch.nn as nn import timm import types import math import torch.nn.functional as F def forward_flex(self, x): b, c, h, w = x.shape pos_embed = self._resize_pos_embed( self.pos_embed, h // self.patch_size[1], w // self.patch_size[0] ) B = x.shape[0] if hasattr(self.patch_...
null
9,390
import torch import torch.nn as nn import timm import types import math import torch.nn.functional as F def _make_vit_b16_backbone( model, features=[96, 192, 384, 768], size=[384, 384], hooks=[2, 5, 8, 11], vit_features=768, use_readout="ignore", start_index=1, ): pretrained = nn.Module(...
null
9,391
import torch import torch.nn as nn import timm import types import math import torch.nn.functional as F def _make_vit_b16_backbone( model, features=[96, 192, 384, 768], size=[384, 384], hooks=[2, 5, 8, 11], vit_features=768, use_readout="ignore", start_index=1, ): pretrained = nn.Module(...
null
9,392
import torch import torch.nn as nn import torch.nn.functional as F from .base_model import BaseModel from .blocks import ( FeatureFusionBlock, FeatureFusionBlock_custom, Interpolate, _make_encoder, forward_vit, ) class FeatureFusionBlock_custom(nn.Module): """Feature fusion block. """ ...
null
9,393
import torch import torch.nn as nn from .vit import ( _make_pretrained_vitb_rn50_384, _make_pretrained_vitl16_384, _make_pretrained_vitb16_384, forward_vit, ) def _make_scratch(in_shape, out_shape, groups=1, expand=False): scratch = nn.Module() out_shape1 = out_shape out_shape2 = out_shape ...
null
9,396
import math import numpy as np import matplotlib import cv2 def transfer(model, model_weights): transfered_model_weights = {} for weights_name in model.state_dict().keys(): transfered_model_weights[weights_name] = model_weights['.'.join(weights_name.split('.')[1:])] return transfered_model_weights
null
9,402
import os import numpy as np import cv2 import torch from torch.nn import functional as F def deccode_output_score_and_ptss(tpMap, topk_n = 200, ksize = 5): def pred_lines(image, model, input_shape=[512, 512], score_thr=0.10, dist_thr=20.0): h, w, _ = image.shape ...
null
9,403
import os import numpy as np import cv2 import torch from torch.nn import functional as F def deccode_output_score_and_ptss(tpMap, topk_n = 200, ksize = 5): ''' tpMap: center: tpMap[1, 0, :, :] displacement: tpMap[1, 1:5, :, :] ''' b, c, h, w = tpMap.shape assert b==1, 'only support bsize...
shape = [height, width]
9,404
import os import sys import torch import torch.nn as nn import torch.utils.model_zoo as model_zoo from torch.nn import functional as F The provided code snippet includes necessary dependencies for implementing the `_make_divisible` function. Write a Python function `def _make_divisible(v, divisor, min_value=None)` t...
This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py :param v: :param divisor: :param min_value: :return:
9,406
import random import warnings import numpy as np import torch from annotator.uniformer.mmcv.parallel import MMDataParallel, MMDistributedDataParallel from annotator.uniformer.mmcv.runner import build_optimizer, build_runner from annotator.uniformer.mmseg.core import DistEvalHook, EvalHook from annotator.uniformer.mmseg...
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.
9,407
import random import warnings import numpy as np import torch from annotator.uniformer.mmcv.parallel import MMDataParallel, MMDistributedDataParallel from annotator.uniformer.mmcv.runner import build_optimizer, build_runner from annotator.uniformer.mmseg.core import DistEvalHook, EvalHook from annotator.uniformer.mmseg...
Launch segmentor training.
9,408
import matplotlib.pyplot as plt import annotator.uniformer.mmcv as mmcv import torch from annotator.uniformer.mmcv.parallel import collate, scatter from annotator.uniformer.mmcv.runner import load_checkpoint from annotator.uniformer.mmseg.datasets.pipelines import Compose from annotator.uniformer.mmseg.models import bu...
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...
9,409
import matplotlib.pyplot as plt import annotator.uniformer.mmcv as mmcv import torch from annotator.uniformer.mmcv.parallel import collate, scatter from annotator.uniformer.mmcv.runner import load_checkpoint from annotator.uniformer.mmseg.datasets.pipelines import Compose from annotator.uniformer.mmseg.models import bu...
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.
9,410
import matplotlib.pyplot as plt import annotator.uniformer.mmcv as mmcv import torch from annotator.uniformer.mmcv.parallel import collate, scatter from annotator.uniformer.mmcv.runner import load_checkpoint from annotator.uniformer.mmseg.datasets.pipelines import Compose from annotator.uniformer.mmseg.models import bu...
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...
9,411
import annotator.uniformer.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_classe...
Cityscapes class names for external use.
9,412
import annotator.uniformer.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 ...
ADE20K class names for external use.
9,413
import annotator.uniformer.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 VO...
Pascal VOC class names for external use.
9,414
import annotator.uniformer.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.
9,415
import annotator.uniformer.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 fo...
ADE20K palette for external use.
9,416
import annotator.uniformer.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 pa...
Pascal VOC palette for external use.
9,417
import annotator.uniformer.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_cla...
Get class names of a dataset.
9,418
import annotator.uniformer.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_pal...
Get class palette (RGB) of a dataset.
9,419
from collections import OrderedDict import annotator.uniformer.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...
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...
9,420
from collections import OrderedDict import annotator.uniformer.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...
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...
9,421
from collections import OrderedDict import annotator.uniformer.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...
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...
9,422
from annotator.uniformer.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 pro...
Build pixel sampler for segmentation map.
9,423
The provided code snippet includes necessary dependencies for implementing the `add_prefix` function. Write a Python function `def add_prefix(inputs, prefix)` to solve the following problem: Add prefix for dict. Args: inputs (dict): The input dict with str keys. prefix (str): The prefix to add. Returns: dict: The dic...
Add prefix for dict. Args: inputs (dict): The input dict with str keys. prefix (str): The prefix to add. Returns: dict: The dict with keys updated with ``prefix``.
9,424
import warnings import torch.nn as nn import torch.nn.functional as F def resize(input, size=None, scale_factor=None, mode='nearest', align_corners=None, warning=True): if warning: if size is not None and align_corners: input_h, input_w = t...
null
9,425
from collections.abc import Sequence import annotator.uniformer.mmcv as mmcv import numpy as np import torch from annotator.uniformer.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 Pyt...
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.
9,426
import copy import platform import random from functools import partial import numpy as np from annotator.uniformer.mmcv.parallel import collate from annotator.uniformer.mmcv.runner import get_dist_info from annotator.uniformer.mmcv.utils import Registry, build_from_cfg from annotator.uniformer.mmcv.utils.parrots_wrapp...
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...
9,427
import annotator.uniformer.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 labe...
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_...
9,428
import annotator.uniformer.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...
9,429
import functools import annotator.uniformer.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 ...
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.
9,430
import functools import annotator.uniformer.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...
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...
9,431
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 regar...
9,432
import torch import torch.nn as nn import torch.nn.functional as F from ..builder import LOSSES from .utils import get_class_weight, weighted_loss def binary_dice_loss(pred, target, valid_mask, smooth=1, exponent=2, **kwards): def dice_loss(pred, target, valid_mask, smooth=1, ...
null
9,433
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 weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Eleme...
The wrapper function for :func:`F.cross_entropy`
9,434
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 _expand_onehot_labels(labels, label_weights, target_shape, ignore_index): """Expand onehot labels to match the size of prediction.""" bin_labels = labels.ne...
Calculate the binary CrossEntropy loss. Args: pred (torch.Tensor): The prediction with shape (N, 1). label (torch.Tensor): The learning label of the prediction. weight (torch.Tensor, optional): Sample-wise loss weight. reduction (str, optional): The method used to reduce the loss. Options are "none", "mean" and "sum". ...
9,435
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 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. target (torch.Tensor): The learning label of the prediction. label (torch.Tensor): ``label`` indicates the class label of the mask' corresponding object. This will be used to select the ma...
9,436
from collections import OrderedDict import math from functools import partial import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint import numpy as np from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from annotator.uniformer.mmcv_custom import lo...
Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C)
9,437
from collections import OrderedDict import math from functools import partial import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint import numpy as np from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from annotator.uniformer.mmcv_custom import lo...
Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C)
9,438
import warnings from annotator.uniformer.mmcv.cnn import MODELS as MMCV_MODELS from annotator.uniformer.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 ...
Build backbone.
9,439
import warnings from annotator.uniformer.mmcv.cnn import MODELS as MMCV_MODELS from annotator.uniformer.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 pr...
Build neck.
9,440
import warnings from annotator.uniformer.mmcv.cnn import MODELS as MMCV_MODELS from annotator.uniformer.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 pr...
Build head.
9,441
import warnings from annotator.uniformer.mmcv.cnn import MODELS as MMCV_MODELS from annotator.uniformer.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 p...
Build loss.
9,442
import warnings from annotator.uniformer.mmcv.cnn import MODELS as MMCV_MODELS from annotator.uniformer.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=N...
Build segmentor.
9,443
import torch import torch.nn as nn from annotator.uniformer.mmcv.cnn import ConvModule, normal_init from annotator.uniformer.mmcv.ops import point_sample from annotator.uniformer.mmseg.models.builder import HEADS from annotator.uniformer.mmseg.ops import resize from ..losses import accuracy from .cascade_decode_head im...
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...
9,444
import math import torch import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F from annotator.uniformer.mmcv.cnn import ConvModule from ..builder import HEADS from .decode_head import BaseDecodeHead The provided code snippet includes necessary dependencies for implementing the `reduce_...
Reduce mean when distributed training.
9,445
The provided code snippet includes necessary dependencies for implementing the `make_divisible` function. Write a Python function `def make_divisible(value, divisor, min_value=None, min_ratio=0.9)` to solve the following problem: Make divisible function. This function rounds the channel number to the nearest value th...
Make divisible function. This function rounds the channel number to the nearest value that can be divisible by the divisor. It is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by divisor. It can be seen here: https://github.com/tensorflow/models/blob/master/research...
9,446
import math import warnings import torch def _no_grad_trunc_normal_(tensor, mean, std, a, b): """Reference: https://people.sc.fsu.edu/~jburkardt/presentations /truncated_normal.pdf""" def norm_cdf(x): # Computes standard normal cumulative distribution function return (1. + math.erf(x / math....
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...
9,447
from annotator.uniformer.mmcv.utils import collect_env as collect_base_env from annotator.uniformer.mmcv.utils import get_git_hash import annotator.uniformer.mmseg as mmseg The provided code snippet includes necessary dependencies for implementing the `collect_env` function. Write a Python function `def collect_env()`...
Collect the information of the running environments.
9,448
import logging from annotator.uniformer.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 ro...
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...
9,449
The provided code snippet includes necessary dependencies for implementing the `parse_version_info` function. Write a Python function `def parse_version_info(version_str: str, length: int = 4) -> tuple` to solve the following problem: Parse a version string into a tuple. Args: version_str (str): The version string. l...
Parse a version string into a tuple. Args: version_str (str): The version string. length (int): The maximum number of version levels. Default: 4. Returns: tuple[int | str]: The version info, e.g., "1.3.0" is parsed into (1, 3, 0, 0, 0, 0), and "2.0.0rc1" is parsed into (2, 0, 0, 0, 'rc', 1) (when length is set to 4).
9,450
from .registry import MODULE_WRAPPERS MODULE_WRAPPERS = Registry('module wrapper') MODULE_WRAPPERS.register_module(module=DataParallel) MODULE_WRAPPERS.register_module(module=DistributedDataParallel) The provided code snippet includes necessary dependencies for implementing the `is_module_wrapper` function. Write a P...
Check if a module is a module wrapper. The following 3 modules in MMCV (and their subclasses) are regarded as module wrappers: DataParallel, DistributedDataParallel, MMDistributedDataParallel (the deprecated version). You may add you own module wrapper by registering it to mmcv.parallel.MODULE_WRAPPERS. Args: module (n...
9,451
import torch from torch.nn.parallel._functions import Scatter as OrigScatter from ._functions import Scatter from .data_container import DataContainer def scatter(inputs, target_gpus, dim=0): """Scatter inputs to target gpus. The only difference from original :func:`scatter` is to add support for :type:`~mm...
Scatter with support for kwargs dictionary.
9,452
import torch from torch.nn.parallel._functions import _get_stream def synchronize_stream(output, devices, streams): if isinstance(output, list): chunk_size = len(output) // len(devices) for i in range(len(devices)): for j in range(chunk_size): synchronize_stream(output[i...
null
9,453
import torch from torch.nn.parallel._functions import _get_stream def get_input_device(input): if isinstance(input, list): for item in input: input_device = get_input_device(item) if input_device != -1: return input_device return -1 elif isinstance(input,...
null
9,454
import functools import torch def assert_tensor_type(func): @functools.wraps(func) def wrapper(*args, **kwargs): if not isinstance(args[0].data, torch.Tensor): raise AttributeError( f'{args[0].__class__.__name__} has no attribute ' f'{func.__name__} for type...
null
9,455
import numpy as np The provided code snippet includes necessary dependencies for implementing the `quantize` function. Write a Python function `def quantize(arr, min_val, max_val, levels, dtype=np.int64)` to solve the following problem: Quantize an array of (-inf, inf) to [0, levels-1]. Args: arr (ndarray): Input arra...
Quantize an array of (-inf, inf) to [0, levels-1]. Args: arr (ndarray): Input array. min_val (scalar): Minimum value to be clipped. max_val (scalar): Maximum value to be clipped. levels (int): Quantization levels. dtype (np.type): The type of the quantized array. Returns: tuple: Quantized array.
9,456
import numpy as np The provided code snippet includes necessary dependencies for implementing the `dequantize` function. Write a Python function `def dequantize(arr, min_val, max_val, levels, dtype=np.float64)` to solve the following problem: Dequantize an array. Args: arr (ndarray): Input array. min_val (scalar): Min...
Dequantize an array. Args: arr (ndarray): Input array. min_val (scalar): Minimum value to be clipped. max_val (scalar): Maximum value to be clipped. levels (int): Quantization levels. dtype (np.type): The type of the dequantized array. Returns: tuple: Dequantized array.
9,457
import torch import torch.nn as nn import torch.nn.functional as F from .registry import CONV_LAYERS def conv_ws_2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1, eps=1e-5): c_in = weight....
null
9,458
import copy import warnings import torch import torch.nn as nn from annotator.uniformer.mmcv import ConfigDict, deprecated_api_warning from annotator.uniformer.mmcv.cnn import Linear, build_activation_layer, build_norm_layer from annotator.uniformer.mmcv.runner.base_module import BaseModule, ModuleList, Sequential from...
Builder for Position Encoding.
9,459
import copy import warnings import torch import torch.nn as nn from annotator.uniformer.mmcv import ConfigDict, deprecated_api_warning from annotator.uniformer.mmcv.cnn import Linear, build_activation_layer, build_norm_layer from annotator.uniformer.mmcv.runner.base_module import BaseModule, ModuleList, Sequential from...
Builder for attention.
9,460
import copy import warnings import torch import torch.nn as nn from annotator.uniformer.mmcv import ConfigDict, deprecated_api_warning from annotator.uniformer.mmcv.cnn import Linear, build_activation_layer, build_norm_layer from annotator.uniformer.mmcv.runner.base_module import BaseModule, ModuleList, Sequential from...
Builder for feed-forward network (FFN).
9,461
import copy import warnings import torch import torch.nn as nn from annotator.uniformer.mmcv import ConfigDict, deprecated_api_warning from annotator.uniformer.mmcv.cnn import Linear, build_activation_layer, build_norm_layer from annotator.uniformer.mmcv.runner.base_module import BaseModule, ModuleList, Sequential from...
Builder for transformer layer.
9,462
import copy import warnings import torch import torch.nn as nn from annotator.uniformer.mmcv import ConfigDict, deprecated_api_warning from annotator.uniformer.mmcv.cnn import Linear, build_activation_layer, build_norm_layer from annotator.uniformer.mmcv.runner.base_module import BaseModule, ModuleList, Sequential from...
Builder for transformer encoder and transformer decoder.
9,463
import math import torch import torch.nn as nn from torch.nn.modules.utils import _pair, _triple from .registry import CONV_LAYERS, UPSAMPLE_LAYERS def obsolete_torch_version(torch_version, version_threshold): return torch_version == 'parrots' or torch_version <= version_threshold
null
9,464
import inspect import platform from .registry import PLUGIN_LAYERS def infer_abbr(class_type): """Infer abbreviation from the class name. This method will infer the abbreviation to map class types to abbreviations. Rule 1: If the class has the property "abbr", return the property. Rule 2: Otherwise,...
Build plugin layer. Args: cfg (None or dict): cfg should contain: type (str): identify plugin layer type. layer args: args needed to instantiate a plugin layer. postfix (int, str): appended into norm abbreviation to create named layer. Default: ''. Returns: tuple[str, nn.Module]: name (str): abbreviation + postfix laye...
9,465
import torch from torch import nn from ..utils import constant_init, kaiming_init from .registry import PLUGIN_LAYERS def last_zero_init(m): if isinstance(m, nn.Sequential): constant_init(m[-1], val=0) else: constant_init(m, val=0)
null
9,466
import torch.nn as nn from .registry import PADDING_LAYERS PADDING_LAYERS.register_module('zero', module=nn.ZeroPad2d) PADDING_LAYERS.register_module('reflect', module=nn.ReflectionPad2d) PADDING_LAYERS.register_module('replicate', module=nn.ReplicationPad2d) PADDING_LAYERS = Registry('padding layer') The provided co...
Build padding layer. Args: cfg (None or dict): The padding layer config, which should contain: - type (str): Layer type. - layer args: Args needed to instantiate a padding layer. Returns: nn.Module: Created padding layer.
9,467
import torch import torch.nn as nn from annotator.uniformer.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 followin...
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
9,468
import torch import torch.nn as nn from annotator.uniformer.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(c...
Builder for drop out layers.
9,469
import inspect import torch.nn as nn from annotator.uniformer.mmcv.utils import is_tuple_of from annotator.uniformer.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', m...
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...
9,470
import inspect import torch.nn as nn from annotator.uniformer.mmcv.utils import is_tuple_of from annotator.uniformer.mmcv.utils.parrots_wrapper import SyncBatchNorm, _BatchNorm, _InstanceNorm from .registry import NORM_LAYERS _BatchNorm, _InstanceNorm, SyncBatchNorm_ = _get_norm() The provided code snippet includes n...
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.
9,471
from torch import nn from .registry import CONV_LAYERS CONV_LAYERS.register_module('Conv1d', module=nn.Conv1d) CONV_LAYERS.register_module('Conv2d', module=nn.Conv2d) CONV_LAYERS.register_module('Conv3d', module=nn.Conv3d) CONV_LAYERS.register_module('Conv', module=nn.Conv2d) CONV_LAYERS = Registry('conv layer') The ...
Build convolution layer. Args: cfg (None or dict): The conv layer config, which should contain: - type (str): Layer type. - layer args: Args needed to instantiate an conv layer. args (argument list): Arguments passed to the `__init__` method of the corresponding conv layer. kwargs (keyword arguments): Keyword arguments...
9,472
import torch import torch.nn as nn import torch.nn.functional as F from annotator.uniformer.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...
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.
9,473
import torch.nn as nn import torch.nn.functional as F from ..utils import xavier_init from .registry import UPSAMPLE_LAYERS UPSAMPLE_LAYERS.register_module('nearest', module=nn.Upsample) UPSAMPLE_LAYERS.register_module('bilinear', module=nn.Upsample) UPSAMPLE_LAYERS = Registry('upsample layer') The provided code snip...
Build upsample layer. Args: cfg (dict): The upsample layer config, which should contain: - type (str): Layer type. - scale_factor (int): Upsample ratio, which is not applicable to deconv. - layer args: Args needed to instantiate a upsample layer. args (argument list): Arguments passed to the ``__init__`` method of the ...
9,474
from ..runner import Sequential from ..utils import Registry, build_from_cfg The provided code snippet includes necessary dependencies for implementing the `build_model_from_cfg` function. Write a Python function `def build_model_from_cfg(cfg, registry, default_args=None)` to solve the following problem: Build a PyTor...
Build a PyTorch model from config dict(s). Different from ``build_from_cfg``, if cfg is a list, a ``nn.Sequential`` will be built. Args: cfg (dict, list[dict]): The config of modules, is is either a config dict or a list of config dicts. If cfg is a list, a the built modules will be wrapped with ``nn.Sequential``. regi...
9,475
import logging import torch.nn as nn import torch.utils.checkpoint as cp from .utils import constant_init, kaiming_init The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, stride=1, dilation=1)` to solve the foll...
3x3 convolution with padding.