id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
3,466
import importlib import math from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator import torch import torch.nn.functional as F import torch.utils.checkpoint from torch.cuda.amp import autocast from torch.nn import CrossEntropyLoss from transformers import PreTrainedTokenizer, Generat...
null
3,467
import base64 import logging import os import requests import unicodedata from typing import Collection, Dict, List, Set, Tuple, Union, Any, Callable, Optional import tiktoken import numpy as np from PIL import Image from PIL import ImageFont from PIL import ImageDraw from transformers import PreTrainedTokenizer, Added...
null
3,468
import base64 import logging import os import requests import unicodedata from typing import Collection, Dict, List, Set, Tuple, Union, Any, Callable, Optional import tiktoken import numpy as np from PIL import Image from PIL import ImageFont from PIL import ImageDraw from transformers import PreTrainedTokenizer, Added...
null
3,472
from collections import OrderedDict import math import requests from io import BytesIO from functools import partial from PIL import Image from typing import Callable, Optional, Sequence, Tuple, List import numpy as np import torch from torch import nn from torch.nn import functional as F from torch.nn.init import trun...
null
3,473
from collections import OrderedDict import math import requests from io import BytesIO from functools import partial from PIL import Image from typing import Callable, Optional, Sequence, Tuple, List import numpy as np import torch from torch import nn from torch.nn import functional as F from torch.nn.init import trun...
null
3,474
from collections import OrderedDict import math import requests from io import BytesIO from functools import partial from PIL import Image from typing import Callable, Optional, Sequence, Tuple, List import numpy as np import torch from torch import nn from torch.nn import functional as F from torch.nn.init import trun...
null
3,475
from collections import OrderedDict import math import requests from io import BytesIO from functools import partial from PIL import Image from typing import Callable, Optional, Sequence, Tuple, List import numpy as np import torch from torch import nn from torch.nn import functional as F from torch.nn.init import trun...
grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
3,476
import json from argparse import ArgumentParser def open_json(path): with open(path,"r") as f: data=json.load(f) return data
null
3,477
import json from argparse import ArgumentParser def save_json(json_list,save_path): with open(save_path, 'w') as file: json.dump(json_list, file, indent=4)
null
3,478
import json from argparse import ArgumentParser def caculate_IOU(box1,box2): Ax1=box1[0] Ay1=box1[1] Ax2=box1[2] Ay2=box1[3] Bx1=box2[0] By1=box2[1] Bx2=box2[2] By2=box2[3] Ix1 = max(Ax1, Bx1) Iy1 = max(Ay1, By1) Ix2 = min(Ax2, Bx2) Iy2 = min(Ay2, By2) Intersection...
null
3,479
import json from argparse import ArgumentParser def _get_args(): parser = ArgumentParser() parser.add_argument("--blip2_caption", type=str, default="./outputs/blip2_cap.json") parser.add_argument("--ori_caption", type=str, default=None) parser.add_argument("--grit", type=str, default="./outputs/grit_sc...
null
3,480
from typing import Any import torch from PIL import Image from argparse import ArgumentParser from lavis.models import load_model_and_preprocess import os import json from tqdm import tqdm import re def save_json(json_list,save_path): with open(save_path, 'w') as file: json.dump(json_list, file, indent=4)
null
3,481
from typing import Any import torch from PIL import Image from argparse import ArgumentParser from lavis.models import load_model_and_preprocess import os import json from tqdm import tqdm import re def _get_args(): parser = ArgumentParser() parser.add_argument("--image_folder", type=str, default="./images") ...
null
3,482
import cv2 from segment_anything import SamAutomaticMaskGenerator, sam_model_registry import argparse import json import os from typing import Any, Dict, List from tqdm import tqdm from PIL import Image def write_masks_to_folder(masks: List[Dict[str, Any]], path: str) -> None: header = "id,area,bbox_x0,bbox_y0,bb...
null
3,483
import cv2 from segment_anything import SamAutomaticMaskGenerator, sam_model_registry import argparse import json import os from typing import Any, Dict, List from tqdm import tqdm from PIL import Image def get_amg_kwargs(args): amg_kwargs = { "points_per_side": args.points_per_side, "points_per_b...
null
3,484
import cv2 from segment_anything import SamAutomaticMaskGenerator, sam_model_registry import argparse import json import os from typing import Any, Dict, List from tqdm import tqdm from PIL import Image def get_image_files(folder_path): image_files = [] for root, dirs, files in os.walk(folder_path): ...
null
3,485
from detectron2.data import transforms as T from .transforms.custom_augmentation_impl import EfficientDetResizeCrop class EfficientDetResizeCrop(Augmentation): """ Scale the shorter edge to the given size, with a limit of `max_size` on the longer edge. If `max_size` is reached, then downscale so that the l...
Create a list of default :class:`Augmentation` from config. Now it includes resizing and flipping. Returns: list[Augmentation]
3,486
import logging import os from fvcore.common.timer import Timer from detectron2.structures import BoxMode from fvcore.common.file_io import PathManager from detectron2.data import DatasetCatalog, MetadataCatalog from lvis import LVIS def load_GRiTcoco_json(json_file, image_root, dataset_name=None): ''' Load COCO...
null
3,487
import logging import os from fvcore.common.timer import Timer from detectron2.structures import BoxMode from fvcore.common.file_io import PathManager from detectron2.data import DatasetCatalog, MetadataCatalog from lvis import LVIS for key, (image_root, json_file) in _CUSTOM_SPLITS_LVIS.items(): register_GRiTcoco_...
null
3,488
import logging import os from fvcore.common.timer import Timer from detectron2.structures import BoxMode from fvcore.common.file_io import PathManager from detectron2.data import DatasetCatalog, MetadataCatalog from lvis import LVIS def load_vg_json(json_file, image_root, dataset_name=None): json_file = PathManager...
null
3,489
import logging import os from fvcore.common.timer import Timer from detectron2.structures import BoxMode from fvcore.common.file_io import PathManager from detectron2.data import DatasetCatalog, MetadataCatalog from lvis import LVIS for key, (image_root, json_file) in _CUSTOM_SPLITS_LVIS.items(): register_vg_instan...
null
3,490
import logging import os from fvcore.common.timer import Timer from detectron2.structures import BoxMode from fvcore.common.file_io import PathManager from detectron2.data import DatasetCatalog, MetadataCatalog from lvis import LVIS def load_o365_json(json_file, image_root, dataset_name=None): def register_o365_instan...
null
3,491
import logging import os from fvcore.common.timer import Timer from detectron2.structures import BoxMode from fvcore.common.file_io import PathManager from detectron2.data import DatasetCatalog, MetadataCatalog from lvis import LVIS for key, (image_root, json_file) in _CUSTOM_SPLITS_LVIS.items(): register_o365_inst...
null
3,492
import operator import torch import torch.utils.data from detectron2.utils.comm import get_world_size from detectron2.config import configurable from torch.utils.data.sampler import BatchSampler, Sampler from detectron2.data.common import DatasetFromList, MapDataset from detectron2.data.dataset_mapper import DatasetMap...
null
3,493
import operator import torch import torch.utils.data from detectron2.utils.comm import get_world_size from detectron2.config import configurable from torch.utils.data.sampler import BatchSampler, Sampler from detectron2.data.common import DatasetFromList, MapDataset from detectron2.data.dataset_mapper import DatasetMap...
null
3,494
import math import torch import torch.nn as nn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `window_partition` function. Write a Python function `def window_partition(x, window_size)` to solve the following problem: Partition into non-overlapping window...
Partition into non-overlapping windows with padding if needed. Args: x (tensor): input tokens with [B, H, W, C]. window_size (int): window size. Returns: windows: windows after partition with [B * num_windows, window_size, window_size, C]. (Hp, Wp): padded height and width before partition
3,495
import math import torch import torch.nn as nn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `window_unpartition` function. Write a Python function `def window_unpartition(windows, window_size, pad_hw, hw)` to solve the following problem: Window unpartit...
Window unpartition into original sequences and removing padding. Args: x (tensor): input tokens with [B * num_windows, window_size, window_size, C]. window_size (int): window size. pad_hw (Tuple): padded height and width (Hp, Wp). hw (Tuple): original height and width (H, W) before padding. Returns: x: unpartitioned se...
3,496
import math import torch import torch.nn as nn import torch.nn.functional as F def get_rel_pos(q_size, k_size, rel_pos): """ Get relative positional embeddings according to the relative positions of query and key sizes. Args: q_size (int): size of query q. k_size (int): size of key k...
Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 Args: attn (Tensor): attention map. q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C). rel_pos_h (Te...
3,497
import math import torch import torch.nn as nn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `get_abs_pos` function. Write a Python function `def get_abs_pos(abs_pos, has_cls_token, hw)` to solve the following problem: Calculate absolute positional embed...
Calculate absolute positional embeddings. If needed, resize embeddings and remove cls_token dimension for the original embeddings. Args: abs_pos (Tensor): absolute positional embeddings with (1, num_position, C). has_cls_token (bool): If true, has 1 embedding in abs_pos for cls token. hw (Tuple): size of input image to...
3,498
import logging import math import fvcore.nn.weight_init as weight_init import torch import torch.nn as nn from functools import partial from detectron2.layers import CNNBlockBase, Conv2d, get_norm from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers import ShapeSpec import sys from ce...
null
3,499
import logging import math import fvcore.nn.weight_init as weight_init import torch import torch.nn as nn from functools import partial from detectron2.layers import CNNBlockBase, Conv2d, get_norm from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers import ShapeSpec import sys from ce...
null
3,500
import logging import math import fvcore.nn.weight_init as weight_init import torch import torch.nn as nn from functools import partial from detectron2.layers import CNNBlockBase, Conv2d, get_norm from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.layers import ShapeSpec import sys from ce...
null
3,501
from __future__ import absolute_import, division, print_function, unicode_literals import sys import json import logging import os import shutil import tempfile import fnmatch from functools import wraps from hashlib import sha256 from io import open import boto3 import requests from botocore.exceptions import ClientEr...
Return the url and etag (which may be ``None``) stored for `filename`. Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist.
3,502
from __future__ import absolute_import, division, print_function, unicode_literals import sys import json import logging import os import shutil import tempfile import fnmatch from functools import wraps from hashlib import sha256 from io import open import boto3 import requests from botocore.exceptions import ClientEr...
Given something that might be a URL (or might be a local path), determine which. If it's a URL, download the file and cache it, and return the path to the cached file. If it's already a local path, make sure the file exists and then return the path.
3,503
from __future__ import absolute_import, division, print_function, unicode_literals import sys import json import logging import os import shutil import tempfile import fnmatch from functools import wraps from hashlib import sha256 from io import open import boto3 import requests from botocore.exceptions import ClientEr...
Wrapper function for s3 requests in order to create more helpful error messages.
3,504
from torch import nn import torch import functools from torch.nn import functional as F import warnings class BertEncoderAsDecoder(nn.Module): def __init__(self, encoder): super().__init__() self.encoder = encoder def forward(self, tgt, memory, tgt_mask=None, tgt_...
null
3,505
from __future__ import absolute_import, division, print_function, unicode_literals import copy import os import json import logging import math import sys from io import open import torch from torch import nn import torch.utils.checkpoint as checkpoint from .file_utils import cached_path def qk2attn(query, key, attent...
null
3,506
from __future__ import absolute_import, division, print_function, unicode_literals import copy import os import json import logging import math import sys from io import open import torch from torch import nn import torch.utils.checkpoint as checkpoint from .file_utils import cached_path def _gelu_python(x): retu...
null
3,507
from typing import Dict, List, Optional, Tuple import torch from detectron2.config import configurable from detectron2.structures import ImageList, Instances, Boxes from detectron2.modeling.meta_arch.build import META_ARCH_REGISTRY from detectron2.modeling.meta_arch.rcnn import GeneralizedRCNN from detectron2.structure...
Rescale the output instances to the target size.
3,508
from typing import Dict, List, Optional, Tuple import torch from detectron2.config import configurable from detectron2.structures import ImageList, Instances, Boxes from detectron2.modeling.meta_arch.build import META_ARCH_REGISTRY from detectron2.modeling.meta_arch.rcnn import GeneralizedRCNN from detectron2.structure...
null
3,509
import torch from detectron2.structures import Boxes, RotatedBoxes, pairwise_iou, pairwise_iou_rotated def soft_nms(boxes, scores, method, gaussian_sigma, linear_threshold, prune_threshold): """ Performs soft non-maximum suppression algorithm on axis aligned boxes Args: boxes (Tensor[N, 5]): ...
Performs soft 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, 4]): boxes where NMS will be performed. They are expected to be in (x1, y1, x2, y2) format scores (Tensor[N]): scores for ea...
3,510
from detectron2.config import CfgNode as CN def add_grit_config(cfg): _C = cfg _C.MODEL.BEAM_SIZE = 1 _C.MODEL.TRAIN_TASK = ["ObjectDet", "DenseCap"] _C.MODEL.TEST_TASK = "DenseCap" # This can be varied if the model is jointly trained on multiple tasks _C.MODEL.ROI_BOX_HEAD.USE_BIAS = 0.0 # >= 0...
null
3,511
import itertools from typing import Any, Callable, Dict, Iterable, List, Set, Type, Union import torch from detectron2.config import CfgNode from detectron2.solver.build import maybe_add_gradient_clipping def get_vit_lr_decay_rate(name, lr_decay_rate=1.0, num_layers=12): """ Calculate lr decay rate for differen...
null
3,512
import itertools import json import os from detectron2.structures import Boxes, BoxMode, pairwise_iou from detectron2.utils.file_io import PathManager import numpy as np import pycocotools.mask as mask_util from detectron2.evaluation.coco_evaluation import COCOEvaluator from detectron2.evaluation.coco_evaluation import...
Add object_descriptions and logit (if applicable) to detectron2's instances_to_coco_json
3,513
import glob import os import shutil from os import path from setuptools import find_packages, setup from typing import List import torch from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension def get_version(): init_py_path = path.join(path.abspath(path.dirname(__file__)), "detectron2", "__in...
null
3,514
import glob import os import shutil from os import path from setuptools import find_packages, setup from typing import List import torch from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension torch_ver = [int(x) for x in torch.__version__.split(".")[:2]] assert torch_ver >= [1, 8], "Requires PyTor...
null
3,515
import glob import os import shutil from os import path from setuptools import find_packages, setup from typing import List import torch from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension The provided code snippet includes necessary dependencies for implementing the `get_model_zoo_configs` fu...
Return a list of configs to include in package for model zoo. Copy over these configs inside detectron2/model_zoo.
3,516
import os import sys from unittest import mock from sphinx.domains import Domain from typing import Dict, List, Tuple import sphinx_rtd_theme class GithubURLDomain(Domain): """ Resolve certain links in markdown files to github source. """ name = "githuburl" ROOT = "https://github.com/facebookresearc...
null
3,517
import copy import logging import re from typing import Dict, List import torch from tabulate import tabulate def convert_c2_detectron_names(weights): """ Map Caffe2 Detectron weight names to Detectron2 names. Args: weights (dict): name -> tensor Returns: dict: detectron2 names -> tensor...
Match names between the two state-dict, and returns a new chkpt_state_dict with names converted to match model_state_dict with heuristics. The returned dict can be later loaded with fvcore checkpointer. If `c2_conversion==True`, `ckpt_state_dict` is assumed to be a Caffe2 model and will be renamed at first. Strategy: s...
3,518
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 `_keypoints_to_heatmap` function. Write a Python function `def _keypoints_to_heatmap( keypoints: torch.Tensor, rois: torch.T...
Encode keypoint locations into a target heatmap for use in SoftmaxWithLoss across space. Maps keypoints from the half-open interval [x1, x2) on continuous image coordinates to the closed interval [0, heatmap_size - 1] on discrete image coordinates. We use the continuous-discrete conversion from Heckbert 1990 ("What is ...
3,519
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...
3,520
import copy import itertools import numpy as np from typing import Any, Iterator, List, Union import pycocotools.mask as mask_util import torch from torch import device from detectron2.layers.roi_align import ROIAlign from detectron2.utils.memory import retry_if_cuda_oom from .boxes import Boxes def polygon_area(x, y)...
null
3,521
import copy import itertools import numpy as np from typing import Any, Iterator, List, Union import pycocotools.mask as mask_util import torch from torch import device from detectron2.layers.roi_align import ROIAlign from detectron2.utils.memory import retry_if_cuda_oom from .boxes import Boxes def polygons_to_bitmask...
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...
3,522
import math from typing import List, Tuple import torch from 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 boxes (`area`, `clip...
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...
3,523
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].
3,524
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].
3,525
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,...
3,526
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].
3,527
import copy import logging import os import torch from caffe2.proto import caffe2_pb2 from torch import nn from detectron2.config import CfgNode from detectron2.utils.file_io import PathManager from .caffe2_inference import ProtobufDetectionModel from .caffe2_modeling import META_ARCH_CAFFE2_EXPORT_TYPE_MAP, convert_ba...
null
3,528
import contextlib from unittest import mock import torch from detectron2.modeling import poolers from detectron2.modeling.proposal_generator import rpn from detectron2.modeling.roi_heads import keypoint_head, mask_head from detectron2.modeling.roi_heads.fast_rcnn import FastRCNNOutputLayers from .c10 import ( Caffe...
null
3,529
import contextlib from unittest import mock import torch from detectron2.modeling import poolers from detectron2.modeling.proposal_generator import rpn from detectron2.modeling.roi_heads import keypoint_head, mask_head from detectron2.modeling.roi_heads.fast_rcnn import FastRCNNOutputLayers from .c10 import ( Caffe...
null
3,530
import contextlib from unittest import mock import torch from detectron2.modeling import poolers from detectron2.modeling.proposal_generator import rpn from detectron2.modeling.roi_heads import keypoint_head, mask_head from detectron2.modeling.roi_heads.fast_rcnn import FastRCNNOutputLayers from .c10 import ( Caffe...
null
3,531
import contextlib from unittest import mock import torch from detectron2.modeling import poolers from detectron2.modeling.proposal_generator import rpn from detectron2.modeling.roi_heads import keypoint_head, mask_head from detectron2.modeling.roi_heads.fast_rcnn import FastRCNNOutputLayers from .c10 import ( Caffe...
null
3,532
import collections from dataclasses import dataclass from typing import Callable, List, Optional, Tuple import torch from torch import nn from detectron2.structures import Boxes, Instances, ROIMasks from detectron2.utils.registry import _convert_target_to_string, locate from .torchscript_patch import patch_builtin_len ...
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 ...
3,533
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 detectron2 from detectron2.structures import Boxes, Instances from detectron2.utils.env import _import_file The provided code snippet inclu...
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.
3,534
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 detectron2 from detectron2.structures import Boxes, Instances from detectron2.utils.env import _import_file The provided code snippet inclu...
Apply patches on a few nonscriptable detectron2 classes. Should not have side-effects on eager usage.
3,535
import functools import io import struct import types import torch from detectron2.modeling import meta_arch from detectron2.modeling.box_regression import Box2BoxTransform from detectron2.modeling.roi_heads import keypoint_head from detectron2.structures import Boxes, ImageList, Instances, RotatedBoxes from .c10 impor...
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_...
3,536
import functools import io import struct import types import torch from detectron2.modeling import meta_arch from detectron2.modeling.box_regression import Box2BoxTransform from detectron2.modeling.roi_heads import keypoint_head from detectron2.structures import Boxes, ImageList, Instances, RotatedBoxes from .c10 impor...
null
3,537
import functools import io import struct import types import torch from detectron2.modeling import meta_arch from detectron2.modeling.box_regression import Box2BoxTransform from detectron2.modeling.roi_heads import keypoint_head from detectron2.structures import Boxes, ImageList, Instances, RotatedBoxes from .c10 impor...
null
3,538
import functools import io import struct import types import torch from detectron2.modeling import meta_arch from detectron2.modeling.box_regression import Box2BoxTransform from detectron2.modeling.roi_heads import keypoint_head from detectron2.structures import Boxes, ImageList, Instances, RotatedBoxes from .c10 impor...
See get_caffe2_inputs() below.
3,539
import copy import io import logging import numpy as np from typing import List import onnx 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.onnx import OperatorExpo...
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.
3,540
import copy import io import logging import numpy as np from typing import List import onnx 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.onnx import OperatorExpo...
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.
3,541
import collections import contextlib 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_p...
null
3,542
import collections import contextlib 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_p...
null
3,543
import collections import contextlib 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_p...
null
3,544
import collections import contextlib 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_p...
null
3,545
import collections import contextlib 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_p...
null
3,546
import collections import contextlib 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_p...
null
3,547
import os import torch from 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 class, defined by `field...
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:...
3,548
import os import torch from 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_handler(Detectron2Hand...
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.
3,549
import os from typing import Optional import pkg_resources import torch from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import CfgNode, LazyConfig, get_cfg, instantiate from detectron2.modeling import build_model def get_config(config_path, trained: bool = False): """ Returns a co...
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...
3,550
from typing import List, Optional import torch from torch.nn import functional as F The provided code snippet includes necessary dependencies for implementing the `shapes_to_tensor` function. Write a Python function `def shapes_to_tensor(x: List[int], device: Optional[torch.device] = None) -> torch.Tensor` to solve th...
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.
3,551
from typing import List, Optional import torch from torch.nn import functional as F The provided code snippet includes necessary dependencies for implementing the `cat` function. Write a Python function `def cat(tensors: List[torch.Tensor], dim: int = 0)` to solve the following problem: Efficient version of torch.cat ...
Efficient version of torch.cat that avoids a copy if there is only a single element in a list
3,552
from typing import List, Optional import torch from torch.nn import functional as F The provided code snippet includes necessary dependencies for implementing the `cross_entropy` function. Write a Python function `def cross_entropy(input, target, *, reduction="mean", **kwargs)` to solve the following problem: Same as ...
Same as `torch.nn.functional.cross_entropy`, but returns 0 (instead of nan) for empty inputs.
3,553
from typing import List, Optional import torch from torch.nn import functional as F The provided code snippet includes necessary dependencies for implementing the `nonzero_tuple` function. Write a Python function `def nonzero_tuple(x)` to solve the following problem: A 'as_tuple=True' version of torch.nonzero to suppo...
A 'as_tuple=True' version of torch.nonzero to support torchscript. because of https://github.com/pytorch/pytorch/issues/38718
3,554
import math import torch The provided code snippet includes necessary dependencies for implementing the `diou_loss` function. Write a Python function `def diou_loss( boxes1: torch.Tensor, boxes2: torch.Tensor, reduction: str = "none", eps: float = 1e-7, ) -> torch.Tensor` to solve the following problem...
Distance 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...
3,555
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...
3,556
import torch from torchvision.ops import boxes as box_ops from torchvision.ops import nms The provided code snippet includes necessary dependencies for implementing the `batched_nms` function. Write a Python function `def batched_nms( boxes: torch.Tensor, scores: torch.Tensor, idxs: torch.Tensor, iou_threshold: fl...
Same as torchvision.ops.boxes.batched_nms, but with float().
3,557
import torch from torchvision.ops import boxes as box_ops from torchvision.ops import nms def nms_rotated(boxes, scores, iou_threshold): """ Performs non-maximum suppression (NMS) on the rotated boxes according to their intersection-over-union (IoU). Rotated NMS iteratively removes lower scoring rotate...
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...
3,558
import numpy as np from typing import Tuple import torch from PIL import Image from torch.nn import functional as F The provided code snippet includes necessary dependencies for implementing the `paste_mask_in_image_old` function. Write a Python function `def paste_mask_in_image_old(mask, box, img_h, img_w, threshold)...
Paste a single mask in an image. This is a per-box implementation of :func:`paste_masks_in_image`. This function has larger quantization error due to incorrect pixel modeling and is not used any more. Args: mask (Tensor): A tensor of shape (Hmask, Wmask) storing the mask of a single object instance. Values are in [0, 1...
3,559
import numpy as np from typing import Tuple import torch from PIL import Image from torch.nn import functional as F The provided code snippet includes necessary dependencies for implementing the `pad_masks` function. Write a Python function `def pad_masks(masks, padding)` to solve the following problem: Args: masks (t...
Args: masks (tensor): A tensor of shape (B, M, M) representing B masks. padding (int): Number of cells to pad on all sides. Returns: The padded masks and the scale factor of the padding size / original size.
3,560
import numpy as np from typing import Tuple import torch from PIL import Image from torch.nn import functional as F The provided code snippet includes necessary dependencies for implementing the `scale_boxes` function. Write a Python function `def scale_boxes(boxes, scale)` to solve the following problem: Args: boxes ...
Args: boxes (tensor): A tensor of shape (B, 4) representing B boxes with 4 coords representing the corners x0, y0, x1, y1, scale (float): The box scaling factor. Returns: Scaled boxes.
3,561
import numpy as np from typing import Tuple import torch from PIL import Image from torch.nn import functional as F def paste_masks_in_image( masks: torch.Tensor, boxes: torch.Tensor, image_shape: Tuple[int, int], threshold: float = 0.5 ): """ Paste a set of masks that are of a fixed resolution (e.g., 28 x ...
A wrapper of paste_masks_in_image where image_shape is Tensor. During tracing, shapes might be tensors instead of ints. The Tensor->int conversion should be scripted rather than traced.
3,562
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 detectron2.utils import comm, env from .wrappers import BatchNorm2d class FrozenBatchNorm2d(nn.Module): """ BatchNorm2d where the batch statist...
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
3,563
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 detectron2.utils import comm from .build import build_batch_data_loader from .common import DatasetFromList, MapDataset from .samplers import TrainingSampler ...
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.
3,564
import copy import itertools import logging import numpy as np import pickle import random import torch.utils.data as data from torch.utils.data.sampler import Sampler from detectron2.utils.serialize import PicklableWrapper def _shard_iterator_dataloader_worker(iterable): # Shard the iterable if we're currently in...
null
3,565
import logging import numpy as np from typing import List, Union import pycocotools.mask as mask_util import torch from PIL import Image from detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, polygons_to_bitmask, ) from detectron2....
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
3,566
import logging import numpy as np from typing import List, Union import pycocotools.mask as mask_util import torch from PIL import Image from detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, polygons_to_bitmask, ) from detectron2....
Raise an error if the image does not match the size specified in the dict.
3,567
import logging import numpy as np from typing import List, Union import pycocotools.mask as mask_util import torch from PIL import Image from detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, polygons_to_bitmask, ) from detectron2....
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...
3,568
import logging import numpy as np from typing import List, Union import pycocotools.mask as mask_util import torch from PIL import Image from detectron2.structures import ( BitMasks, Boxes, BoxMode, Instances, Keypoints, PolygonMasks, RotatedBoxes, polygons_to_bitmask, ) from detectron2....
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...