id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
34,112
import logging import numpy as np import torch import torch.nn as nn from .backbone import Backbone from .utils import ( PatchEmbed, add_decomposed_rel_pos, get_abs_pos, window_partition, window_unpartition, ) def attention_pool(x, pool, norm=None): # (B, H, W, C) -> (B, C, H, W) x = x.perm...
null
34,113
import logging import math import fvcore.nn.weight_init as weight_init import torch import torch.nn as nn from annotator.oneformer.detectron2.layers import CNNBlockBase, Conv2d, get_norm from annotator.oneformer.detectron2.modeling.backbone.fpn import _assert_strides_are_log2_contiguous from .backbone import Backbone f...
Calculate lr decay rate for different ViT blocks. Args: name (string): parameter name. lr_decay_rate (float): base lr decay rate. num_layers (int): number of ViT blocks. Returns: lr decay rate for the given parameter.
34,114
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint from annotator.oneformer.detectron2.modeling.backbone.backbone import Backbone The provided code snippet includes necessary dependencies for implementing the `window_partition` function. Wr...
Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C)
34,115
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint from annotator.oneformer.detectron2.modeling.backbone.backbone import Backbone The provided code snippet includes necessary dependencies for implementing the `window_reverse` function. Writ...
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,116
import numpy as np from torch import nn from annotator.oneformer.detectron2.layers import CNNBlockBase, ShapeSpec, get_norm from .backbone import Backbone The provided code snippet includes necessary dependencies for implementing the `conv2d` function. Write a Python function `def conv2d(w_in, w_out, k, *, stride=1, g...
Helper for building a conv2d layer.
34,117
import numpy as np from torch import nn from annotator.oneformer.detectron2.layers import CNNBlockBase, ShapeSpec, get_norm from .backbone import Backbone The provided code snippet includes necessary dependencies for implementing the `gap2d` function. Write a Python function `def gap2d()` to solve the following proble...
Helper for building a global average pooling layer.
34,118
import numpy as np from torch import nn from annotator.oneformer.detectron2.layers import CNNBlockBase, ShapeSpec, get_norm from .backbone import Backbone The provided code snippet includes necessary dependencies for implementing the `pool2d` function. Write a Python function `def pool2d(k, *, stride=1)` to solve the ...
Helper for building a pool2d layer.
34,119
import numpy as np from torch import nn from annotator.oneformer.detectron2.layers import CNNBlockBase, ShapeSpec, get_norm from .backbone import Backbone The provided code snippet includes necessary dependencies for implementing the `init_weights` function. Write a Python function `def init_weights(m)` to solve the f...
Performs ResNet-style weight initialization.
34,120
import numpy as np from torch import nn from annotator.oneformer.detectron2.layers import CNNBlockBase, ShapeSpec, get_norm from .backbone import Backbone The provided code snippet includes necessary dependencies for implementing the `adjust_block_compatibility` function. Write a Python function `def adjust_block_comp...
Adjusts the compatibility of widths, bottlenecks, and groups.
34,121
import numpy as np from torch import nn from annotator.oneformer.detectron2.layers import CNNBlockBase, ShapeSpec, get_norm from .backbone import Backbone The provided code snippet includes necessary dependencies for implementing the `generate_regnet_parameters` function. Write a Python function `def generate_regnet_p...
Generates per stage widths and depths from RegNet parameters.
34,122
from annotator.oneformer.detectron2.layers import ShapeSpec from annotator.oneformer.detectron2.utils.registry import Registry from .backbone import Backbone BACKBONE_REGISTRY = Registry("BACKBONE") BACKBONE_REGISTRY.__doc__ = """ Registry for backbones, which extract feature maps from images The registered object must...
Build a backbone from `cfg.MODEL.BACKBONE.NAME`. Returns: an instance of :class:`Backbone`
34,123
import math from typing import List, Optional import torch from torch import nn from torchvision.ops import RoIPool from annotator.oneformer.detectron2.layers import ROIAlign, ROIAlignRotated, cat, nonzero_tuple, shapes_to_tensor from annotator.oneformer.detectron2.structures import Boxes from annotator.oneformer.detec...
Map each box in `box_lists` to a feature map level index and return the assignment vector. Args: box_lists (list[Boxes] | list[RotatedBoxes]): A list of N Boxes or N RotatedBoxes, where N is the number of images in the batch. min_level (int): Smallest feature map level index. The input is considered index 0, the output...
34,124
import math from typing import List, Optional import torch from torch import nn from torchvision.ops import RoIPool from annotator.oneformer.detectron2.layers import ROIAlign, ROIAlignRotated, cat, nonzero_tuple, shapes_to_tensor from annotator.oneformer.detectron2.structures import Boxes from annotator.oneformer.detec...
Convert all boxes in `box_lists` to the low-level format used by ROI pooling ops (see description under Returns). Args: box_lists (list[Boxes] | list[RotatedBoxes]): A list of N Boxes or N RotatedBoxes, where N is the number of images in the batch. Returns: When input is list[Boxes]: A tensor of shape (M, 5), where M i...
34,125
import math from typing import List, Optional import torch from torch import nn from torchvision.ops import RoIPool from annotator.oneformer.detectron2.layers import ROIAlign, ROIAlignRotated, cat, nonzero_tuple, shapes_to_tensor from annotator.oneformer.detectron2.structures import Boxes from annotator.oneformer.detec...
null
34,126
import itertools import logging import numpy as np from collections import OrderedDict from collections.abc import Mapping from typing import Dict, List, Optional, Tuple, Union import torch from omegaconf import DictConfig, OmegaConf from torch import Tensor, nn from annotator.oneformer.detectron2.layers import ShapeSp...
mmdet will assert the type of dict/list. So convert omegaconf objects to dict/list.
34,127
import itertools import logging import numpy as np from collections import OrderedDict from collections.abc import Mapping from typing import Dict, List, Optional, Tuple, Union import torch from omegaconf import DictConfig, OmegaConf from torch import Tensor, nn from annotator.oneformer.detectron2.layers import ShapeSp...
null
34,128
import itertools import logging import numpy as np from collections import OrderedDict from collections.abc import Mapping from typing import Dict, List, Optional, Tuple, Union import torch from omegaconf import DictConfig, OmegaConf from torch import Tensor, nn from annotator.oneformer.detectron2.layers import ShapeSp...
null
34,129
import logging from typing import Dict, List import torch from torch import nn from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.structures import ImageList from ..postprocessing import detector_postprocess, sem_seg_postprocess from .build import META_ARCH_REGISTRY from ...
Implement a simple combining logic following "combine_semantic_and_instance_predictions.py" in panopticapi to produce panoptic segmentation outputs. Args: instance_results: output of :func:`detector_postprocess`. semantic_results: an (H, W) tensor, each element is the contiguous semantic category id Returns: panoptic_s...
34,130
import numpy as np from typing import Dict, List, Optional, Tuple import torch from torch import Tensor, nn from annotator.oneformer.detectron2.data.detection_utils import convert_image_to_rgb from annotator.oneformer.detectron2.layers import move_device_like from annotator.oneformer.detectron2.modeling import Backbone...
Transpose/reshape a tensor from (N, (Ai x K), H, W) to (N, (HxWxAi), K)
34,131
import numpy as np from typing import Callable, Dict, 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 annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import Conv2d, ShapeSp...
Build a semantic segmentation head from `cfg.MODEL.SEM_SEG_HEAD.NAME`.
34,132
import torch from annotator.oneformer.detectron2.utils.logger import _log_api_usage from annotator.oneformer.detectron2.utils.registry import Registry META_ARCH_REGISTRY = Registry("META_ARCH") META_ARCH_REGISTRY.__doc__ = """ Registry for meta-architectures, i.e. the whole model. The registered object will be called ...
Build the whole model architecture, defined by ``cfg.MODEL.META_ARCHITECTURE``. Note that it does not load any weights from ``cfg``.
34,133
import collections import math from typing import List import torch from torch import nn from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import ShapeSpec, move_device_like from annotator.oneformer.detectron2.structures import Boxes, RotatedBoxes from annotator.o...
null
34,134
import collections import math from typing import List import torch from torch import nn from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import ShapeSpec, move_device_like from annotator.oneformer.detectron2.structures import Boxes, RotatedBoxes from annotator.o...
If one size (or aspect ratio) is specified and there are multiple feature maps, we "broadcast" anchors of that single size (or aspect ratio) over all feature maps. If params is list[float], or list[list[float]] with len(params) == 1, repeat it num_features time. Returns: list[list[float]]: param for each feature
34,135
import collections import math from typing import List import torch from torch import nn from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import ShapeSpec, move_device_like from annotator.oneformer.detectron2.structures import Boxes, RotatedBoxes from annotator.o...
Built an anchor generator from `cfg.MODEL.ANCHOR_GENERATOR.NAME`.
34,136
from typing import List import torch from torch import nn from torch.nn import functional as F from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import Conv2d, ConvTranspose2d, cat, interpolate from annotator.oneformer.detectron2.structures import Instances, heatm...
Build a keypoint head from `cfg.MODEL.ROI_KEYPOINT_HEAD.NAME`.
34,137
from typing import List import torch from torch import nn from torch.nn import functional as F from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import Conv2d, ConvTranspose2d, cat, interpolate from annotator.oneformer.detectron2.structures import Instances, heatm...
Arguments: pred_keypoint_logits (Tensor): A tensor of shape (N, K, S, S) where N is the total number of instances in the batch, K is the number of keypoints, and S is the side length of the keypoint heatmap. The values are spatial logits. instances (list[Instances]): A list of M Instances, where M is the batch size. Th...
34,138
from typing import List import fvcore.nn.weight_init as weight_init import torch from torch import nn from torch.nn import functional as F from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, cat, get_norm from annotator.one...
Compute the mask prediction loss defined in the Mask R-CNN paper. Args: pred_mask_logits (Tensor): A tensor of shape (B, C, Hmask, Wmask) or (B, 1, Hmask, Wmask) for class-specific or class-agnostic, where B is the total number of predicted masks in all images, C is the number of foreground classes, and Hmask, Wmask ar...
34,139
from typing import List import fvcore.nn.weight_init as weight_init import torch from torch import nn from torch.nn import functional as F from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, cat, get_norm from annotator.one...
Convert pred_mask_logits to estimated foreground probability masks while also extracting only the masks for the predicted classes in pred_instances. For each predicted box, the mask of the same class is attached to the instance by adding a new "pred_masks" field to pred_instances. Args: pred_mask_logits (Tensor): A ten...
34,140
from typing import List import fvcore.nn.weight_init as weight_init import torch from torch import nn from torch.nn import functional as F from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, cat, get_norm from annotator.one...
Build a mask head defined by `cfg.MODEL.ROI_MASK_HEAD.NAME`.
34,141
import numpy as np from typing import List import fvcore.nn.weight_init as weight_init import torch from torch import nn from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import Conv2d, ShapeSpec, get_norm from annotator.oneformer.detectron2.utils.registry import ...
Build a box head defined by `cfg.MODEL.ROI_BOX_HEAD.NAME`.
34,142
import logging from typing import Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.nn import functional as F from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.data.detection_utils import get_fed_loss_cls_weights from annotator.one...
Call `fast_rcnn_inference_single_image` for all images. Args: boxes (list[Tensor]): A list of Tensors of predicted class-specific or class-agnostic boxes for each image. Element i has shape (Ri, K * 4) if doing class-specific regression, or (Ri, 4) if doing class-agnostic regression, where Ri is the number of predicted...
34,143
import logging from typing import Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.nn import functional as F from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.data.detection_utils import get_fed_loss_cls_weights from annotator.one...
Log the classification metrics to EventStorage. Args: pred_logits: Rx(K+1) logits. The last column is for background class. gt_classes: R labels
34,144
import logging import numpy as np import torch from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import ShapeSpec, batched_nms_rotated from annotator.oneformer.detectron2.structures import Instances, RotatedBoxes, pairwise_iou_rotated from annotator.oneformer.dete...
Call `fast_rcnn_inference_single_image_rotated` for all images. Args: boxes (list[Tensor]): A list of Tensors of predicted class-specific or class-agnostic boxes for each image. Element i has shape (Ri, K * 5) if doing class-specific regression, or (Ri, 5) if doing class-agnostic regression, where Ri is the number of p...
34,145
import inspect import logging import numpy as np from typing import Dict, List, Optional, Tuple import torch from torch import nn from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import ShapeSpec, nonzero_tuple from annotator.oneformer.detectron2.structures impor...
Build ROIHeads defined by `cfg.MODEL.ROI_HEADS.NAME`.
34,146
import inspect import logging import numpy as np from typing import Dict, List, Optional, Tuple import torch from torch import nn from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import ShapeSpec, nonzero_tuple from annotator.oneformer.detectron2.structures impor...
Given a list of N Instances (for N images), each containing a `gt_classes` field, return a list of Instances that contain only instances with `gt_classes != -1 && gt_classes != bg_label`. Args: proposals (list[Instances]): A list of N Instances, where N is the number of images in the batch. bg_label: label index of bac...
34,147
import inspect import logging import numpy as np from typing import Dict, List, Optional, Tuple import torch from torch import nn from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import ShapeSpec, nonzero_tuple from annotator.oneformer.detectron2.structures impor...
Args: proposals (list[Instances]): a list of N Instances, where N is the number of images. Returns: proposals: only contains proposals with at least one visible keypoint. Note that this is still slightly different from Detectron. In Detectron, proposals for training keypoint head are re-sampled from all the proposals w...
34,149
import copy import itertools import logging from collections import defaultdict from enum import Enum from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Type, Union import torch from fvcore.common.param_scheduler import ( CosineParamScheduler, MultiStepParamScheduler, StepWithFixedGammaP...
Build an optimizer from config.
34,150
import copy import itertools import logging from collections import defaultdict from enum import Enum from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Type, Union import torch from fvcore.common.param_scheduler import ( CosineParamScheduler, MultiStepParamScheduler, StepWithFixedGammaP...
Build a LR scheduler from config.
34,151
import numpy as np from typing import List from annotator.oneformer.detectron2.structures import Instances The provided code snippet includes necessary dependencies for implementing the `create_prediction_pairs` function. Write a Python function `def create_prediction_pairs( instances: Instances, prev_instance...
Args: instances: predictions from current frame prev_instances: predictions from previous frame iou_all: 2D numpy array containing iou for each bbox pair threshold: below the threshold, doesn't consider the pair of bbox is valid Return: List of bbox pairs
34,152
from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.utils.registry import Registry from ..config.config import CfgNode as CfgNode_ from ..structures import Instances TRACKER_HEADS_REGISTRY = Registry("TRACKER_HEADS") TRACKER_HEADS_REGISTRY.__doc__ = """ Registry for tracki...
Build a tracker head from `cfg.TRACKER_HEADS.TRACKER_NAME`. Args: cfg: D2 CfgNode, config file with tracker information Return: tracker object
34,153
import datetime import logging import time from collections import OrderedDict, abc from contextlib import ExitStack, contextmanager from typing import List, Union import torch from torch import nn from annotator.oneformer.detectron2.utils.comm import get_world_size, is_main_process from annotator.oneformer.detectron2....
Run model on the data_loader and evaluate the metrics with evaluator. Also benchmark the inference speed of `model.__call__` accurately. The model will be used in eval mode. Args: model (callable): a callable which takes an object from `data_loader` and returns some outputs. If it's an nn.Module, it will be temporarily...
34,154
import contextlib import io import itertools import json import logging import numpy as np import os import tempfile from collections import OrderedDict from typing import Optional from PIL import Image from tabulate import tabulate from annotator.oneformer.detectron2.data import MetadataCatalog from annotator.oneforme...
null
34,155
import itertools import json import logging import numpy as np import os from collections import OrderedDict from typing import Optional, Union import annotator.oneformer.pycocotools.mask as mask_util import torch from PIL import Image from annotator.oneformer.detectron2.data import DatasetCatalog, MetadataCatalog from...
null
34,156
import copy import itertools import json import logging import os import pickle from collections import OrderedDict import torch import annotator.oneformer.detectron2.utils.comm as comm from annotator.oneformer.detectron2.config import CfgNode from annotator.oneformer.detectron2.data import MetadataCatalog from annotat...
Evaluate detection proposal recall metrics. This function is a much faster alternative to the official LVIS API recall evaluation code. However, it produces slightly different results.
34,157
import copy import itertools import json import logging import os import pickle from collections import OrderedDict import torch import annotator.oneformer.detectron2.utils.comm as comm from annotator.oneformer.detectron2.config import CfgNode from annotator.oneformer.detectron2.data import MetadataCatalog from annotat...
Args: iou_type (str): max_dets_per_image (None or int): limit on maximum detections per image in evaluating AP This limit, by default of the LVIS dataset, is 300. class_names (None or list[str]): if provided, will use it to predict per-category AP. Returns: a dict of {metric name: score}
34,158
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,159
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 detection proposal recall metrics. This function is a much faster alternative to the official COCO API recall evaluation code. However, it produces slightly different results.
34,160
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,161
import logging import numpy as np import os import tempfile import xml.etree.ElementTree as ET from collections import OrderedDict, defaultdict from functools import lru_cache import torch from annotator.oneformer.detectron2.data import MetadataCatalog from annotator.oneformer.detectron2.utils import comm from annotato...
rec, prec, ap = voc_eval(detpath, annopath, imagesetfile, classname, [ovthresh], [use_07_metric]) Top level function that does the PASCAL VOC evaluation. detpath: Path to detections detpath.format(classname) should produce the detection results file. annopath: Path to annotations annopath.format(imagename) should be th...
34,162
import ast import builtins import collections.abc as abc import importlib import inspect import logging import os import uuid from contextlib import contextmanager from copy import deepcopy from dataclasses import is_dataclass from typing import List, Tuple, Union import yaml from omegaconf import DictConfig, ListConfi...
Apply func recursively to all DictConfig in cfg.
34,163
import ast import builtins import collections.abc as abc import importlib import inspect import logging import os import uuid from contextlib import contextmanager from copy import deepcopy from dataclasses import is_dataclass from typing import List, Tuple, Union import yaml from omegaconf import DictConfig, ListConfi...
Enhance relative import statements in config files, so that they: 1. locate files purely based on relative location, regardless of packages. e.g. you can import file without having __init__ 2. do not cache modules globally; modifications of module states has no side effect 3. support other storage system through PathMa...
34,164
import collections.abc as abc import dataclasses import logging from typing import Any from annotator.oneformer.detectron2.utils.registry import _convert_target_to_string, locate def _convert_target_to_string(t: Any) -> str: """ Inverse of ``locate()``. Args: t: any object with ``__module__`` and ...
Dump a dataclass recursively into a dict that can be later instantiated. Args: obj: a dataclass object Returns: dict
34,165
import functools import inspect import logging from fvcore.common.config import CfgNode as _CfgNode from annotator.oneformer.detectron2.utils.file_io import PathManager class CfgNode(_CfgNode): """ The same as `fvcore.common.config.CfgNode`, but different in: 1. Use unsafe yaml loading by default. No...
Get a copy of the default config. Returns: a detectron2 CfgNode instance.
34,166
import functools import inspect import logging from fvcore.common.config import CfgNode as _CfgNode from annotator.oneformer.detectron2.utils.file_io import PathManager class CfgNode(_CfgNode): """ The same as `fvcore.common.config.CfgNode`, but different in: 1. Use unsafe yaml loading by default. No...
Let the global config point to the given cfg. Assume that the given "cfg" has the key "KEY", after calling `set_global_cfg(cfg)`, the key can be accessed by: :: from annotator.oneformer.detectron2.config import global_cfg print(global_cfg.KEY) By using a hacky global config, you can access these configs anywhere, witho...
34,167
import functools import inspect import logging from fvcore.common.config import CfgNode as _CfgNode from annotator.oneformer.detectron2.utils.file_io import PathManager def _get_args_from_config(from_config_func, *args, **kwargs): """ Use `from_config` to obtain explicit arguments. Returns: dict: ar...
Decorate a function or a class's __init__ method so that it can be called with a :class:`CfgNode` object using a :func:`from_config` function that translates :class:`CfgNode` to arguments. Examples: :: # Usage 1: Decorator on __init__: class A: @configurable def __init__(self, a, b=2, c=3): pass @classmethod def from_c...
34,168
import logging from typing import List, Optional, Tuple from .config import CfgNode as CN from .defaults import _C _C = CN() _C.VERSION = 2 _C.MODEL = CN() _C.MODEL.LOAD_PROPOSALS = False _C.MODEL.MASK_ON = False _C.MODEL.KEYPOINT_ON = False _C.MODEL.DEVICE = "cuda" _C.MODEL.META_ARCHITECTURE = "GeneralizedRCNN" _C...
Upgrade a config from its current version to a newer version. Args: cfg (CfgNode): to_version (int): defaults to the latest version.
34,170
import logging from typing import List, Optional, Tuple from .config import CfgNode as CN from .defaults import _C _C = CN() _C.VERSION = 2 _C.MODEL = CN() _C.MODEL.LOAD_PROPOSALS = False _C.MODEL.MASK_ON = False _C.MODEL.KEYPOINT_ON = False _C.MODEL.DEVICE = "cuda" _C.MODEL.META_ARCHITECTURE = "GeneralizedRCNN" _C...
Guess the version of a partial config where the VERSION field is not specified. Returns the version, or the latest if cannot make a guess. This makes it easier for users to migrate.
34,172
import argparse import logging import os import sys import weakref from collections import OrderedDict from typing import Optional import torch from fvcore.nn.precise_bn import get_bn_modules from omegaconf import OmegaConf from torch.nn.parallel import DistributedDataParallel import annotator.oneformer.detectron2.data...
Create a DistributedDataParallel model if there are >1 processes. Args: model: a torch.nn.Module fp16_compression: add fp16 compression hooks to the ddp object. See more at https://pytorch.org/docs/stable/ddp_comm_hooks.html#torch.distributed.algorithms.ddp_comm_hooks.default_hooks.fp16_compress_hook kwargs: other argu...
34,173
import argparse import logging import os import sys import weakref from collections import OrderedDict from typing import Optional import torch from fvcore.nn.precise_bn import get_bn_modules from omegaconf import OmegaConf from torch.nn.parallel import DistributedDataParallel import annotator.oneformer.detectron2.data...
Create a parser with some common arguments used by detectron2 users. Args: epilog (str): epilog passed to ArgumentParser describing the usage. Returns: argparse.ArgumentParser:
34,174
import argparse import logging import os import sys import weakref from collections import OrderedDict from typing import Optional import torch from fvcore.nn.precise_bn import get_bn_modules from omegaconf import OmegaConf from torch.nn.parallel import DistributedDataParallel import annotator.oneformer.detectron2.data...
Perform some basic common setups at the beginning of a job, including: 1. Set up the detectron2 logger 2. Log basic information about environment, cmdline arguments, and config 3. Backup the config to the output directory Args: cfg (CfgNode or omegaconf.DictConfig): the full config to be used args (argparse.NameSpace):...
34,175
import argparse import logging import os import sys import weakref from collections import OrderedDict from typing import Optional import torch from fvcore.nn.precise_bn import get_bn_modules from omegaconf import OmegaConf from torch.nn.parallel import DistributedDataParallel import annotator.oneformer.detectron2.data...
Build a list of :class:`EventWriter` to be used. It now consists of a :class:`CommonMetricPrinter`, :class:`TensorboardXWriter` and :class:`JSONWriter`. Args: output_dir: directory to store JSON metrics and tensorboard events max_iter: the total number of iterations Returns: list[EventWriter]: a list of :class:`EventWr...
34,176
import logging from datetime import timedelta import torch import torch.distributed as dist import torch.multiprocessing as mp from annotator.oneformer.detectron2.utils import comm DEFAULT_TIMEOUT = timedelta(minutes=30) def _find_free_port(): import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREA...
Launch multi-process or distributed training. This function must be called on all machines involved in the training. It will spawn child processes (defined by ``num_gpus_per_machine``) on each machine. Args: main_func: a function that will be called by `main_func(*args)` num_gpus_per_machine (int): number of processes ...
34,177
import numpy as np import random _COLORS = np.array( [ 0.000, 0.447, 0.741, 0.850, 0.325, 0.098, 0.929, 0.694, 0.125, 0.494, 0.184, 0.556, 0.466, 0.674, 0.188, 0.301, 0.745, 0.933, 0.635, 0.078, 0.184, 0.300, 0.300, 0.300, 0.600, 0.600, 0.600, ...
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,178
import numpy as np import random _COLORS = np.array( [ 0.000, 0.447, 0.741, 0.850, 0.325, 0.098, 0.929, 0.694, 0.125, 0.494, 0.184, 0.556, 0.466, 0.674, 0.188, 0.301, 0.745, 0.933, 0.635, 0.078, 0.184, 0.300, 0.300, 0.300, 0.600, 0.600, 0.600, ...
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,179
import numpy as np import random _COLORS = np.array( [ 0.000, 0.447, 0.741, 0.850, 0.325, 0.098, 0.929, 0.694, 0.125, 0.494, 0.184, 0.556, 0.466, 0.674, 0.188, 0.301, 0.745, 0.933, 0.635, 0.078, 0.184, 0.300, 0.300, 0.300, 0.600, 0.600, 0.600, ...
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,180
import importlib import numpy as np import os import re import subprocess import sys from collections import defaultdict import PIL import torch import torchvision from tabulate import tabulate def _test_nccl_worker(rank, num_gpu, dist_url): import torch.distributed as dist dist.init_process_group(backend="NCCL...
null
34,181
import inspect import torch from annotator.oneformer.detectron2.utils.env import TORCH_VERSION try: from torch.fx._symbolic_trace import is_fx_tracing as is_fx_tracing_current tracing_current_exists = True except ImportError: tracing_current_exists = False try: from torch.fx._symbolic_trace import _orig...
An FX-tracing safe version of assert. Avoids erroneous type assertion triggering when types are masked inside an fx.proxy.Proxy object during tracing. Args: condition - either a boolean expression or a string representing the condition to test. If this assert triggers an exception when tracing due to dynamic control fl...
34,182
import functools import numpy as np import torch import torch.distributed as dist _LOCAL_PROCESS_GROUP = None _MISSING_LOCAL_PG_ERROR = ( "Local process group is not yet created! Please use detectron2's `launch()` " "to start processes and initialize pytorch process group. If you need to start " "processes ...
Returns: A torch process group which only includes processes that are on the same machine as the current process. This group can be useful for communication within a machine, e.g. a per-machine SyncBN.
34,183
import functools import numpy as np import torch import torch.distributed as dist _LOCAL_PROCESS_GROUP = None _MISSING_LOCAL_PG_ERROR = ( "Local process group is not yet created! Please use detectron2's `launch()` " "to start processes and initialize pytorch process group. If you need to start " "processes ...
Returns: The size of the per-machine process group, i.e. the number of processes per machine.
34,185
import functools import numpy as np import torch import torch.distributed as dist def all_gather(data, group=None): """ Run all_gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object group: a torch process group. By default, will use a group which ...
Returns: int: a random number that is the same across all workers. If workers need a shared RNG, they can use this shared seed to create one. All workers must call this function, otherwise it will deadlock.
34,186
import functools import numpy as np import torch import torch.distributed as dist def get_world_size() -> int: if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() def get_rank() -> int: if not dist.is_available(): return 0 ...
Reduce the values in the dictionary from all processes so that process with rank 0 has the reduced results. Args: input_dict (dict): inputs to be reduced. All the values must be scalar CUDA Tensor. average (bool): whether to do average or sum Returns: a dict with the same keys as input_dict, after reduction.
34,187
The provided code snippet includes necessary dependencies for implementing the `create_dummy_class` function. Write a Python function `def create_dummy_class(klass, dependency, message="")` to solve the following problem: When a dependency of a class is not available, create a dummy class which throws ImportError whe...
When a dependency of a class is not available, create a dummy class which throws ImportError when used. Args: klass (str): name of the class. dependency (str): name of the dependency. message: extra message to print Returns: class: a class object
34,188
The provided code snippet includes necessary dependencies for implementing the `create_dummy_func` function. Write a Python function `def create_dummy_func(func, dependency, message="")` to solve the following problem: When a dependency of a function is not available, create a dummy function which throws ImportError ...
When a dependency of a function is not available, create a dummy function which throws ImportError when used. Args: func (str): name of the function. dependency (str or list[str]): name(s) of the dependency. message: extra message to print Returns: function: a function object
34,190
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,191
import typing from typing import Any, List import fvcore from fvcore.nn import activation_count, flop_count, parameter_count, parameter_count_table from torch import nn from annotator.oneformer.detectron2.export import TracingAdapter class FlopCountAnalysis(fvcore.nn.FlopCountAnalysis): """ Same as :class:`fvco...
Implement operator-level flops counting using jit. This is a wrapper of :func:`fvcore.nn.flop_count` and adds supports for standard detection models in detectron2. Please use :class:`FlopCountAnalysis` for more advanced functionalities. Note: The function runs the input through the model to compute flops. The flops of ...
34,192
import typing from typing import Any, List import fvcore from fvcore.nn import activation_count, flop_count, parameter_count, parameter_count_table from torch import nn from annotator.oneformer.detectron2.export import TracingAdapter ACTIVATIONS_MODE = "activations" def _wrapper_count_operators( model: nn.Module, i...
Implement operator-level activations counting using jit. This is a wrapper of fvcore.nn.activation_count, that supports standard detection models in detectron2. Note: The function runs the input through the model to compute activations. The activations of a detection model is often input-dependent, for example, the act...
34,193
import typing from typing import Any, List import fvcore from fvcore.nn import activation_count, flop_count, parameter_count, parameter_count_table from torch import nn from annotator.oneformer.detectron2.export import TracingAdapter The provided code snippet includes necessary dependencies for implementing the `find_...
Given a model, find parameters that do not contribute to the loss. Args: model: a model in training mode that returns losses inputs: argument or a tuple of arguments. Inputs of the model Returns: list[str]: the name of unused parameters
34,194
import logging from contextlib import contextmanager from functools import wraps import torch def _ignore_torch_cuda_oom(): """ A context which ignores CUDA OOM exception from pytorch. """ try: yield except RuntimeError as e: # NOTE: the string may change? if "CUDA out of mem...
Makes a function retry itself after encountering pytorch's CUDA OOM error. It will first retry after calling `torch.cuda.empty_cache()`. If that still fails, it will then retry by trying to convert inputs to CPUs. In this case, it expects the function to dispatch to CPU implementation. The return values may become CPU ...
34,195
import atexit import functools import logging import os import sys import time from collections import Counter import torch from tabulate import tabulate from termcolor import colored from annotator.oneformer.detectron2.utils.file_io import PathManager def _find_caller(): """ Returns: str: module name o...
Log once per n times. Args: lvl (int): the logging level msg (str): n (int): name (str): name of the logger to use. Will use the caller's module by default.
34,196
def toBbox(rleObjs): pass # if type(rleObjs) == list: # return _mask.toBbox(rleObjs) # else: # return _mask.toBbox([rleObjs])[0]
null
34,197
import json import time import numpy as np import copy import itertools from . import mask as maskUtils import os from collections import defaultdict import sys def _isArrayLike(obj): return hasattr(obj, '__iter__') and hasattr(obj, '__len__')
null
34,198
import gzip import html import os from functools import lru_cache import ftfy import regex as re import torch def default_bpe(): return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bpe_simple_vocab_16e6.txt.gz')
null
34,199
import gzip import html import os from functools import lru_cache import ftfy import regex as re import torch The provided code snippet includes necessary dependencies for implementing the `bytes_to_unicode` function. Write a Python function `def bytes_to_unicode()` to solve the following problem: Returns list of utf-...
Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This ...
34,200
import gzip import html import os from functools import lru_cache import ftfy import regex as re import torch The provided code snippet includes necessary dependencies for implementing the `get_pairs` function. Write a Python function `def get_pairs(word)` to solve the following problem: Return set of symbol pairs in ...
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings).
34,201
import gzip import html import os from functools import lru_cache import ftfy import regex as re import torch def basic_clean(text): text = ftfy.fix_text(text) text = html.unescape(html.unescape(text)) return text.strip()
null
34,202
import gzip import html import os from functools import lru_cache import ftfy import regex as re import torch def whitespace_clean(text): text = re.sub(r'\s+', ' ', text) text = text.strip() return text
null
34,203
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,204
import json import logging import numpy as np import os from PIL import Image from annotator.oneformer.detectron2.data import DatasetCatalog, MetadataCatalog from annotator.oneformer.detectron2.data.datasets.coco import load_coco_json, register_coco_instances from annotator.oneformer.detectron2.utils.file_io import Pat...
null
34,205
import json import os from annotator.oneformer.detectron2.data import DatasetCatalog, MetadataCatalog from annotator.oneformer.detectron2.utils.file_io import PathManager def register_ade20k_panoptic( name, metadata, image_root, panoptic_root, semantic_root, panoptic_json, instances_json=None, ): """ Regist...
null
34,206
import os from annotator.oneformer.detectron2.data.datasets.builtin_meta import _get_builtin_metadata from annotator.oneformer.detectron2.data.datasets.coco import register_coco_instances _PREDEFINED_SPLITS_COCO = { "coco_2017_val_panoptic2instance": ("coco/val2017", "coco/annotations/panoptic2instances_val2017.js...
null
34,207
import json import os from annotator.oneformer.detectron2.data import DatasetCatalog, MetadataCatalog from annotator.oneformer.detectron2.data.datasets import load_sem_seg from annotator.oneformer.detectron2.data.datasets.builtin_meta import COCO_CATEGORIES from annotator.oneformer.detectron2.utils.file_io import PathM...
null
34,208
import copy import logging import numpy as np import torch from annotator.oneformer.detectron2.data import MetadataCatalog from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.data import detection_utils as utils from annotator.oneformer.detectron2.data import transforms as...
Create a list of default :class:`Augmentation` from config. Now it includes resizing and flipping. Returns: list[Augmentation]
34,209
from typing import Any, Callable, Dict, List, Optional, Union import torch.utils.data as torchdata from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.data.common import DatasetFromList, MapDataset from annotator.oneformer.detectron2.data.dataset_mapper import DatasetMappe...
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,210
from typing import Any, Callable, Dict, List, Optional, Union import torch.utils.data as torchdata from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.data.common import DatasetFromList, MapDataset from annotator.oneformer.detectron2.data.dataset_mapper import DatasetMappe...
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,211
import copy from typing import List, Optional import torch import torch.nn.functional as F from torch import Tensor, nn def _get_clones(module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
null
34,212
import copy from typing import List, Optional import torch import torch.nn.functional as F from torch import Tensor, nn The provided code snippet includes necessary dependencies for implementing the `_get_activation_fn` function. Write a Python function `def _get_activation_fn(activation)` to solve the following probl...
Return an activation function given a string
34,213
import logging import fvcore.nn.weight_init as weight_init from typing import Optional import torch from torch import nn, Tensor from torch.nn import functional as F from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import Conv2d from .position_encoding import Pos...
Build a instance embedding branch from `cfg.MODEL.INS_EMBED_HEAD.NAME`.
34,214
import logging import fvcore.nn.weight_init as weight_init from typing import Optional import torch from torch import nn, Tensor from torch.nn import functional as F from annotator.oneformer.detectron2.config import configurable from annotator.oneformer.detectron2.layers import Conv2d from .position_encoding import Pos...
Return an activation function given a string
34,215
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from annotator.oneformer.detectron2.modeling import BACKBONE_REGISTRY, Backbone, ShapeSpec The provided code snippet includ...
Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C)
34,216
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from annotator.oneformer.detectron2.modeling import BACKBONE_REGISTRY, Backbone, ShapeSpec The provided code snippet includ...
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)