id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
33,994
import logging import torch import torch.nn.functional as F from omegaconf import OmegaConf from annotator.lama.saicinpainting.training.losses.distance_weighting import make_mask_distance_weighter from annotator.lama.saicinpainting.training.losses.feature_matching import feature_matching_loss, masked_l1_loss from annot...
null
33,995
import copy import logging from typing import Dict, Tuple import pandas as pd import pytorch_lightning as ptl import torch import torch.nn as nn import torch.nn.functional as F from annotator.lama.saicinpainting.training.modules import make_generator from annotator.lama.saicinpainting.utils import add_prefix_to_keys, ...
null
33,996
import copy import logging from typing import Dict, Tuple import pandas as pd import pytorch_lightning as ptl import torch import torch.nn as nn import torch.nn.functional as F from annotator.lama.saicinpainting.training.modules import make_generator from annotator.lama.saicinpainting.utils import add_prefix_to_keys, ...
null
33,997
import copy import logging from typing import Dict, Tuple import pandas as pd import pytorch_lightning as ptl import torch import torch.nn as nn import torch.nn.functional as F from annotator.lama.saicinpainting.training.modules import make_generator from annotator.lama.saicinpainting.utils import add_prefix_to_keys, ...
null
33,998
import os import numpy as np import cv2 import torch from torch.nn import functional as F from modules import devices 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 asser...
null
33,999
import os import numpy as np import cv2 import torch from torch.nn import functional as F from modules import devices 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 asser...
shape = [height, width]
34,002
import math import torch import torch.nn as nn import torch.nn.functional as F from modules import devices class PiDiNet(nn.Module): def __init__(self, inplane, pdcs, dil=None, sa=False, convert=False): super(PiDiNet, self).__init__() self.sa = sa if dil is not None: assert isins...
null
34,003
import torch try: import mmcv as mmcv from mmcv.parallel import collate, scatter from mmcv.runner import load_checkpoint from mmseg.datasets.pipelines import Compose from mmseg.models import build_segmentor except ImportError: import annotator.mmpkg.mmcv as mmcv from annotator.mmpkg.mmcv.par...
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,004
import torch class LoadImage: """A simple pipeline to load image.""" def __call__(self, results): """Call function to load images into results. Args: results (dict): A result dict contains the file name of the image to be read. Returns: dict: ``res...
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,005
import torch try: import mmcv as mmcv from mmcv.parallel import collate, scatter from mmcv.runner import load_checkpoint from mmseg.datasets.pipelines import Compose from mmseg.models import build_segmentor except ImportError: import annotator.mmpkg.mmcv as mmcv from annotator.mmpkg.mmcv.par...
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,006
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint from functools import partial from collections import OrderedDict from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from annotator.uniformer.mmcv_custom import load_checkpoint The provided cod...
Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C)
34,007
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint from functools import partial from collections import OrderedDict from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from annotator.uniformer.mmcv_custom import load_checkpoint The provided cod...
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)
34,008
import io import os import os.path as osp import pkgutil import time import warnings from collections import OrderedDict from importlib import import_module from tempfile import TemporaryDirectory import torch import torchvision from torch.optim import Optimizer from torch.utils import model_zoo from torch.nn import fu...
Load checkpoint from a file or URI. Args: model (Module): Module to load checkpoint. filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for details. map_location (str): Same as :func:`torch.load`. strict (bool): Whether to allow different param...
34,009
import io import os import os.path as osp import pkgutil import time import warnings from collections import OrderedDict from importlib import import_module from tempfile import TemporaryDirectory import torch import torchvision from torch.optim import Optimizer from torch.utils import model_zoo from torch.nn import fu...
Save checkpoint to file. The checkpoint will have 3 fields: ``meta``, ``state_dict`` and ``optimizer``. By default ``meta`` will contain version and time info. Args: model (Module): Module whose params are to be saved. filename (str): Checkpoint filename. optimizer (:obj:`Optimizer`, optional): Optimizer to be saved. m...
34,010
import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `smish` function. Write a Python function `def smish(input)` to solve the following problem: Applies the mish function element-wise: mish(x) = x * tanh(softplus(x)) = x * tanh(ln(1 + exp(sigmoid(...
Applies the mish function element-wise: mish(x) = x * tanh(softplus(x)) = x * tanh(ln(1 + exp(sigmoid(x)))) See additional documentation for mish class.
34,011
import torch import torch.nn as nn import torch.nn.functional as F from .Fsmish import smish as Fsmish from .Xsmish import Smish def weight_init(m): if isinstance(m, (nn.Conv2d,)): torch.nn.init.xavier_normal_(m.weight, gain=1.0) if m.bias is not None: torch.nn.init.zeros_(m.bias) ...
null
34,012
import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `mish` function. Write a Python function `def mish(input)` to solve the following problem: Applies the mish function element-wise: mish(x) = x * tanh(softplus(x)) = x * tanh(ln(1 + exp(x))) See a...
Applies the mish function element-wise: mish(x) = x * tanh(softplus(x)) = x * tanh(ln(1 + exp(x))) See additional documentation for mish class.
34,013
import os import torch from annotator.oneformer.detectron2.config import get_cfg from annotator.oneformer.detectron2.projects.deeplab import add_deeplab_config from annotator.oneformer.detectron2.data import MetadataCatalog from annotator.oneformer.oneformer import ( add_oneformer_config, add_common_config, ...
null
34,014
import os import torch from annotator.oneformer.detectron2.config import get_cfg from annotator.oneformer.detectron2.projects.deeplab import add_deeplab_config from annotator.oneformer.detectron2.data import MetadataCatalog from annotator.oneformer.oneformer import ( add_oneformer_config, add_common_config, ...
null
34,017
import numpy as np from typing import Any, List, Tuple, Union import torch from torch.nn import functional as F The provided code snippet includes necessary dependencies for implementing the `heatmaps_to_keypoints` function. Write a Python function `def heatmaps_to_keypoints(maps: torch.Tensor, rois: torch.Tensor) -> ...
Extract predicted keypoint locations from heatmaps. Args: maps (Tensor): (#ROIs, #keypoints, POOL_H, POOL_W). The predicted heatmap of logits for each ROI and each keypoint. rois (Tensor): (#ROIs, 4). The box of each ROI. Returns: Tensor of shape (#ROIs, #keypoints, 4) with the last dimension corresponding to (x, y, lo...
34,018
import copy import itertools import numpy as np from typing import Any, Iterator, List, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from torch import device from annotator.oneformer.detectron2.layers.roi_align import ROIAlign from annotator.oneformer.detectron2.utils.memory import retry_...
null
34,019
import copy import itertools import numpy as np from typing import Any, Iterator, List, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from torch import device from annotator.oneformer.detectron2.layers.roi_align import ROIAlign from annotator.oneformer.detectron2.utils.memory import retry_...
Rasterize the polygons into a mask image and crop the mask content in the given box. The cropped mask is resized to (mask_size, mask_size). This function is used when generating training targets for mask head in Mask R-CNN. Given original ground-truth masks for an image, new ground-truth mask training targets in the si...
34,020
import math from typing import List, Tuple import torch from annotator.oneformer.detectron2.layers.rotated_boxes import pairwise_iou_rotated from .boxes import Boxes class RotatedBoxes(Boxes): """ This structure stores a list of rotated boxes as a Nx5 torch.Tensor. It supports some common methods about boxe...
Given two lists of rotated boxes of size N and M, compute the IoU (intersection over union) between **all** N x M pairs of boxes. The box order must be (x_center, y_center, width, height, angle). Args: boxes1, boxes2 (RotatedBoxes): two `RotatedBoxes`. Contains N & M rotated boxes, respectively. Returns: Tensor: IoU, s...
34,021
import math import numpy as np from enum import IntEnum, unique from typing import List, Tuple, Union import torch from torch import device class Boxes: """ This structure stores a list of boxes as a Nx4 torch.Tensor. It supports some common methods about boxes (`area`, `clip`, `nonempty`, etc), and...
Given two lists of boxes of size N and M, compute the IoU (intersection over union) between **all** N x M pairs of boxes. The box order must be (xmin, ymin, xmax, ymax). Args: boxes1,boxes2 (Boxes): two `Boxes`. Contains N & M boxes, respectively. Returns: Tensor: IoU, sized [N,M].
34,022
import math import numpy as np from enum import IntEnum, unique from typing import List, Tuple, Union import torch from torch import device class Boxes: """ This structure stores a list of boxes as a Nx4 torch.Tensor. It supports some common methods about boxes (`area`, `clip`, `nonempty`, etc), and...
Similar to :func:`pariwise_iou` but compute the IoA (intersection over boxes2 area). Args: boxes1,boxes2 (Boxes): two `Boxes`. Contains N & M boxes, respectively. Returns: Tensor: IoA, sized [N,M].
34,023
import math import numpy as np from enum import IntEnum, unique from typing import List, Tuple, Union import torch from torch import device class Boxes: """ This structure stores a list of boxes as a Nx4 torch.Tensor. It supports some common methods about boxes (`area`, `clip`, `nonempty`, etc), and...
Pairwise distance between N points and M boxes. The distance between a point and a box is represented by the distance from the point to 4 edges of the box. Distances are all positive when the point is inside the box. Args: points: Nx2 coordinates. Each row is (x, y) boxes: M boxes Returns: Tensor: distances of size (N,...
34,024
import math import numpy as np from enum import IntEnum, unique from typing import List, Tuple, Union import torch from torch import device class Boxes: """ This structure stores a list of boxes as a Nx4 torch.Tensor. It supports some common methods about boxes (`area`, `clip`, `nonempty`, etc), and...
Compute pairwise intersection over union (IOU) of two sets of matched boxes that have the same number of boxes. Similar to :func:`pairwise_iou`, but computes only diagonal elements of the matrix. Args: boxes1 (Boxes): bounding boxes, sized [N,4]. boxes2 (Boxes): same length as boxes1 Returns: Tensor: iou, sized [N].
34,025
import contextlib from unittest import mock import torch from annotator.oneformer.detectron2.modeling import poolers from annotator.oneformer.detectron2.modeling.proposal_generator import rpn from annotator.oneformer.detectron2.modeling.roi_heads import keypoint_head, mask_head from annotator.oneformer.detectron2.model...
null
34,026
import contextlib from unittest import mock import torch from annotator.oneformer.detectron2.modeling import poolers from annotator.oneformer.detectron2.modeling.proposal_generator import rpn from annotator.oneformer.detectron2.modeling.roi_heads import keypoint_head, mask_head from annotator.oneformer.detectron2.model...
null
34,027
import contextlib from unittest import mock import torch from annotator.oneformer.detectron2.modeling import poolers from annotator.oneformer.detectron2.modeling.proposal_generator import rpn from annotator.oneformer.detectron2.modeling.roi_heads import keypoint_head, mask_head from annotator.oneformer.detectron2.model...
null
34,028
import contextlib from unittest import mock import torch from annotator.oneformer.detectron2.modeling import poolers from annotator.oneformer.detectron2.modeling.proposal_generator import rpn from annotator.oneformer.detectron2.modeling.roi_heads import keypoint_head, mask_head from annotator.oneformer.detectron2.model...
null
34,029
import collections from dataclasses import dataclass from typing import Callable, List, Optional, Tuple import torch from torch import nn from annotator.oneformer.detectron2.structures import Boxes, Instances, ROIMasks from annotator.oneformer.detectron2.utils.registry import _convert_target_to_string, locate from .tor...
Flatten an object so it can be used for PyTorch tracing. Also returns how to rebuild the original object from the flattened outputs. Returns: res (tuple): the flattened results that can be used as tracing outputs schema: an object with a ``__call__`` method such that ``schema(res) == obj``. It is a pure dataclass that ...
34,030
import os import sys import tempfile from contextlib import ExitStack, contextmanager from copy import deepcopy from unittest import mock import torch from torch import nn import annotator.oneformer.detectron2 from annotator.oneformer.detectron2.structures import Boxes, Instances from annotator.oneformer.detectron2.ut...
Patch the builtin len() function of a few detectron2 modules to use __len__ instead, because __len__ does not convert values to integers and therefore is friendly to tracing. Args: modules (list[stsr]): names of extra modules to patch len(), in addition to those in detectron2.
34,031
import os import sys import tempfile from contextlib import ExitStack, contextmanager from copy import deepcopy from unittest import mock import torch from torch import nn import annotator.oneformer.detectron2 from annotator.oneformer.detectron2.structures import Boxes, Instances from annotator.oneformer.detectron2.ut...
Apply patches on a few nonscriptable detectron2 classes. Should not have side-effects on eager usage.
34,032
import functools import io import struct import types import torch from annotator.oneformer.detectron2.modeling import meta_arch from annotator.oneformer.detectron2.modeling.box_regression import Box2BoxTransform from annotator.oneformer.detectron2.modeling.roi_heads import keypoint_head from annotator.oneformer.detect...
A function to assemble caffe2 model's outputs (i.e. Dict[str, Tensor]) to detectron2's format (i.e. list of Instances instance). This only works when the model follows the Caffe2 detectron's naming convention. Args: image_sizes (List[List[int, int]]): [H, W] of every image. tensor_outputs (Dict[str, Tensor]): external_...
34,033
import functools import io import struct import types import torch from annotator.oneformer.detectron2.modeling import meta_arch from annotator.oneformer.detectron2.modeling.box_regression import Box2BoxTransform from annotator.oneformer.detectron2.modeling.roi_heads import keypoint_head from annotator.oneformer.detect...
null
34,034
import functools import io import struct import types import torch from annotator.oneformer.detectron2.modeling import meta_arch from annotator.oneformer.detectron2.modeling.box_regression import Box2BoxTransform from annotator.oneformer.detectron2.modeling.roi_heads import keypoint_head from annotator.oneformer.detect...
null
34,035
import functools import io import struct import types import torch from annotator.oneformer.detectron2.modeling import meta_arch from annotator.oneformer.detectron2.modeling.box_regression import Box2BoxTransform from annotator.oneformer.detectron2.modeling.roi_heads import keypoint_head from annotator.oneformer.detect...
See get_caffe2_inputs() below.
34,036
import copy import io import logging import numpy as np from typing import List import onnx import onnx.optimizer import torch from caffe2.proto import caffe2_pb2 from caffe2.python import core from caffe2.python.onnx.backend import Caffe2Backend from tabulate import tabulate from termcolor import colored from torch.on...
Export a caffe2-compatible Detectron2 model to caffe2 format via ONNX. Arg: model: a caffe2-compatible version of detectron2 model, defined in caffe2_modeling.py tensor_inputs: a list of tensors that caffe2 model takes as input.
34,037
import copy import io import logging import numpy as np from typing import List import onnx import onnx.optimizer import torch from caffe2.proto import caffe2_pb2 from caffe2.python import core from caffe2.python.onnx.backend import Caffe2Backend from tabulate import tabulate from termcolor import colored from torch.on...
Run the caffe2 model on given inputs, recording the shape and draw the graph. predict_net/init_net: caffe2 model. tensor_inputs: a list of tensors that caffe2 model takes as input. graph_save_path: path for saving graph of exported model.
34,038
import collections import copy import functools import logging import numpy as np import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union from unittest import mock import caffe2.python.utils as putils import torch import torch.nn.functional as F from caffe2.proto import caffe2_pb2 from caffe2.pyt...
null
34,039
import collections import copy import functools import logging import numpy as np import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union from unittest import mock import caffe2.python.utils as putils import torch import torch.nn.functional as F from caffe2.proto import caffe2_pb2 from caffe2.pyt...
null
34,040
import collections import copy import functools import logging import numpy as np import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union from unittest import mock import caffe2.python.utils as putils import torch import torch.nn.functional as F from caffe2.proto import caffe2_pb2 from caffe2.pyt...
null
34,041
import collections import copy import functools import logging import numpy as np import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union from unittest import mock import caffe2.python.utils as putils import torch import torch.nn.functional as F from caffe2.proto import caffe2_pb2 from caffe2.pyt...
null
34,042
import collections import copy import functools import logging import numpy as np import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union from unittest import mock import caffe2.python.utils as putils import torch import torch.nn.functional as F from caffe2.proto import caffe2_pb2 from caffe2.pyt...
null
34,043
import collections import copy import functools import logging import numpy as np import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union from unittest import mock import caffe2.python.utils as putils import torch import torch.nn.functional as F from caffe2.proto import caffe2_pb2 from caffe2.pyt...
null
34,044
import os import torch from annotator.oneformer.detectron2.utils.file_io import PathManager from .torchscript_patch import freeze_training_mode, patch_instances def patch_instances(fields): """ A contextmanager, under which the Instances class in detectron2 is replaced by a statically-typed scriptable clas...
Run :func:`torch.jit.script` on a model that uses the :class:`Instances` class. Since attributes of :class:`Instances` are "dynamically" added in eager mode,it is difficult for scripting to support it out of the box. This function is made to support scripting a model that uses :class:`Instances`. It does the following:...
34,045
import os import torch from annotator.oneformer.detectron2.utils.file_io import PathManager from .torchscript_patch import freeze_training_mode, patch_instances PathManager = PathManagerBase() PathManager.register_handler(HTTPURLHandler()) PathManager.register_handler(OneDrivePathHandler()) PathManager.register_ha...
Dump IR of a TracedModule/ScriptModule/Function in various format (code, graph, inlined graph). Useful for debugging. Args: model (TracedModule/ScriptModule/ScriptFUnction): traced or scripted module dir (str): output directory to dump files.
34,046
import os from typing import Optional import pkg_resources import torch from annotator.oneformer.detectron2.checkpoint import DetectionCheckpointer from annotator.oneformer.detectron2.config import CfgNode, LazyConfig, get_cfg, instantiate from annotator.oneformer.detectron2.modeling import build_model def get_config(c...
Get a model specified by relative path under Detectron2's official ``configs/`` directory. Args: config_path (str): config file name relative to detectron2's "configs/" directory, e.g., "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml" trained (bool): see :func:`get_config`. device (str or None): overwrite the dev...
34,047
import warnings from typing import List, Optional import torch from torch.nn import functional as F from annotator.oneformer.detectron2.utils.env import TORCH_VERSION The provided code snippet includes necessary dependencies for implementing the `shapes_to_tensor` function. Write a Python function `def shapes_to_tenso...
Turn a list of integer scalars or integer Tensor scalars into a vector, in a way that's both traceable and scriptable. In tracing, `x` should be a list of scalar Tensor, so the output can trace to the inputs. In scripting or eager, `x` should be a list of int.
34,048
import warnings from typing import List, Optional import torch from torch.nn import functional as F from annotator.oneformer.detectron2.utils.env import TORCH_VERSION TORCH_VERSION = tuple(int(x) for x in torch.__version__.split(".")[:2]) def check_if_dynamo_compiling(): if TORCH_VERSION >= (1, 14): from ...
null
34,049
import warnings from typing import List, Optional import torch from torch.nn import functional as F from annotator.oneformer.detectron2.utils.env import TORCH_VERSION def empty_input_loss_func_wrapper(loss_func): def wrapped_loss_func(input, target, *, reduction="mean", **kwargs): """ Same as `loss...
null
34,050
import warnings from typing import List, Optional import torch from torch.nn import functional as F from annotator.oneformer.detectron2.utils.env import TORCH_VERSION The provided code snippet includes necessary dependencies for implementing the `nonzero_tuple` function. Write a Python function `def nonzero_tuple(x)` ...
A 'as_tuple=True' version of torch.nonzero to support torchscript. because of https://github.com/pytorch/pytorch/issues/38718
34,052
import math import torch The provided code snippet includes necessary dependencies for implementing the `ciou_loss` function. Write a Python function `def ciou_loss( boxes1: torch.Tensor, boxes2: torch.Tensor, reduction: str = "none", eps: float = 1e-7, ) -> torch.Tensor` to solve the following problem...
Complete Intersection over Union Loss (Zhaohui Zheng et. al) https://arxiv.org/abs/1911.08287 Args: boxes1, boxes2 (Tensor): box locations in XYXY format, shape (N, 4) or (4,). reduction: 'none' | 'mean' | 'sum' 'none': No reduction will be applied to the output. 'mean': The output will be averaged. 'sum': The output w...
34,054
import torch from torchvision.ops import boxes as box_ops from torchvision.ops import nms def nms_rotated(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float): """ Performs non-maximum suppression (NMS) on the rotated boxes according to their intersection-over-union (IoU). Rotated NMS itera...
Performs non-maximum suppression in a batched fashion. Each index value correspond to a category, and NMS will not be applied between elements of different categories. Args: boxes (Tensor[N, 5]): boxes where NMS will be performed. They are expected to be in (x_ctr, y_ctr, width, height, angle_degrees) format scores (Te...
34,059
import torch import torch.distributed as dist from fvcore.nn.distributed import differentiable_all_reduce from torch import nn from torch.nn import functional as F from annotator.oneformer.detectron2.utils import comm, env from .wrappers import BatchNorm2d class FrozenBatchNorm2d(nn.Module): """ BatchNorm2d whe...
Args: norm (str or callable): either one of BN, SyncBN, FrozenBN, GN; or a callable that takes a channel number and returns the normalization layer as a nn.Module. Returns: nn.Module or None: the normalization layer
34,060
import logging import numpy as np from itertools import count from typing import List, Tuple import torch import tqdm from fvcore.common.timer import Timer from annotator.oneformer.detectron2.utils import comm from .build import build_batch_data_loader from .common import DatasetFromList, MapDataset from .samplers impo...
Benchmark an iterator/iterable for `num_iter` iterations with an extra `warmup` iterations of warmup. End early if `max_time_seconds` time is spent on iterations. Returns: float: average time (seconds) per iteration list[float]: time spent on each iteration. Sometimes useful for further analysis.
34,061
import contextlib import copy import itertools import logging import numpy as np import pickle import random from typing import Callable, Union import torch import torch.utils.data as data from torch.utils.data.sampler import Sampler from annotator.oneformer.detectron2.utils.serialize import PicklableWrapper def _shar...
null
34,062
import contextlib import copy import itertools import logging import numpy as np import pickle import random from typing import Callable, Union import torch import torch.utils.data as data from torch.utils.data.sampler import Sampler from annotator.oneformer.detectron2.utils.serialize import PicklableWrapper _DEFAULT_D...
Context manager for using custom serialize function when creating DatasetFromList
34,063
import logging import numpy as np from typing import List, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from PIL import Image from annotator.oneformer.detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, ...
Convert an image from given format to RGB. Args: image (np.ndarray or Tensor): an HWC image format (str): the format of input image, also see `read_image` Returns: (np.ndarray): (H,W,3) RGB image in 0-255 range, can be either float or uint8
34,064
import logging import numpy as np from typing import List, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from PIL import Image from annotator.oneformer.detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, ...
Read an image into the given format. Will apply rotation and flipping if the image has such exif information. Args: file_name (str): image file path format (str): one of the supported image modes in PIL, or "BGR" or "YUV-BT.601". Returns: image (np.ndarray): an HWC image in the given format, which is 0-255, uint8 for s...
34,065
import logging import numpy as np from typing import List, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from PIL import Image from annotator.oneformer.detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, ...
Raise an error if the image does not match the size specified in the dict.
34,066
import logging import numpy as np from typing import List, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from PIL import Image from annotator.oneformer.detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, ...
Apply transformations to the proposals in dataset_dict, if any. Args: dataset_dict (dict): a dict read from the dataset, possibly contains fields "proposal_boxes", "proposal_objectness_logits", "proposal_bbox_mode" image_shape (tuple): height, width transforms (TransformList): proposal_topk (int): only keep top-K scori...
34,067
import logging import numpy as np from typing import List, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from PIL import Image from annotator.oneformer.detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, ...
Get bbox from data Args: annotation (dict): dict of instance annotations for a single instance. Returns: bbox (ndarray): x1, y1, x2, y2 coordinates
34,068
import logging import numpy as np from typing import List, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from PIL import Image from annotator.oneformer.detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, ...
Apply transforms to box, segmentation and keypoints annotations of a single instance. It will use `transforms.apply_box` for the box, and `transforms.apply_coords` for segmentation polygons & keypoints. If you need anything more specially designed for each data structure, you'll need to implement your own version of th...
34,069
import logging import numpy as np from typing import List, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from PIL import Image from annotator.oneformer.detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, ...
Create an :class:`Instances` object used by the models, from instance annotations in the dataset dict. Args: annos (list[dict]): a list of instance annotations in one image, each element for one instance. image_size (tuple): height, width Returns: Instances: It will contain fields "gt_boxes", "gt_classes", "gt_masks", ...
34,070
import logging import numpy as np from typing import List, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from PIL import Image from annotator.oneformer.detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, ...
Create an :class:`Instances` object used by the models, from instance annotations in the dataset dict. Compared to `annotations_to_instances`, this function is for rotated boxes only Args: annos (list[dict]): a list of instance annotations in one image, each element for one instance. image_size (tuple): height, width R...
34,071
import logging import numpy as np from typing import List, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from PIL import Image from annotator.oneformer.detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, ...
Filter out empty instances in an `Instances` object. Args: instances (Instances): by_box (bool): whether to filter out instances with empty boxes by_mask (bool): whether to filter out instances with empty masks box_threshold (float): minimum width and height to be considered non-empty return_mask (bool): whether to ret...
34,072
import logging import numpy as np from typing import List, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from PIL import Image from annotator.oneformer.detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, ...
Args: dataset_names: list of dataset names Returns: list[int]: a list of size=#keypoints, storing the horizontally-flipped keypoint indices.
34,073
import logging import numpy as np from typing import List, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from PIL import Image from annotator.oneformer.detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, ...
Get frequency weight for each class sorted by class id. We now calcualte freqency weight using image_count to the power freq_weight_power. Args: dataset_names: list of dataset names freq_weight_power: power value
34,074
import logging import numpy as np from typing import List, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from PIL import Image from annotator.oneformer.detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, ...
Generate a CropTransform so that the cropping region contains the center of the given instance. Args: crop_size (tuple): h, w in pixels image_size (tuple): h, w instance (dict): an annotation dict of one instance, in Detectron2's dataset format.
34,075
import logging import numpy as np from typing import List, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from PIL import Image from annotator.oneformer.detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, ...
Create a list of default :class:`Augmentation` from config. Now it includes resizing and flipping. Returns: list[Augmentation]
34,077
import inspect import numpy as np import pprint from typing import Any, List, Optional, Tuple, Union from fvcore.transforms.transform import Transform, TransformList The provided code snippet includes necessary dependencies for implementing the `_get_aug_input_args` function. Write a Python function `def _get_aug_inpu...
Get the arguments to be passed to ``aug.get_transform`` from the input ``aug_input``.
34,078
import inspect import numpy as np import pprint from typing import Any, List, Optional, Tuple, Union from fvcore.transforms.transform import Transform, TransformList class Augmentation: """ Augmentation defines (often random) policies/strategies to generate :class:`Transform` from data. It is often used for...
Wrap Transform into Augmentation. Private, used internally to implement augmentations.
34,082
import contextlib import datetime import io import json import logging import numpy as np import os import shutil import annotator.oneformer.pycocotools.mask as mask_util from fvcore.common.timer import Timer from iopath.common.file_io import file_lock from PIL import Image from annotator.oneformer.detectron2.structure...
Converts dataset into COCO format and saves it to a json file. dataset_name must be registered in DatasetCatalog and in detectron2's standard format. Args: dataset_name: reference from the config file to the catalogs must be registered in DatasetCatalog and in detectron2's standard format output_file: path of json file...
34,083
import os from annotator.oneformer.detectron2.data import DatasetCatalog, MetadataCatalog from .builtin_meta import ADE20K_SEM_SEG_CATEGORIES, _get_builtin_metadata from .cityscapes import load_cityscapes_instances, load_cityscapes_semantic from .cityscapes_panoptic import register_all_cityscapes_panoptic from .coco im...
null
34,084
import os from annotator.oneformer.detectron2.data import DatasetCatalog, MetadataCatalog from .builtin_meta import ADE20K_SEM_SEG_CATEGORIES, _get_builtin_metadata from .cityscapes import load_cityscapes_instances, load_cityscapes_semantic from .cityscapes_panoptic import register_all_cityscapes_panoptic from .coco im...
null
34,085
import os from annotator.oneformer.detectron2.data import DatasetCatalog, MetadataCatalog from .builtin_meta import ADE20K_SEM_SEG_CATEGORIES, _get_builtin_metadata from .cityscapes import load_cityscapes_instances, load_cityscapes_semantic from .cityscapes_panoptic import register_all_cityscapes_panoptic from .coco im...
null
34,086
import os from annotator.oneformer.detectron2.data import DatasetCatalog, MetadataCatalog from .builtin_meta import ADE20K_SEM_SEG_CATEGORIES, _get_builtin_metadata from .cityscapes import load_cityscapes_instances, load_cityscapes_semantic from .cityscapes_panoptic import register_all_cityscapes_panoptic from .coco im...
null
34,087
import os from annotator.oneformer.detectron2.data import DatasetCatalog, MetadataCatalog from .builtin_meta import ADE20K_SEM_SEG_CATEGORIES, _get_builtin_metadata from .cityscapes import load_cityscapes_instances, load_cityscapes_semantic from .cityscapes_panoptic import register_all_cityscapes_panoptic from .coco im...
null
34,088
import json import logging import os from annotator.oneformer.detectron2.data import DatasetCatalog, MetadataCatalog from annotator.oneformer.detectron2.data.datasets.builtin_meta import CITYSCAPES_CATEGORIES from annotator.oneformer.detectron2.utils.file_io import PathManager def load_cityscapes_panoptic(image_dir, gt...
null
34,089
import itertools import logging import numpy as np import operator import pickle from typing import Any, Callable, Dict, List, Optional, Union import torch import torch.utils.data as torchdata from tabulate import tabulate from termcolor import colored from annotator.oneformer.detectron2.config import configurable from...
null
34,090
import itertools import logging import numpy as np import operator import pickle from typing import Any, Callable, Dict, List, Optional, Union import torch import torch.utils.data as torchdata from tabulate import tabulate from termcolor import colored from annotator.oneformer.detectron2.config import configurable from...
Build a dataloader for object detection with some default features. Args: dataset (list or torch.utils.data.Dataset): a list of dataset dicts, or a pytorch dataset (either map-style or iterable). It can be obtained by using :func:`DatasetCatalog.get` or :func:`get_detection_dataset_dicts`. mapper (callable): a callable...
34,091
import itertools import logging import numpy as np import operator import pickle from typing import Any, Callable, Dict, List, Optional, Union import torch import torch.utils.data as torchdata from tabulate import tabulate from termcolor import colored from annotator.oneformer.detectron2.config import configurable from...
Uses the given `dataset_name` argument (instead of the names in cfg), because the standard practice is to evaluate each test set individually (not combining them).
34,092
import itertools import logging import numpy as np import operator import pickle from typing import Any, Callable, Dict, List, Optional, Union import torch import torch.utils.data as torchdata from tabulate import tabulate from termcolor import colored from annotator.oneformer.detectron2.config import configurable from...
Similar to `build_detection_train_loader`, with default batch size = 1, and sampler = :class:`InferenceSampler`. This sampler coordinates all workers to produce the exact set of all samples. Args: dataset: a list of dataset dicts, or a pytorch dataset (either map-style or iterable). They can be obtained by using :func:...
34,093
import torch from annotator.oneformer.detectron2.config import CfgNode from annotator.oneformer.detectron2.solver import LRScheduler from annotator.oneformer.detectron2.solver import build_lr_scheduler as build_d2_lr_scheduler from .lr_scheduler import WarmupPolyLR class WarmupPolyLR(LRScheduler): """ Poly lea...
Build a LR scheduler from config.
34,094
The provided code snippet includes necessary dependencies for implementing the `add_deeplab_config` function. Write a Python function `def add_deeplab_config(cfg)` to solve the following problem: Add config for DeepLab. Here is the function: def add_deeplab_config(cfg): """ Add config for DeepLab. """ ...
Add config for DeepLab.
34,095
import fvcore.nn.weight_init as weight_init import torch.nn.functional as F from annotator.oneformer.detectron2.layers import CNNBlockBase, Conv2d, get_norm from annotator.oneformer.detectron2.modeling import BACKBONE_REGISTRY from annotator.oneformer.detectron2.modeling.backbone.resnet import ( BasicStem, Bott...
Create a ResNet instance from config. Returns: ResNet: a :class:`ResNet` instance.
34,096
import itertools import logging from typing import Dict, List import torch from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import ShapeSpec, batched_nms_rotated, cat from annotator.oneformer.detectron2.structures import Instances, RotatedBoxes, pairwise_iou_rota...
For each feature map, select the `pre_nms_topk` highest scoring proposals, apply NMS, clip proposals, and remove small boxes. Return the `post_nms_topk` highest scoring proposals among all the feature maps if `training` is True, otherwise, returns the highest `post_nms_topk` scoring proposals for each feature map. Args...
34,097
from typing import Dict, List, Optional, Tuple, Union import torch import torch.nn.functional as F from torch import nn from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import Conv2d, ShapeSpec, cat from annotator.oneformer.detectron2.structures import Boxes, Ima...
Build an RPN head defined by `cfg.MODEL.RPN.HEAD_NAME`.
34,098
import logging import math from typing import List, Tuple, Union import torch from annotator.oneformer.detectron2.layers import batched_nms, cat, move_device_like from annotator.oneformer.detectron2.structures import Boxes, Instances def _is_tracing(): # (fixed in TORCH_VERSION >= 1.9) if torch.jit.is_scripting...
For each feature map, select the `pre_nms_topk` highest scoring proposals, apply NMS, clip proposals, and remove small boxes. Return the `post_nms_topk` highest scoring proposals among all the feature maps for each image. Args: proposals (list[Tensor]): A list of L tensors. Tensor i has shape (N, Hi*Wi*A, 4). All propo...
34,099
import logging import math from typing import List, Tuple, Union import torch from annotator.oneformer.detectron2.layers import batched_nms, cat, move_device_like from annotator.oneformer.detectron2.structures import Boxes, Instances def add_ground_truth_to_proposals_single_image( gt: Union[Instances, Boxes], propo...
Call `add_ground_truth_to_proposals_single_image` for all images. Args: gt(Union[List[Instances], List[Boxes]): list of N elements. Element i is a Instances representing the ground-truth for image i. proposals (list[Instances]): list of N elements. Element i is a Instances representing the proposals for image i. Return...
34,100
from annotator.oneformer.detectron2.utils.registry import Registry PROPOSAL_GENERATOR_REGISTRY = Registry("PROPOSAL_GENERATOR") PROPOSAL_GENERATOR_REGISTRY.__doc__ = """ Registry for proposal generator, which produces object proposals from feature maps. The registered object will be called with `obj(cfg, input_shape)`....
Build a proposal generator from `cfg.MODEL.PROPOSAL_GENERATOR.NAME`. The name can be "PrecomputedProposals" to use no proposal generator.
34,101
import math from typing import List, Tuple, Union import torch from fvcore.nn import giou_loss, smooth_l1_loss from torch.nn import functional as F from annotator.oneformer.detectron2.layers import cat, ciou_loss, diou_loss from annotator.oneformer.detectron2.structures import Boxes class Box2BoxTransform(object): ...
Compute loss for dense multi-level box regression. Loss is accumulated over ``fg_mask``. Args: anchors: #lvl anchor boxes, each is (HixWixA, 4) pred_anchor_deltas: #lvl predictions, each is (N, HixWixA, 4) gt_boxes: N ground truth boxes, each has shape (R, 4) (R = sum(Hi * Wi * A)) fg_mask: the foreground boolean mask ...
34,102
import torch from torch.nn import functional as F from annotator.oneformer.detectron2.structures import Instances, ROIMasks The provided code snippet includes necessary dependencies for implementing the `detector_postprocess` function. Write a Python function `def detector_postprocess( results: Instances, output_h...
Resize the output instances. The input images are often resized when entering an object detector. As a result, we often need the outputs of the detector in a different resolution from its inputs. This function will resize the raw outputs of an R-CNN detector to produce outputs according to the desired output resolution...
34,103
import torch from torch.nn import functional as F from annotator.oneformer.detectron2.structures import Instances, ROIMasks The provided code snippet includes necessary dependencies for implementing the `sem_seg_postprocess` function. Write a Python function `def sem_seg_postprocess(result, img_size, output_height, ou...
Return semantic segmentation predictions in the original resolution. The input images are often resized when entering semantic segmentor. Moreover, in same cases, they also padded inside segmentor to be divisible by maximum network stride. As a result, we often need the predictions of the segmentor in a different resol...
34,104
import torch from annotator.oneformer.detectron2.layers import nonzero_tuple The provided code snippet includes necessary dependencies for implementing the `subsample_labels` function. Write a Python function `def subsample_labels( labels: torch.Tensor, num_samples: int, positive_fraction: float, bg_label: int )` ...
Return `num_samples` (or fewer, if not enough found) random samples from `labels` which is a mixture of positives & negatives. It will try to return as many positives as possible without exceeding `positive_fraction * num_samples`, and then try to fill the remaining slots with negatives. Args: labels (Tensor): (N, ) la...
34,109
import math import fvcore.nn.weight_init as weight_init import torch import torch.nn.functional as F from torch import nn from annotator.oneformer.detectron2.layers import Conv2d, ShapeSpec, get_norm from .backbone import Backbone from .build import BACKBONE_REGISTRY from .resnet import build_resnet_backbone The provi...
Assert that each stride is 2x times its preceding stride, i.e. "contiguous in log2".
34,110
import math import fvcore.nn.weight_init as weight_init import torch import torch.nn.functional as F from torch import nn from annotator.oneformer.detectron2.layers import Conv2d, ShapeSpec, get_norm from .backbone import Backbone from .build import BACKBONE_REGISTRY from .resnet import build_resnet_backbone class FPN(...
Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`.
34,111
import math import fvcore.nn.weight_init as weight_init import torch import torch.nn.functional as F from torch import nn from annotator.oneformer.detectron2.layers import Conv2d, ShapeSpec, get_norm from .backbone import Backbone from .build import BACKBONE_REGISTRY from .resnet import build_resnet_backbone class FPN(...
Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`.