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, GenerationConfig, StoppingCriteriaList from transformers.generation.logits_process import LogitsProcessorList from transformers.generation.utils import GenerateOutput from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, ) from transformers.modeling_utils import PreTrainedModel from transformers.utils import logging from torch import nn from .configuration_qwen import QWenConfig from .qwen_generation_utils import ( HistoryType, make_context, decode_tokens, get_stop_words_ids, StopWordsLogitsProcessor, ) from .visual import VisionTransformer apply_rotary_emb_func = None def _rotate_half(x): from einops import rearrange x = rearrange(x, "... (j d) -> ... j d", j=2) x1, x2 = x.unbind(dim=-2) return torch.cat((-x2, x1), dim=-1) def apply_rotary_pos_emb(t, freqs): cos, sin = freqs if apply_rotary_emb_func is not None and t.is_cuda: t_ = t.float() cos = cos.squeeze(0).squeeze(1)[:, : cos.shape[-1] // 2] sin = sin.squeeze(0).squeeze(1)[:, : sin.shape[-1] // 2] output = apply_rotary_emb_func(t_, cos, sin).type_as(t) return output else: rot_dim = freqs[0].shape[-1] cos, sin = freqs t_, t_pass_ = t[..., :rot_dim], t[..., rot_dim:] t_ = t_.float() t_pass_ = t_pass_.float() t_ = (t_ * cos) + (_rotate_half(t_) * sin) return torch.cat((t_, t_pass_), dim=-1).type_as(t)
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, AddedToken from transformers.utils import try_to_load_from_cache import matplotlib.colors as mcolors from matplotlib.font_manager import FontProperties import colorsys import logging import math import numpy as np import matplotlib as mpl import matplotlib.colors as mplc import matplotlib.figure as mplfigure import torch from matplotlib.backends.backend_agg import FigureCanvasAgg from PIL import Image import random def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]: with open(tiktoken_bpe_file, "rb") as f: contents = f.read() return { base64.b64decode(token): int(rank) for token, rank in (line.split() for line in contents.splitlines() if line) }
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, AddedToken from transformers.utils import try_to_load_from_cache import matplotlib.colors as mcolors from matplotlib.font_manager import FontProperties def _list_find( input_list: List[Any], candidates: Tuple[Any], start: int = 0, ): for i in range(start, len(input_list)): if input_list[i] in candidates: return i return -1 import colorsys import logging import math import numpy as np import matplotlib as mpl import matplotlib.colors as mplc import matplotlib.figure as mplfigure import torch from matplotlib.backends.backend_agg import FigureCanvasAgg from PIL import Image import random def _replace_closed_tag( input_tokens: List[Any], start_tags: Union[Any, Tuple[Any]], end_tags: Union[Any, Tuple[Any]], inclusive_replace_func: Callable, exclusive_replace_func: Callable = lambda x: x, ): if isinstance(start_tags, (str, int)): start_tags = (start_tags,) if isinstance(end_tags, (str, int)): end_tags = (end_tags,) assert len(start_tags) == len(end_tags) output_tokens = [] end = 0 while True: start = _list_find(input_tokens, start_tags, end) if start == -1: break output_tokens.extend(exclusive_replace_func(input_tokens[end : start])) tag_idx = start_tags.index(input_tokens[start]) end = _list_find(input_tokens, (end_tags[tag_idx],), start) if end == -1: raise ValueError("Unclosed image token") output_tokens.extend(inclusive_replace_func(input_tokens[start : end + 1])) end += 1 output_tokens.extend(exclusive_replace_func(input_tokens[end : ])) return output_tokens
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 trunc_normal_ from torchvision import transforms from torchvision.transforms import InterpolationMode def reconstruct_matrix(windows): temp =[] for col in windows: temp.append(torch.cat((col),dim=3)) all_img = torch.cat(temp,dim=2) return all_img
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 trunc_normal_ from torchvision import transforms from torchvision.transforms import InterpolationMode def sliding_window(matrix, window_size, stride): b,c,height, width = matrix.shape window_rows = (height - window_size[0]) // stride + 1 window_cols = (width - window_size[1]) // stride + 1 windows = [] for i in range(window_rows): windows_col = [] for j in range(window_cols): window = matrix[:,:, i*stride:i*stride+window_size[0], j*stride:j*stride+window_size[1]] windows_col.append(window) windows.append(windows_col) return windows
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 trunc_normal_ from torchvision import transforms from torchvision.transforms import InterpolationMode def get_abs_pos(abs_pos, tgt_size): # abs_pos: L, C # tgt_size: M # return: M, C src_size = int(math.sqrt(abs_pos.size(0))) tgt_size = int(math.sqrt(tgt_size)) dtype = abs_pos.dtype if src_size != tgt_size: return F.interpolate( abs_pos.float().reshape(1, src_size, src_size, -1).permute(0, 3, 1, 2), size=(tgt_size, tgt_size), mode="bicubic", align_corners=False, ).permute(0, 2, 3, 1).flatten(0, 2).to(dtype=dtype) else: return abs_pos
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 trunc_normal_ from torchvision import transforms from torchvision.transforms import InterpolationMode def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): assert embed_dim % 2 == 0 # use half of dimensions to encode grid_h emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2) emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) return emb The provided code snippet includes necessary dependencies for implementing the `get_2d_sincos_pos_embed` function. Write a Python function `def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False)` to solve the following problem: 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) Here is the function: def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False): """ 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) """ grid_h = np.arange(grid_size, dtype=np.float32) grid_w = np.arange(grid_size, dtype=np.float32) grid = np.meshgrid(grid_w, grid_h) # here w goes first grid = np.stack(grid, axis=0) grid = grid.reshape([2, 1, grid_size, grid_size]) pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) if cls_token: pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0) return pos_embed
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) IntersectionArea = max(0, Ix2 - Ix1 + 1) * max(0, Iy2 - Iy1 + 1) BoxAArea = (Ax2 - Ax1 + 1) * (Ay2 - Ay1 + 1) BoxBArea = (Bx2 - Bx1 + 1) * (By2 - By1 + 1) UnionArea = BoxAArea + BoxBArea - IntersectionArea IOU = IntersectionArea / UnionArea return IOU
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_score.json") parser.add_argument("--ppocr", type=str, default="./outputs/ppocr.json") parser.add_argument("--sam_blip2", type=str, default="./outputs/sam_blip2_score.json") parser.add_argument("--output", type=str, default="./outputs/ann_all.json") args = parser.parse_args() return args
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") parser.add_argument("--ann_path", type=str, default="./outputs/sam_blip2.json") parser.add_argument("--output_path", type=str, default="./outputs/sam_blip2_score.json") parser.add_argument("--device", type=str, default="cuda:0") args = parser.parse_args() return args
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,bbox_w,bbox_h,point_input_x,point_input_y,predicted_iou,stability_score,crop_box_x0,crop_box_y0,crop_box_w,crop_box_h" # noqa metadata = [header] for i, mask_data in enumerate(masks): mask = mask_data["segmentation"] filename = f"{i}.png" cv2.imwrite(os.path.join(path, filename), mask * 255) mask_metadata = [ str(i), str(mask_data["area"]), *[str(x) for x in mask_data["bbox"]], *[str(x) for x in mask_data["point_coords"][0]], str(mask_data["predicted_iou"]), str(mask_data["stability_score"]), *[str(x) for x in mask_data["crop_box"]], ] row = ",".join(mask_metadata) metadata.append(row) metadata_path = os.path.join(path, "metadata.csv") with open(metadata_path, "w") as f: f.write("\n".join(metadata)) return
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_batch": args.points_per_batch, "pred_iou_thresh": args.pred_iou_thresh, "stability_score_thresh": args.stability_score_thresh, "stability_score_offset": args.stability_score_offset, "box_nms_thresh": args.box_nms_thresh, "crop_n_layers": args.crop_n_layers, "crop_nms_thresh": args.crop_nms_thresh, "crop_overlap_ratio": args.crop_overlap_ratio, "crop_n_points_downscale_factor": args.crop_n_points_downscale_factor, "min_mask_region_area": args.min_mask_region_area, } amg_kwargs = {k: v for k, v in amg_kwargs.items() if v is not None} return amg_kwargs
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): for file in files: if file.endswith('.jpg') or file.endswith('.png'): image_files.append(os.path.join(root, file)) return image_files
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 longer edge does not exceed max_size. """ def __init__( self, size, scale, interp=Image.BILINEAR ): """ """ super().__init__() self.target_size = (size, size) self.scale = scale self.interp = interp def get_transform(self, img): # Select a random scale factor. scale_factor = np.random.uniform(*self.scale) scaled_target_height = scale_factor * self.target_size[0] scaled_target_width = scale_factor * self.target_size[1] # Recompute the accurate scale_factor using rounded scaled image size. width, height = img.shape[1], img.shape[0] img_scale_y = scaled_target_height / height img_scale_x = scaled_target_width / width img_scale = min(img_scale_y, img_scale_x) # Select non-zero random offset (x, y) if scaled image is larger than target size scaled_h = int(height * img_scale) scaled_w = int(width * img_scale) offset_y = scaled_h - self.target_size[0] offset_x = scaled_w - self.target_size[1] offset_y = int(max(0.0, float(offset_y)) * np.random.uniform(0, 1)) offset_x = int(max(0.0, float(offset_x)) * np.random.uniform(0, 1)) return EfficientDetResizeCropTransform( scaled_h, scaled_w, offset_y, offset_x, img_scale, self.target_size, self.interp) The provided code snippet includes necessary dependencies for implementing the `build_custom_augmentation` function. Write a Python function `def build_custom_augmentation(cfg, is_train, scale=None, size=None, min_size=None, max_size=None)` to solve the following problem: Create a list of default :class:`Augmentation` from config. Now it includes resizing and flipping. Returns: list[Augmentation] Here is the function: def build_custom_augmentation(cfg, is_train, scale=None, size=None, \ min_size=None, max_size=None): """ Create a list of default :class:`Augmentation` from config. Now it includes resizing and flipping. Returns: list[Augmentation] """ if cfg.INPUT.CUSTOM_AUG == 'ResizeShortestEdge': if is_train: min_size = cfg.INPUT.MIN_SIZE_TRAIN if min_size is None else min_size max_size = cfg.INPUT.MAX_SIZE_TRAIN if max_size is None else max_size sample_style = cfg.INPUT.MIN_SIZE_TRAIN_SAMPLING else: min_size = cfg.INPUT.MIN_SIZE_TEST max_size = cfg.INPUT.MAX_SIZE_TEST sample_style = "choice" augmentation = [T.ResizeShortestEdge(min_size, max_size, sample_style)] elif cfg.INPUT.CUSTOM_AUG == 'EfficientDetResizeCrop': if is_train: scale = cfg.INPUT.SCALE_RANGE if scale is None else scale size = cfg.INPUT.TRAIN_SIZE if size is None else size else: scale = (1, 1) size = cfg.INPUT.TEST_SIZE augmentation = [EfficientDetResizeCrop(size, scale)] else: assert 0, cfg.INPUT.CUSTOM_AUG if is_train: augmentation.append(T.RandomFlip()) return augmentation
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 class name text for object description for GRiT ''' json_file = PathManager.get_local_path(json_file) timer = Timer() lvis_api = LVIS(json_file) if timer.seconds() > 1: logger.info("Loading {} takes {:.2f} seconds.".format( json_file, timer.seconds())) class_names = {} sort_cat = sorted(lvis_api.dataset['categories'], key=lambda x: x['id']) for x in sort_cat: class_names[x['id']] = x['name'] img_ids = sorted(lvis_api.imgs.keys()) imgs = lvis_api.load_imgs(img_ids) anns = [lvis_api.img_ann_map[img_id] for img_id in img_ids] ann_ids = [ann["id"] for anns_per_image in anns for ann in anns_per_image] assert len(set(ann_ids)) == len(ann_ids), \ "Annotation ids in '{}' are not unique".format(json_file) imgs_anns = list(zip(imgs, anns)) logger.info("Loaded {} images in the LVIS v1 format from {}".format( len(imgs_anns), json_file)) dataset_dicts = [] for (img_dict, anno_dict_list) in imgs_anns: record = {} if "file_name" in img_dict: file_name = img_dict["file_name"] record["file_name"] = os.path.join(image_root, file_name) record["height"] = int(img_dict["height"]) record["width"] = int(img_dict["width"]) image_id = record["image_id"] = img_dict["id"] objs = [] for anno in anno_dict_list: assert anno["image_id"] == image_id if anno.get('iscrowd', 0) > 0: continue obj = {"bbox": anno["bbox"], "bbox_mode": BoxMode.XYWH_ABS} obj["category_id"] = 0 obj["object_description"] = class_names[anno['category_id']] if 'segmentation' in anno: segm = anno["segmentation"] valid_segm = [poly for poly in segm \ if len(poly) % 2 == 0 and len(poly) >= 6] if not len(segm) == len(valid_segm): print('Annotation contains an invalid polygon with < 3 points') assert len(segm) > 0 obj["segmentation"] = segm objs.append(obj) record["annotations"] = objs if len(record["annotations"]) == 0: continue record["task"] = "ObjectDet" dataset_dicts.append(record) return dataset_dicts def register_GRiTcoco_instances(name, metadata, json_file, image_root): """ """ DatasetCatalog.register(name, lambda: load_GRiTcoco_json( json_file, image_root, name)) MetadataCatalog.get(name).set( json_file=json_file, image_root=image_root, evaluator_type="coco", **metadata )
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_instances( key, get_GRiTcoco_meta(), os.path.join("datasets", json_file) if "://" not in json_file else json_file, os.path.join("datasets", image_root), ) def get_GRiTcoco_meta(): categories = [{'supercategory': 'object', 'id': 1, 'name': 'object'}] categories = sorted(categories, key=lambda x: x["id"]) thing_classes = [k["name"] for k in categories] meta = {"thing_classes": thing_classes} return meta
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.get_local_path(json_file) timer = Timer() lvis_api = LVIS(json_file) if timer.seconds() > 1: logger.info("Loading {} takes {:.2f} seconds.".format( json_file, timer.seconds())) img_ids = sorted(lvis_api.imgs.keys()) imgs = lvis_api.load_imgs(img_ids) anns = [lvis_api.img_ann_map[img_id] for img_id in img_ids] ann_ids = [ann["id"] for anns_per_image in anns for ann in anns_per_image] assert len(set(ann_ids)) == len(ann_ids), \ "Annotation ids in '{}' are not unique".format(json_file) imgs_anns = list(zip(imgs, anns)) logger.info("Loaded {} images in the LVIS v1 format from {}".format( len(imgs_anns), json_file)) dataset_dicts = [] for (img_dict, anno_dict_list) in imgs_anns: record = {} if "file_name" in img_dict: file_name = img_dict["file_name"] record["file_name"] = os.path.join(image_root, file_name) record["height"] = int(img_dict["height"]) record["width"] = int(img_dict["width"]) image_id = record["image_id"] = img_dict["id"] objs = [] for anno in anno_dict_list: assert anno["image_id"] == image_id if anno.get('iscrowd', 0) > 0: continue obj = {"bbox": anno["bbox"], "bbox_mode": BoxMode.XYWH_ABS} obj["category_id"] = 0 obj["object_description"] = anno["caption"] objs.append(obj) record["annotations"] = objs if len(record["annotations"]) == 0: continue record["task"] = "DenseCap" dataset_dicts.append(record) return dataset_dicts def register_vg_instances(name, metadata, json_file, image_root): """ """ DatasetCatalog.register(name, lambda: load_vg_json( json_file, image_root, name)) MetadataCatalog.get(name).set( json_file=json_file, image_root=image_root, evaluator_type="vg", **metadata )
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_instances( key, get_vg_meta(), os.path.join("datasets", json_file) if "://" not in json_file else json_file, os.path.join("datasets", image_root), ) def get_vg_meta(): categories = [{'supercategory': 'object', 'id': 1, 'name': 'object'}] vg_categories = sorted(categories, key=lambda x: x["id"]) thing_classes = [k["name"] for k in vg_categories] meta = {"thing_classes": thing_classes} return meta
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_instances(name, metadata, json_file, image_root): DatasetCatalog.register(name, lambda: load_o365_json( json_file, image_root, name)) MetadataCatalog.get(name).set( json_file=json_file, image_root=image_root, evaluator_type="lvis", **metadata )
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_instances( key, get_o365_meta(), os.path.join("datasets", json_file) if "://" not in json_file else json_file, os.path.join("datasets", image_root), ) def get_o365_meta(): categories = [{'supercategory': 'object', 'id': 1, 'name': 'object'}] o365_categories = sorted(categories, key=lambda x: x["id"]) thing_classes = [k["name"] for k in o365_categories] meta = {"thing_classes": thing_classes} return meta
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 DatasetMapper from detectron2.data.build import get_detection_dataset_dicts, build_batch_data_loader from detectron2.data.samplers import TrainingSampler from detectron2.data.build import worker_init_reset_seed, print_instances_class_histogram from detectron2.data.build import filter_images_with_only_crowd_annotations from detectron2.data.build import filter_images_with_few_keypoints from detectron2.data.build import check_metadata_consistency from detectron2.data.catalog import MetadataCatalog, DatasetCatalog from detectron2.utils import comm import itertools from typing import Optional def get_detection_dataset_dicts_with_source( dataset_names, filter_empty=True, min_keypoints=0, proposal_files=None ): assert len(dataset_names) dataset_dicts = [DatasetCatalog.get(dataset_name) for dataset_name in dataset_names] for dataset_name, dicts in zip(dataset_names, dataset_dicts): assert len(dicts), "Dataset '{}' is empty!".format(dataset_name) for source_id, (dataset_name, dicts) in \ enumerate(zip(dataset_names, dataset_dicts)): assert len(dicts), "Dataset '{}' is empty!".format(dataset_name) for d in dicts: d['dataset_source'] = source_id if "annotations" in dicts[0]: try: class_names = MetadataCatalog.get(dataset_name).thing_classes check_metadata_consistency("thing_classes", dataset_name) print_instances_class_histogram(dicts, class_names) except AttributeError: # class names are not available for this dataset pass assert proposal_files is None dataset_dicts = list(itertools.chain.from_iterable(dataset_dicts)) has_instances = "annotations" in dataset_dicts[0] if filter_empty and has_instances: dataset_dicts = filter_images_with_only_crowd_annotations(dataset_dicts) if min_keypoints > 0 and has_instances: dataset_dicts = filter_images_with_few_keypoints(dataset_dicts, min_keypoints) return dataset_dicts class MultiDatasetSampler(Sampler): def __init__( self, dataset_dicts, dataset_ratio, seed: Optional[int] = None, ): sizes = [0 for _ in range(len(dataset_ratio))] for d in dataset_dicts: sizes[d['dataset_source']] += 1 print('dataset sizes', sizes) self.sizes = sizes assert len(dataset_ratio) == len(sizes), \ 'length of dataset ratio {} should be equal to number if dataset {}'.format( len(dataset_ratio), len(sizes) ) if seed is None: seed = comm.shared_random_seed() self._seed = int(seed) self._rank = comm.get_rank() self._world_size = comm.get_world_size() self.dataset_ids = torch.tensor( [d['dataset_source'] for d in dataset_dicts], dtype=torch.long) self.dataset_ratio = dataset_ratio dataset_weight = [torch.ones(s) * max(sizes) / s * r / sum(dataset_ratio) \ for i, (r, s) in enumerate(zip(dataset_ratio, sizes))] dataset_weight = torch.cat(dataset_weight) self.weights = dataset_weight self.sample_epoch_size = len(self.weights) def __iter__(self): start = self._rank yield from itertools.islice( self._infinite_indices(), start, None, self._world_size) def _infinite_indices(self): g = torch.Generator() g.manual_seed(self._seed) while True: if len(self.dataset_ratio) > 1: # multiple datasets ids = torch.multinomial( self.weights, self.sample_epoch_size, generator=g, replacement=True) nums = [(self.dataset_ids[ids] == i).sum().int().item() \ for i in range(len(self.sizes))] yield from ids else: # single dataset yield from torch.randperm(self.sizes[0], generator=g).tolist() class DatasetMapper: """ A callable which takes a dataset dict in Detectron2 Dataset format, and map it into a format used by the model. This is the default callable to be used to map your dataset dict into training data. You may need to follow it to implement your own one for customized logic, such as a different way to read or transform images. See :doc:`/tutorials/data_loading` for details. The callable currently does the following: 1. Read the image from "file_name" 2. Applies cropping/geometric transforms to the image and annotations 3. Prepare data and annotations to Tensor and :class:`Instances` """ def __init__( self, is_train: bool, *, augmentations: List[Union[T.Augmentation, T.Transform]], image_format: str, use_instance_mask: bool = False, use_keypoint: bool = False, instance_mask_format: str = "polygon", keypoint_hflip_indices: Optional[np.ndarray] = None, precomputed_proposal_topk: Optional[int] = None, recompute_boxes: bool = False, ): """ NOTE: this interface is experimental. Args: is_train: whether it's used in training or inference augmentations: a list of augmentations or deterministic transforms to apply image_format: an image format supported by :func:`detection_utils.read_image`. use_instance_mask: whether to process instance segmentation annotations, if available use_keypoint: whether to process keypoint annotations if available instance_mask_format: one of "polygon" or "bitmask". Process instance segmentation masks into this format. keypoint_hflip_indices: see :func:`detection_utils.create_keypoint_hflip_indices` precomputed_proposal_topk: if given, will load pre-computed proposals from dataset_dict and keep the top k proposals for each image. recompute_boxes: whether to overwrite bounding box annotations by computing tight bounding boxes from instance mask annotations. """ if recompute_boxes: assert use_instance_mask, "recompute_boxes requires instance masks" # fmt: off self.is_train = is_train self.augmentations = T.AugmentationList(augmentations) self.image_format = image_format self.use_instance_mask = use_instance_mask self.instance_mask_format = instance_mask_format self.use_keypoint = use_keypoint self.keypoint_hflip_indices = keypoint_hflip_indices self.proposal_topk = precomputed_proposal_topk self.recompute_boxes = recompute_boxes # fmt: on logger = logging.getLogger(__name__) mode = "training" if is_train else "inference" logger.info(f"[DatasetMapper] Augmentations used in {mode}: {augmentations}") def from_config(cls, cfg, is_train: bool = True): augs = utils.build_augmentation(cfg, is_train) if cfg.INPUT.CROP.ENABLED and is_train: augs.insert(0, T.RandomCrop(cfg.INPUT.CROP.TYPE, cfg.INPUT.CROP.SIZE)) recompute_boxes = cfg.MODEL.MASK_ON else: recompute_boxes = False ret = { "is_train": is_train, "augmentations": augs, "image_format": cfg.INPUT.FORMAT, "use_instance_mask": cfg.MODEL.MASK_ON, "instance_mask_format": cfg.INPUT.MASK_FORMAT, "use_keypoint": cfg.MODEL.KEYPOINT_ON, "recompute_boxes": recompute_boxes, } if cfg.MODEL.KEYPOINT_ON: ret["keypoint_hflip_indices"] = utils.create_keypoint_hflip_indices(cfg.DATASETS.TRAIN) if cfg.MODEL.LOAD_PROPOSALS: ret["precomputed_proposal_topk"] = ( cfg.DATASETS.PRECOMPUTED_PROPOSAL_TOPK_TRAIN if is_train else cfg.DATASETS.PRECOMPUTED_PROPOSAL_TOPK_TEST ) return ret def _transform_annotations(self, dataset_dict, transforms, image_shape): # USER: Modify this if you want to keep them for some reason. for anno in dataset_dict["annotations"]: if not self.use_instance_mask: anno.pop("segmentation", None) if not self.use_keypoint: anno.pop("keypoints", None) # USER: Implement additional transformations if you have other types of data annos = [ utils.transform_instance_annotations( obj, transforms, image_shape, keypoint_hflip_indices=self.keypoint_hflip_indices ) for obj in dataset_dict.pop("annotations") if obj.get("iscrowd", 0) == 0 ] instances = utils.annotations_to_instances( annos, image_shape, mask_format=self.instance_mask_format ) # After transforms such as cropping are applied, the bounding box may no longer # tightly bound the object. As an example, imagine a triangle object # [(0,0), (2,0), (0,2)] cropped by a box [(1,0),(2,2)] (XYXY format). The tight # bounding box of the cropped triangle should be [(1,0),(2,1)], which is not equal to # the intersection of original bounding box and the cropping box. if self.recompute_boxes: instances.gt_boxes = instances.gt_masks.get_bounding_boxes() dataset_dict["instances"] = utils.filter_empty_instances(instances) def __call__(self, dataset_dict): """ Args: dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format. Returns: dict: a format that builtin models in detectron2 accept """ dataset_dict = copy.deepcopy(dataset_dict) # it will be modified by code below # USER: Write your own image loading if it's not from a file image = utils.read_image(dataset_dict["file_name"], format=self.image_format) utils.check_image_size(dataset_dict, image) # USER: Remove if you don't do semantic/panoptic segmentation. if "sem_seg_file_name" in dataset_dict: sem_seg_gt = utils.read_image(dataset_dict.pop("sem_seg_file_name"), "L").squeeze(2) else: sem_seg_gt = None aug_input = T.AugInput(image, sem_seg=sem_seg_gt) transforms = self.augmentations(aug_input) image, sem_seg_gt = aug_input.image, aug_input.sem_seg image_shape = image.shape[:2] # h, w # Pytorch's dataloader is efficient on torch.Tensor due to shared-memory, # but not efficient on large generic data structures due to the use of pickle & mp.Queue. # Therefore it's important to use torch.Tensor. dataset_dict["image"] = torch.as_tensor(np.ascontiguousarray(image.transpose(2, 0, 1))) if sem_seg_gt is not None: dataset_dict["sem_seg"] = torch.as_tensor(sem_seg_gt.astype("long")) # USER: Remove if you don't use pre-computed proposals. # Most users would not need this feature. if self.proposal_topk is not None: utils.transform_proposals( dataset_dict, image_shape, transforms, proposal_topk=self.proposal_topk ) if not self.is_train: # USER: Modify this if you want to keep them for some reason. dataset_dict.pop("annotations", None) dataset_dict.pop("sem_seg_file_name", None) return dataset_dict if "annotations" in dataset_dict: self._transform_annotations(dataset_dict, transforms, image_shape) return dataset_dict def get_detection_dataset_dicts( names, filter_empty=True, min_keypoints=0, proposal_files=None, check_consistency=True, ): """ Load and prepare dataset dicts for instance detection/segmentation and semantic segmentation. Args: names (str or list[str]): a dataset name or a list of dataset names filter_empty (bool): whether to filter out images without instance annotations min_keypoints (int): filter out images with fewer keypoints than `min_keypoints`. Set to 0 to do nothing. proposal_files (list[str]): if given, a list of object proposal files that match each dataset in `names`. check_consistency (bool): whether to check if datasets have consistent metadata. Returns: list[dict]: a list of dicts following the standard dataset dict format. """ if isinstance(names, str): names = [names] assert len(names), names dataset_dicts = [DatasetCatalog.get(dataset_name) for dataset_name in names] for dataset_name, dicts in zip(names, dataset_dicts): assert len(dicts), "Dataset '{}' is empty!".format(dataset_name) if proposal_files is not None: assert len(names) == len(proposal_files) # load precomputed proposals from proposal files dataset_dicts = [ load_proposals_into_dataset(dataset_i_dicts, proposal_file) for dataset_i_dicts, proposal_file in zip(dataset_dicts, proposal_files) ] if isinstance(dataset_dicts[0], torchdata.Dataset): return torchdata.ConcatDataset(dataset_dicts) dataset_dicts = list(itertools.chain.from_iterable(dataset_dicts)) has_instances = "annotations" in dataset_dicts[0] if filter_empty and has_instances: dataset_dicts = filter_images_with_only_crowd_annotations(dataset_dicts) if min_keypoints > 0 and has_instances: dataset_dicts = filter_images_with_few_keypoints(dataset_dicts, min_keypoints) if check_consistency and has_instances: try: class_names = MetadataCatalog.get(names[0]).thing_classes check_metadata_consistency("thing_classes", names) print_instances_class_histogram(dataset_dicts, class_names) except AttributeError: # class names are not available for this dataset pass assert len(dataset_dicts), "No valid data found in {}.".format(",".join(names)) return dataset_dicts def _custom_train_loader_from_config(cfg, mapper=None, *, dataset=None, sampler=None): sampler_name = cfg.DATALOADER.SAMPLER_TRAIN if 'MultiDataset' in sampler_name: dataset_dicts = get_detection_dataset_dicts_with_source( cfg.DATASETS.TRAIN, filter_empty=cfg.DATALOADER.FILTER_EMPTY_ANNOTATIONS, min_keypoints=cfg.MODEL.ROI_KEYPOINT_HEAD.MIN_KEYPOINTS_PER_IMAGE if cfg.MODEL.KEYPOINT_ON else 0, proposal_files=cfg.DATASETS.PROPOSAL_FILES_TRAIN if cfg.MODEL.LOAD_PROPOSALS else None, ) else: dataset_dicts = get_detection_dataset_dicts( cfg.DATASETS.TRAIN, filter_empty=cfg.DATALOADER.FILTER_EMPTY_ANNOTATIONS, min_keypoints=cfg.MODEL.ROI_KEYPOINT_HEAD.MIN_KEYPOINTS_PER_IMAGE if cfg.MODEL.KEYPOINT_ON else 0, proposal_files=cfg.DATASETS.PROPOSAL_FILES_TRAIN if cfg.MODEL.LOAD_PROPOSALS else None, ) if mapper is None: mapper = DatasetMapper(cfg, True) if sampler is not None: pass elif sampler_name == "TrainingSampler": sampler = TrainingSampler(len(dataset)) elif sampler_name == "MultiDatasetSampler": sampler = MultiDatasetSampler( dataset_dicts, dataset_ratio=cfg.DATALOADER.DATASET_RATIO, ) else: raise ValueError("Unknown training sampler: {}".format(sampler_name)) return { "dataset": dataset_dicts, "sampler": sampler, "mapper": mapper, "total_batch_size": cfg.SOLVER.IMS_PER_BATCH, "num_workers": cfg.DATALOADER.NUM_WORKERS, 'dataset_bs': cfg.DATALOADER.DATASET_BS, 'num_datasets': len(cfg.DATASETS.TRAIN) }
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 DatasetMapper from detectron2.data.build import get_detection_dataset_dicts, build_batch_data_loader from detectron2.data.samplers import TrainingSampler from detectron2.data.build import worker_init_reset_seed, print_instances_class_histogram from detectron2.data.build import filter_images_with_only_crowd_annotations from detectron2.data.build import filter_images_with_few_keypoints from detectron2.data.build import check_metadata_consistency from detectron2.data.catalog import MetadataCatalog, DatasetCatalog from detectron2.utils import comm import itertools from typing import Optional def build_dataset_batch_data_loader( dataset_bs, dataset, sampler, total_batch_size, num_datasets, num_workers=0 ): world_size = get_world_size() assert ( total_batch_size > 0 and total_batch_size % world_size == 0 ), "Total batch size ({}) must be divisible by the number of gpus ({}).".format( total_batch_size, world_size ) data_loader = torch.utils.data.DataLoader( dataset, sampler=sampler, num_workers=num_workers, batch_sampler=None, collate_fn=operator.itemgetter(0), # don't batch, but yield individual elements worker_init_fn=worker_init_reset_seed, ) if num_datasets > 1: return MultiDatasets(data_loader, dataset_bs, num_datasets) else: return SingleDataset(data_loader, dataset_bs) class MapDataset(data.Dataset): """ Map a function over the elements in a dataset. """ def __init__(self, dataset, map_func): """ Args: dataset: a dataset where map function is applied. Can be either map-style or iterable dataset. When given an iterable dataset, the returned object will also be an iterable dataset. map_func: a callable which maps the element in dataset. map_func can return None to skip the data (e.g. in case of errors). How None is handled depends on the style of `dataset`. If `dataset` is map-style, it randomly tries other elements. If `dataset` is iterable, it skips the data and tries the next. """ self._dataset = dataset self._map_func = PicklableWrapper(map_func) # wrap so that a lambda will work self._rng = random.Random(42) self._fallback_candidates = set(range(len(dataset))) def __new__(cls, dataset, map_func): is_iterable = isinstance(dataset, data.IterableDataset) if is_iterable: return _MapIterableDataset(dataset, map_func) else: return super().__new__(cls) def __getnewargs__(self): return self._dataset, self._map_func def __len__(self): return len(self._dataset) def __getitem__(self, idx): retry_count = 0 cur_idx = int(idx) while True: data = self._map_func(self._dataset[cur_idx]) if data is not None: self._fallback_candidates.add(cur_idx) return data # _map_func fails for this idx, use a random new index from the pool retry_count += 1 self._fallback_candidates.discard(cur_idx) cur_idx = self._rng.sample(self._fallback_candidates, k=1)[0] if retry_count >= 3: logger = logging.getLogger(__name__) logger.warning( "Failed to apply `_map_func` for idx: {}, retry count: {}".format( idx, retry_count ) ) class DatasetFromList(data.Dataset): """ Wrap a list to a torch Dataset. It produces elements of the list as data. """ def __init__(self, lst: list, copy: bool = True, serialize: bool = True): """ Args: lst (list): a list which contains elements to produce. copy (bool): whether to deepcopy the element when producing it, so that the result can be modified in place without affecting the source in the list. serialize (bool): whether to hold memory using serialized objects, when enabled, data loader workers can use shared RAM from master process instead of making a copy. """ self._lst = lst self._copy = copy self._serialize = serialize def _serialize(data): buffer = pickle.dumps(data, protocol=-1) return np.frombuffer(buffer, dtype=np.uint8) if self._serialize: logger = logging.getLogger(__name__) logger.info( "Serializing {} elements to byte tensors and concatenating them all ...".format( len(self._lst) ) ) self._lst = [_serialize(x) for x in self._lst] self._addr = np.asarray([len(x) for x in self._lst], dtype=np.int64) self._addr = np.cumsum(self._addr) self._lst = np.concatenate(self._lst) logger.info("Serialized dataset takes {:.2f} MiB".format(len(self._lst) / 1024 ** 2)) def __len__(self): if self._serialize: return len(self._addr) else: return len(self._lst) def __getitem__(self, idx): if self._serialize: start_addr = 0 if idx == 0 else self._addr[idx - 1].item() end_addr = self._addr[idx].item() bytes = memoryview(self._lst[start_addr:end_addr]) return pickle.loads(bytes) elif self._copy: return copy.deepcopy(self._lst[idx]) else: return self._lst[idx] def build_custom_train_loader( dataset, *, mapper, sampler, total_batch_size=16, num_workers=0, num_datasets=1, dataset_bs=1 ): if isinstance(dataset, list): dataset = DatasetFromList(dataset, copy=False) if mapper is not None: dataset = MapDataset(dataset, mapper) if sampler is None: sampler = TrainingSampler(len(dataset)) assert isinstance(sampler, torch.utils.data.sampler.Sampler) return build_dataset_batch_data_loader( dataset_bs, dataset, sampler, total_batch_size, num_datasets=num_datasets, num_workers=num_workers, )
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 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 Here is the function: def window_partition(x, window_size): """ 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 """ B, H, W, C = x.shape pad_h = (window_size - H % window_size) % window_size pad_w = (window_size - W % window_size) % window_size if pad_h > 0 or pad_w > 0: x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) Hp, Wp = H + pad_h, W + pad_w x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) return windows, (Hp, Wp)
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 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 sequences with [B, H, W, C]. Here is the function: def window_unpartition(windows, window_size, pad_hw, hw): """ 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 sequences with [B, H, W, C]. """ Hp, Wp = pad_hw H, W = hw B = windows.shape[0] // (Hp * Wp // window_size // window_size) x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) if Hp > H or Wp > W: x = x[:, :H, :W, :].contiguous() return x
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 sequences with [B, H, W, C].
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. rel_pos (Tensor): relative position embeddings (L, C). Returns: Extracted positional embeddings according to relative positions. """ max_rel_dist = int(2 * max(q_size, k_size) - 1) # Interpolate rel pos if needed. if rel_pos.shape[0] != max_rel_dist: # Interpolate rel pos. rel_pos_resized = F.interpolate( rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), size=max_rel_dist, mode="linear", ) rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0) else: rel_pos_resized = rel_pos # Scale the coords with short length if shapes for q and k are different. q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0) k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0) relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0) return rel_pos_resized[relative_coords.long()] The provided code snippet includes necessary dependencies for implementing the `add_decomposed_rel_pos` function. Write a Python function `def add_decomposed_rel_pos(attn, q, rel_pos_h, rel_pos_w, q_size, k_size)` to solve the following problem: 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 (Tensor): relative position embeddings (Lh, C) for height axis. rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis. q_size (Tuple): spatial sequence size of query q with (q_h, q_w). k_size (Tuple): spatial sequence size of key k with (k_h, k_w). Returns: attn (Tensor): attention map with added relative positional embeddings. Here is the function: def add_decomposed_rel_pos(attn, q, rel_pos_h, rel_pos_w, q_size, k_size): """ 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 (Tensor): relative position embeddings (Lh, C) for height axis. rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis. q_size (Tuple): spatial sequence size of query q with (q_h, q_w). k_size (Tuple): spatial sequence size of key k with (k_h, k_w). Returns: attn (Tensor): attention map with added relative positional embeddings. """ q_h, q_w = q_size k_h, k_w = k_size Rh = get_rel_pos(q_h, k_h, rel_pos_h) Rw = get_rel_pos(q_w, k_w, rel_pos_w) B, _, dim = q.shape r_q = q.reshape(B, q_h, q_w, dim) rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) attn = ( attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :] ).view(B, q_h * q_w, k_h * k_w) return attn
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 (Tensor): relative position embeddings (Lh, C) for height axis. rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis. q_size (Tuple): spatial sequence size of query q with (q_h, q_w). k_size (Tuple): spatial sequence size of key k with (k_h, k_w). Returns: attn (Tensor): attention map with added relative positional embeddings.
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 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 tokens. Returns: Absolute positional embeddings after processing with shape (1, H, W, C) Here is the function: def get_abs_pos(abs_pos, has_cls_token, hw): """ 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 tokens. Returns: Absolute positional embeddings after processing with shape (1, H, W, C) """ h, w = hw if has_cls_token: abs_pos = abs_pos[:, 1:] xy_num = abs_pos.shape[1] size = int(math.sqrt(xy_num)) assert size * size == xy_num if size != h or size != w: new_abs_pos = F.interpolate( abs_pos.reshape(1, size, size, -1).permute(0, 3, 1, 2), size=(h, w), mode="bicubic", align_corners=False, ) return new_abs_pos.permute(0, 2, 3, 1) else: return abs_pos.reshape(1, h, w, -1)
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 tokens. Returns: Absolute positional embeddings after processing with shape (1, H, W, C)
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 centernet.modeling.backbone.fpn_p5 import LastLevelP6P7_P5 import torch.utils.checkpoint as checkpoint from timm.models.layers import DropPath, Mlp, trunc_normal_ from detectron2.modeling.backbone.backbone import Backbone from .utils import ( PatchEmbed, add_decomposed_rel_pos, get_abs_pos, window_partition, window_unpartition, ) class ViT(Backbone): """ This module implements Vision Transformer (ViT) backbone in :paper:`vitdet`. "Exploring Plain Vision Transformer Backbones for Object Detection", https://arxiv.org/abs/2203.16527 """ def __init__( self, img_size=1024, patch_size=16, in_chans=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=True, drop_path_rate=0.0, norm_layer=nn.LayerNorm, act_layer=nn.GELU, use_abs_pos=True, use_rel_pos=False, rel_pos_zero_init=True, window_size=0, window_block_indexes=(), residual_block_indexes=(), use_act_checkpoint=True, pretrain_img_size=224, pretrain_use_cls_token=True, out_feature="last_feat", ): """ Args: img_size (int): Input image size. patch_size (int): Patch size. in_chans (int): Number of input image channels. embed_dim (int): Patch embedding dimension. depth (int): Depth of ViT. num_heads (int): Number of attention heads in each ViT block. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool): If True, add a learnable bias to query, key, value. drop_path_rate (float): Stochastic depth rate. norm_layer (nn.Module): Normalization layer. act_layer (nn.Module): Activation layer. use_abs_pos (bool): If True, use absolute positional embeddings. use_rel_pos (bool): If True, add relative positional embeddings to the attention map. rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. window_size (int): Window size for window attention blocks. window_block_indexes (list): Indexes for blocks using window attention. residual_block_indexes (list): Indexes for blocks using conv propagation. use_act_checkpoint (bool): If True, use activation checkpointing. pretrain_img_size (int): input image size for pretraining models. pretrain_use_cls_token (bool): If True, pretrainig models use class token. out_feature (str): name of the feature from the last block. """ super().__init__() self.pretrain_use_cls_token = pretrain_use_cls_token self.use_act_checkpoint = use_act_checkpoint self.patch_embed = PatchEmbed( kernel_size=(patch_size, patch_size), stride=(patch_size, patch_size), in_chans=in_chans, embed_dim=embed_dim, ) if use_abs_pos: # Initialize absolute positional embedding with pretrain image size. num_patches = (pretrain_img_size // patch_size) * (pretrain_img_size // patch_size) num_positions = (num_patches + 1) if pretrain_use_cls_token else num_patches self.pos_embed = nn.Parameter(torch.zeros(1, num_positions, embed_dim)) else: self.pos_embed = None # stochastic depth decay rule dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] self.blocks = nn.ModuleList() for i in range(depth): block = Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer, use_rel_pos=use_rel_pos, rel_pos_zero_init=rel_pos_zero_init, window_size=window_size if i in window_block_indexes else 0, use_residual_block=i in residual_block_indexes, input_size=(img_size // patch_size, img_size // patch_size), ) self.blocks.append(block) self._out_feature_channels = {out_feature: embed_dim} self._out_feature_strides = {out_feature: patch_size} self._out_features = [out_feature] if self.pos_embed is not None: trunc_normal_(self.pos_embed, std=0.02) self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=0.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) def forward(self, x): x = self.patch_embed(x) if self.pos_embed is not None: x = x + get_abs_pos( self.pos_embed, self.pretrain_use_cls_token, (x.shape[1], x.shape[2]) ) for blk in self.blocks: if self.use_act_checkpoint: x = checkpoint.checkpoint(blk, x) else: x = blk(x) return x.permute(0, 3, 1, 2) class ViT_FPN(Backbone): def __init__(self, bottom_up=None, top_block=None, out_channels=None, strides=None, vit_out_dim=None): super(ViT_FPN, self).__init__() assert isinstance(bottom_up, Backbone) self.bottom_up = bottom_up self.top_block = top_block self._out_feature_strides = {"p{}".format(int(math.log2(s))): s for s in strides} self._out_features = list(self._out_feature_strides.keys()) self._out_feature_channels = {k: out_channels for k in self._out_features} self._size_divisibility = strides[2] self.maxpool = nn.MaxPool2d(2, stride=2) self.fpn_stride_16_8 = nn.ConvTranspose2d(vit_out_dim, vit_out_dim, 2, stride=2, bias=False) self.fpn_stride8_conv1 = nn.Conv2d(in_channels=vit_out_dim, out_channels=out_channels, kernel_size=1, bias=False) self.fpn_stride8_norm1 = nn.LayerNorm(out_channels) self.fpn_stride8_conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1, bias=False) self.fpn_stride8_norm2 = nn.LayerNorm(out_channels) self.fpn_stride16_conv1 = nn.Conv2d(in_channels=vit_out_dim, out_channels=out_channels, kernel_size=1, bias=False) self.fpn_stride16_norm1 = nn.LayerNorm(out_channels) self.fpn_stride16_conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1, bias=False) self.fpn_stride16_norm2 = nn.LayerNorm(out_channels) self.fpn_stride32_conv1 = nn.Conv2d(in_channels=vit_out_dim, out_channels=out_channels, kernel_size=1, bias=False) self.fpn_stride32_norm1 = nn.LayerNorm(out_channels) self.fpn_stride32_conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1, bias=False) self.fpn_stride32_norm2 = nn.LayerNorm(out_channels) def forward(self, x): vit_output_featuremap = self.bottom_up(x) stride8_feature = self.fpn_stride_16_8(vit_output_featuremap) stride8_feature = self.fpn_stride8_norm1(self.fpn_stride8_conv1(stride8_feature) .permute(0, 2, 3, 1)).permute(0, 3, 1, 2) stride8_feature = self.fpn_stride8_norm2(self.fpn_stride8_conv2(stride8_feature) .permute(0, 2, 3, 1)).permute(0, 3, 1, 2) stride32_feature = self.maxpool(vit_output_featuremap) stride32_feature = self.fpn_stride32_norm1(self.fpn_stride32_conv1(stride32_feature) .permute(0, 2, 3, 1)).permute(0, 3, 1, 2) stride32_feature = self.fpn_stride32_norm2(self.fpn_stride32_conv2(stride32_feature) .permute(0, 2, 3, 1)).permute(0, 3, 1, 2) stride16_feature = self.fpn_stride16_norm1(self.fpn_stride16_conv1(vit_output_featuremap). permute(0, 2, 3, 1)).permute(0, 3, 1, 2) stride16_feature = self.fpn_stride16_norm2(self.fpn_stride16_conv2(stride16_feature) .permute(0, 2, 3, 1)).permute(0, 3, 1, 2) results = [stride8_feature, stride16_feature, stride32_feature] results.extend(self.top_block(stride32_feature)) assert len(self._out_features) == len(results) fpn_out = {f: res for f, res in zip(self._out_features, results)} return fpn_out def size_divisibility(self): return self._size_divisibility def output_shape(self): return { name: ShapeSpec( channels=self._out_feature_channels[name], stride=self._out_feature_strides[name] ) for name in self._out_features } class LastLevelP6P7_P5(nn.Module): """ This module is used in RetinaNet to generate extra layers, P6 and P7 from C5 feature. """ def __init__(self, in_channels, out_channels): super().__init__() self.num_levels = 2 self.in_feature = "p5" self.p6 = nn.Conv2d(in_channels, out_channels, 3, 2, 1) self.p7 = nn.Conv2d(out_channels, out_channels, 3, 2, 1) for module in [self.p6, self.p7]: weight_init.c2_xavier_fill(module) def forward(self, c5): p6 = self.p6(c5) p7 = self.p7(F.relu(p6)) return [p6, p7] def build_vit_fpn_backbone(cfg, input_shape: ShapeSpec): embed_dim = 768 vit_out_dim = embed_dim bottom_up = ViT( # Single-scale ViT backbone img_size=1024, patch_size=16, embed_dim=embed_dim, depth=12, num_heads=12, drop_path_rate=0.1, window_size=14, mlp_ratio=4, qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), window_block_indexes=[ # 2, 5, 8 11 for global attention 0, 1, 3, 4, 6, 7, 9, 10, ], residual_block_indexes=[], use_act_checkpoint=cfg.USE_ACT_CHECKPOINT, use_rel_pos=True, out_feature="last_feat",) out_channels = cfg.MODEL.FPN.OUT_CHANNELS assert out_channels == 256 or out_channels == 768 or out_channels == 1024 backbone = ViT_FPN(bottom_up=bottom_up, top_block=LastLevelP6P7_P5(out_channels, out_channels), out_channels=out_channels, strides=[8, 16, 32, 64, 128], vit_out_dim=vit_out_dim) return backbone
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 centernet.modeling.backbone.fpn_p5 import LastLevelP6P7_P5 import torch.utils.checkpoint as checkpoint from timm.models.layers import DropPath, Mlp, trunc_normal_ from detectron2.modeling.backbone.backbone import Backbone from .utils import ( PatchEmbed, add_decomposed_rel_pos, get_abs_pos, window_partition, window_unpartition, ) class ViT(Backbone): """ This module implements Vision Transformer (ViT) backbone in :paper:`vitdet`. "Exploring Plain Vision Transformer Backbones for Object Detection", https://arxiv.org/abs/2203.16527 """ def __init__( self, img_size=1024, patch_size=16, in_chans=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=True, drop_path_rate=0.0, norm_layer=nn.LayerNorm, act_layer=nn.GELU, use_abs_pos=True, use_rel_pos=False, rel_pos_zero_init=True, window_size=0, window_block_indexes=(), residual_block_indexes=(), use_act_checkpoint=True, pretrain_img_size=224, pretrain_use_cls_token=True, out_feature="last_feat", ): """ Args: img_size (int): Input image size. patch_size (int): Patch size. in_chans (int): Number of input image channels. embed_dim (int): Patch embedding dimension. depth (int): Depth of ViT. num_heads (int): Number of attention heads in each ViT block. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool): If True, add a learnable bias to query, key, value. drop_path_rate (float): Stochastic depth rate. norm_layer (nn.Module): Normalization layer. act_layer (nn.Module): Activation layer. use_abs_pos (bool): If True, use absolute positional embeddings. use_rel_pos (bool): If True, add relative positional embeddings to the attention map. rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. window_size (int): Window size for window attention blocks. window_block_indexes (list): Indexes for blocks using window attention. residual_block_indexes (list): Indexes for blocks using conv propagation. use_act_checkpoint (bool): If True, use activation checkpointing. pretrain_img_size (int): input image size for pretraining models. pretrain_use_cls_token (bool): If True, pretrainig models use class token. out_feature (str): name of the feature from the last block. """ super().__init__() self.pretrain_use_cls_token = pretrain_use_cls_token self.use_act_checkpoint = use_act_checkpoint self.patch_embed = PatchEmbed( kernel_size=(patch_size, patch_size), stride=(patch_size, patch_size), in_chans=in_chans, embed_dim=embed_dim, ) if use_abs_pos: # Initialize absolute positional embedding with pretrain image size. num_patches = (pretrain_img_size // patch_size) * (pretrain_img_size // patch_size) num_positions = (num_patches + 1) if pretrain_use_cls_token else num_patches self.pos_embed = nn.Parameter(torch.zeros(1, num_positions, embed_dim)) else: self.pos_embed = None # stochastic depth decay rule dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] self.blocks = nn.ModuleList() for i in range(depth): block = Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer, use_rel_pos=use_rel_pos, rel_pos_zero_init=rel_pos_zero_init, window_size=window_size if i in window_block_indexes else 0, use_residual_block=i in residual_block_indexes, input_size=(img_size // patch_size, img_size // patch_size), ) self.blocks.append(block) self._out_feature_channels = {out_feature: embed_dim} self._out_feature_strides = {out_feature: patch_size} self._out_features = [out_feature] if self.pos_embed is not None: trunc_normal_(self.pos_embed, std=0.02) self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=0.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) def forward(self, x): x = self.patch_embed(x) if self.pos_embed is not None: x = x + get_abs_pos( self.pos_embed, self.pretrain_use_cls_token, (x.shape[1], x.shape[2]) ) for blk in self.blocks: if self.use_act_checkpoint: x = checkpoint.checkpoint(blk, x) else: x = blk(x) return x.permute(0, 3, 1, 2) class ViT_FPN(Backbone): def __init__(self, bottom_up=None, top_block=None, out_channels=None, strides=None, vit_out_dim=None): super(ViT_FPN, self).__init__() assert isinstance(bottom_up, Backbone) self.bottom_up = bottom_up self.top_block = top_block self._out_feature_strides = {"p{}".format(int(math.log2(s))): s for s in strides} self._out_features = list(self._out_feature_strides.keys()) self._out_feature_channels = {k: out_channels for k in self._out_features} self._size_divisibility = strides[2] self.maxpool = nn.MaxPool2d(2, stride=2) self.fpn_stride_16_8 = nn.ConvTranspose2d(vit_out_dim, vit_out_dim, 2, stride=2, bias=False) self.fpn_stride8_conv1 = nn.Conv2d(in_channels=vit_out_dim, out_channels=out_channels, kernel_size=1, bias=False) self.fpn_stride8_norm1 = nn.LayerNorm(out_channels) self.fpn_stride8_conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1, bias=False) self.fpn_stride8_norm2 = nn.LayerNorm(out_channels) self.fpn_stride16_conv1 = nn.Conv2d(in_channels=vit_out_dim, out_channels=out_channels, kernel_size=1, bias=False) self.fpn_stride16_norm1 = nn.LayerNorm(out_channels) self.fpn_stride16_conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1, bias=False) self.fpn_stride16_norm2 = nn.LayerNorm(out_channels) self.fpn_stride32_conv1 = nn.Conv2d(in_channels=vit_out_dim, out_channels=out_channels, kernel_size=1, bias=False) self.fpn_stride32_norm1 = nn.LayerNorm(out_channels) self.fpn_stride32_conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1, bias=False) self.fpn_stride32_norm2 = nn.LayerNorm(out_channels) def forward(self, x): vit_output_featuremap = self.bottom_up(x) stride8_feature = self.fpn_stride_16_8(vit_output_featuremap) stride8_feature = self.fpn_stride8_norm1(self.fpn_stride8_conv1(stride8_feature) .permute(0, 2, 3, 1)).permute(0, 3, 1, 2) stride8_feature = self.fpn_stride8_norm2(self.fpn_stride8_conv2(stride8_feature) .permute(0, 2, 3, 1)).permute(0, 3, 1, 2) stride32_feature = self.maxpool(vit_output_featuremap) stride32_feature = self.fpn_stride32_norm1(self.fpn_stride32_conv1(stride32_feature) .permute(0, 2, 3, 1)).permute(0, 3, 1, 2) stride32_feature = self.fpn_stride32_norm2(self.fpn_stride32_conv2(stride32_feature) .permute(0, 2, 3, 1)).permute(0, 3, 1, 2) stride16_feature = self.fpn_stride16_norm1(self.fpn_stride16_conv1(vit_output_featuremap). permute(0, 2, 3, 1)).permute(0, 3, 1, 2) stride16_feature = self.fpn_stride16_norm2(self.fpn_stride16_conv2(stride16_feature) .permute(0, 2, 3, 1)).permute(0, 3, 1, 2) results = [stride8_feature, stride16_feature, stride32_feature] results.extend(self.top_block(stride32_feature)) assert len(self._out_features) == len(results) fpn_out = {f: res for f, res in zip(self._out_features, results)} return fpn_out def size_divisibility(self): return self._size_divisibility def output_shape(self): return { name: ShapeSpec( channels=self._out_feature_channels[name], stride=self._out_feature_strides[name] ) for name in self._out_features } class LastLevelP6P7_P5(nn.Module): """ This module is used in RetinaNet to generate extra layers, P6 and P7 from C5 feature. """ def __init__(self, in_channels, out_channels): super().__init__() self.num_levels = 2 self.in_feature = "p5" self.p6 = nn.Conv2d(in_channels, out_channels, 3, 2, 1) self.p7 = nn.Conv2d(out_channels, out_channels, 3, 2, 1) for module in [self.p6, self.p7]: weight_init.c2_xavier_fill(module) def forward(self, c5): p6 = self.p6(c5) p7 = self.p7(F.relu(p6)) return [p6, p7] def build_vit_fpn_backbone_large(cfg, input_shape: ShapeSpec): window_block_indexes = (list(range(0, 5)) + list(range(6, 11)) + list(range(12, 17)) + list(range(18, 23))) embed_dim = 1024 vit_out_dim = embed_dim bottom_up = ViT( # Single-scale ViT backbone img_size=1024, patch_size=16, embed_dim=embed_dim, depth=24, num_heads=16, drop_path_rate=0.4, window_size=14, mlp_ratio=4, qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), window_block_indexes=window_block_indexes, residual_block_indexes=[], use_act_checkpoint=cfg.USE_ACT_CHECKPOINT, use_rel_pos=True, out_feature="last_feat",) out_channels = cfg.MODEL.FPN.OUT_CHANNELS assert out_channels == 256 or out_channels == 768 or out_channels == 1024 backbone = ViT_FPN(bottom_up=bottom_up, top_block=LastLevelP6P7_P5(out_channels, out_channels), out_channels=out_channels, strides=[8, 16, 32, 64, 128], vit_out_dim=vit_out_dim) return backbone
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 centernet.modeling.backbone.fpn_p5 import LastLevelP6P7_P5 import torch.utils.checkpoint as checkpoint from timm.models.layers import DropPath, Mlp, trunc_normal_ from detectron2.modeling.backbone.backbone import Backbone from .utils import ( PatchEmbed, add_decomposed_rel_pos, get_abs_pos, window_partition, window_unpartition, ) class ViT(Backbone): """ This module implements Vision Transformer (ViT) backbone in :paper:`vitdet`. "Exploring Plain Vision Transformer Backbones for Object Detection", https://arxiv.org/abs/2203.16527 """ def __init__( self, img_size=1024, patch_size=16, in_chans=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=True, drop_path_rate=0.0, norm_layer=nn.LayerNorm, act_layer=nn.GELU, use_abs_pos=True, use_rel_pos=False, rel_pos_zero_init=True, window_size=0, window_block_indexes=(), residual_block_indexes=(), use_act_checkpoint=True, pretrain_img_size=224, pretrain_use_cls_token=True, out_feature="last_feat", ): """ Args: img_size (int): Input image size. patch_size (int): Patch size. in_chans (int): Number of input image channels. embed_dim (int): Patch embedding dimension. depth (int): Depth of ViT. num_heads (int): Number of attention heads in each ViT block. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool): If True, add a learnable bias to query, key, value. drop_path_rate (float): Stochastic depth rate. norm_layer (nn.Module): Normalization layer. act_layer (nn.Module): Activation layer. use_abs_pos (bool): If True, use absolute positional embeddings. use_rel_pos (bool): If True, add relative positional embeddings to the attention map. rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. window_size (int): Window size for window attention blocks. window_block_indexes (list): Indexes for blocks using window attention. residual_block_indexes (list): Indexes for blocks using conv propagation. use_act_checkpoint (bool): If True, use activation checkpointing. pretrain_img_size (int): input image size for pretraining models. pretrain_use_cls_token (bool): If True, pretrainig models use class token. out_feature (str): name of the feature from the last block. """ super().__init__() self.pretrain_use_cls_token = pretrain_use_cls_token self.use_act_checkpoint = use_act_checkpoint self.patch_embed = PatchEmbed( kernel_size=(patch_size, patch_size), stride=(patch_size, patch_size), in_chans=in_chans, embed_dim=embed_dim, ) if use_abs_pos: # Initialize absolute positional embedding with pretrain image size. num_patches = (pretrain_img_size // patch_size) * (pretrain_img_size // patch_size) num_positions = (num_patches + 1) if pretrain_use_cls_token else num_patches self.pos_embed = nn.Parameter(torch.zeros(1, num_positions, embed_dim)) else: self.pos_embed = None # stochastic depth decay rule dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] self.blocks = nn.ModuleList() for i in range(depth): block = Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer, use_rel_pos=use_rel_pos, rel_pos_zero_init=rel_pos_zero_init, window_size=window_size if i in window_block_indexes else 0, use_residual_block=i in residual_block_indexes, input_size=(img_size // patch_size, img_size // patch_size), ) self.blocks.append(block) self._out_feature_channels = {out_feature: embed_dim} self._out_feature_strides = {out_feature: patch_size} self._out_features = [out_feature] if self.pos_embed is not None: trunc_normal_(self.pos_embed, std=0.02) self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=0.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) def forward(self, x): x = self.patch_embed(x) if self.pos_embed is not None: x = x + get_abs_pos( self.pos_embed, self.pretrain_use_cls_token, (x.shape[1], x.shape[2]) ) for blk in self.blocks: if self.use_act_checkpoint: x = checkpoint.checkpoint(blk, x) else: x = blk(x) return x.permute(0, 3, 1, 2) class ViT_FPN(Backbone): def __init__(self, bottom_up=None, top_block=None, out_channels=None, strides=None, vit_out_dim=None): super(ViT_FPN, self).__init__() assert isinstance(bottom_up, Backbone) self.bottom_up = bottom_up self.top_block = top_block self._out_feature_strides = {"p{}".format(int(math.log2(s))): s for s in strides} self._out_features = list(self._out_feature_strides.keys()) self._out_feature_channels = {k: out_channels for k in self._out_features} self._size_divisibility = strides[2] self.maxpool = nn.MaxPool2d(2, stride=2) self.fpn_stride_16_8 = nn.ConvTranspose2d(vit_out_dim, vit_out_dim, 2, stride=2, bias=False) self.fpn_stride8_conv1 = nn.Conv2d(in_channels=vit_out_dim, out_channels=out_channels, kernel_size=1, bias=False) self.fpn_stride8_norm1 = nn.LayerNorm(out_channels) self.fpn_stride8_conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1, bias=False) self.fpn_stride8_norm2 = nn.LayerNorm(out_channels) self.fpn_stride16_conv1 = nn.Conv2d(in_channels=vit_out_dim, out_channels=out_channels, kernel_size=1, bias=False) self.fpn_stride16_norm1 = nn.LayerNorm(out_channels) self.fpn_stride16_conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1, bias=False) self.fpn_stride16_norm2 = nn.LayerNorm(out_channels) self.fpn_stride32_conv1 = nn.Conv2d(in_channels=vit_out_dim, out_channels=out_channels, kernel_size=1, bias=False) self.fpn_stride32_norm1 = nn.LayerNorm(out_channels) self.fpn_stride32_conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1, bias=False) self.fpn_stride32_norm2 = nn.LayerNorm(out_channels) def forward(self, x): vit_output_featuremap = self.bottom_up(x) stride8_feature = self.fpn_stride_16_8(vit_output_featuremap) stride8_feature = self.fpn_stride8_norm1(self.fpn_stride8_conv1(stride8_feature) .permute(0, 2, 3, 1)).permute(0, 3, 1, 2) stride8_feature = self.fpn_stride8_norm2(self.fpn_stride8_conv2(stride8_feature) .permute(0, 2, 3, 1)).permute(0, 3, 1, 2) stride32_feature = self.maxpool(vit_output_featuremap) stride32_feature = self.fpn_stride32_norm1(self.fpn_stride32_conv1(stride32_feature) .permute(0, 2, 3, 1)).permute(0, 3, 1, 2) stride32_feature = self.fpn_stride32_norm2(self.fpn_stride32_conv2(stride32_feature) .permute(0, 2, 3, 1)).permute(0, 3, 1, 2) stride16_feature = self.fpn_stride16_norm1(self.fpn_stride16_conv1(vit_output_featuremap). permute(0, 2, 3, 1)).permute(0, 3, 1, 2) stride16_feature = self.fpn_stride16_norm2(self.fpn_stride16_conv2(stride16_feature) .permute(0, 2, 3, 1)).permute(0, 3, 1, 2) results = [stride8_feature, stride16_feature, stride32_feature] results.extend(self.top_block(stride32_feature)) assert len(self._out_features) == len(results) fpn_out = {f: res for f, res in zip(self._out_features, results)} return fpn_out def size_divisibility(self): return self._size_divisibility def output_shape(self): return { name: ShapeSpec( channels=self._out_feature_channels[name], stride=self._out_feature_strides[name] ) for name in self._out_features } class LastLevelP6P7_P5(nn.Module): """ This module is used in RetinaNet to generate extra layers, P6 and P7 from C5 feature. """ def __init__(self, in_channels, out_channels): super().__init__() self.num_levels = 2 self.in_feature = "p5" self.p6 = nn.Conv2d(in_channels, out_channels, 3, 2, 1) self.p7 = nn.Conv2d(out_channels, out_channels, 3, 2, 1) for module in [self.p6, self.p7]: weight_init.c2_xavier_fill(module) def forward(self, c5): p6 = self.p6(c5) p7 = self.p7(F.relu(p6)) return [p6, p7] def build_vit_fpn_backbone_huge(cfg, input_shape: ShapeSpec): window_block_indexes = (list(range(0, 7)) + list(range(8, 15)) + list(range(16, 23)) + list(range(24, 31))) embed_dim = 1280 vit_out_dim = embed_dim bottom_up = ViT( # Single-scale ViT backbone img_size=1024, patch_size=16, embed_dim=embed_dim, depth=32, num_heads=16, drop_path_rate=0.5, window_size=14, mlp_ratio=4, qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), window_block_indexes=window_block_indexes, residual_block_indexes=[], use_act_checkpoint=cfg.USE_ACT_CHECKPOINT, use_rel_pos=True, out_feature="last_feat",) out_channels = cfg.MODEL.FPN.OUT_CHANNELS assert out_channels == 256 or out_channels == 768 or out_channels == 1024 backbone = ViT_FPN(bottom_up=bottom_up, top_block=LastLevelP6P7_P5(out_channels, out_channels), out_channels=out_channels, strides=[8, 16, 32, 64, 128], vit_out_dim=vit_out_dim) return backbone
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 ClientError from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the `filename_to_url` function. Write a Python function `def filename_to_url(filename, cache_dir=None)` to solve the following problem: Return the url and etag (which may be ``None``) stored for `filename`. Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist. Here is the function: def filename_to_url(filename, cache_dir=None): """ Return the url and etag (which may be ``None``) stored for `filename`. Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist. """ if cache_dir is None: cache_dir = PYTORCH_PRETRAINED_BERT_CACHE if sys.version_info[0] == 3 and isinstance(cache_dir, Path): cache_dir = str(cache_dir) cache_path = os.path.join(cache_dir, filename) if not os.path.exists(cache_path): raise EnvironmentError("file {} not found".format(cache_path)) meta_path = cache_path + '.json' if not os.path.exists(meta_path): raise EnvironmentError("file {} not found".format(meta_path)) with open(meta_path, encoding="utf-8") as meta_file: metadata = json.load(meta_file) url = metadata['url'] etag = metadata['etag'] return url, etag
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 ClientError from tqdm import tqdm def get_from_cache(url, cache_dir=None): """ Given a URL, look for the corresponding dataset in the local cache. If it's not there, download it. Then return the path to the cached file. """ if cache_dir is None: cache_dir = PYTORCH_PRETRAINED_BERT_CACHE if sys.version_info[0] == 3 and isinstance(cache_dir, Path): cache_dir = str(cache_dir) if sys.version_info[0] == 2 and not isinstance(cache_dir, str): cache_dir = str(cache_dir) if not os.path.exists(cache_dir): os.makedirs(cache_dir) # Get eTag to add to filename, if it exists. if url.startswith("s3://"): etag = s3_etag(url) else: try: response = requests.head(url, allow_redirects=True) if response.status_code != 200: etag = None else: etag = response.headers.get("ETag") except EnvironmentError: etag = None if sys.version_info[0] == 2 and etag is not None: etag = etag.decode('utf-8') filename = url_to_filename(url, etag) # get cache path to put the file cache_path = os.path.join(cache_dir, filename) # If we don't have a connection (etag is None) and can't identify the file # try to get the last downloaded one if not os.path.exists(cache_path) and etag is None: matching_files = fnmatch.filter(os.listdir(cache_dir), filename + '.*') matching_files = list(filter(lambda s: not s.endswith('.json'), matching_files)) if matching_files: cache_path = os.path.join(cache_dir, matching_files[-1]) if not os.path.exists(cache_path): # Download to temporary file, then copy to cache dir once finished. # Otherwise you get corrupt cache entries if the download gets interrupted. with tempfile.NamedTemporaryFile() as temp_file: logger.info("%s not found in cache, downloading to %s", url, temp_file.name) # GET file object if url.startswith("s3://"): s3_get(url, temp_file) else: http_get(url, temp_file) # we are copying the file before closing it, so flush to avoid truncation temp_file.flush() # shutil.copyfileobj() starts at the current position, so go to the start temp_file.seek(0) logger.info("copying %s to cache at %s", temp_file.name, cache_path) with open(cache_path, 'wb') as cache_file: shutil.copyfileobj(temp_file, cache_file) logger.info("creating metadata file for %s", cache_path) meta = {'url': url, 'etag': etag} meta_path = cache_path + '.json' with open(meta_path, 'w') as meta_file: output_string = json.dumps(meta) meta_file.write(output_string) logger.info("removing temp file %s", temp_file.name) return cache_path The provided code snippet includes necessary dependencies for implementing the `cached_path` function. Write a Python function `def cached_path(url_or_filename, cache_dir=None)` to solve the following problem: 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. Here is the function: def cached_path(url_or_filename, cache_dir=None): """ 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. """ if cache_dir is None: cache_dir = PYTORCH_PRETRAINED_BERT_CACHE if sys.version_info[0] == 3 and isinstance(url_or_filename, Path): url_or_filename = str(url_or_filename) if sys.version_info[0] == 3 and isinstance(cache_dir, Path): cache_dir = str(cache_dir) parsed = urlparse(url_or_filename) if parsed.scheme in ('http', 'https', 's3'): # URL, so get it from the cache (downloading if necessary) return get_from_cache(url_or_filename, cache_dir) elif os.path.exists(url_or_filename): # File, and it exists. return url_or_filename elif parsed.scheme == '': # File, but it doesn't exist. raise EnvironmentError("file {} not found".format(url_or_filename)) else: # Something unknown raise ValueError("unable to parse {} as a URL or as a local path".format(url_or_filename))
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 ClientError from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the `s3_request` function. Write a Python function `def s3_request(func)` to solve the following problem: Wrapper function for s3 requests in order to create more helpful error messages. Here is the function: def s3_request(func): """ Wrapper function for s3 requests in order to create more helpful error messages. """ @wraps(func) def wrapper(url, *args, **kwargs): try: return func(url, *args, **kwargs) except ClientError as exc: if int(exc.response["Error"]["Code"]) == 404: raise EnvironmentError("file {} not found".format(url)) else: raise return wrapper
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_key_padding_mask=None, memory_key_padding_mask=None, tgt_bi_valid_mask=None, encoder_history_states=None, ): assert tgt_key_padding_mask is None, 'not supported' assert tgt_mask.dim() == 2 assert tgt_mask.shape[0] == tgt_mask.shape[1] # tgt_mask should always be 0/negative infinity tgt = tgt.transpose(0, 1) memory = memory.transpose(0, 1) hidden_states = torch.cat((memory, tgt), dim=1) num_tgt = tgt.shape[1] num_memory = memory.shape[1] device = tgt.device dtype = tgt.dtype top_left = torch.zeros((num_memory, num_memory), device=device, dtype=dtype) top_right = torch.full((num_memory, num_tgt), float('-inf'), device=tgt.device, dtype=dtype,) bottom_left = torch.zeros((num_tgt, num_memory), dtype=dtype, device=tgt_mask.device,) left = torch.cat((top_left, bottom_left), dim=0) right = torch.cat((top_right, tgt_mask.to(dtype)), dim=0) full_attention_mask = torch.cat((left, right), dim=1)[None, :] if memory_key_padding_mask is None: memory_key_padding_mask = torch.full((memory.shape[0], memory.shape[1]), fill_value=False, device=device) # if it is False, it means valid. That is, it is not a padding assert memory_key_padding_mask.dtype == torch.bool zero_negative_infinity = torch.zeros_like(memory_key_padding_mask, dtype=tgt.dtype) zero_negative_infinity[memory_key_padding_mask] = float('-inf') full_attention_mask = full_attention_mask.expand((memory_key_padding_mask.shape[0], num_memory + num_tgt, num_memory + num_tgt)) full_attention_mask = full_attention_mask.clone() origin_left = full_attention_mask[:, :, :num_memory] update = zero_negative_infinity[:, None, :] full_attention_mask[:, :, :num_memory] = origin_left + update if tgt_bi_valid_mask is not None: # verify the correctness bs = full_attention_mask.shape[0] # during inference, tgt_bi_valid_mask's length is not changed, but # num_tgt can be increased max_valid_target = tgt_bi_valid_mask.shape[1] mask = tgt_bi_valid_mask[:, None, :].expand((bs, num_memory+num_tgt, max_valid_target)) full_attention_mask[:, :, num_memory:(num_memory+max_valid_target)][mask] = 0 # add axis for multi-head full_attention_mask = full_attention_mask[:, None, :, :] if encoder_history_states is None: result = self.encoder( hidden_states=hidden_states, attention_mask=full_attention_mask, encoder_history_states=encoder_history_states, ) result = list(result) result[0] = result[0][:, num_memory:].transpose(0, 1) if self.encoder.output_hidden_states: return result[0], result[1] else: # make it back-compatible return result[0] else: encoder_out = self.encoder( hidden_states=hidden_states[:, -1:], attention_mask=full_attention_mask[:, :, -1:], encoder_history_states=encoder_history_states, ) result = encoder_out[0].transpose(0, 1) if self.encoder.output_hidden_states: return result, encoder_out[1] else: return result class PreNormTransformerDecoderLayer(nn.TransformerDecoderLayer): def forward(self, tgt, memory, tgt_mask=None, memory_mask=None, tgt_key_padding_mask=None, memory_key_padding_mask=None): # fmt: off # We use the members (modules) from super-class, just the order of # operations is changed here. First layernorm, then attention. tgt2 = self.norm1(tgt) tgt2, _ = self.self_attn( tgt2, tgt2, tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask ) tgt = tgt + self.dropout1(tgt2) # Layernorm first, then decoder attention. tgt2 = self.norm2(tgt) tgt2, _ = self.multihead_attn( tgt2, memory, memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask ) tgt = tgt + self.dropout2(tgt2) # Layernorm first, then transformation through feedforward network. tgt2 = self.norm3(tgt) tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) tgt = tgt + self.dropout3(tgt2) return tgt class BertEncoder(nn.Module): def __init__(self, config, use_act_checkpoint=True): super(BertEncoder, self).__init__() self.output_attentions = config.output_attentions self.output_hidden_states = config.output_hidden_states self.layer = nn.ModuleList([BertLayer(config, use_act_checkpoint=use_act_checkpoint) for _ in range(config.num_hidden_layers)]) self.pre_norm = hasattr(config, 'pre_norm') and config.pre_norm if self.pre_norm: self.LayerNorm = LayerNormClass(config.hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states, attention_mask, head_mask=None, encoder_history_states=None): all_hidden_states = () all_attentions = () for i, layer_module in enumerate(self.layer): if self.output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) history_state = None if encoder_history_states is None else encoder_history_states[i] layer_outputs = layer_module( hidden_states, attention_mask, (None if head_mask is None else head_mask[i]), history_state, ) hidden_states = layer_outputs[0] if self.output_attentions: all_attentions = all_attentions + (layer_outputs[1],) if self.pre_norm: hidden_states = self.LayerNorm(hidden_states) outputs = (hidden_states,) if self.output_hidden_states: outputs = outputs + (all_hidden_states,) if self.output_attentions: outputs = outputs + (all_attentions,) return outputs class BertConfig(PretrainedConfig): r""" :class:`~pytorch_transformers.BertConfig` is the configuration class to store the configuration of a `BertModel`. Arguments: vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `BertModel`. hidden_size: Size of the encoder layers and the pooler layer. num_hidden_layers: Number of hidden layers in the Transformer encoder. num_attention_heads: Number of attention heads for each attention layer in the Transformer encoder. intermediate_size: The size of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. hidden_act: The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu", "relu" and "swish" are supported. hidden_dropout_prob: The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler. attention_probs_dropout_prob: The dropout ratio for the attention probabilities. max_position_embeddings: The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). type_vocab_size: The vocabulary size of the `token_type_ids` passed into `BertModel`. initializer_range: The sttdev of the truncated_normal_initializer for initializing all weight matrices. layer_norm_eps: The epsilon used by LayerNorm. """ pretrained_config_archive_map = BERT_PRETRAINED_CONFIG_ARCHIVE_MAP def __init__(self, vocab_size_or_config_json_file=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, layer_norm_eps=1e-12, **kwargs): super(BertConfig, self).__init__(**kwargs) if isinstance(vocab_size_or_config_json_file, str): with open(vocab_size_or_config_json_file, "r", encoding='utf-8') as reader: json_config = json.loads(reader.read()) for key, value in json_config.items(): self.__dict__[key] = value elif isinstance(vocab_size_or_config_json_file, int): self.vocab_size = vocab_size_or_config_json_file self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_act = hidden_act self.intermediate_size = intermediate_size self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.initializer_range = initializer_range self.layer_norm_eps = layer_norm_eps else: raise ValueError("First argument must be either a vocabulary size (int)" "or the path to a pretrained model config file (str)") def create_transformer(decoder_type, norm_type, textual_feature_size, attention_heads, feedforward_size, dropout, num_layers, output_hidden_states=False, use_mlp_wrapper=None, use_act_checkpoint=True, ): assert norm_type in ['post', 'pre'] if decoder_type is None: LayerClass = ( nn.TransformerDecoderLayer if norm_type == "post" else PreNormTransformerDecoderLayer ) _layer = LayerClass( textual_feature_size, attention_heads, dim_feedforward=feedforward_size, dropout=dropout, activation="gelu", ) return nn.TransformerDecoder(_layer, num_layers) elif decoder_type == 'bert_en': from .modeling_bert import BertConfig, BertEncoder config = BertConfig( vocab_size_or_config_json_file=30522, hidden_size=textual_feature_size, num_hidden_layers=num_layers, num_attention_heads=attention_heads, intermediate_size=feedforward_size, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, layer_norm_eps=1e-12, ) config.pre_norm = (norm_type == 'pre') config.use_mlp_wrapper = use_mlp_wrapper config.output_hidden_states = output_hidden_states encoder = BertEncoder(config, use_act_checkpoint=use_act_checkpoint) return BertEncoderAsDecoder(encoder)
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, attention_mask, gamma): query = query / gamma attention_scores = torch.matmul(query, key.transpose(-1, -2)) if attention_mask is not None: # Apply the attention mask is (precomputed for all layers in BertModel forward() function) attention_scores = attention_scores + attention_mask return attention_scores.softmax(dim=-1)
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): return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
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.structures import Instances, ROIMasks def detector_postprocess( results: Instances, output_height: int, output_width: int, mask_threshold: float = 0.5 ): """ 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. Args: results (Instances): the raw outputs from the detector. `results.image_size` contains the input image resolution the detector sees. This object might be modified in-place. output_height, output_width: the desired output resolution. Returns: Instances: the resized output from the model, based on the output resolution """ if isinstance(output_width, torch.Tensor): # This shape might (but not necessarily) be tensors during tracing. # Converts integer tensors to float temporaries to ensure true # division is performed when computing scale_x and scale_y. output_width_tmp = output_width.float() output_height_tmp = output_height.float() new_size = torch.stack([output_height, output_width]) else: new_size = (output_height, output_width) output_width_tmp = output_width output_height_tmp = output_height scale_x, scale_y = ( output_width_tmp / results.image_size[1], output_height_tmp / results.image_size[0], ) results = Instances(new_size, **results.get_fields()) if results.has("pred_boxes"): output_boxes = results.pred_boxes elif results.has("proposal_boxes"): output_boxes = results.proposal_boxes else: output_boxes = None assert output_boxes is not None, "Predictions must contain boxes!" output_boxes.scale(scale_x, scale_y) output_boxes.clip(results.image_size) results = results[output_boxes.nonempty()] if results.has("pred_masks"): if isinstance(results.pred_masks, ROIMasks): roi_masks = results.pred_masks else: # pred_masks is a tensor of shape (N, 1, M, M) roi_masks = ROIMasks(results.pred_masks[:, 0, :, :]) results.pred_masks = roi_masks.to_bitmasks( results.pred_boxes, output_height, output_width, mask_threshold ).tensor # TODO return ROIMasks/BitMask object in the future if results.has("pred_keypoints"): results.pred_keypoints[:, :, 0] *= scale_x results.pred_keypoints[:, :, 1] *= scale_y return results The provided code snippet includes necessary dependencies for implementing the `_postprocess` function. Write a Python function `def _postprocess(instances, batched_inputs: List[Dict[str, torch.Tensor]], image_sizes)` to solve the following problem: Rescale the output instances to the target size. Here is the function: def _postprocess(instances, batched_inputs: List[Dict[str, torch.Tensor]], image_sizes): """ Rescale the output instances to the target size. """ # note: private function; subject to changes processed_results = [] for results_per_image, input_per_image, image_size in zip( instances, batched_inputs, image_sizes ): height = input_per_image.get("height", image_size[0]) width = input_per_image.get("width", image_size[1]) # r = detector_postprocess(results_per_image, height, width) if type(results_per_image)==list: r=detector_postprocess(results_per_image[0], height, width) else: r=detector_postprocess(results_per_image, height, width) processed_results.append({"instances": r}) return processed_results
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.structures import Instances, ROIMasks def get_feature(i, features): new_features={} for key, value in features.items(): new_features[key]=value[i].unsqueeze(0) return new_features
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]): boxes where NMS will be performed. They are expected to be in (x_ctr, y_ctr, width, height, angle_degrees) format scores (Tensor[N]): scores for each one of the boxes method (str): one of ['gaussian', 'linear', 'hard'] see paper for details. users encouraged not to use "hard", as this is the same nms available elsewhere in detectron2 gaussian_sigma (float): parameter for Gaussian penalty function linear_threshold (float): iou threshold for applying linear decay. Nt from the paper re-used as threshold for standard "hard" nms prune_threshold (float): boxes with scores below this threshold are pruned at each iteration. Dramatically reduces computation time. Authors use values in [10e-4, 10e-2] Returns: tuple(Tensor, Tensor): [0]: int64 tensor with the indices of the elements that have been kept by Soft NMS, sorted in decreasing order of scores [1]: float tensor with the re-scored scores of the elements that were kept """ return _soft_nms( Boxes, pairwise_iou, boxes, scores, method, gaussian_sigma, linear_threshold, prune_threshold, ) The provided code snippet includes necessary dependencies for implementing the `batched_soft_nms` function. Write a Python function `def batched_soft_nms( boxes, scores, idxs, method, gaussian_sigma, linear_threshold, prune_threshold )` to solve the following problem: 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 each one of the boxes idxs (Tensor[N]): indices of the categories for each one of the boxes. method (str): one of ['gaussian', 'linear', 'hard'] see paper for details. users encouraged not to use "hard", as this is the same nms available elsewhere in detectron2 gaussian_sigma (float): parameter for Gaussian penalty function linear_threshold (float): iou threshold for applying linear decay. Nt from the paper re-used as threshold for standard "hard" nms prune_threshold (float): boxes with scores below this threshold are pruned at each iteration. Dramatically reduces computation time. Authors use values in [10e-4, 10e-2] Returns: tuple(Tensor, Tensor): [0]: int64 tensor with the indices of the elements that have been kept by Soft NMS, sorted in decreasing order of scores [1]: float tensor with the re-scored scores of the elements that were kept Here is the function: def batched_soft_nms( boxes, scores, idxs, method, gaussian_sigma, linear_threshold, prune_threshold ): """ 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 each one of the boxes idxs (Tensor[N]): indices of the categories for each one of the boxes. method (str): one of ['gaussian', 'linear', 'hard'] see paper for details. users encouraged not to use "hard", as this is the same nms available elsewhere in detectron2 gaussian_sigma (float): parameter for Gaussian penalty function linear_threshold (float): iou threshold for applying linear decay. Nt from the paper re-used as threshold for standard "hard" nms prune_threshold (float): boxes with scores below this threshold are pruned at each iteration. Dramatically reduces computation time. Authors use values in [10e-4, 10e-2] Returns: tuple(Tensor, Tensor): [0]: int64 tensor with the indices of the elements that have been kept by Soft NMS, sorted in decreasing order of scores [1]: float tensor with the re-scored scores of the elements that were kept """ if boxes.numel() == 0: return ( torch.empty((0,), dtype=torch.int64, device=boxes.device), torch.empty((0,), dtype=torch.float32, device=scores.device), ) # strategy: in order to perform NMS independently per class. # we add an offset to all the boxes. The offset is dependent # only on the class idx, and is large enough so that boxes # from different classes do not overlap max_coordinate = boxes.max() offsets = idxs.to(boxes) * (max_coordinate + 1) boxes_for_nms = boxes + offsets[:, None] return soft_nms( boxes_for_nms, scores, method, gaussian_sigma, linear_threshold, prune_threshold )
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 each one of the boxes idxs (Tensor[N]): indices of the categories for each one of the boxes. method (str): one of ['gaussian', 'linear', 'hard'] see paper for details. users encouraged not to use "hard", as this is the same nms available elsewhere in detectron2 gaussian_sigma (float): parameter for Gaussian penalty function linear_threshold (float): iou threshold for applying linear decay. Nt from the paper re-used as threshold for standard "hard" nms prune_threshold (float): boxes with scores below this threshold are pruned at each iteration. Dramatically reduces computation time. Authors use values in [10e-4, 10e-2] Returns: tuple(Tensor, Tensor): [0]: int64 tensor with the indices of the elements that have been kept by Soft NMS, sorted in decreasing order of scores [1]: float tensor with the re-scored scores of the elements that were kept
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: not use _C.MODEL.ROI_BOX_HEAD.MULT_PROPOSAL_SCORE = False _C.MODEL.ROI_HEADS.MASK_WEIGHT = 1.0 _C.MODEL.ROI_HEADS.OBJECT_FEAT_POOLER_RES = 14 _C.MODEL.ROI_HEADS.SOFT_NMS_ENABLED = False # Backbones _C.MODEL.VIT_LAYERS = 12 # Text Decoder _C.TEXT_DECODER = CN() _C.TEXT_DECODER.VOCAB_SIZE = 30522 _C.TEXT_DECODER.HIDDEN_SIZE = 768 _C.TEXT_DECODER.NUM_LAYERS = 6 _C.TEXT_DECODER.ATTENTION_HEADS = 12 _C.TEXT_DECODER.FEEDFORWARD_SIZE = 768 * 4 # Multi-dataset dataloader _C.DATALOADER.DATASET_RATIO = [1, 1] # sample ratio _C.DATALOADER.DATASET_BS = 1 _C.DATALOADER.DATASET_INPUT_SIZE = [1024, 1024] _C.DATALOADER.DATASET_INPUT_SCALE = [(0.1, 2.0), (0.1, 2.0)] _C.DATALOADER.DATASET_MIN_SIZES = [(640, 800), (640, 800)] _C.DATALOADER.DATASET_MAX_SIZES = [1333, 1333] _C.SOLVER.USE_CUSTOM_SOLVER = True _C.SOLVER.OPTIMIZER = 'ADAMW' _C.SOLVER.VIT_LAYER_DECAY = True _C.SOLVER.VIT_LAYER_DECAY_RATE = 0.7 _C.INPUT.CUSTOM_AUG = 'EfficientDetResizeCrop' _C.INPUT.TRAIN_SIZE = 1024 _C.INPUT.TEST_SIZE = 1024 _C.INPUT.SCALE_RANGE = (0.1, 2.) # 'default' for fixed short / long edge _C.INPUT.TEST_INPUT_TYPE = 'default' _C.FIND_UNUSED_PARAM = True _C.USE_ACT_CHECKPOINT = True
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 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. """ layer_id = num_layers + 1 if name.startswith("backbone"): if ".pos_embed" in name or ".patch_embed" in name: layer_id = 0 elif ".blocks." in name and ".residual." not in name: layer_id = int(name[name.find(".blocks.") :].split(".")[2]) + 1 return lr_decay_rate ** (num_layers + 1 - layer_id) def maybe_add_gradient_clipping( cfg: CfgNode, optimizer: Type[torch.optim.Optimizer] ) -> Type[torch.optim.Optimizer]: """ If gradient clipping is enabled through config options, wraps the existing optimizer type to become a new dynamically created class OptimizerWithGradientClip that inherits the given optimizer and overrides the `step` method to include gradient clipping. Args: cfg: CfgNode, configuration options optimizer: type. A subclass of torch.optim.Optimizer Return: type: either the input `optimizer` (if gradient clipping is disabled), or a subclass of it with gradient clipping included in the `step` method. """ if not cfg.SOLVER.CLIP_GRADIENTS.ENABLED: return optimizer if isinstance(optimizer, torch.optim.Optimizer): optimizer_type = type(optimizer) else: assert issubclass(optimizer, torch.optim.Optimizer), optimizer optimizer_type = optimizer grad_clipper = _create_gradient_clipper(cfg.SOLVER.CLIP_GRADIENTS) OptimizerWithGradientClip = _generate_optimizer_class_with_gradient_clipping( optimizer_type, per_param_clipper=grad_clipper ) if isinstance(optimizer, torch.optim.Optimizer): optimizer.__class__ = OptimizerWithGradientClip # a bit hacky, not recommended return optimizer else: return OptimizerWithGradientClip def build_custom_optimizer(cfg: CfgNode, model: torch.nn.Module) -> torch.optim.Optimizer: params: List[Dict[str, Any]] = [] memo: Set[torch.nn.parameter.Parameter] = set() optimizer_type = cfg.SOLVER.OPTIMIZER for key, value in model.named_parameters(recurse=True): if not value.requires_grad: continue # Avoid duplicating parameters if value in memo: continue memo.add(value) lr = cfg.SOLVER.BASE_LR weight_decay = cfg.SOLVER.WEIGHT_DECAY if cfg.SOLVER.VIT_LAYER_DECAY: lr = lr * get_vit_lr_decay_rate(key, cfg.SOLVER.VIT_LAYER_DECAY_RATE, cfg.MODEL.VIT_LAYERS) param = {"params": [value], "lr": lr} if optimizer_type != 'ADAMW': param['weight_decay'] = weight_decay params += [param] def maybe_add_full_model_gradient_clipping(optim): # optim: the optimizer class # detectron2 doesn't have full model gradient clipping now clip_norm_val = cfg.SOLVER.CLIP_GRADIENTS.CLIP_VALUE enable = ( cfg.SOLVER.CLIP_GRADIENTS.ENABLED and cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE == "full_model" and clip_norm_val > 0.0 ) class FullModelGradientClippingOptimizer(optim): def step(self, closure=None): all_params = itertools.chain(*[x["params"] for x in self.param_groups]) torch.nn.utils.clip_grad_norm_(all_params, clip_norm_val) super().step(closure=closure) return FullModelGradientClippingOptimizer if enable else optim if optimizer_type == 'SGD': optimizer = maybe_add_full_model_gradient_clipping(torch.optim.SGD)( params, cfg.SOLVER.BASE_LR, momentum=cfg.SOLVER.MOMENTUM, nesterov=cfg.SOLVER.NESTEROV ) elif optimizer_type == 'ADAMW': optimizer = maybe_add_full_model_gradient_clipping(torch.optim.AdamW)( params, cfg.SOLVER.BASE_LR, weight_decay=cfg.SOLVER.WEIGHT_DECAY ) else: raise NotImplementedError(f"no optimizer type {optimizer_type}") if not cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE == "full_model": optimizer = maybe_add_gradient_clipping(cfg, optimizer) return optimizer
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 _evaluate_predictions_on_coco The provided code snippet includes necessary dependencies for implementing the `instances_to_coco_json` function. Write a Python function `def instances_to_coco_json(instances, img_id, output_logits=False)` to solve the following problem: Add object_descriptions and logit (if applicable) to detectron2's instances_to_coco_json Here is the function: def instances_to_coco_json(instances, img_id, output_logits=False): """ Add object_descriptions and logit (if applicable) to detectron2's instances_to_coco_json """ num_instance = len(instances) if num_instance == 0: return [] boxes = instances.pred_boxes.tensor.numpy() boxes = BoxMode.convert(boxes, BoxMode.XYXY_ABS, BoxMode.XYWH_ABS) boxes = boxes.tolist() scores = instances.scores.tolist() classes = instances.pred_classes.tolist() object_descriptions = instances.pred_object_descriptions.data if output_logits: logits = instances.logits.tolist() results = [] for k in range(num_instance): result = { "image_id": img_id, "category_id": classes[k], "bbox": boxes[k], "score": scores[k], 'object_descriptions': object_descriptions[k], } if output_logits: result["logit"] = logits[k] results.append(result) return results
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", "__init__.py") init_py = open(init_py_path, "r").readlines() version_line = [l.strip() for l in init_py if l.startswith("__version__")][0] version = version_line.split("=")[-1].strip().strip("'\"") # The following is used to build release packages. # Users should never use it. suffix = os.getenv("D2_VERSION_SUFFIX", "") version = version + suffix if os.getenv("BUILD_NIGHTLY", "0") == "1": from datetime import datetime date_str = datetime.today().strftime("%y%m%d") version = version + ".dev" + date_str new_init_py = [l for l in init_py if not l.startswith("__version__")] new_init_py.append('__version__ = "{}"\n'.format(version)) with open(init_py_path, "w") as f: f.write("".join(new_init_py)) return version
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 PyTorch >= 1.8" def get_extensions(): this_dir = path.dirname(path.abspath(__file__)) extensions_dir = path.join(this_dir, "detectron2", "layers", "csrc") main_source = path.join(extensions_dir, "vision.cpp") sources = glob.glob(path.join(extensions_dir, "**", "*.cpp")) from torch.utils.cpp_extension import ROCM_HOME is_rocm_pytorch = ( True if ((torch.version.hip is not None) and (ROCM_HOME is not None)) else False ) if is_rocm_pytorch: assert torch_ver >= [1, 8], "ROCM support requires PyTorch >= 1.8!" # common code between cuda and rocm platforms, for hipify version [1,0,0] and later. source_cuda = glob.glob(path.join(extensions_dir, "**", "*.cu")) + glob.glob( path.join(extensions_dir, "*.cu") ) sources = [main_source] + sources extension = CppExtension extra_compile_args = {"cxx": []} define_macros = [] if (torch.cuda.is_available() and ((CUDA_HOME is not None) or is_rocm_pytorch)) or os.getenv( "FORCE_CUDA", "0" ) == "1": extension = CUDAExtension sources += source_cuda if not is_rocm_pytorch: define_macros += [("WITH_CUDA", None)] extra_compile_args["nvcc"] = [ "-O3", "-DCUDA_HAS_FP16=1", "-D__CUDA_NO_HALF_OPERATORS__", "-D__CUDA_NO_HALF_CONVERSIONS__", "-D__CUDA_NO_HALF2_OPERATORS__", ] else: define_macros += [("WITH_HIP", None)] extra_compile_args["nvcc"] = [] if torch_ver < [1, 7]: # supported by https://github.com/pytorch/pytorch/pull/43931 CC = os.environ.get("CC", None) if CC is not None: extra_compile_args["nvcc"].append("-ccbin={}".format(CC)) include_dirs = [extensions_dir] ext_modules = [ extension( "detectron2._C", sources, include_dirs=include_dirs, define_macros=define_macros, extra_compile_args=extra_compile_args, ) ] return ext_modules
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` function. Write a Python function `def get_model_zoo_configs() -> List[str]` to solve the following problem: Return a list of configs to include in package for model zoo. Copy over these configs inside detectron2/model_zoo. Here is the function: def get_model_zoo_configs() -> List[str]: """ Return a list of configs to include in package for model zoo. Copy over these configs inside detectron2/model_zoo. """ # Use absolute paths while symlinking. source_configs_dir = path.join(path.dirname(path.realpath(__file__)), "configs") destination = path.join( path.dirname(path.realpath(__file__)), "detectron2", "model_zoo", "configs" ) # Symlink the config directory inside package to have a cleaner pip install. # Remove stale symlink/directory from a previous build. if path.exists(source_configs_dir): if path.islink(destination): os.unlink(destination) elif path.isdir(destination): shutil.rmtree(destination) if not path.exists(destination): try: os.symlink(source_configs_dir, destination) except OSError: # Fall back to copying if symlink fails: ex. on Windows. shutil.copytree(source_configs_dir, destination) config_paths = glob.glob("configs/**/*.yaml", recursive=True) + glob.glob( "configs/**/*.py", recursive=True ) return config_paths
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/facebookresearch/detectron2/blob/main/" LINKED_DOC = ["tutorials/install", "tutorials/getting_started"] def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode): github_url = None if not target.endswith("html") and target.startswith("../../"): url = target.replace("../", "") github_url = url if fromdocname in self.LINKED_DOC: # unresolved links in these docs are all github links github_url = target if github_url is not None: if github_url.endswith("MODEL_ZOO") or github_url.endswith("README"): # bug of recommonmark. # https://github.com/readthedocs/recommonmark/blob/ddd56e7717e9745f11300059e4268e204138a6b1/recommonmark/parser.py#L152-L155 github_url += ".md" print("Ref {} resolved to github:{}".format(target, github_url)) contnode["refuri"] = self.ROOT + github_url return [("githuburl:any", contnode)] else: return [] from recommonmark.parser import CommonMarkParser import detectron2 def autodoc_skip_member(app, what, name, obj, skip, options): # we hide something deliberately if getattr(obj, "__HIDE_SPHINX_DOC__", False): return True # Hide some that are deprecated or not intended to be used HIDDEN = { "ResNetBlockBase", "GroupedBatchSampler", "build_transform_gen", "apply_transform_gens", "TransformGen", "apply_augmentations", "StandardAugInput", "build_batch_data_loader", "draw_panoptic_seg_predictions", "WarmupCosineLR", "WarmupMultiStepLR", "downgrade_config", "upgrade_config", "add_export_config", } try: if name in HIDDEN or ( hasattr(obj, "__doc__") and obj.__doc__.lower().strip().startswith("deprecated") ): print("Skipping deprecated object: {}".format(name)) return True except: pass return skip def paper_ref_role( typ: str, rawtext: str, text: str, lineno: int, inliner, options: Dict = {}, content: List[str] = [], ): """ Parse :paper:`xxx`. Similar to the "extlinks" sphinx extension. """ from docutils import nodes, utils from sphinx.util.nodes import split_explicit_title text = utils.unescape(text) has_explicit_title, title, link = split_explicit_title(text) link = link.lower() if link not in _PAPER_DATA: inliner.reporter.warning("Cannot find paper " + link) paper_url, paper_title = "#", link else: paper_url, paper_title = _PAPER_DATA[link] if "/" not in paper_url: paper_url = "https://arxiv.org/abs/" + paper_url if not has_explicit_title: title = paper_title pnode = nodes.reference(title, title, internal=False, refuri=paper_url) return [pnode], [] def setup(app): from recommonmark.transform import AutoStructify app.add_domain(GithubURLDomain) app.connect("autodoc-skip-member", autodoc_skip_member) app.add_role("paper", paper_ref_role) app.add_config_value( "recommonmark_config", {"enable_math": True, "enable_inline_math": True, "enable_eval_rst": True}, True, ) app.add_transform(AutoStructify)
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 dict: detectron2 names -> C2 names """ logger = logging.getLogger(__name__) logger.info("Renaming Caffe2 weights ......") original_keys = sorted(weights.keys()) layer_keys = copy.deepcopy(original_keys) layer_keys = convert_basic_c2_names(layer_keys) # -------------------------------------------------------------------------- # RPN hidden representation conv # -------------------------------------------------------------------------- # FPN case # In the C2 model, the RPN hidden layer conv is defined for FPN level 2 and then # shared for all other levels, hence the appearance of "fpn2" layer_keys = [ k.replace("conv.rpn.fpn2", "proposal_generator.rpn_head.conv") for k in layer_keys ] # Non-FPN case layer_keys = [k.replace("conv.rpn", "proposal_generator.rpn_head.conv") for k in layer_keys] # -------------------------------------------------------------------------- # RPN box transformation conv # -------------------------------------------------------------------------- # FPN case (see note above about "fpn2") layer_keys = [ k.replace("rpn.bbox.pred.fpn2", "proposal_generator.rpn_head.anchor_deltas") for k in layer_keys ] layer_keys = [ k.replace("rpn.cls.logits.fpn2", "proposal_generator.rpn_head.objectness_logits") for k in layer_keys ] # Non-FPN case layer_keys = [ k.replace("rpn.bbox.pred", "proposal_generator.rpn_head.anchor_deltas") for k in layer_keys ] layer_keys = [ k.replace("rpn.cls.logits", "proposal_generator.rpn_head.objectness_logits") for k in layer_keys ] # -------------------------------------------------------------------------- # Fast R-CNN box head # -------------------------------------------------------------------------- layer_keys = [re.sub("^bbox\\.pred", "bbox_pred", k) for k in layer_keys] layer_keys = [re.sub("^cls\\.score", "cls_score", k) for k in layer_keys] layer_keys = [re.sub("^fc6\\.", "box_head.fc1.", k) for k in layer_keys] layer_keys = [re.sub("^fc7\\.", "box_head.fc2.", k) for k in layer_keys] # 4conv1fc head tensor names: head_conv1_w, head_conv1_gn_s layer_keys = [re.sub("^head\\.conv", "box_head.conv", k) for k in layer_keys] # -------------------------------------------------------------------------- # FPN lateral and output convolutions # -------------------------------------------------------------------------- def fpn_map(name): """ Look for keys with the following patterns: 1) Starts with "fpn.inner." Example: "fpn.inner.res2.2.sum.lateral.weight" Meaning: These are lateral pathway convolutions 2) Starts with "fpn.res" Example: "fpn.res2.2.sum.weight" Meaning: These are FPN output convolutions """ splits = name.split(".") norm = ".norm" if "norm" in splits else "" if name.startswith("fpn.inner."): # splits example: ['fpn', 'inner', 'res2', '2', 'sum', 'lateral', 'weight'] stage = int(splits[2][len("res") :]) return "fpn_lateral{}{}.{}".format(stage, norm, splits[-1]) elif name.startswith("fpn.res"): # splits example: ['fpn', 'res2', '2', 'sum', 'weight'] stage = int(splits[1][len("res") :]) return "fpn_output{}{}.{}".format(stage, norm, splits[-1]) return name layer_keys = [fpn_map(k) for k in layer_keys] # -------------------------------------------------------------------------- # Mask R-CNN mask head # -------------------------------------------------------------------------- # roi_heads.StandardROIHeads case layer_keys = [k.replace(".[mask].fcn", "mask_head.mask_fcn") for k in layer_keys] layer_keys = [re.sub("^\\.mask\\.fcn", "mask_head.mask_fcn", k) for k in layer_keys] layer_keys = [k.replace("mask.fcn.logits", "mask_head.predictor") for k in layer_keys] # roi_heads.Res5ROIHeads case layer_keys = [k.replace("conv5.mask", "mask_head.deconv") for k in layer_keys] # -------------------------------------------------------------------------- # Keypoint R-CNN head # -------------------------------------------------------------------------- # interestingly, the keypoint head convs have blob names that are simply "conv_fcnX" layer_keys = [k.replace("conv.fcn", "roi_heads.keypoint_head.conv_fcn") for k in layer_keys] layer_keys = [ k.replace("kps.score.lowres", "roi_heads.keypoint_head.score_lowres") for k in layer_keys ] layer_keys = [k.replace("kps.score.", "roi_heads.keypoint_head.score.") for k in layer_keys] # -------------------------------------------------------------------------- # Done with replacements # -------------------------------------------------------------------------- assert len(set(layer_keys)) == len(layer_keys) assert len(original_keys) == len(layer_keys) new_weights = {} new_keys_to_original_keys = {} for orig, renamed in zip(original_keys, layer_keys): new_keys_to_original_keys[renamed] = orig if renamed.startswith("bbox_pred.") or renamed.startswith("mask_head.predictor."): # remove the meaningless prediction weight for background class new_start_idx = 4 if renamed.startswith("bbox_pred.") else 1 new_weights[renamed] = weights[orig][new_start_idx:] logger.info( "Remove prediction weight for background class in {}. The shape changes from " "{} to {}.".format( renamed, tuple(weights[orig].shape), tuple(new_weights[renamed].shape) ) ) elif renamed.startswith("cls_score."): # move weights of bg class from original index 0 to last index logger.info( "Move classification weights for background class in {} from index 0 to " "index {}.".format(renamed, weights[orig].shape[0] - 1) ) new_weights[renamed] = torch.cat([weights[orig][1:], weights[orig][:1]]) else: new_weights[renamed] = weights[orig] return new_weights, new_keys_to_original_keys def _group_keys_by_module(keys: List[str], original_names: Dict[str, str]): """ Params in the same submodule are grouped together. Args: keys: names of all parameters original_names: mapping from parameter name to their name in the checkpoint Returns: dict[name -> all other names in the same group] """ def _submodule_name(key): pos = key.rfind(".") if pos < 0: return None prefix = key[: pos + 1] return prefix all_submodules = [_submodule_name(k) for k in keys] all_submodules = [x for x in all_submodules if x] all_submodules = sorted(all_submodules, key=len) ret = {} for prefix in all_submodules: group = [k for k in keys if k.startswith(prefix)] if len(group) <= 1: continue original_name_lcp = _longest_common_prefix_str([original_names[k] for k in group]) if len(original_name_lcp) == 0: # don't group weights if original names don't share prefix continue for k in group: if k in ret: continue ret[k] = group return ret def _longest_common_prefix(names: List[str]) -> str: """ ["abc.zfg", "abc.zef"] -> "abc." """ names = [n.split(".") for n in names] m1, m2 = min(names), max(names) ret = [a for a, b in zip(m1, m2) if a == b] ret = ".".join(ret) + "." if len(ret) else "" return ret def _group_str(names: List[str]) -> str: """ Turn "common1", "common2", "common3" into "common{1,2,3}" """ lcp = _longest_common_prefix_str(names) rest = [x[len(lcp) :] for x in names] rest = "{" + ",".join(rest) + "}" ret = lcp + rest # add some simplification for BN specifically ret = ret.replace("bn_{beta,running_mean,running_var,gamma}", "bn_*") ret = ret.replace("bn_beta,bn_running_mean,bn_running_var,bn_gamma", "bn_*") return ret The provided code snippet includes necessary dependencies for implementing the `align_and_update_state_dicts` function. Write a Python function `def align_and_update_state_dicts(model_state_dict, ckpt_state_dict, c2_conversion=True)` to solve the following problem: 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: suppose that the models that we will create will have prefixes appended to each of its keys, for example due to an extra level of nesting that the original pre-trained weights from ImageNet won't contain. For example, model.state_dict() might return backbone[0].body.res2.conv1.weight, while the pre-trained model contains res2.conv1.weight. We thus want to match both parameters together. For that, we look for each model weight, look among all loaded keys if there is one that is a suffix of the current weight name, and use it if that's the case. If multiple matches exist, take the one with longest size of the corresponding name. For example, for the same model as before, the pretrained weight file can contain both res2.conv1.weight, as well as conv1.weight. In this case, we want to match backbone[0].body.conv1.weight to conv1.weight, and backbone[0].body.res2.conv1.weight to res2.conv1.weight. Here is the function: def align_and_update_state_dicts(model_state_dict, ckpt_state_dict, c2_conversion=True): """ 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: suppose that the models that we will create will have prefixes appended to each of its keys, for example due to an extra level of nesting that the original pre-trained weights from ImageNet won't contain. For example, model.state_dict() might return backbone[0].body.res2.conv1.weight, while the pre-trained model contains res2.conv1.weight. We thus want to match both parameters together. For that, we look for each model weight, look among all loaded keys if there is one that is a suffix of the current weight name, and use it if that's the case. If multiple matches exist, take the one with longest size of the corresponding name. For example, for the same model as before, the pretrained weight file can contain both res2.conv1.weight, as well as conv1.weight. In this case, we want to match backbone[0].body.conv1.weight to conv1.weight, and backbone[0].body.res2.conv1.weight to res2.conv1.weight. """ model_keys = sorted(model_state_dict.keys()) if c2_conversion: ckpt_state_dict, original_keys = convert_c2_detectron_names(ckpt_state_dict) # original_keys: the name in the original dict (before renaming) else: original_keys = {x: x for x in ckpt_state_dict.keys()} ckpt_keys = sorted(ckpt_state_dict.keys()) def match(a, b): # Matched ckpt_key should be a complete (starts with '.') suffix. # For example, roi_heads.mesh_head.whatever_conv1 does not match conv1, # but matches whatever_conv1 or mesh_head.whatever_conv1. return a == b or a.endswith("." + b) # get a matrix of string matches, where each (i, j) entry correspond to the size of the # ckpt_key string, if it matches match_matrix = [len(j) if match(i, j) else 0 for i in model_keys for j in ckpt_keys] match_matrix = torch.as_tensor(match_matrix).view(len(model_keys), len(ckpt_keys)) # use the matched one with longest size in case of multiple matches max_match_size, idxs = match_matrix.max(1) # remove indices that correspond to no-match idxs[max_match_size == 0] = -1 logger = logging.getLogger(__name__) # matched_pairs (matched checkpoint key --> matched model key) matched_keys = {} result_state_dict = {} for idx_model, idx_ckpt in enumerate(idxs.tolist()): if idx_ckpt == -1: continue key_model = model_keys[idx_model] key_ckpt = ckpt_keys[idx_ckpt] value_ckpt = ckpt_state_dict[key_ckpt] shape_in_model = model_state_dict[key_model].shape if shape_in_model != value_ckpt.shape: logger.warning( "Shape of {} in checkpoint is {}, while shape of {} in model is {}.".format( key_ckpt, value_ckpt.shape, key_model, shape_in_model ) ) logger.warning( "{} will not be loaded. Please double check and see if this is desired.".format( key_ckpt ) ) continue assert key_model not in result_state_dict result_state_dict[key_model] = value_ckpt if key_ckpt in matched_keys: # already added to matched_keys logger.error( "Ambiguity found for {} in checkpoint!" "It matches at least two keys in the model ({} and {}).".format( key_ckpt, key_model, matched_keys[key_ckpt] ) ) raise ValueError("Cannot match one checkpoint key to multiple keys in the model.") matched_keys[key_ckpt] = key_model # logging: matched_model_keys = sorted(matched_keys.values()) if len(matched_model_keys) == 0: logger.warning("No weights in checkpoint matched with model.") return ckpt_state_dict common_prefix = _longest_common_prefix(matched_model_keys) rev_matched_keys = {v: k for k, v in matched_keys.items()} original_keys = {k: original_keys[rev_matched_keys[k]] for k in matched_model_keys} model_key_groups = _group_keys_by_module(matched_model_keys, original_keys) table = [] memo = set() for key_model in matched_model_keys: if key_model in memo: continue if key_model in model_key_groups: group = model_key_groups[key_model] memo |= set(group) shapes = [tuple(model_state_dict[k].shape) for k in group] table.append( ( _longest_common_prefix([k[len(common_prefix) :] for k in group]) + "*", _group_str([original_keys[k] for k in group]), " ".join([str(x).replace(" ", "") for x in shapes]), ) ) else: key_checkpoint = original_keys[key_model] shape = str(tuple(model_state_dict[key_model].shape)) table.append((key_model[len(common_prefix) :], key_checkpoint, shape)) table_str = tabulate( table, tablefmt="pipe", headers=["Names in Model", "Names in Checkpoint", "Shapes"] ) logger.info( "Following weights matched with " + (f"submodule {common_prefix[:-1]}" if common_prefix else "model") + ":\n" + table_str ) unmatched_ckpt_keys = [k for k in ckpt_keys if k not in set(matched_keys.keys())] for k in unmatched_ckpt_keys: result_state_dict[k] = ckpt_state_dict[k] return result_state_dict
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: suppose that the models that we will create will have prefixes appended to each of its keys, for example due to an extra level of nesting that the original pre-trained weights from ImageNet won't contain. For example, model.state_dict() might return backbone[0].body.res2.conv1.weight, while the pre-trained model contains res2.conv1.weight. We thus want to match both parameters together. For that, we look for each model weight, look among all loaded keys if there is one that is a suffix of the current weight name, and use it if that's the case. If multiple matches exist, take the one with longest size of the corresponding name. For example, for the same model as before, the pretrained weight file can contain both res2.conv1.weight, as well as conv1.weight. In this case, we want to match backbone[0].body.conv1.weight to conv1.weight, and backbone[0].body.res2.conv1.weight to res2.conv1.weight.
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.Tensor, heatmap_size: int ) -> Tuple[torch.Tensor, torch.Tensor]` to solve the following problem: 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 the coordinate of a pixel?"): d = floor(c) and c = d + 0.5, where d is a discrete coordinate and c is a continuous coordinate. Arguments: keypoints: tensor of keypoint locations in of shape (N, K, 3). rois: Nx4 tensor of rois in xyxy format heatmap_size: integer side length of square heatmap. Returns: heatmaps: A tensor of shape (N, K) containing an integer spatial label in the range [0, heatmap_size**2 - 1] for each keypoint in the input. valid: A tensor of shape (N, K) containing whether each keypoint is in the roi or not. Here is the function: def _keypoints_to_heatmap( keypoints: torch.Tensor, rois: torch.Tensor, heatmap_size: int ) -> Tuple[torch.Tensor, torch.Tensor]: """ 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 the coordinate of a pixel?"): d = floor(c) and c = d + 0.5, where d is a discrete coordinate and c is a continuous coordinate. Arguments: keypoints: tensor of keypoint locations in of shape (N, K, 3). rois: Nx4 tensor of rois in xyxy format heatmap_size: integer side length of square heatmap. Returns: heatmaps: A tensor of shape (N, K) containing an integer spatial label in the range [0, heatmap_size**2 - 1] for each keypoint in the input. valid: A tensor of shape (N, K) containing whether each keypoint is in the roi or not. """ if rois.numel() == 0: return rois.new().long(), rois.new().long() offset_x = rois[:, 0] offset_y = rois[:, 1] scale_x = heatmap_size / (rois[:, 2] - rois[:, 0]) scale_y = heatmap_size / (rois[:, 3] - rois[:, 1]) offset_x = offset_x[:, None] offset_y = offset_y[:, None] scale_x = scale_x[:, None] scale_y = scale_y[:, None] x = keypoints[..., 0] y = keypoints[..., 1] x_boundary_inds = x == rois[:, 2][:, None] y_boundary_inds = y == rois[:, 3][:, None] x = (x - offset_x) * scale_x x = x.floor().long() y = (y - offset_y) * scale_y y = y.floor().long() x[x_boundary_inds] = heatmap_size - 1 y[y_boundary_inds] = heatmap_size - 1 valid_loc = (x >= 0) & (y >= 0) & (x < heatmap_size) & (y < heatmap_size) vis = keypoints[..., 2] > 0 valid = (valid_loc & vis).long() lin_ind = y * heatmap_size + x heatmaps = lin_ind * valid return heatmaps, valid
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 the coordinate of a pixel?"): d = floor(c) and c = d + 0.5, where d is a discrete coordinate and c is a continuous coordinate. Arguments: keypoints: tensor of keypoint locations in of shape (N, K, 3). rois: Nx4 tensor of rois in xyxy format heatmap_size: integer side length of square heatmap. Returns: heatmaps: A tensor of shape (N, K) containing an integer spatial label in the range [0, heatmap_size**2 - 1] for each keypoint in the input. valid: A tensor of shape (N, K) containing whether each keypoint is in the roi or not.
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) -> torch.Tensor` to solve the following problem: 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, logit, score) for each keypoint. When converting discrete pixel indices in an NxN image to a continuous keypoint coordinate, we maintain consistency with :meth:`Keypoints.to_heatmap` by using the conversion from Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a continuous coordinate. Here is the function: def heatmaps_to_keypoints(maps: torch.Tensor, rois: torch.Tensor) -> 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, logit, score) for each keypoint. When converting discrete pixel indices in an NxN image to a continuous keypoint coordinate, we maintain consistency with :meth:`Keypoints.to_heatmap` by using the conversion from Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a continuous coordinate. """ # The decorator use of torch.no_grad() was not supported by torchscript. # https://github.com/pytorch/pytorch/issues/44768 maps = maps.detach() rois = rois.detach() offset_x = rois[:, 0] offset_y = rois[:, 1] widths = (rois[:, 2] - rois[:, 0]).clamp(min=1) heights = (rois[:, 3] - rois[:, 1]).clamp(min=1) widths_ceil = widths.ceil() heights_ceil = heights.ceil() num_rois, num_keypoints = maps.shape[:2] xy_preds = maps.new_zeros(rois.shape[0], num_keypoints, 4) width_corrections = widths / widths_ceil height_corrections = heights / heights_ceil keypoints_idx = torch.arange(num_keypoints, device=maps.device) for i in range(num_rois): outsize = (int(heights_ceil[i]), int(widths_ceil[i])) roi_map = F.interpolate( maps[[i]], size=outsize, mode="bicubic", align_corners=False ).squeeze( 0 ) # #keypoints x H x W # softmax over the spatial region max_score, _ = roi_map.view(num_keypoints, -1).max(1) max_score = max_score.view(num_keypoints, 1, 1) tmp_full_resolution = (roi_map - max_score).exp_() tmp_pool_resolution = (maps[i] - max_score).exp_() # Produce scores over the region H x W, but normalize with POOL_H x POOL_W, # so that the scores of objects of different absolute sizes will be more comparable roi_map_scores = tmp_full_resolution / tmp_pool_resolution.sum((1, 2), keepdim=True) w = roi_map.shape[2] pos = roi_map.view(num_keypoints, -1).argmax(1) x_int = pos % w y_int = (pos - x_int) // w assert ( roi_map_scores[keypoints_idx, y_int, x_int] == roi_map_scores.view(num_keypoints, -1).max(1)[0] ).all() x = (x_int.float() + 0.5) * width_corrections[i] y = (y_int.float() + 0.5) * height_corrections[i] xy_preds[i, :, 0] = x + offset_x[i] xy_preds[i, :, 1] = y + offset_y[i] xy_preds[i, :, 2] = roi_map[keypoints_idx, y_int, x_int] xy_preds[i, :, 3] = roi_map_scores[keypoints_idx, y_int, x_int] return xy_preds
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, logit, score) for each keypoint. When converting discrete pixel indices in an NxN image to a continuous keypoint coordinate, we maintain consistency with :meth:`Keypoints.to_heatmap` by using the conversion from Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a continuous coordinate.
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): # Using the shoelace formula # https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
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(polygons: List[np.ndarray], height: int, width: int) -> np.ndarray: """ Args: polygons (list[ndarray]): each array has shape (Nx2,) height, width (int) Returns: ndarray: a bool mask of shape (height, width) """ if len(polygons) == 0: # COCOAPI does not support empty polygons return np.zeros((height, width)).astype(np.bool) rles = mask_util.frPyObjects(polygons, height, width) rle = mask_util.merge(rles) return mask_util.decode(rle).astype(np.bool) The provided code snippet includes necessary dependencies for implementing the `rasterize_polygons_within_box` function. Write a Python function `def rasterize_polygons_within_box( polygons: List[np.ndarray], box: np.ndarray, mask_size: int ) -> torch.Tensor` to solve the following problem: 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 size of `mask_size x mask_size` must be provided for each predicted box. This function will be called to produce such targets. Args: polygons (list[ndarray[float]]): a list of polygons, which represents an instance. box: 4-element numpy array mask_size (int): Returns: Tensor: BoolTensor of shape (mask_size, mask_size) Here is the function: def rasterize_polygons_within_box( polygons: List[np.ndarray], box: np.ndarray, mask_size: int ) -> torch.Tensor: """ 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 size of `mask_size x mask_size` must be provided for each predicted box. This function will be called to produce such targets. Args: polygons (list[ndarray[float]]): a list of polygons, which represents an instance. box: 4-element numpy array mask_size (int): Returns: Tensor: BoolTensor of shape (mask_size, mask_size) """ # 1. Shift the polygons w.r.t the boxes w, h = box[2] - box[0], box[3] - box[1] polygons = copy.deepcopy(polygons) for p in polygons: p[0::2] = p[0::2] - box[0] p[1::2] = p[1::2] - box[1] # 2. Rescale the polygons to the new box size # max() to avoid division by small number ratio_h = mask_size / max(h, 0.1) ratio_w = mask_size / max(w, 0.1) if ratio_h == ratio_w: for p in polygons: p *= ratio_h else: for p in polygons: p[0::2] *= ratio_w p[1::2] *= ratio_h # 3. Rasterize the polygons with coco api mask = polygons_to_bitmask(polygons, mask_size, mask_size) mask = torch.from_numpy(mask) return mask
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 size of `mask_size x mask_size` must be provided for each predicted box. This function will be called to produce such targets. Args: polygons (list[ndarray[float]]): a list of polygons, which represents an instance. box: 4-element numpy array mask_size (int): Returns: Tensor: BoolTensor of shape (mask_size, mask_size)
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`, `nonempty`, etc), and also behaves like a Tensor (support indexing, `to(device)`, `.device`, and iteration over all boxes) """ def __init__(self, tensor: torch.Tensor): """ Args: tensor (Tensor[float]): a Nx5 matrix. Each row is (x_center, y_center, width, height, angle), in which angle is represented in degrees. While there's no strict range restriction for it, the recommended principal range is between [-180, 180) degrees. Assume we have a horizontal box B = (x_center, y_center, width, height), where width is along the x-axis and height is along the y-axis. The rotated box B_rot (x_center, y_center, width, height, angle) can be seen as: 1. When angle == 0: B_rot == B 2. When angle > 0: B_rot is obtained by rotating B w.r.t its center by :math:`|angle|` degrees CCW; 3. When angle < 0: B_rot is obtained by rotating B w.r.t its center by :math:`|angle|` degrees CW. Mathematically, since the right-handed coordinate system for image space is (y, x), where y is top->down and x is left->right, the 4 vertices of the rotated rectangle :math:`(yr_i, xr_i)` (i = 1, 2, 3, 4) can be obtained from the vertices of the horizontal rectangle :math:`(y_i, x_i)` (i = 1, 2, 3, 4) in the following way (:math:`\\theta = angle*\\pi/180` is the angle in radians, :math:`(y_c, x_c)` is the center of the rectangle): .. math:: yr_i = \\cos(\\theta) (y_i - y_c) - \\sin(\\theta) (x_i - x_c) + y_c, xr_i = \\sin(\\theta) (y_i - y_c) + \\cos(\\theta) (x_i - x_c) + x_c, which is the standard rigid-body rotation transformation. Intuitively, the angle is (1) the rotation angle from y-axis in image space to the height vector (top->down in the box's local coordinate system) of the box in CCW, and (2) the rotation angle from x-axis in image space to the width vector (left->right in the box's local coordinate system) of the box in CCW. More intuitively, consider the following horizontal box ABCD represented in (x1, y1, x2, y2): (3, 2, 7, 4), covering the [3, 7] x [2, 4] region of the continuous coordinate system which looks like this: .. code:: none O--------> x | | A---B | | | | D---C | v y Note that each capital letter represents one 0-dimensional geometric point instead of a 'square pixel' here. In the example above, using (x, y) to represent a point we have: .. math:: O = (0, 0), A = (3, 2), B = (7, 2), C = (7, 4), D = (3, 4) We name vector AB = vector DC as the width vector in box's local coordinate system, and vector AD = vector BC as the height vector in box's local coordinate system. Initially, when angle = 0 degree, they're aligned with the positive directions of x-axis and y-axis in the image space, respectively. For better illustration, we denote the center of the box as E, .. code:: none O--------> x | | A---B | | E | | D---C | v y where the center E = ((3+7)/2, (2+4)/2) = (5, 3). Also, .. math:: width = |AB| = |CD| = 7 - 3 = 4, height = |AD| = |BC| = 4 - 2 = 2. Therefore, the corresponding representation for the same shape in rotated box in (x_center, y_center, width, height, angle) format is: (5, 3, 4, 2, 0), Now, let's consider (5, 3, 4, 2, 90), which is rotated by 90 degrees CCW (counter-clockwise) by definition. It looks like this: .. code:: none O--------> x | B-C | | | | |E| | | | | A-D v y The center E is still located at the same point (5, 3), while the vertices ABCD are rotated by 90 degrees CCW with regard to E: A = (4, 5), B = (4, 1), C = (6, 1), D = (6, 5) Here, 90 degrees can be seen as the CCW angle to rotate from y-axis to vector AD or vector BC (the top->down height vector in box's local coordinate system), or the CCW angle to rotate from x-axis to vector AB or vector DC (the left->right width vector in box's local coordinate system). .. math:: width = |AB| = |CD| = 5 - 1 = 4, height = |AD| = |BC| = 6 - 4 = 2. Next, how about (5, 3, 4, 2, -90), which is rotated by 90 degrees CW (clockwise) by definition? It looks like this: .. code:: none O--------> x | D-A | | | | |E| | | | | C-B v y The center E is still located at the same point (5, 3), while the vertices ABCD are rotated by 90 degrees CW with regard to E: A = (6, 1), B = (6, 5), C = (4, 5), D = (4, 1) .. math:: width = |AB| = |CD| = 5 - 1 = 4, height = |AD| = |BC| = 6 - 4 = 2. This covers exactly the same region as (5, 3, 4, 2, 90) does, and their IoU will be 1. However, these two will generate different RoI Pooling results and should not be treated as an identical box. On the other hand, it's easy to see that (X, Y, W, H, A) is identical to (X, Y, W, H, A+360N), for any integer N. For example (5, 3, 4, 2, 270) would be identical to (5, 3, 4, 2, -90), because rotating the shape 270 degrees CCW is equivalent to rotating the same shape 90 degrees CW. We could rotate further to get (5, 3, 4, 2, 180), or (5, 3, 4, 2, -180): .. code:: none O--------> x | | C---D | | E | | B---A | v y .. math:: A = (7, 4), B = (3, 4), C = (3, 2), D = (7, 2), width = |AB| = |CD| = 7 - 3 = 4, height = |AD| = |BC| = 4 - 2 = 2. Finally, this is a very inaccurate (heavily quantized) illustration of how (5, 3, 4, 2, 60) looks like in case anyone wonders: .. code:: none O--------> x | B\ | / C | /E / | A / | `D v y It's still a rectangle with center of (5, 3), width of 4 and height of 2, but its angle (and thus orientation) is somewhere between (5, 3, 4, 2, 0) and (5, 3, 4, 2, 90). """ device = tensor.device if isinstance(tensor, torch.Tensor) else torch.device("cpu") tensor = torch.as_tensor(tensor, dtype=torch.float32, device=device) if tensor.numel() == 0: # Use reshape, so we don't end up creating a new tensor that does not depend on # the inputs (and consequently confuses jit) tensor = tensor.reshape((0, 5)).to(dtype=torch.float32, device=device) assert tensor.dim() == 2 and tensor.size(-1) == 5, tensor.size() self.tensor = tensor def clone(self) -> "RotatedBoxes": """ Clone the RotatedBoxes. Returns: RotatedBoxes """ return RotatedBoxes(self.tensor.clone()) def to(self, device: torch.device): # Boxes are assumed float32 and does not support to(dtype) return RotatedBoxes(self.tensor.to(device=device)) def area(self) -> torch.Tensor: """ Computes the area of all the boxes. Returns: torch.Tensor: a vector with areas of each box. """ box = self.tensor area = box[:, 2] * box[:, 3] return area def normalize_angles(self) -> None: """ Restrict angles to the range of [-180, 180) degrees """ self.tensor[:, 4] = (self.tensor[:, 4] + 180.0) % 360.0 - 180.0 def clip(self, box_size: Tuple[int, int], clip_angle_threshold: float = 1.0) -> None: """ Clip (in place) the boxes by limiting x coordinates to the range [0, width] and y coordinates to the range [0, height]. For RRPN: Only clip boxes that are almost horizontal with a tolerance of clip_angle_threshold to maintain backward compatibility. Rotated boxes beyond this threshold are not clipped for two reasons: 1. There are potentially multiple ways to clip a rotated box to make it fit within the image. 2. It's tricky to make the entire rectangular box fit within the image and still be able to not leave out pixels of interest. Therefore we rely on ops like RoIAlignRotated to safely handle this. Args: box_size (height, width): The clipping box's size. clip_angle_threshold: Iff. abs(normalized(angle)) <= clip_angle_threshold (in degrees), we do the clipping as horizontal boxes. """ h, w = box_size # normalize angles to be within (-180, 180] degrees self.normalize_angles() idx = torch.where(torch.abs(self.tensor[:, 4]) <= clip_angle_threshold)[0] # convert to (x1, y1, x2, y2) x1 = self.tensor[idx, 0] - self.tensor[idx, 2] / 2.0 y1 = self.tensor[idx, 1] - self.tensor[idx, 3] / 2.0 x2 = self.tensor[idx, 0] + self.tensor[idx, 2] / 2.0 y2 = self.tensor[idx, 1] + self.tensor[idx, 3] / 2.0 # clip x1.clamp_(min=0, max=w) y1.clamp_(min=0, max=h) x2.clamp_(min=0, max=w) y2.clamp_(min=0, max=h) # convert back to (xc, yc, w, h) self.tensor[idx, 0] = (x1 + x2) / 2.0 self.tensor[idx, 1] = (y1 + y2) / 2.0 # make sure widths and heights do not increase due to numerical errors self.tensor[idx, 2] = torch.min(self.tensor[idx, 2], x2 - x1) self.tensor[idx, 3] = torch.min(self.tensor[idx, 3], y2 - y1) def nonempty(self, threshold: float = 0.0) -> torch.Tensor: """ Find boxes that are non-empty. A box is considered empty, if either of its side is no larger than threshold. Returns: Tensor: a binary vector which represents whether each box is empty (False) or non-empty (True). """ box = self.tensor widths = box[:, 2] heights = box[:, 3] keep = (widths > threshold) & (heights > threshold) return keep def __getitem__(self, item) -> "RotatedBoxes": """ Returns: RotatedBoxes: Create a new :class:`RotatedBoxes` by indexing. The following usage are allowed: 1. `new_boxes = boxes[3]`: return a `RotatedBoxes` which contains only one box. 2. `new_boxes = boxes[2:10]`: return a slice of boxes. 3. `new_boxes = boxes[vector]`, where vector is a torch.ByteTensor with `length = len(boxes)`. Nonzero elements in the vector will be selected. Note that the returned RotatedBoxes might share storage with this RotatedBoxes, subject to Pytorch's indexing semantics. """ if isinstance(item, int): return RotatedBoxes(self.tensor[item].view(1, -1)) b = self.tensor[item] assert b.dim() == 2, "Indexing on RotatedBoxes with {} failed to return a matrix!".format( item ) return RotatedBoxes(b) def __len__(self) -> int: return self.tensor.shape[0] def __repr__(self) -> str: return "RotatedBoxes(" + str(self.tensor) + ")" def inside_box(self, box_size: Tuple[int, int], boundary_threshold: int = 0) -> torch.Tensor: """ Args: box_size (height, width): Size of the reference box covering [0, width] x [0, height] boundary_threshold (int): Boxes that extend beyond the reference box boundary by more than boundary_threshold are considered "outside". For RRPN, it might not be necessary to call this function since it's common for rotated box to extend to outside of the image boundaries (the clip function only clips the near-horizontal boxes) Returns: a binary vector, indicating whether each box is inside the reference box. """ height, width = box_size cnt_x = self.tensor[..., 0] cnt_y = self.tensor[..., 1] half_w = self.tensor[..., 2] / 2.0 half_h = self.tensor[..., 3] / 2.0 a = self.tensor[..., 4] c = torch.abs(torch.cos(a * math.pi / 180.0)) s = torch.abs(torch.sin(a * math.pi / 180.0)) # This basically computes the horizontal bounding rectangle of the rotated box max_rect_dx = c * half_w + s * half_h max_rect_dy = c * half_h + s * half_w inds_inside = ( (cnt_x - max_rect_dx >= -boundary_threshold) & (cnt_y - max_rect_dy >= -boundary_threshold) & (cnt_x + max_rect_dx < width + boundary_threshold) & (cnt_y + max_rect_dy < height + boundary_threshold) ) return inds_inside def get_centers(self) -> torch.Tensor: """ Returns: The box centers in a Nx2 array of (x, y). """ return self.tensor[:, :2] def scale(self, scale_x: float, scale_y: float) -> None: """ Scale the rotated box with horizontal and vertical scaling factors Note: when scale_factor_x != scale_factor_y, the rotated box does not preserve the rectangular shape when the angle is not a multiple of 90 degrees under resize transformation. Instead, the shape is a parallelogram (that has skew) Here we make an approximation by fitting a rotated rectangle to the parallelogram. """ self.tensor[:, 0] *= scale_x self.tensor[:, 1] *= scale_y theta = self.tensor[:, 4] * math.pi / 180.0 c = torch.cos(theta) s = torch.sin(theta) # In image space, y is top->down and x is left->right # Consider the local coordintate system for the rotated box, # where the box center is located at (0, 0), and the four vertices ABCD are # A(-w / 2, -h / 2), B(w / 2, -h / 2), C(w / 2, h / 2), D(-w / 2, h / 2) # the midpoint of the left edge AD of the rotated box E is: # E = (A+D)/2 = (-w / 2, 0) # the midpoint of the top edge AB of the rotated box F is: # F(0, -h / 2) # To get the old coordinates in the global system, apply the rotation transformation # (Note: the right-handed coordinate system for image space is yOx): # (old_x, old_y) = (s * y + c * x, c * y - s * x) # E(old) = (s * 0 + c * (-w/2), c * 0 - s * (-w/2)) = (-c * w / 2, s * w / 2) # F(old) = (s * (-h / 2) + c * 0, c * (-h / 2) - s * 0) = (-s * h / 2, -c * h / 2) # After applying the scaling factor (sfx, sfy): # E(new) = (-sfx * c * w / 2, sfy * s * w / 2) # F(new) = (-sfx * s * h / 2, -sfy * c * h / 2) # The new width after scaling tranformation becomes: # w(new) = |E(new) - O| * 2 # = sqrt[(sfx * c * w / 2)^2 + (sfy * s * w / 2)^2] * 2 # = sqrt[(sfx * c)^2 + (sfy * s)^2] * w # i.e., scale_factor_w = sqrt[(sfx * c)^2 + (sfy * s)^2] # # For example, # when angle = 0 or 180, |c| = 1, s = 0, scale_factor_w == scale_factor_x; # when |angle| = 90, c = 0, |s| = 1, scale_factor_w == scale_factor_y self.tensor[:, 2] *= torch.sqrt((scale_x * c) ** 2 + (scale_y * s) ** 2) # h(new) = |F(new) - O| * 2 # = sqrt[(sfx * s * h / 2)^2 + (sfy * c * h / 2)^2] * 2 # = sqrt[(sfx * s)^2 + (sfy * c)^2] * h # i.e., scale_factor_h = sqrt[(sfx * s)^2 + (sfy * c)^2] # # For example, # when angle = 0 or 180, |c| = 1, s = 0, scale_factor_h == scale_factor_y; # when |angle| = 90, c = 0, |s| = 1, scale_factor_h == scale_factor_x self.tensor[:, 3] *= torch.sqrt((scale_x * s) ** 2 + (scale_y * c) ** 2) # The angle is the rotation angle from y-axis in image space to the height # vector (top->down in the box's local coordinate system) of the box in CCW. # # angle(new) = angle_yOx(O - F(new)) # = angle_yOx( (sfx * s * h / 2, sfy * c * h / 2) ) # = atan2(sfx * s * h / 2, sfy * c * h / 2) # = atan2(sfx * s, sfy * c) # # For example, # when sfx == sfy, angle(new) == atan2(s, c) == angle(old) self.tensor[:, 4] = torch.atan2(scale_x * s, scale_y * c) * 180 / math.pi def cat(cls, boxes_list: List["RotatedBoxes"]) -> "RotatedBoxes": """ Concatenates a list of RotatedBoxes into a single RotatedBoxes Arguments: boxes_list (list[RotatedBoxes]) Returns: RotatedBoxes: the concatenated RotatedBoxes """ assert isinstance(boxes_list, (list, tuple)) if len(boxes_list) == 0: return cls(torch.empty(0)) assert all([isinstance(box, RotatedBoxes) for box in boxes_list]) # use torch.cat (v.s. layers.cat) so the returned boxes never share storage with input cat_boxes = cls(torch.cat([b.tensor for b in boxes_list], dim=0)) return cat_boxes def device(self) -> torch.device: return self.tensor.device def __iter__(self): """ Yield a box as a Tensor of shape (5,) at a time. """ yield from self.tensor def pairwise_iou_rotated(boxes1, boxes2): """ Return intersection-over-union (Jaccard index) of boxes. Both sets of boxes are expected to be in (x_center, y_center, width, height, angle) format. Arguments: boxes1 (Tensor[N, 5]) boxes2 (Tensor[M, 5]) Returns: iou (Tensor[N, M]): the NxM matrix containing the pairwise IoU values for every element in boxes1 and boxes2 """ return torch.ops.detectron2.box_iou_rotated(boxes1, boxes2) The provided code snippet includes necessary dependencies for implementing the `pairwise_iou` function. Write a Python function `def pairwise_iou(boxes1: RotatedBoxes, boxes2: RotatedBoxes) -> None` to solve the following problem: 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, sized [N,M]. Here is the function: def pairwise_iou(boxes1: RotatedBoxes, boxes2: RotatedBoxes) -> None: """ 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, sized [N,M]. """ return pairwise_iou_rotated(boxes1.tensor, boxes2.tensor)
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, sized [N,M].
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 also behaves like a Tensor (support indexing, `to(device)`, `.device`, and iteration over all boxes) Attributes: tensor (torch.Tensor): float matrix of Nx4. Each row is (x1, y1, x2, y2). """ def __init__(self, tensor: torch.Tensor): """ Args: tensor (Tensor[float]): a Nx4 matrix. Each row is (x1, y1, x2, y2). """ device = tensor.device if isinstance(tensor, torch.Tensor) else torch.device("cpu") tensor = torch.as_tensor(tensor, dtype=torch.float32, device=device) if tensor.numel() == 0: # Use reshape, so we don't end up creating a new tensor that does not depend on # the inputs (and consequently confuses jit) tensor = tensor.reshape((-1, 4)).to(dtype=torch.float32, device=device) assert tensor.dim() == 2 and tensor.size(-1) == 4, tensor.size() self.tensor = tensor def clone(self) -> "Boxes": """ Clone the Boxes. Returns: Boxes """ return Boxes(self.tensor.clone()) def to(self, device: torch.device): # Boxes are assumed float32 and does not support to(dtype) return Boxes(self.tensor.to(device=device)) def area(self) -> torch.Tensor: """ Computes the area of all the boxes. Returns: torch.Tensor: a vector with areas of each box. """ box = self.tensor area = (box[:, 2] - box[:, 0]) * (box[:, 3] - box[:, 1]) return area def clip(self, box_size: Tuple[int, int]) -> None: """ Clip (in place) the boxes by limiting x coordinates to the range [0, width] and y coordinates to the range [0, height]. Args: box_size (height, width): The clipping box's size. """ assert torch.isfinite(self.tensor).all(), "Box tensor contains infinite or NaN!" h, w = box_size x1 = self.tensor[:, 0].clamp(min=0, max=w) y1 = self.tensor[:, 1].clamp(min=0, max=h) x2 = self.tensor[:, 2].clamp(min=0, max=w) y2 = self.tensor[:, 3].clamp(min=0, max=h) self.tensor = torch.stack((x1, y1, x2, y2), dim=-1) def nonempty(self, threshold: float = 0.0) -> torch.Tensor: """ Find boxes that are non-empty. A box is considered empty, if either of its side is no larger than threshold. Returns: Tensor: a binary vector which represents whether each box is empty (False) or non-empty (True). """ box = self.tensor widths = box[:, 2] - box[:, 0] heights = box[:, 3] - box[:, 1] keep = (widths > threshold) & (heights > threshold) return keep def __getitem__(self, item) -> "Boxes": """ Args: item: int, slice, or a BoolTensor Returns: Boxes: Create a new :class:`Boxes` by indexing. The following usage are allowed: 1. `new_boxes = boxes[3]`: return a `Boxes` which contains only one box. 2. `new_boxes = boxes[2:10]`: return a slice of boxes. 3. `new_boxes = boxes[vector]`, where vector is a torch.BoolTensor with `length = len(boxes)`. Nonzero elements in the vector will be selected. Note that the returned Boxes might share storage with this Boxes, subject to Pytorch's indexing semantics. """ if isinstance(item, int): return Boxes(self.tensor[item].view(1, -1)) b = self.tensor[item] assert b.dim() == 2, "Indexing on Boxes with {} failed to return a matrix!".format(item) return Boxes(b) def __len__(self) -> int: return self.tensor.shape[0] def __repr__(self) -> str: return "Boxes(" + str(self.tensor) + ")" def inside_box(self, box_size: Tuple[int, int], boundary_threshold: int = 0) -> torch.Tensor: """ Args: box_size (height, width): Size of the reference box. boundary_threshold (int): Boxes that extend beyond the reference box boundary by more than boundary_threshold are considered "outside". Returns: a binary vector, indicating whether each box is inside the reference box. """ height, width = box_size inds_inside = ( (self.tensor[..., 0] >= -boundary_threshold) & (self.tensor[..., 1] >= -boundary_threshold) & (self.tensor[..., 2] < width + boundary_threshold) & (self.tensor[..., 3] < height + boundary_threshold) ) return inds_inside def get_centers(self) -> torch.Tensor: """ Returns: The box centers in a Nx2 array of (x, y). """ return (self.tensor[:, :2] + self.tensor[:, 2:]) / 2 def scale(self, scale_x: float, scale_y: float) -> None: """ Scale the box with horizontal and vertical scaling factors """ self.tensor[:, 0::2] *= scale_x self.tensor[:, 1::2] *= scale_y def cat(cls, boxes_list: List["Boxes"]) -> "Boxes": """ Concatenates a list of Boxes into a single Boxes Arguments: boxes_list (list[Boxes]) Returns: Boxes: the concatenated Boxes """ assert isinstance(boxes_list, (list, tuple)) if len(boxes_list) == 0: return cls(torch.empty(0)) assert all([isinstance(box, Boxes) for box in boxes_list]) # use torch.cat (v.s. layers.cat) so the returned boxes never share storage with input cat_boxes = cls(torch.cat([b.tensor for b in boxes_list], dim=0)) return cat_boxes def device(self) -> device: return self.tensor.device # type "Iterator[torch.Tensor]", yield, and iter() not supported by torchscript # https://github.com/pytorch/pytorch/issues/18627 def __iter__(self): """ Yield a box as a Tensor of shape (4,) at a time. """ yield from self.tensor def pairwise_intersection(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor: """ Given two lists of boxes of size N and M, compute the intersection area 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: intersection, sized [N,M]. """ boxes1, boxes2 = boxes1.tensor, boxes2.tensor width_height = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) - torch.max( boxes1[:, None, :2], boxes2[:, :2] ) # [N,M,2] width_height.clamp_(min=0) # [N,M,2] intersection = width_height.prod(dim=2) # [N,M] return intersection The provided code snippet includes necessary dependencies for implementing the `pairwise_iou` function. Write a Python function `def pairwise_iou(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor` to solve the following problem: 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]. Here is the function: def pairwise_iou(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor: """ 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]. """ area1 = boxes1.area() # [N] area2 = boxes2.area() # [M] inter = pairwise_intersection(boxes1, boxes2) # handle empty boxes iou = torch.where( inter > 0, inter / (area1[:, None] + area2 - inter), torch.zeros(1, dtype=inter.dtype, device=inter.device), ) return iou
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 also behaves like a Tensor (support indexing, `to(device)`, `.device`, and iteration over all boxes) Attributes: tensor (torch.Tensor): float matrix of Nx4. Each row is (x1, y1, x2, y2). """ def __init__(self, tensor: torch.Tensor): """ Args: tensor (Tensor[float]): a Nx4 matrix. Each row is (x1, y1, x2, y2). """ device = tensor.device if isinstance(tensor, torch.Tensor) else torch.device("cpu") tensor = torch.as_tensor(tensor, dtype=torch.float32, device=device) if tensor.numel() == 0: # Use reshape, so we don't end up creating a new tensor that does not depend on # the inputs (and consequently confuses jit) tensor = tensor.reshape((-1, 4)).to(dtype=torch.float32, device=device) assert tensor.dim() == 2 and tensor.size(-1) == 4, tensor.size() self.tensor = tensor def clone(self) -> "Boxes": """ Clone the Boxes. Returns: Boxes """ return Boxes(self.tensor.clone()) def to(self, device: torch.device): # Boxes are assumed float32 and does not support to(dtype) return Boxes(self.tensor.to(device=device)) def area(self) -> torch.Tensor: """ Computes the area of all the boxes. Returns: torch.Tensor: a vector with areas of each box. """ box = self.tensor area = (box[:, 2] - box[:, 0]) * (box[:, 3] - box[:, 1]) return area def clip(self, box_size: Tuple[int, int]) -> None: """ Clip (in place) the boxes by limiting x coordinates to the range [0, width] and y coordinates to the range [0, height]. Args: box_size (height, width): The clipping box's size. """ assert torch.isfinite(self.tensor).all(), "Box tensor contains infinite or NaN!" h, w = box_size x1 = self.tensor[:, 0].clamp(min=0, max=w) y1 = self.tensor[:, 1].clamp(min=0, max=h) x2 = self.tensor[:, 2].clamp(min=0, max=w) y2 = self.tensor[:, 3].clamp(min=0, max=h) self.tensor = torch.stack((x1, y1, x2, y2), dim=-1) def nonempty(self, threshold: float = 0.0) -> torch.Tensor: """ Find boxes that are non-empty. A box is considered empty, if either of its side is no larger than threshold. Returns: Tensor: a binary vector which represents whether each box is empty (False) or non-empty (True). """ box = self.tensor widths = box[:, 2] - box[:, 0] heights = box[:, 3] - box[:, 1] keep = (widths > threshold) & (heights > threshold) return keep def __getitem__(self, item) -> "Boxes": """ Args: item: int, slice, or a BoolTensor Returns: Boxes: Create a new :class:`Boxes` by indexing. The following usage are allowed: 1. `new_boxes = boxes[3]`: return a `Boxes` which contains only one box. 2. `new_boxes = boxes[2:10]`: return a slice of boxes. 3. `new_boxes = boxes[vector]`, where vector is a torch.BoolTensor with `length = len(boxes)`. Nonzero elements in the vector will be selected. Note that the returned Boxes might share storage with this Boxes, subject to Pytorch's indexing semantics. """ if isinstance(item, int): return Boxes(self.tensor[item].view(1, -1)) b = self.tensor[item] assert b.dim() == 2, "Indexing on Boxes with {} failed to return a matrix!".format(item) return Boxes(b) def __len__(self) -> int: return self.tensor.shape[0] def __repr__(self) -> str: return "Boxes(" + str(self.tensor) + ")" def inside_box(self, box_size: Tuple[int, int], boundary_threshold: int = 0) -> torch.Tensor: """ Args: box_size (height, width): Size of the reference box. boundary_threshold (int): Boxes that extend beyond the reference box boundary by more than boundary_threshold are considered "outside". Returns: a binary vector, indicating whether each box is inside the reference box. """ height, width = box_size inds_inside = ( (self.tensor[..., 0] >= -boundary_threshold) & (self.tensor[..., 1] >= -boundary_threshold) & (self.tensor[..., 2] < width + boundary_threshold) & (self.tensor[..., 3] < height + boundary_threshold) ) return inds_inside def get_centers(self) -> torch.Tensor: """ Returns: The box centers in a Nx2 array of (x, y). """ return (self.tensor[:, :2] + self.tensor[:, 2:]) / 2 def scale(self, scale_x: float, scale_y: float) -> None: """ Scale the box with horizontal and vertical scaling factors """ self.tensor[:, 0::2] *= scale_x self.tensor[:, 1::2] *= scale_y def cat(cls, boxes_list: List["Boxes"]) -> "Boxes": """ Concatenates a list of Boxes into a single Boxes Arguments: boxes_list (list[Boxes]) Returns: Boxes: the concatenated Boxes """ assert isinstance(boxes_list, (list, tuple)) if len(boxes_list) == 0: return cls(torch.empty(0)) assert all([isinstance(box, Boxes) for box in boxes_list]) # use torch.cat (v.s. layers.cat) so the returned boxes never share storage with input cat_boxes = cls(torch.cat([b.tensor for b in boxes_list], dim=0)) return cat_boxes def device(self) -> device: return self.tensor.device # type "Iterator[torch.Tensor]", yield, and iter() not supported by torchscript # https://github.com/pytorch/pytorch/issues/18627 def __iter__(self): """ Yield a box as a Tensor of shape (4,) at a time. """ yield from self.tensor def pairwise_intersection(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor: """ Given two lists of boxes of size N and M, compute the intersection area 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: intersection, sized [N,M]. """ boxes1, boxes2 = boxes1.tensor, boxes2.tensor width_height = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) - torch.max( boxes1[:, None, :2], boxes2[:, :2] ) # [N,M,2] width_height.clamp_(min=0) # [N,M,2] intersection = width_height.prod(dim=2) # [N,M] return intersection The provided code snippet includes necessary dependencies for implementing the `pairwise_ioa` function. Write a Python function `def pairwise_ioa(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor` to solve the following problem: 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]. Here is the function: def pairwise_ioa(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor: """ 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]. """ area2 = boxes2.area() # [M] inter = pairwise_intersection(boxes1, boxes2) # handle empty boxes ioa = torch.where( inter > 0, inter / area2, torch.zeros(1, dtype=inter.dtype, device=inter.device) ) return ioa
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 also behaves like a Tensor (support indexing, `to(device)`, `.device`, and iteration over all boxes) Attributes: tensor (torch.Tensor): float matrix of Nx4. Each row is (x1, y1, x2, y2). """ def __init__(self, tensor: torch.Tensor): """ Args: tensor (Tensor[float]): a Nx4 matrix. Each row is (x1, y1, x2, y2). """ device = tensor.device if isinstance(tensor, torch.Tensor) else torch.device("cpu") tensor = torch.as_tensor(tensor, dtype=torch.float32, device=device) if tensor.numel() == 0: # Use reshape, so we don't end up creating a new tensor that does not depend on # the inputs (and consequently confuses jit) tensor = tensor.reshape((-1, 4)).to(dtype=torch.float32, device=device) assert tensor.dim() == 2 and tensor.size(-1) == 4, tensor.size() self.tensor = tensor def clone(self) -> "Boxes": """ Clone the Boxes. Returns: Boxes """ return Boxes(self.tensor.clone()) def to(self, device: torch.device): # Boxes are assumed float32 and does not support to(dtype) return Boxes(self.tensor.to(device=device)) def area(self) -> torch.Tensor: """ Computes the area of all the boxes. Returns: torch.Tensor: a vector with areas of each box. """ box = self.tensor area = (box[:, 2] - box[:, 0]) * (box[:, 3] - box[:, 1]) return area def clip(self, box_size: Tuple[int, int]) -> None: """ Clip (in place) the boxes by limiting x coordinates to the range [0, width] and y coordinates to the range [0, height]. Args: box_size (height, width): The clipping box's size. """ assert torch.isfinite(self.tensor).all(), "Box tensor contains infinite or NaN!" h, w = box_size x1 = self.tensor[:, 0].clamp(min=0, max=w) y1 = self.tensor[:, 1].clamp(min=0, max=h) x2 = self.tensor[:, 2].clamp(min=0, max=w) y2 = self.tensor[:, 3].clamp(min=0, max=h) self.tensor = torch.stack((x1, y1, x2, y2), dim=-1) def nonempty(self, threshold: float = 0.0) -> torch.Tensor: """ Find boxes that are non-empty. A box is considered empty, if either of its side is no larger than threshold. Returns: Tensor: a binary vector which represents whether each box is empty (False) or non-empty (True). """ box = self.tensor widths = box[:, 2] - box[:, 0] heights = box[:, 3] - box[:, 1] keep = (widths > threshold) & (heights > threshold) return keep def __getitem__(self, item) -> "Boxes": """ Args: item: int, slice, or a BoolTensor Returns: Boxes: Create a new :class:`Boxes` by indexing. The following usage are allowed: 1. `new_boxes = boxes[3]`: return a `Boxes` which contains only one box. 2. `new_boxes = boxes[2:10]`: return a slice of boxes. 3. `new_boxes = boxes[vector]`, where vector is a torch.BoolTensor with `length = len(boxes)`. Nonzero elements in the vector will be selected. Note that the returned Boxes might share storage with this Boxes, subject to Pytorch's indexing semantics. """ if isinstance(item, int): return Boxes(self.tensor[item].view(1, -1)) b = self.tensor[item] assert b.dim() == 2, "Indexing on Boxes with {} failed to return a matrix!".format(item) return Boxes(b) def __len__(self) -> int: return self.tensor.shape[0] def __repr__(self) -> str: return "Boxes(" + str(self.tensor) + ")" def inside_box(self, box_size: Tuple[int, int], boundary_threshold: int = 0) -> torch.Tensor: """ Args: box_size (height, width): Size of the reference box. boundary_threshold (int): Boxes that extend beyond the reference box boundary by more than boundary_threshold are considered "outside". Returns: a binary vector, indicating whether each box is inside the reference box. """ height, width = box_size inds_inside = ( (self.tensor[..., 0] >= -boundary_threshold) & (self.tensor[..., 1] >= -boundary_threshold) & (self.tensor[..., 2] < width + boundary_threshold) & (self.tensor[..., 3] < height + boundary_threshold) ) return inds_inside def get_centers(self) -> torch.Tensor: """ Returns: The box centers in a Nx2 array of (x, y). """ return (self.tensor[:, :2] + self.tensor[:, 2:]) / 2 def scale(self, scale_x: float, scale_y: float) -> None: """ Scale the box with horizontal and vertical scaling factors """ self.tensor[:, 0::2] *= scale_x self.tensor[:, 1::2] *= scale_y def cat(cls, boxes_list: List["Boxes"]) -> "Boxes": """ Concatenates a list of Boxes into a single Boxes Arguments: boxes_list (list[Boxes]) Returns: Boxes: the concatenated Boxes """ assert isinstance(boxes_list, (list, tuple)) if len(boxes_list) == 0: return cls(torch.empty(0)) assert all([isinstance(box, Boxes) for box in boxes_list]) # use torch.cat (v.s. layers.cat) so the returned boxes never share storage with input cat_boxes = cls(torch.cat([b.tensor for b in boxes_list], dim=0)) return cat_boxes def device(self) -> device: return self.tensor.device # type "Iterator[torch.Tensor]", yield, and iter() not supported by torchscript # https://github.com/pytorch/pytorch/issues/18627 def __iter__(self): """ Yield a box as a Tensor of shape (4,) at a time. """ yield from self.tensor The provided code snippet includes necessary dependencies for implementing the `pairwise_point_box_distance` function. Write a Python function `def pairwise_point_box_distance(points: torch.Tensor, boxes: Boxes)` to solve the following problem: 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, M, 4). The 4 values are distances from the point to the left, top, right, bottom of the box. Here is the function: def pairwise_point_box_distance(points: torch.Tensor, boxes: Boxes): """ 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, M, 4). The 4 values are distances from the point to the left, top, right, bottom of the box. """ x, y = points.unsqueeze(dim=2).unbind(dim=1) # (N, 1) x0, y0, x1, y1 = boxes.tensor.unsqueeze(dim=0).unbind(dim=2) # (1, M) return torch.stack([x - x0, y - y0, x1 - x, y1 - y], dim=2)
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, M, 4). The 4 values are distances from the point to the left, top, right, bottom of the box.
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 also behaves like a Tensor (support indexing, `to(device)`, `.device`, and iteration over all boxes) Attributes: tensor (torch.Tensor): float matrix of Nx4. Each row is (x1, y1, x2, y2). """ def __init__(self, tensor: torch.Tensor): """ Args: tensor (Tensor[float]): a Nx4 matrix. Each row is (x1, y1, x2, y2). """ device = tensor.device if isinstance(tensor, torch.Tensor) else torch.device("cpu") tensor = torch.as_tensor(tensor, dtype=torch.float32, device=device) if tensor.numel() == 0: # Use reshape, so we don't end up creating a new tensor that does not depend on # the inputs (and consequently confuses jit) tensor = tensor.reshape((-1, 4)).to(dtype=torch.float32, device=device) assert tensor.dim() == 2 and tensor.size(-1) == 4, tensor.size() self.tensor = tensor def clone(self) -> "Boxes": """ Clone the Boxes. Returns: Boxes """ return Boxes(self.tensor.clone()) def to(self, device: torch.device): # Boxes are assumed float32 and does not support to(dtype) return Boxes(self.tensor.to(device=device)) def area(self) -> torch.Tensor: """ Computes the area of all the boxes. Returns: torch.Tensor: a vector with areas of each box. """ box = self.tensor area = (box[:, 2] - box[:, 0]) * (box[:, 3] - box[:, 1]) return area def clip(self, box_size: Tuple[int, int]) -> None: """ Clip (in place) the boxes by limiting x coordinates to the range [0, width] and y coordinates to the range [0, height]. Args: box_size (height, width): The clipping box's size. """ assert torch.isfinite(self.tensor).all(), "Box tensor contains infinite or NaN!" h, w = box_size x1 = self.tensor[:, 0].clamp(min=0, max=w) y1 = self.tensor[:, 1].clamp(min=0, max=h) x2 = self.tensor[:, 2].clamp(min=0, max=w) y2 = self.tensor[:, 3].clamp(min=0, max=h) self.tensor = torch.stack((x1, y1, x2, y2), dim=-1) def nonempty(self, threshold: float = 0.0) -> torch.Tensor: """ Find boxes that are non-empty. A box is considered empty, if either of its side is no larger than threshold. Returns: Tensor: a binary vector which represents whether each box is empty (False) or non-empty (True). """ box = self.tensor widths = box[:, 2] - box[:, 0] heights = box[:, 3] - box[:, 1] keep = (widths > threshold) & (heights > threshold) return keep def __getitem__(self, item) -> "Boxes": """ Args: item: int, slice, or a BoolTensor Returns: Boxes: Create a new :class:`Boxes` by indexing. The following usage are allowed: 1. `new_boxes = boxes[3]`: return a `Boxes` which contains only one box. 2. `new_boxes = boxes[2:10]`: return a slice of boxes. 3. `new_boxes = boxes[vector]`, where vector is a torch.BoolTensor with `length = len(boxes)`. Nonzero elements in the vector will be selected. Note that the returned Boxes might share storage with this Boxes, subject to Pytorch's indexing semantics. """ if isinstance(item, int): return Boxes(self.tensor[item].view(1, -1)) b = self.tensor[item] assert b.dim() == 2, "Indexing on Boxes with {} failed to return a matrix!".format(item) return Boxes(b) def __len__(self) -> int: return self.tensor.shape[0] def __repr__(self) -> str: return "Boxes(" + str(self.tensor) + ")" def inside_box(self, box_size: Tuple[int, int], boundary_threshold: int = 0) -> torch.Tensor: """ Args: box_size (height, width): Size of the reference box. boundary_threshold (int): Boxes that extend beyond the reference box boundary by more than boundary_threshold are considered "outside". Returns: a binary vector, indicating whether each box is inside the reference box. """ height, width = box_size inds_inside = ( (self.tensor[..., 0] >= -boundary_threshold) & (self.tensor[..., 1] >= -boundary_threshold) & (self.tensor[..., 2] < width + boundary_threshold) & (self.tensor[..., 3] < height + boundary_threshold) ) return inds_inside def get_centers(self) -> torch.Tensor: """ Returns: The box centers in a Nx2 array of (x, y). """ return (self.tensor[:, :2] + self.tensor[:, 2:]) / 2 def scale(self, scale_x: float, scale_y: float) -> None: """ Scale the box with horizontal and vertical scaling factors """ self.tensor[:, 0::2] *= scale_x self.tensor[:, 1::2] *= scale_y def cat(cls, boxes_list: List["Boxes"]) -> "Boxes": """ Concatenates a list of Boxes into a single Boxes Arguments: boxes_list (list[Boxes]) Returns: Boxes: the concatenated Boxes """ assert isinstance(boxes_list, (list, tuple)) if len(boxes_list) == 0: return cls(torch.empty(0)) assert all([isinstance(box, Boxes) for box in boxes_list]) # use torch.cat (v.s. layers.cat) so the returned boxes never share storage with input cat_boxes = cls(torch.cat([b.tensor for b in boxes_list], dim=0)) return cat_boxes def device(self) -> device: return self.tensor.device # type "Iterator[torch.Tensor]", yield, and iter() not supported by torchscript # https://github.com/pytorch/pytorch/issues/18627 def __iter__(self): """ Yield a box as a Tensor of shape (4,) at a time. """ yield from self.tensor The provided code snippet includes necessary dependencies for implementing the `matched_pairwise_iou` function. Write a Python function `def matched_pairwise_iou(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor` to solve the following problem: 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]. Here is the function: def matched_pairwise_iou(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor: """ 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]. """ assert len(boxes1) == len( boxes2 ), "boxlists should have the same" "number of entries, got {}, {}".format( len(boxes1), len(boxes2) ) area1 = boxes1.area() # [N] area2 = boxes2.area() # [N] box1, box2 = boxes1.tensor, boxes2.tensor lt = torch.max(box1[:, :2], box2[:, :2]) # [N,2] rb = torch.min(box1[:, 2:], box2[:, 2:]) # [N,2] wh = (rb - lt).clamp(min=0) # [N,2] inter = wh[:, 0] * wh[:, 1] # [N] iou = inter / (area1 + area2 - inter) # [N] return iou
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_batched_inputs_to_c2_format from .shared import get_pb_arg_vali, get_pb_arg_vals, save_graph def add_export_config(cfg): return cfg
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 ( Caffe2Compatible, Caffe2FastRCNNOutputsInference, Caffe2KeypointRCNNInference, Caffe2MaskRCNNInference, Caffe2ROIPooler, Caffe2RPN, ) class Caffe2CompatibleConverter(object): """ A GenericUpdater which implements the `create_from` interface, by modifying module object and assign it with another class replaceCls. """ def __init__(self, replaceCls): self.replaceCls = replaceCls def create_from(self, module): # update module's class to the new class assert isinstance(module, torch.nn.Module) if issubclass(self.replaceCls, GenericMixin): # replaceCls should act as mixin, create a new class on-the-fly new_class = type( "{}MixedWith{}".format(self.replaceCls.__name__, module.__class__.__name__), (self.replaceCls, module.__class__), {}, # {"new_method": lambda self: ...}, ) module.__class__ = new_class else: # replaceCls is complete class, this allow arbitrary class swap module.__class__ = self.replaceCls # initialize Caffe2Compatible if isinstance(module, Caffe2Compatible): module.tensor_mode = False return module def patch(model, target, updater, *args, **kwargs): """ recursively (post-order) update all modules with the target type and its subclasses, make a initialization/composition/inheritance/... via the updater.create_from. """ for name, module in model.named_children(): model._modules[name] = patch(module, target, updater, *args, **kwargs) if isinstance(model, target): return updater.create_from(model, *args, **kwargs) return model class Caffe2RPN(Caffe2Compatible, rpn.RPN): def _generate_proposals( self, images, objectness_logits_pred, anchor_deltas_pred, gt_instances=None ): assert isinstance(images, ImageList) if self.tensor_mode: im_info = images.image_sizes else: im_info = torch.tensor([[im_sz[0], im_sz[1], 1.0] for im_sz in images.image_sizes]).to( images.tensor.device ) assert isinstance(im_info, torch.Tensor) rpn_rois_list = [] rpn_roi_probs_list = [] for scores, bbox_deltas, cell_anchors_tensor, feat_stride in zip( objectness_logits_pred, anchor_deltas_pred, iter(self.anchor_generator.cell_anchors), self.anchor_generator.strides, ): scores = scores.detach() bbox_deltas = bbox_deltas.detach() rpn_rois, rpn_roi_probs = torch.ops._caffe2.GenerateProposals( scores, bbox_deltas, im_info, cell_anchors_tensor, spatial_scale=1.0 / feat_stride, pre_nms_topN=self.pre_nms_topk[self.training], post_nms_topN=self.post_nms_topk[self.training], nms_thresh=self.nms_thresh, min_size=self.min_box_size, # correct_transform_coords=True, # deprecated argument angle_bound_on=True, # Default angle_bound_lo=-180, angle_bound_hi=180, clip_angle_thresh=1.0, # Default legacy_plus_one=False, ) rpn_rois_list.append(rpn_rois) rpn_roi_probs_list.append(rpn_roi_probs) # For FPN in D2, in RPN all proposals from different levels are concated # together, ranked and picked by top post_nms_topk. Then in ROIPooler # it calculates level_assignments and calls the RoIAlign from # the corresponding level. if len(objectness_logits_pred) == 1: rpn_rois = rpn_rois_list[0] rpn_roi_probs = rpn_roi_probs_list[0] else: assert len(rpn_rois_list) == len(rpn_roi_probs_list) rpn_post_nms_topN = self.post_nms_topk[self.training] device = rpn_rois_list[0].device input_list = [to_device(x, "cpu") for x in (rpn_rois_list + rpn_roi_probs_list)] # TODO remove this after confirming rpn_max_level/rpn_min_level # is not needed in CollectRpnProposals. feature_strides = list(self.anchor_generator.strides) rpn_min_level = int(math.log2(feature_strides[0])) rpn_max_level = int(math.log2(feature_strides[-1])) assert (rpn_max_level - rpn_min_level + 1) == len( rpn_rois_list ), "CollectRpnProposals requires continuous levels" rpn_rois = torch.ops._caffe2.CollectRpnProposals( input_list, # NOTE: in current implementation, rpn_max_level and rpn_min_level # are not needed, only the subtraction of two matters and it # can be infer from the number of inputs. Keep them now for # consistency. rpn_max_level=2 + len(rpn_rois_list) - 1, rpn_min_level=2, rpn_post_nms_topN=rpn_post_nms_topN, ) rpn_rois = to_device(rpn_rois, device) rpn_roi_probs = [] proposals = self.c2_postprocess(im_info, rpn_rois, rpn_roi_probs, self.tensor_mode) return proposals, {} def forward(self, images, features, gt_instances=None): assert not self.training features = [features[f] for f in self.in_features] objectness_logits_pred, anchor_deltas_pred = self.rpn_head(features) return self._generate_proposals( images, objectness_logits_pred, anchor_deltas_pred, gt_instances, ) def c2_postprocess(im_info, rpn_rois, rpn_roi_probs, tensor_mode): proposals = InstancesList( im_info=im_info, indices=rpn_rois[:, 0], extra_fields={ "proposal_boxes": Caffe2Boxes(rpn_rois), "objectness_logits": (torch.Tensor, rpn_roi_probs), }, ) if not tensor_mode: proposals = InstancesList.to_d2_instances_list(proposals) else: proposals = [proposals] return proposals class Caffe2ROIPooler(Caffe2Compatible, poolers.ROIPooler): def c2_preprocess(box_lists): assert all(isinstance(x, Boxes) for x in box_lists) if all(isinstance(x, Caffe2Boxes) for x in box_lists): # input is pure-tensor based assert len(box_lists) == 1 pooler_fmt_boxes = box_lists[0].tensor else: pooler_fmt_boxes = poolers.convert_boxes_to_pooler_format(box_lists) return pooler_fmt_boxes def forward(self, x, box_lists): assert not self.training pooler_fmt_boxes = self.c2_preprocess(box_lists) num_level_assignments = len(self.level_poolers) if num_level_assignments == 1: if isinstance(self.level_poolers[0], ROIAlignRotated): c2_roi_align = torch.ops._caffe2.RoIAlignRotated aligned = True else: c2_roi_align = torch.ops._caffe2.RoIAlign aligned = self.level_poolers[0].aligned x0 = x[0] if x0.is_quantized: x0 = x0.dequantize() out = c2_roi_align( x0, pooler_fmt_boxes, order="NCHW", spatial_scale=float(self.level_poolers[0].spatial_scale), pooled_h=int(self.output_size[0]), pooled_w=int(self.output_size[1]), sampling_ratio=int(self.level_poolers[0].sampling_ratio), aligned=aligned, ) return out device = pooler_fmt_boxes.device assert ( self.max_level - self.min_level + 1 == 4 ), "Currently DistributeFpnProposals only support 4 levels" fpn_outputs = torch.ops._caffe2.DistributeFpnProposals( to_device(pooler_fmt_boxes, "cpu"), roi_canonical_scale=self.canonical_box_size, roi_canonical_level=self.canonical_level, roi_max_level=self.max_level, roi_min_level=self.min_level, legacy_plus_one=False, ) fpn_outputs = [to_device(x, device) for x in fpn_outputs] rois_fpn_list = fpn_outputs[:-1] rois_idx_restore_int32 = fpn_outputs[-1] roi_feat_fpn_list = [] for roi_fpn, x_level, pooler in zip(rois_fpn_list, x, self.level_poolers): if isinstance(pooler, ROIAlignRotated): c2_roi_align = torch.ops._caffe2.RoIAlignRotated aligned = True else: c2_roi_align = torch.ops._caffe2.RoIAlign aligned = bool(pooler.aligned) if x_level.is_quantized: x_level = x_level.dequantize() roi_feat_fpn = c2_roi_align( x_level, roi_fpn, order="NCHW", spatial_scale=float(pooler.spatial_scale), pooled_h=int(self.output_size[0]), pooled_w=int(self.output_size[1]), sampling_ratio=int(pooler.sampling_ratio), aligned=aligned, ) roi_feat_fpn_list.append(roi_feat_fpn) roi_feat_shuffled = cat(roi_feat_fpn_list, dim=0) assert roi_feat_shuffled.numel() > 0 and rois_idx_restore_int32.numel() > 0, ( "Caffe2 export requires tracing with a model checkpoint + input that can produce valid" " detections. But no detections were obtained with the given checkpoint and input!" ) roi_feat = torch.ops._caffe2.BatchPermutation(roi_feat_shuffled, rois_idx_restore_int32) return roi_feat def patch_generalized_rcnn(model): ccc = Caffe2CompatibleConverter model = patch(model, rpn.RPN, ccc(Caffe2RPN)) model = patch(model, poolers.ROIPooler, ccc(Caffe2ROIPooler)) return model
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 ( Caffe2Compatible, Caffe2FastRCNNOutputsInference, Caffe2KeypointRCNNInference, Caffe2MaskRCNNInference, Caffe2ROIPooler, Caffe2RPN, ) def patch(model, target, updater, *args, **kwargs): """ recursively (post-order) update all modules with the target type and its subclasses, make a initialization/composition/inheritance/... via the updater.create_from. """ for name, module in model.named_children(): model._modules[name] = patch(module, target, updater, *args, **kwargs) if isinstance(model, target): return updater.create_from(model, *args, **kwargs) return model class FastRCNNOutputLayers(nn.Module): """ Two linear layers for predicting Fast R-CNN outputs: 1. proposal-to-detection box regression deltas 2. classification scores """ def __init__( self, input_shape: ShapeSpec, *, box2box_transform, num_classes: int, test_score_thresh: float = 0.0, test_nms_thresh: float = 0.5, test_topk_per_image: int = 100, cls_agnostic_bbox_reg: bool = False, smooth_l1_beta: float = 0.0, box_reg_loss_type: str = "smooth_l1", loss_weight: Union[float, Dict[str, float]] = 1.0, ): """ NOTE: this interface is experimental. Args: input_shape (ShapeSpec): shape of the input feature to this module box2box_transform (Box2BoxTransform or Box2BoxTransformRotated): num_classes (int): number of foreground classes test_score_thresh (float): threshold to filter predictions results. test_nms_thresh (float): NMS threshold for prediction results. test_topk_per_image (int): number of top predictions to produce per image. cls_agnostic_bbox_reg (bool): whether to use class agnostic for bbox regression smooth_l1_beta (float): transition point from L1 to L2 loss. Only used if `box_reg_loss_type` is "smooth_l1" box_reg_loss_type (str): Box regression loss type. One of: "smooth_l1", "giou", "diou", "ciou" loss_weight (float|dict): weights to use for losses. Can be single float for weighting all losses, or a dict of individual weightings. Valid dict keys are: * "loss_cls": applied to classification loss * "loss_box_reg": applied to box regression loss """ super().__init__() if isinstance(input_shape, int): # some backward compatibility input_shape = ShapeSpec(channels=input_shape) self.num_classes = num_classes input_size = input_shape.channels * (input_shape.width or 1) * (input_shape.height or 1) # prediction layer for num_classes foreground classes and one background class (hence + 1) self.cls_score = nn.Linear(input_size, num_classes + 1) num_bbox_reg_classes = 1 if cls_agnostic_bbox_reg else num_classes box_dim = len(box2box_transform.weights) self.bbox_pred = nn.Linear(input_size, num_bbox_reg_classes * box_dim) nn.init.normal_(self.cls_score.weight, std=0.01) nn.init.normal_(self.bbox_pred.weight, std=0.001) for l in [self.cls_score, self.bbox_pred]: nn.init.constant_(l.bias, 0) self.box2box_transform = box2box_transform self.smooth_l1_beta = smooth_l1_beta self.test_score_thresh = test_score_thresh self.test_nms_thresh = test_nms_thresh self.test_topk_per_image = test_topk_per_image self.box_reg_loss_type = box_reg_loss_type if isinstance(loss_weight, float): loss_weight = {"loss_cls": loss_weight, "loss_box_reg": loss_weight} self.loss_weight = loss_weight def from_config(cls, cfg, input_shape): return { "input_shape": input_shape, "box2box_transform": Box2BoxTransform(weights=cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_WEIGHTS), # fmt: off "num_classes" : cfg.MODEL.ROI_HEADS.NUM_CLASSES, "cls_agnostic_bbox_reg" : cfg.MODEL.ROI_BOX_HEAD.CLS_AGNOSTIC_BBOX_REG, "smooth_l1_beta" : cfg.MODEL.ROI_BOX_HEAD.SMOOTH_L1_BETA, "test_score_thresh" : cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST, "test_nms_thresh" : cfg.MODEL.ROI_HEADS.NMS_THRESH_TEST, "test_topk_per_image" : cfg.TEST.DETECTIONS_PER_IMAGE, "box_reg_loss_type" : cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_LOSS_TYPE, "loss_weight" : {"loss_box_reg": cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_LOSS_WEIGHT}, # fmt: on } def forward(self, x): """ Args: x: per-region features of shape (N, ...) for N bounding boxes to predict. Returns: (Tensor, Tensor): First tensor: shape (N,K+1), scores for each of the N box. Each row contains the scores for K object categories and 1 background class. Second tensor: bounding box regression deltas for each box. Shape is shape (N,Kx4), or (N,4) for class-agnostic regression. """ if x.dim() > 2: x = torch.flatten(x, start_dim=1) scores = self.cls_score(x) proposal_deltas = self.bbox_pred(x) return scores, proposal_deltas def losses(self, predictions, proposals): """ Args: predictions: return values of :meth:`forward()`. proposals (list[Instances]): proposals that match the features that were used to compute predictions. The fields ``proposal_boxes``, ``gt_boxes``, ``gt_classes`` are expected. Returns: Dict[str, Tensor]: dict of losses """ scores, proposal_deltas = predictions # parse classification outputs gt_classes = ( cat([p.gt_classes for p in proposals], dim=0) if len(proposals) else torch.empty(0) ) _log_classification_stats(scores, gt_classes) # parse box regression outputs if len(proposals): proposal_boxes = cat([p.proposal_boxes.tensor for p in proposals], dim=0) # Nx4 assert not proposal_boxes.requires_grad, "Proposals should not require gradients!" # If "gt_boxes" does not exist, the proposals must be all negative and # should not be included in regression loss computation. # Here we just use proposal_boxes as an arbitrary placeholder because its # value won't be used in self.box_reg_loss(). gt_boxes = cat( [(p.gt_boxes if p.has("gt_boxes") else p.proposal_boxes).tensor for p in proposals], dim=0, ) else: proposal_boxes = gt_boxes = torch.empty((0, 4), device=proposal_deltas.device) losses = { "loss_cls": cross_entropy(scores, gt_classes, reduction="mean"), "loss_box_reg": self.box_reg_loss( proposal_boxes, gt_boxes, proposal_deltas, gt_classes ), } return {k: v * self.loss_weight.get(k, 1.0) for k, v in losses.items()} def box_reg_loss(self, proposal_boxes, gt_boxes, pred_deltas, gt_classes): """ Args: proposal_boxes/gt_boxes are tensors with the same shape (R, 4 or 5). pred_deltas has shape (R, 4 or 5), or (R, num_classes * (4 or 5)). gt_classes is a long tensor of shape R, the gt class label of each proposal. R shall be the number of proposals. """ box_dim = proposal_boxes.shape[1] # 4 or 5 # Regression loss is only computed for foreground proposals (those matched to a GT) fg_inds = nonzero_tuple((gt_classes >= 0) & (gt_classes < self.num_classes))[0] if pred_deltas.shape[1] == box_dim: # cls-agnostic regression fg_pred_deltas = pred_deltas[fg_inds] else: fg_pred_deltas = pred_deltas.view(-1, self.num_classes, box_dim)[ fg_inds, gt_classes[fg_inds] ] loss_box_reg = _dense_box_regression_loss( [proposal_boxes[fg_inds]], self.box2box_transform, [fg_pred_deltas.unsqueeze(0)], [gt_boxes[fg_inds]], ..., self.box_reg_loss_type, self.smooth_l1_beta, ) # The reg loss is normalized using the total number of regions (R), not the number # of foreground regions even though the box regression loss is only defined on # foreground regions. Why? Because doing so gives equal training influence to # each foreground example. To see how, consider two different minibatches: # (1) Contains a single foreground region # (2) Contains 100 foreground regions # If we normalize by the number of foreground regions, the single example in # minibatch (1) will be given 100 times as much influence as each foreground # example in minibatch (2). Normalizing by the total number of regions, R, # means that the single example in minibatch (1) and each of the 100 examples # in minibatch (2) are given equal influence. return loss_box_reg / max(gt_classes.numel(), 1.0) # return 0 if empty def inference(self, predictions: Tuple[torch.Tensor, torch.Tensor], proposals: List[Instances]): """ Args: predictions: return values of :meth:`forward()`. proposals (list[Instances]): proposals that match the features that were used to compute predictions. The ``proposal_boxes`` field is expected. Returns: list[Instances]: same as `fast_rcnn_inference`. list[Tensor]: same as `fast_rcnn_inference`. """ boxes = self.predict_boxes(predictions, proposals) scores = self.predict_probs(predictions, proposals) image_shapes = [x.image_size for x in proposals] return fast_rcnn_inference( boxes, scores, image_shapes, self.test_score_thresh, self.test_nms_thresh, self.test_topk_per_image, ) def predict_boxes_for_gt_classes(self, predictions, proposals): """ Args: predictions: return values of :meth:`forward()`. proposals (list[Instances]): proposals that match the features that were used to compute predictions. The fields ``proposal_boxes``, ``gt_classes`` are expected. Returns: list[Tensor]: A list of Tensors of predicted boxes for GT classes in case of class-specific box head. Element i of the list has shape (Ri, B), where Ri is the number of proposals for image i and B is the box dimension (4 or 5) """ if not len(proposals): return [] scores, proposal_deltas = predictions proposal_boxes = cat([p.proposal_boxes.tensor for p in proposals], dim=0) N, B = proposal_boxes.shape predict_boxes = self.box2box_transform.apply_deltas( proposal_deltas, proposal_boxes ) # Nx(KxB) K = predict_boxes.shape[1] // B if K > 1: gt_classes = torch.cat([p.gt_classes for p in proposals], dim=0) # Some proposals are ignored or have a background class. Their gt_classes # cannot be used as index. gt_classes = gt_classes.clamp_(0, K - 1) predict_boxes = predict_boxes.view(N, K, B)[ torch.arange(N, dtype=torch.long, device=predict_boxes.device), gt_classes ] num_prop_per_image = [len(p) for p in proposals] return predict_boxes.split(num_prop_per_image) def predict_boxes( self, predictions: Tuple[torch.Tensor, torch.Tensor], proposals: List[Instances] ): """ Args: predictions: return values of :meth:`forward()`. proposals (list[Instances]): proposals that match the features that were used to compute predictions. The ``proposal_boxes`` field is expected. Returns: list[Tensor]: A list of Tensors of predicted class-specific or class-agnostic boxes for each image. Element i has shape (Ri, K * B) or (Ri, B), where Ri is the number of proposals for image i and B is the box dimension (4 or 5) """ if not len(proposals): return [] _, proposal_deltas = predictions num_prop_per_image = [len(p) for p in proposals] proposal_boxes = cat([p.proposal_boxes.tensor for p in proposals], dim=0) predict_boxes = self.box2box_transform.apply_deltas( proposal_deltas, proposal_boxes, ) # Nx(KxB) return predict_boxes.split(num_prop_per_image) def predict_probs( self, predictions: Tuple[torch.Tensor, torch.Tensor], proposals: List[Instances] ): """ Args: predictions: return values of :meth:`forward()`. proposals (list[Instances]): proposals that match the features that were used to compute predictions. Returns: list[Tensor]: A list of Tensors of predicted class probabilities for each image. Element i has shape (Ri, K + 1), where Ri is the number of proposals for image i. """ scores, _ = predictions num_inst_per_image = [len(p) for p in proposals] probs = F.softmax(scores, dim=-1) return probs.split(num_inst_per_image, dim=0) class Caffe2FastRCNNOutputsInference: def __init__(self, tensor_mode): self.tensor_mode = tensor_mode # whether the output is caffe2 tensor mode def __call__(self, box_predictor, predictions, proposals): """equivalent to FastRCNNOutputLayers.inference""" num_classes = box_predictor.num_classes score_thresh = box_predictor.test_score_thresh nms_thresh = box_predictor.test_nms_thresh topk_per_image = box_predictor.test_topk_per_image is_rotated = len(box_predictor.box2box_transform.weights) == 5 if is_rotated: box_dim = 5 assert box_predictor.box2box_transform.weights[4] == 1, ( "The weights for Rotated BBoxTransform in C2 have only 4 dimensions," + " thus enforcing the angle weight to be 1 for now" ) box2box_transform_weights = box_predictor.box2box_transform.weights[:4] else: box_dim = 4 box2box_transform_weights = box_predictor.box2box_transform.weights class_logits, box_regression = predictions if num_classes + 1 == class_logits.shape[1]: class_prob = F.softmax(class_logits, -1) else: assert num_classes == class_logits.shape[1] class_prob = F.sigmoid(class_logits) # BoxWithNMSLimit will infer num_classes from the shape of the class_prob # So append a zero column as placeholder for the background class class_prob = torch.cat((class_prob, torch.zeros(class_prob.shape[0], 1)), dim=1) assert box_regression.shape[1] % box_dim == 0 cls_agnostic_bbox_reg = box_regression.shape[1] // box_dim == 1 input_tensor_mode = proposals[0].proposal_boxes.tensor.shape[1] == box_dim + 1 rois = type(proposals[0].proposal_boxes).cat([p.proposal_boxes for p in proposals]) device, dtype = rois.tensor.device, rois.tensor.dtype if input_tensor_mode: im_info = proposals[0].image_size rois = rois.tensor else: im_info = torch.tensor( [[sz[0], sz[1], 1.0] for sz in [x.image_size for x in proposals]] ) batch_ids = cat( [ torch.full((b, 1), i, dtype=dtype, device=device) for i, b in enumerate(len(p) for p in proposals) ], dim=0, ) rois = torch.cat([batch_ids, rois.tensor], dim=1) roi_pred_bbox, roi_batch_splits = torch.ops._caffe2.BBoxTransform( to_device(rois, "cpu"), to_device(box_regression, "cpu"), to_device(im_info, "cpu"), weights=box2box_transform_weights, apply_scale=True, rotated=is_rotated, angle_bound_on=True, angle_bound_lo=-180, angle_bound_hi=180, clip_angle_thresh=1.0, legacy_plus_one=False, ) roi_pred_bbox = to_device(roi_pred_bbox, device) roi_batch_splits = to_device(roi_batch_splits, device) nms_outputs = torch.ops._caffe2.BoxWithNMSLimit( to_device(class_prob, "cpu"), to_device(roi_pred_bbox, "cpu"), to_device(roi_batch_splits, "cpu"), score_thresh=float(score_thresh), nms=float(nms_thresh), detections_per_im=int(topk_per_image), soft_nms_enabled=False, soft_nms_method="linear", soft_nms_sigma=0.5, soft_nms_min_score_thres=0.001, rotated=is_rotated, cls_agnostic_bbox_reg=cls_agnostic_bbox_reg, input_boxes_include_bg_cls=False, output_classes_include_bg_cls=False, legacy_plus_one=False, ) roi_score_nms = to_device(nms_outputs[0], device) roi_bbox_nms = to_device(nms_outputs[1], device) roi_class_nms = to_device(nms_outputs[2], device) roi_batch_splits_nms = to_device(nms_outputs[3], device) roi_keeps_nms = to_device(nms_outputs[4], device) roi_keeps_size_nms = to_device(nms_outputs[5], device) if not self.tensor_mode: roi_class_nms = roi_class_nms.to(torch.int64) roi_batch_ids = cat( [ torch.full((b, 1), i, dtype=dtype, device=device) for i, b in enumerate(int(x.item()) for x in roi_batch_splits_nms) ], dim=0, ) roi_class_nms = alias(roi_class_nms, "class_nms") roi_score_nms = alias(roi_score_nms, "score_nms") roi_bbox_nms = alias(roi_bbox_nms, "bbox_nms") roi_batch_splits_nms = alias(roi_batch_splits_nms, "batch_splits_nms") roi_keeps_nms = alias(roi_keeps_nms, "keeps_nms") roi_keeps_size_nms = alias(roi_keeps_size_nms, "keeps_size_nms") results = InstancesList( im_info=im_info, indices=roi_batch_ids[:, 0], extra_fields={ "pred_boxes": Caffe2Boxes(roi_bbox_nms), "scores": roi_score_nms, "pred_classes": roi_class_nms, }, ) if not self.tensor_mode: results = InstancesList.to_d2_instances_list(results) batch_splits = roi_batch_splits_nms.int().tolist() kept_indices = list(roi_keeps_nms.to(torch.int64).split(batch_splits)) else: results = [results] kept_indices = [roi_keeps_nms] return results, kept_indices def mock_fastrcnn_outputs_inference( tensor_mode, check=True, box_predictor_type=FastRCNNOutputLayers ): with mock.patch.object( box_predictor_type, "inference", autospec=True, side_effect=Caffe2FastRCNNOutputsInference(tensor_mode), ) as mocked_func: yield if check: assert mocked_func.call_count > 0
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 ( Caffe2Compatible, Caffe2FastRCNNOutputsInference, Caffe2KeypointRCNNInference, Caffe2MaskRCNNInference, Caffe2ROIPooler, Caffe2RPN, ) def patch(model, target, updater, *args, **kwargs): """ recursively (post-order) update all modules with the target type and its subclasses, make a initialization/composition/inheritance/... via the updater.create_from. """ for name, module in model.named_children(): model._modules[name] = patch(module, target, updater, *args, **kwargs) if isinstance(model, target): return updater.create_from(model, *args, **kwargs) return model class Caffe2MaskRCNNInference: def __call__(self, pred_mask_logits, pred_instances): """equivalent to mask_head.mask_rcnn_inference""" if all(isinstance(x, InstancesList) for x in pred_instances): assert len(pred_instances) == 1 mask_probs_pred = pred_mask_logits.sigmoid() mask_probs_pred = alias(mask_probs_pred, "mask_fcn_probs") pred_instances[0].pred_masks = mask_probs_pred else: mask_rcnn_inference(pred_mask_logits, pred_instances) def mock_mask_rcnn_inference(tensor_mode, patched_module, check=True): with mock.patch( "{}.mask_rcnn_inference".format(patched_module), side_effect=Caffe2MaskRCNNInference() ) as mocked_func: yield if check: assert mocked_func.call_count > 0
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 ( Caffe2Compatible, Caffe2FastRCNNOutputsInference, Caffe2KeypointRCNNInference, Caffe2MaskRCNNInference, Caffe2ROIPooler, Caffe2RPN, ) def patch(model, target, updater, *args, **kwargs): """ recursively (post-order) update all modules with the target type and its subclasses, make a initialization/composition/inheritance/... via the updater.create_from. """ for name, module in model.named_children(): model._modules[name] = patch(module, target, updater, *args, **kwargs) if isinstance(model, target): return updater.create_from(model, *args, **kwargs) return model class Caffe2KeypointRCNNInference: def __init__(self, use_heatmap_max_keypoint): self.use_heatmap_max_keypoint = use_heatmap_max_keypoint def __call__(self, pred_keypoint_logits, pred_instances): # just return the keypoint heatmap for now, # there will be option to call HeatmapMaxKeypointOp output = alias(pred_keypoint_logits, "kps_score") if all(isinstance(x, InstancesList) for x in pred_instances): assert len(pred_instances) == 1 if self.use_heatmap_max_keypoint: device = output.device output = torch.ops._caffe2.HeatmapMaxKeypoint( to_device(output, "cpu"), pred_instances[0].pred_boxes.tensor, should_output_softmax=True, # worth make it configerable? ) output = to_device(output, device) output = alias(output, "keypoints_out") pred_instances[0].pred_keypoints = output return pred_keypoint_logits def mock_keypoint_rcnn_inference(tensor_mode, patched_module, use_heatmap_max_keypoint, check=True): with mock.patch( "{}.keypoint_rcnn_inference".format(patched_module), side_effect=Caffe2KeypointRCNNInference(use_heatmap_max_keypoint), ) as mocked_func: yield if check: assert mocked_func.call_count > 0
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 class ListSchema(Schema): schemas: List[Schema] # the schemas that define how to flatten each element in the list sizes: List[int] # the flattened length of each element def __call__(self, values): values = self._split(values, self.sizes) if len(values) != len(self.schemas): raise ValueError( f"Values has length {len(values)} but schemas " f"has length {len(self.schemas)}!" ) values = [m(v) for m, v in zip(self.schemas, values)] return list(values) def flatten(cls, obj): res = [flatten_to_tuple(k) for k in obj] values, sizes = cls._concat([k[0] for k in res]) return values, cls([k[1] for k in res], sizes) class TupleSchema(ListSchema): def __call__(self, values): return tuple(super().__call__(values)) class IdentitySchema(Schema): def __call__(self, values): return values[0] def flatten(cls, obj): return (obj,), cls() class DictSchema(ListSchema): keys: List[str] def __call__(self, values): values = super().__call__(values) return dict(zip(self.keys, values)) def flatten(cls, obj): for k in obj.keys(): if not isinstance(k, str): raise KeyError("Only support flattening dictionaries if keys are str.") keys = sorted(obj.keys()) values = [obj[k] for k in keys] ret, schema = ListSchema.flatten(values) return ret, cls(schema.schemas, schema.sizes, keys) class InstancesSchema(DictSchema): def __call__(self, values): image_size, fields = values[-1], values[:-1] fields = super().__call__(fields) return Instances(image_size, **fields) def flatten(cls, obj): ret, schema = super().flatten(obj.get_fields()) size = obj.image_size if not isinstance(size, torch.Tensor): size = torch.tensor(size) return ret + (size,), schema class TensorWrapSchema(Schema): """ For classes that are simple wrapper of tensors, e.g. Boxes, RotatedBoxes, BitMasks """ class_name: str def __call__(self, values): return locate(self.class_name)(values[0]) def flatten(cls, obj): return (obj.tensor,), cls(_convert_target_to_string(type(obj))) The provided code snippet includes necessary dependencies for implementing the `flatten_to_tuple` function. Write a Python function `def flatten_to_tuple(obj)` to solve the following problem: 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 can be serialized. Here is the function: def flatten_to_tuple(obj): """ 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 can be serialized. """ schemas = [ ((str, bytes), IdentitySchema), (list, ListSchema), (tuple, TupleSchema), (collections.abc.Mapping, DictSchema), (Instances, InstancesSchema), ((Boxes, ROIMasks), TensorWrapSchema), ] for klass, schema in schemas: if isinstance(obj, klass): F = schema break else: F = IdentitySchema return F.flatten(obj)
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 can be serialized.
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 includes necessary dependencies for implementing the `patch_builtin_len` function. Write a Python function `def patch_builtin_len(modules=())` to solve the following problem: 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. Here is the function: def patch_builtin_len(modules=()): """ 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. """ def _new_len(obj): return obj.__len__() with ExitStack() as stack: MODULES = [ "detectron2.modeling.roi_heads.fast_rcnn", "detectron2.modeling.roi_heads.mask_head", "detectron2.modeling.roi_heads.keypoint_head", ] + list(modules) ctxs = [stack.enter_context(mock.patch(mod + ".len")) for mod in MODULES] for m in ctxs: m.side_effect = _new_len yield
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 includes necessary dependencies for implementing the `patch_nonscriptable_classes` function. Write a Python function `def patch_nonscriptable_classes()` to solve the following problem: Apply patches on a few nonscriptable detectron2 classes. Should not have side-effects on eager usage. Here is the function: def patch_nonscriptable_classes(): """ Apply patches on a few nonscriptable detectron2 classes. Should not have side-effects on eager usage. """ # __prepare_scriptable__ can also be added to models for easier maintenance. # But it complicates the clean model code. from detectron2.modeling.backbone import ResNet, FPN # Due to https://github.com/pytorch/pytorch/issues/36061, # we change backbone to use ModuleList for scripting. # (note: this changes param names in state_dict) def prepare_resnet(self): ret = deepcopy(self) ret.stages = nn.ModuleList(ret.stages) for k in self.stage_names: delattr(ret, k) return ret ResNet.__prepare_scriptable__ = prepare_resnet def prepare_fpn(self): ret = deepcopy(self) ret.lateral_convs = nn.ModuleList(ret.lateral_convs) ret.output_convs = nn.ModuleList(ret.output_convs) for name, _ in self.named_children(): if name.startswith("fpn_"): delattr(ret, name) return ret FPN.__prepare_scriptable__ = prepare_fpn # Annotate some attributes to be constants for the purpose of scripting, # even though they are not constants in eager mode. from detectron2.modeling.roi_heads import StandardROIHeads if hasattr(StandardROIHeads, "__annotations__"): # copy first to avoid editing annotations of base class StandardROIHeads.__annotations__ = deepcopy(StandardROIHeads.__annotations__) StandardROIHeads.__annotations__["mask_on"] = torch.jit.Final[bool] StandardROIHeads.__annotations__["keypoint_on"] = torch.jit.Final[bool]
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 import Caffe2Compatible from .caffe2_patch import ROIHeadsPatcher, patch_generalized_rcnn from .shared import ( alias, check_set_pb_arg, get_pb_arg_floats, get_pb_arg_valf, get_pb_arg_vali, get_pb_arg_vals, mock_torch_nn_functional_interpolate, ) The provided code snippet includes necessary dependencies for implementing the `assemble_rcnn_outputs_by_name` function. Write a Python function `def assemble_rcnn_outputs_by_name(image_sizes, tensor_outputs, force_mask_on=False)` to solve the following problem: 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_output to its tensor. force_mask_on (Bool): if true, the it make sure there'll be pred_masks even if the mask is not found from tensor_outputs (usually due to model crash) Here is the function: def assemble_rcnn_outputs_by_name(image_sizes, tensor_outputs, force_mask_on=False): """ 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_output to its tensor. force_mask_on (Bool): if true, the it make sure there'll be pred_masks even if the mask is not found from tensor_outputs (usually due to model crash) """ results = [Instances(image_size) for image_size in image_sizes] batch_splits = tensor_outputs.get("batch_splits", None) if batch_splits: raise NotImplementedError() assert len(image_sizes) == 1 result = results[0] bbox_nms = tensor_outputs["bbox_nms"] score_nms = tensor_outputs["score_nms"] class_nms = tensor_outputs["class_nms"] # Detection will always success because Conv support 0-batch assert bbox_nms is not None assert score_nms is not None assert class_nms is not None if bbox_nms.shape[1] == 5: result.pred_boxes = RotatedBoxes(bbox_nms) else: result.pred_boxes = Boxes(bbox_nms) result.scores = score_nms result.pred_classes = class_nms.to(torch.int64) mask_fcn_probs = tensor_outputs.get("mask_fcn_probs", None) if mask_fcn_probs is not None: # finish the mask pred mask_probs_pred = mask_fcn_probs num_masks = mask_probs_pred.shape[0] class_pred = result.pred_classes indices = torch.arange(num_masks, device=class_pred.device) mask_probs_pred = mask_probs_pred[indices, class_pred][:, None] result.pred_masks = mask_probs_pred elif force_mask_on: # NOTE: there's no way to know the height/width of mask here, it won't be # used anyway when batch size is 0, so just set them to 0. result.pred_masks = torch.zeros([0, 1, 0, 0], dtype=torch.uint8) keypoints_out = tensor_outputs.get("keypoints_out", None) kps_score = tensor_outputs.get("kps_score", None) if keypoints_out is not None: # keypoints_out: [N, 4, #kypoints], where 4 is in order of (x, y, score, prob) keypoints_tensor = keypoints_out # NOTE: it's possible that prob is not calculated if "should_output_softmax" # is set to False in HeatmapMaxKeypoint, so just using raw score, seems # it doesn't affect mAP. TODO: check more carefully. keypoint_xyp = keypoints_tensor.transpose(1, 2)[:, :, [0, 1, 2]] result.pred_keypoints = keypoint_xyp elif kps_score is not None: # keypoint heatmap to sparse data structure pred_keypoint_logits = kps_score keypoint_head.keypoint_rcnn_inference(pred_keypoint_logits, [result]) return results
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_output to its tensor. force_mask_on (Bool): if true, the it make sure there'll be pred_masks even if the mask is not found from tensor_outputs (usually due to model crash)
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 import Caffe2Compatible from .caffe2_patch import ROIHeadsPatcher, patch_generalized_rcnn from .shared import ( alias, check_set_pb_arg, get_pb_arg_floats, get_pb_arg_valf, get_pb_arg_vali, get_pb_arg_vals, mock_torch_nn_functional_interpolate, ) def _cast_to_f32(f64): return struct.unpack("f", struct.pack("f", f64))[0]
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 import Caffe2Compatible from .caffe2_patch import ROIHeadsPatcher, patch_generalized_rcnn from .shared import ( alias, check_set_pb_arg, get_pb_arg_floats, get_pb_arg_valf, get_pb_arg_vali, get_pb_arg_vals, mock_torch_nn_functional_interpolate, ) class Caffe2Compatible(object): """ A model can inherit this class to indicate that it can be traced and deployed with caffe2. """ def _get_tensor_mode(self): return self._tensor_mode def _set_tensor_mode(self, v): self._tensor_mode = v tensor_mode = property(_get_tensor_mode, _set_tensor_mode) """ If true, the model expects C2-style tensor only inputs/outputs format. """ def set_caffe2_compatible_tensor_mode(model, enable=True): def _fn(m): if isinstance(m, Caffe2Compatible): m.tensor_mode = enable model.apply(_fn)
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 import Caffe2Compatible from .caffe2_patch import ROIHeadsPatcher, patch_generalized_rcnn from .shared import ( alias, check_set_pb_arg, get_pb_arg_floats, get_pb_arg_valf, get_pb_arg_vali, get_pb_arg_vals, mock_torch_nn_functional_interpolate, ) The provided code snippet includes necessary dependencies for implementing the `convert_batched_inputs_to_c2_format` function. Write a Python function `def convert_batched_inputs_to_c2_format(batched_inputs, size_divisibility, device)` to solve the following problem: See get_caffe2_inputs() below. Here is the function: def convert_batched_inputs_to_c2_format(batched_inputs, size_divisibility, device): """ See get_caffe2_inputs() below. """ assert all(isinstance(x, dict) for x in batched_inputs) assert all(x["image"].dim() == 3 for x in batched_inputs) images = [x["image"] for x in batched_inputs] images = ImageList.from_tensors(images, size_divisibility) im_info = [] for input_per_image, image_size in zip(batched_inputs, images.image_sizes): target_height = input_per_image.get("height", image_size[0]) target_width = input_per_image.get("width", image_size[1]) # noqa # NOTE: The scale inside im_info is kept as convention and for providing # post-processing information if further processing is needed. For # current Caffe2 model definitions that don't include post-processing inside # the model, this number is not used. # NOTE: There can be a slight difference between width and height # scales, using a single number can results in numerical difference # compared with D2's post-processing. scale = target_height / image_size[0] im_info.append([image_size[0], image_size[1], scale]) im_info = torch.Tensor(im_info) return images.tensor.to(device), im_info.to(device)
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 OperatorExportTypes from .shared import ( ScopedWS, construct_init_net_from_params, fuse_alias_placeholder, fuse_copy_between_cpu_and_gpu, get_params_from_init_net, group_norm_replace_aten_with_caffe2, infer_device_type, remove_dead_end_ops, remove_reshape_for_fc, save_graph, ) logger = logging.getLogger(__name__) def export_onnx_model(model, inputs): """ Trace and export a model to onnx format. Args: model (nn.Module): inputs (tuple[args]): the model will be called by `model(*inputs)` Returns: an onnx model """ assert isinstance(model, torch.nn.Module) # make sure all modules are in eval mode, onnx may change the training state # of the module if the states are not consistent def _check_eval(module): assert not module.training model.apply(_check_eval) # Export the model to ONNX with torch.no_grad(): with io.BytesIO() as f: torch.onnx.export( model, inputs, f, operator_export_type=OperatorExportTypes.ONNX_ATEN_FALLBACK, # verbose=True, # NOTE: uncomment this for debugging # export_params=True, ) onnx_model = onnx.load_from_string(f.getvalue()) # Apply ONNX's Optimization all_passes = onnx.optimizer.get_available_passes() passes = ["fuse_bn_into_conv"] assert all(p in all_passes for p in passes) onnx_model = onnx.optimizer.optimize(onnx_model, passes) return onnx_model def _op_stats(net_def): type_count = {} for t in [op.type for op in net_def.op]: type_count[t] = type_count.get(t, 0) + 1 type_count_list = sorted(type_count.items(), key=lambda kv: kv[0]) # alphabet type_count_list = sorted(type_count_list, key=lambda kv: -kv[1]) # count return "\n".join("{:>4}x {}".format(count, name) for name, count in type_count_list) def _assign_device_option( predict_net: caffe2_pb2.NetDef, init_net: caffe2_pb2.NetDef, tensor_inputs: List[torch.Tensor] ): """ ONNX exported network doesn't have concept of device, assign necessary device option for each op in order to make it runable on GPU runtime. """ def _get_device_type(torch_tensor): assert torch_tensor.device.type in ["cpu", "cuda"] assert torch_tensor.device.index == 0 return torch_tensor.device.type def _assign_op_device_option(net_proto, net_ssa, blob_device_types): for op, ssa_i in zip(net_proto.op, net_ssa): if op.type in ["CopyCPUToGPU", "CopyGPUToCPU"]: op.device_option.CopyFrom(core.DeviceOption(caffe2_pb2.CUDA, 0)) else: devices = [blob_device_types[b] for b in ssa_i[0] + ssa_i[1]] assert all(d == devices[0] for d in devices) if devices[0] == "cuda": op.device_option.CopyFrom(core.DeviceOption(caffe2_pb2.CUDA, 0)) # update ops in predict_net predict_net_input_device_types = { (name, 0): _get_device_type(tensor) for name, tensor in zip(predict_net.external_input, tensor_inputs) } predict_net_device_types = infer_device_type( predict_net, known_status=predict_net_input_device_types, device_name_style="pytorch" ) predict_net_ssa, _ = core.get_ssa(predict_net) _assign_op_device_option(predict_net, predict_net_ssa, predict_net_device_types) # update ops in init_net init_net_ssa, versions = core.get_ssa(init_net) init_net_output_device_types = { (name, versions[name]): predict_net_device_types[(name, 0)] for name in init_net.external_output } init_net_device_types = infer_device_type( init_net, known_status=init_net_output_device_types, device_name_style="pytorch" ) _assign_op_device_option(init_net, init_net_ssa, init_net_device_types) def construct_init_net_from_params( params: Dict[str, Any], device_options: Optional[Dict[str, caffe2_pb2.DeviceOption]] = None ) -> caffe2_pb2.NetDef: """ Construct the init_net from params dictionary """ init_net = caffe2_pb2.NetDef() device_options = device_options or {} for name, blob in params.items(): if isinstance(blob, str): logger.warning( ( "Blob {} with type {} is not supported in generating init net," " skipped.".format(name, type(blob)) ) ) continue init_net.op.extend( [create_const_fill_op(name, blob, device_option=device_options.get(name, None))] ) init_net.external_output.append(name) return init_net def get_params_from_init_net( init_net: caffe2_pb2.NetDef, ) -> [Dict[str, Any], Dict[str, caffe2_pb2.DeviceOption]]: """ Take the output blobs from init_net by running it. Outputs: params: dict from blob name to numpy array device_options: dict from blob name to the device option of its creating op """ # NOTE: this assumes that the params is determined by producer op with the # only exception be CopyGPUToCPU which is CUDA op but returns CPU tensor. def _get_device_option(producer_op): if producer_op.type == "CopyGPUToCPU": return caffe2_pb2.DeviceOption() else: return producer_op.device_option with ScopedWS("__get_params_from_init_net__", is_reset=True, is_cleanup=True) as ws: ws.RunNetOnce(init_net) params = {b: fetch_any_blob(b) for b in init_net.external_output} ssa, versions = core.get_ssa(init_net) producer_map = get_producer_map(ssa) device_options = { b: _get_device_option(init_net.op[producer_map[(b, versions[b])][0]]) for b in init_net.external_output } return params, device_options def group_norm_replace_aten_with_caffe2(predict_net: caffe2_pb2.NetDef): """ For ONNX exported model, GroupNorm will be represented as ATen op, this can be a drop in replacement from ATen to GroupNorm """ count = 0 for op in predict_net.op: if op.type == "ATen": op_name = get_pb_arg_vals(op, "operator", None) # return byte in py3 if op_name and op_name.decode() == "group_norm": op.arg.remove(get_pb_arg(op, "operator")) if get_pb_arg_vali(op, "cudnn_enabled", None): op.arg.remove(get_pb_arg(op, "cudnn_enabled")) num_groups = get_pb_arg_vali(op, "num_groups", None) if num_groups is not None: op.arg.remove(get_pb_arg(op, "num_groups")) check_set_pb_arg(op, "group", "i", num_groups) op.type = "GroupNorm" count += 1 if count > 1: logger.info("Replaced {} ATen operator to GroupNormOp".format(count)) def fuse_alias_placeholder(predict_net, init_net): """Remove AliasWithName placeholder and rename the input/output of it""" # First we finish all the re-naming for i, op in enumerate(predict_net.op): if op.type == "AliasWithName": assert len(op.input) == 1 assert len(op.output) == 1 name = get_pb_arg_vals(op, "name", None).decode() is_backward = bool(get_pb_arg_vali(op, "is_backward", 0)) rename_op_input(predict_net, init_net, i, 0, name, from_producer=is_backward) rename_op_output(predict_net, i, 0, name) # Remove AliasWithName, should be very safe since it's a non-op new_ops = [] for op in predict_net.op: if op.type != "AliasWithName": new_ops.append(op) else: # safety check assert op.input == op.output assert op.input[0] == op.arg[0].s.decode() del predict_net.op[:] predict_net.op.extend(new_ops) def remove_reshape_for_fc(predict_net, params): """ In PyTorch nn.Linear has to take 2D tensor, this often leads to reshape a 4D tensor to 2D by calling .view(). However this (dynamic) reshaping doesn't work well with ONNX and Int8 tools, and cause using extra ops (eg. ExpandDims) that might not be available on mobile. Luckily Caffe2 supports 4D tensor for FC, so we can remove those reshape after exporting ONNX model. """ from caffe2.python import core # find all reshape sub-graph that can be removed, which is now all Reshape # sub-graph whose output is only consumed by FC. # TODO: to make it safer, we may need the actually value to better determine # if a Reshape before FC is removable. reshape_sub_graphs = identify_reshape_sub_graph(predict_net) sub_graphs_to_remove = [] for reshape_sub_graph in reshape_sub_graphs: reshape_op_id = reshape_sub_graph[-1] assert predict_net.op[reshape_op_id].type == "Reshape" ssa, _ = core.get_ssa(predict_net) reshape_output = ssa[reshape_op_id][1][0] consumers = [i for i in range(len(ssa)) if reshape_output in ssa[i][0]] if all(predict_net.op[consumer].type == "FC" for consumer in consumers): # safety check if the sub-graph is isolated, for this reshape sub-graph, # it means it has one non-param external input and one external output. ext_inputs, ext_outputs = get_sub_graph_external_input_output( predict_net, reshape_sub_graph ) non_params_ext_inputs = [inp for inp in ext_inputs if inp[1] != 0] if len(non_params_ext_inputs) == 1 and len(ext_outputs) == 1: sub_graphs_to_remove.append(reshape_sub_graph) # perform removing subgraph by: # 1: rename the Reshape's output to its input, then the graph can be # seen as in-place itentify, meaning whose external input/output are the same. # 2: simply remove those ops. remove_op_ids = [] params_to_remove = [] for sub_graph in sub_graphs_to_remove: logger.info( "Remove Reshape sub-graph:\n{}".format( "".join(["(#{:>4})\n{}".format(i, predict_net.op[i]) for i in sub_graph]) ) ) reshape_op_id = sub_graph[-1] new_reshap_output = predict_net.op[reshape_op_id].input[0] rename_op_output(predict_net, reshape_op_id, 0, new_reshap_output) ext_inputs, ext_outputs = get_sub_graph_external_input_output(predict_net, sub_graph) non_params_ext_inputs = [inp for inp in ext_inputs if inp[1] != 0] params_ext_inputs = [inp for inp in ext_inputs if inp[1] == 0] assert len(non_params_ext_inputs) == 1 and len(ext_outputs) == 1 assert ext_outputs[0][0] == non_params_ext_inputs[0][0] assert ext_outputs[0][1] == non_params_ext_inputs[0][1] + 1 remove_op_ids.extend(sub_graph) params_to_remove.extend(params_ext_inputs) predict_net = copy.deepcopy(predict_net) new_ops = [op for i, op in enumerate(predict_net.op) if i not in remove_op_ids] del predict_net.op[:] predict_net.op.extend(new_ops) for versioned_params in params_to_remove: name = versioned_params[0] logger.info("Remove params: {} from init_net and predict_net.external_input".format(name)) del params[name] predict_net.external_input.remove(name) return predict_net, params def fuse_copy_between_cpu_and_gpu(predict_net: caffe2_pb2.NetDef): """ In-place fuse extra copy ops between cpu/gpu for the following case: a -CopyAToB-> b -CopyBToA> c1 -NextOp1-> d1 -CopyBToA> c2 -NextOp2-> d2 The fused network will look like: a -NextOp1-> d1 -NextOp2-> d2 """ _COPY_OPS = ["CopyCPUToGPU", "CopyGPUToCPU"] def _fuse_once(predict_net): ssa, blob_versions = core.get_ssa(predict_net) consumer_map = get_consumer_map(ssa) versioned_external_output = [ (name, blob_versions[name]) for name in predict_net.external_output ] for op_id, op in enumerate(predict_net.op): if op.type in _COPY_OPS: fw_copy_versioned_output = ssa[op_id][1][0] consumer_ids = [x[0] for x in consumer_map[fw_copy_versioned_output]] reverse_op_type = _COPY_OPS[1 - _COPY_OPS.index(op.type)] is_fusable = ( len(consumer_ids) > 0 and fw_copy_versioned_output not in versioned_external_output and all( predict_net.op[_op_id].type == reverse_op_type and ssa[_op_id][1][0] not in versioned_external_output for _op_id in consumer_ids ) ) if is_fusable: for rv_copy_op_id in consumer_ids: # making each NextOp uses "a" directly and removing Copy ops rs_copy_versioned_output = ssa[rv_copy_op_id][1][0] next_op_id, inp_id = consumer_map[rs_copy_versioned_output][0] predict_net.op[next_op_id].input[inp_id] = op.input[0] # remove CopyOps new_ops = [ op for i, op in enumerate(predict_net.op) if i != op_id and i not in consumer_ids ] del predict_net.op[:] predict_net.op.extend(new_ops) return True return False # _fuse_once returns False is nothing can be fused while _fuse_once(predict_net): pass def remove_dead_end_ops(net_def: caffe2_pb2.NetDef): """remove ops if its output is not used or not in external_output""" ssa, versions = core.get_ssa(net_def) versioned_external_output = [(name, versions[name]) for name in net_def.external_output] consumer_map = get_consumer_map(ssa) removed_op_ids = set() def _is_dead_end(versioned_blob): return not ( versioned_blob in versioned_external_output or ( len(consumer_map[versioned_blob]) > 0 and all(x[0] not in removed_op_ids for x in consumer_map[versioned_blob]) ) ) for i, ssa_i in reversed(list(enumerate(ssa))): versioned_outputs = ssa_i[1] if all(_is_dead_end(outp) for outp in versioned_outputs): removed_op_ids.add(i) # simply removing those deadend ops should have no effect to external_output new_ops = [op for i, op in enumerate(net_def.op) if i not in removed_op_ids] del net_def.op[:] net_def.op.extend(new_ops) The provided code snippet includes necessary dependencies for implementing the `export_caffe2_detection_model` function. Write a Python function `def export_caffe2_detection_model(model: torch.nn.Module, tensor_inputs: List[torch.Tensor])` to solve the following problem: 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. Here is the function: def export_caffe2_detection_model(model: torch.nn.Module, tensor_inputs: List[torch.Tensor]): """ 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. """ model = copy.deepcopy(model) assert isinstance(model, torch.nn.Module) assert hasattr(model, "encode_additional_info") # Export via ONNX logger.info( "Exporting a {} model via ONNX ...".format(type(model).__name__) + " Some warnings from ONNX are expected and are usually not to worry about." ) onnx_model = export_onnx_model(model, (tensor_inputs,)) # Convert ONNX model to Caffe2 protobuf init_net, predict_net = Caffe2Backend.onnx_graph_to_caffe2_net(onnx_model) ops_table = [[op.type, op.input, op.output] for op in predict_net.op] table = tabulate(ops_table, headers=["type", "input", "output"], tablefmt="pipe") logger.info( "ONNX export Done. Exported predict_net (before optimizations):\n" + colored(table, "cyan") ) # Apply protobuf optimization fuse_alias_placeholder(predict_net, init_net) if any(t.device.type != "cpu" for t in tensor_inputs): fuse_copy_between_cpu_and_gpu(predict_net) remove_dead_end_ops(init_net) _assign_device_option(predict_net, init_net, tensor_inputs) params, device_options = get_params_from_init_net(init_net) predict_net, params = remove_reshape_for_fc(predict_net, params) init_net = construct_init_net_from_params(params, device_options) group_norm_replace_aten_with_caffe2(predict_net) # Record necessary information for running the pb model in Detectron2 system. model.encode_additional_info(predict_net, init_net) logger.info("Operators used in predict_net: \n{}".format(_op_stats(predict_net))) logger.info("Operators used in init_net: \n{}".format(_op_stats(init_net))) return predict_net, init_net
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 OperatorExportTypes from .shared import ( ScopedWS, construct_init_net_from_params, fuse_alias_placeholder, fuse_copy_between_cpu_and_gpu, get_params_from_init_net, group_norm_replace_aten_with_caffe2, infer_device_type, remove_dead_end_ops, remove_reshape_for_fc, save_graph, ) logger = logging.getLogger(__name__) class ScopedWS(object): def __init__(self, ws_name, is_reset, is_cleanup=False): self.ws_name = ws_name self.is_reset = is_reset self.is_cleanup = is_cleanup self.org_ws = "" def __enter__(self): self.org_ws = workspace.CurrentWorkspace() if self.ws_name is not None: workspace.SwitchWorkspace(self.ws_name, True) if self.is_reset: workspace.ResetWorkspace() return workspace def __exit__(self, *args): if self.is_cleanup: workspace.ResetWorkspace() if self.ws_name is not None: workspace.SwitchWorkspace(self.org_ws) def save_graph(net, file_name, graph_name="net", op_only=True, blob_sizes=None, blob_ranges=None): blob_rename_f = functools.partial(_rename_blob, blob_sizes=blob_sizes, blob_ranges=blob_ranges) return save_graph_base(net, file_name, graph_name, op_only, blob_rename_f) The provided code snippet includes necessary dependencies for implementing the `run_and_save_graph` function. Write a Python function `def run_and_save_graph(predict_net, init_net, tensor_inputs, graph_save_path)` to solve the following problem: 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. Here is the function: def run_and_save_graph(predict_net, init_net, tensor_inputs, graph_save_path): """ 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. """ logger.info("Saving graph of ONNX exported model to {} ...".format(graph_save_path)) save_graph(predict_net, graph_save_path, op_only=False) # Run the exported Caffe2 net logger.info("Running ONNX exported model ...") with ScopedWS("__ws_tmp__", True) as ws: ws.RunNetOnce(init_net) initialized_blobs = set(ws.Blobs()) uninitialized = [inp for inp in predict_net.external_input if inp not in initialized_blobs] for name, blob in zip(uninitialized, tensor_inputs): ws.FeedBlob(name, blob) try: ws.RunNetOnce(predict_net) except RuntimeError as e: logger.warning("Encountered RuntimeError: \n{}".format(str(e))) ws_blobs = {b: ws.FetchBlob(b) for b in ws.Blobs()} blob_sizes = {b: ws_blobs[b].shape for b in ws_blobs if isinstance(ws_blobs[b], np.ndarray)} logger.info("Saving graph with blob shapes to {} ...".format(graph_save_path)) save_graph(predict_net, graph_save_path, op_only=False, blob_sizes=blob_sizes) return ws_blobs
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_pb2 from caffe2.python import core, net_drawer, workspace from torch.nn.functional import interpolate as interp def onnx_compatibale_interpolate( input, size=None, scale_factor=None, mode="nearest", align_corners=None ): def mock_torch_nn_functional_interpolate(): if torch.onnx.is_in_onnx_export(): with mock.patch( "torch.nn.functional.interpolate", side_effect=onnx_compatibale_interpolate ): yield else: yield
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_pb2 from caffe2.python import core, net_drawer, workspace from torch.nn.functional import interpolate as interp def get_pb_arg(pb, arg_name): for x in pb.arg: if x.name == arg_name: return x return None def get_pb_arg_valf(pb, arg_name, default_val): arg = get_pb_arg(pb, arg_name) return arg.f if arg is not None else default_val
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_pb2 from caffe2.python import core, net_drawer, workspace from torch.nn.functional import interpolate as interp def get_pb_arg(pb, arg_name): for x in pb.arg: if x.name == arg_name: return x return None def get_pb_arg_floats(pb, arg_name, default_val): arg = get_pb_arg(pb, arg_name) return list(map(float, arg.floats)) if arg is not None else default_val
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_pb2 from caffe2.python import core, net_drawer, workspace from torch.nn.functional import interpolate as interp def get_pb_arg(pb, arg_name): for x in pb.arg: if x.name == arg_name: return x return None def get_pb_arg_ints(pb, arg_name, default_val): arg = get_pb_arg(pb, arg_name) return list(map(int, arg.ints)) if arg is not None else default_val
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_pb2 from caffe2.python import core, net_drawer, workspace from torch.nn.functional import interpolate as interp def get_pb_arg(pb, arg_name): for x in pb.arg: if x.name == arg_name: return x return None def get_pb_arg_valstrings(pb, arg_name, default_val): arg = get_pb_arg(pb, arg_name) return list(arg.strings) if arg is not None else default_val
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_pb2 from caffe2.python import core, net_drawer, workspace from torch.nn.functional import interpolate as interp def alias(x, name, is_backward=False): if not torch.onnx.is_in_onnx_export(): return x assert isinstance(x, torch.Tensor) return torch.ops._caffe2.AliasWithName(x, name, is_backward=is_backward)
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 `fields`. See more in `scripting_with_instances`. """ with tempfile.TemporaryDirectory(prefix="detectron2") as dir, tempfile.NamedTemporaryFile( mode="w", encoding="utf-8", suffix=".py", dir=dir, delete=False ) as f: try: # Objects that use Instances should not reuse previously-compiled # results in cache, because `Instances` could be a new class each time. _clear_jit_cache() cls_name, s = _gen_instance_module(fields) f.write(s) f.flush() f.close() module = _import(f.name) new_instances = getattr(module, cls_name) _ = torch.jit.script(new_instances) # let torchscript think Instances was scripted already Instances.__torch_script_class__ = True # let torchscript find new_instances when looking for the jit type of Instances Instances._jit_override_qualname = torch._jit_internal._qualified_name(new_instances) _add_instances_conversion_methods(new_instances) yield new_instances finally: try: del Instances.__torch_script_class__ del Instances._jit_override_qualname except AttributeError: pass sys.modules.pop(module.__name__) def freeze_training_mode(model): """ A context manager that annotates the "training" attribute of every submodule to constant, so that the training codepath in these modules can be meta-compiled away. Upon exiting, the annotations are reverted. """ classes = {type(x) for x in model.modules()} # __constants__ is the old way to annotate constants and not compatible # with __annotations__ . classes = {x for x in classes if not hasattr(x, "__constants__")} for cls in classes: cls.__annotations__["training"] = torch.jit.Final[bool] yield for cls in classes: cls.__annotations__["training"] = bool The provided code snippet includes necessary dependencies for implementing the `scripting_with_instances` function. Write a Python function `def scripting_with_instances(model, fields)` to solve the following problem: 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: 1. Create a scriptable ``new_Instances`` class which behaves similarly to ``Instances``, but with all attributes been "static". The attributes need to be statically declared in the ``fields`` argument. 2. Register ``new_Instances``, and force scripting compiler to use it when trying to compile ``Instances``. After this function, the process will be reverted. User should be able to script another model using different fields. Example: Assume that ``Instances`` in the model consist of two attributes named ``proposal_boxes`` and ``objectness_logits`` with type :class:`Boxes` and :class:`Tensor` respectively during inference. You can call this function like: :: fields = {"proposal_boxes": Boxes, "objectness_logits": torch.Tensor} torchscipt_model = scripting_with_instances(model, fields) Note: It only support models in evaluation mode. Args: model (nn.Module): The input model to be exported by scripting. fields (Dict[str, type]): Attribute names and corresponding type that ``Instances`` will use in the model. Note that all attributes used in ``Instances`` need to be added, regardless of whether they are inputs/outputs of the model. Data type not defined in detectron2 is not supported for now. Returns: torch.jit.ScriptModule: the model in torchscript format Here is the function: def scripting_with_instances(model, fields): """ 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: 1. Create a scriptable ``new_Instances`` class which behaves similarly to ``Instances``, but with all attributes been "static". The attributes need to be statically declared in the ``fields`` argument. 2. Register ``new_Instances``, and force scripting compiler to use it when trying to compile ``Instances``. After this function, the process will be reverted. User should be able to script another model using different fields. Example: Assume that ``Instances`` in the model consist of two attributes named ``proposal_boxes`` and ``objectness_logits`` with type :class:`Boxes` and :class:`Tensor` respectively during inference. You can call this function like: :: fields = {"proposal_boxes": Boxes, "objectness_logits": torch.Tensor} torchscipt_model = scripting_with_instances(model, fields) Note: It only support models in evaluation mode. Args: model (nn.Module): The input model to be exported by scripting. fields (Dict[str, type]): Attribute names and corresponding type that ``Instances`` will use in the model. Note that all attributes used in ``Instances`` need to be added, regardless of whether they are inputs/outputs of the model. Data type not defined in detectron2 is not supported for now. Returns: torch.jit.ScriptModule: the model in torchscript format """ assert ( not model.training ), "Currently we only support exporting models in evaluation mode to torchscript" with freeze_training_mode(model), patch_instances(fields): scripted_model = torch.jit.script(model) return scripted_model
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: 1. Create a scriptable ``new_Instances`` class which behaves similarly to ``Instances``, but with all attributes been "static". The attributes need to be statically declared in the ``fields`` argument. 2. Register ``new_Instances``, and force scripting compiler to use it when trying to compile ``Instances``. After this function, the process will be reverted. User should be able to script another model using different fields. Example: Assume that ``Instances`` in the model consist of two attributes named ``proposal_boxes`` and ``objectness_logits`` with type :class:`Boxes` and :class:`Tensor` respectively during inference. You can call this function like: :: fields = {"proposal_boxes": Boxes, "objectness_logits": torch.Tensor} torchscipt_model = scripting_with_instances(model, fields) Note: It only support models in evaluation mode. Args: model (nn.Module): The input model to be exported by scripting. fields (Dict[str, type]): Attribute names and corresponding type that ``Instances`` will use in the model. Note that all attributes used in ``Instances`` need to be added, regardless of whether they are inputs/outputs of the model. Data type not defined in detectron2 is not supported for now. Returns: torch.jit.ScriptModule: the model in torchscript format
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(Detectron2Handler()) The provided code snippet includes necessary dependencies for implementing the `dump_torchscript_IR` function. Write a Python function `def dump_torchscript_IR(model, dir)` to solve the following problem: 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. Here is the function: def dump_torchscript_IR(model, dir): """ 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. """ dir = os.path.expanduser(dir) PathManager.mkdirs(dir) def _get_script_mod(mod): if isinstance(mod, torch.jit.TracedModule): return mod._actual_script_module return mod # Dump pretty-printed code: https://pytorch.org/docs/stable/jit.html#inspecting-code with PathManager.open(os.path.join(dir, "model_ts_code.txt"), "w") as f: def get_code(mod): # Try a few ways to get code using private attributes. try: # This contains more information than just `mod.code` return _get_script_mod(mod)._c.code except AttributeError: pass try: return mod.code except AttributeError: return None def dump_code(prefix, mod): code = get_code(mod) name = prefix or "root model" if code is None: f.write(f"Could not found code for {name} (type={mod.original_name})\n") f.write("\n") else: f.write(f"\nCode for {name}, type={mod.original_name}:\n") f.write(code) f.write("\n") f.write("-" * 80) for name, m in mod.named_children(): dump_code(prefix + "." + name, m) if isinstance(model, torch.jit.ScriptFunction): f.write(get_code(model)) else: dump_code("", model) def _get_graph(model): try: # Recursively dump IR of all modules return _get_script_mod(model)._c.dump_to_str(True, False, False) except AttributeError: return model.graph.str() with PathManager.open(os.path.join(dir, "model_ts_IR.txt"), "w") as f: f.write(_get_graph(model)) # Dump IR of the entire graph (all submodules inlined) with PathManager.open(os.path.join(dir, "model_ts_IR_inlined.txt"), "w") as f: f.write(str(model.inlined_graph)) if not isinstance(model, torch.jit.ScriptFunction): # Dump the model structure in pytorch style with PathManager.open(os.path.join(dir, "model.txt"), "w") as f: f.write(str(model))
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 config object for a model in model zoo. 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): If True, will set ``MODEL.WEIGHTS`` to trained model zoo weights. If False, the checkpoint specified in the config file's ``MODEL.WEIGHTS`` is used instead; this will typically (though not always) initialize a subset of weights using an ImageNet pre-trained model, while randomly initializing the other weights. Returns: CfgNode or omegaconf.DictConfig: a config object """ cfg_file = get_config_file(config_path) if cfg_file.endswith(".yaml"): cfg = get_cfg() cfg.merge_from_file(cfg_file) if trained: cfg.MODEL.WEIGHTS = get_checkpoint_url(config_path) return cfg elif cfg_file.endswith(".py"): cfg = LazyConfig.load(cfg_file) if trained: url = get_checkpoint_url(config_path) if "train" in cfg and "init_checkpoint" in cfg.train: cfg.train.init_checkpoint = url else: raise NotImplementedError return cfg def instantiate(cfg): """ Recursively instantiate objects defined in dictionaries by "_target_" and arguments. Args: cfg: a dict-like object with "_target_" that defines the caller, and other keys that define the arguments Returns: object instantiated by cfg """ from omegaconf import ListConfig if isinstance(cfg, ListConfig): lst = [instantiate(x) for x in cfg] return ListConfig(lst, flags={"allow_objects": True}) if isinstance(cfg, list): # Specialize for list, because many classes take # list[objects] as arguments, such as ResNet, DatasetMapper return [instantiate(x) for x in cfg] if isinstance(cfg, abc.Mapping) and "_target_" in cfg: # conceptually equivalent to hydra.utils.instantiate(cfg) with _convert_=all, # but faster: https://github.com/facebookresearch/hydra/issues/1200 cfg = {k: instantiate(v) for k, v in cfg.items()} cls = cfg.pop("_target_") cls = instantiate(cls) if isinstance(cls, str): cls_name = cls cls = locate(cls_name) assert cls is not None, cls_name else: try: cls_name = cls.__module__ + "." + cls.__qualname__ except Exception: # target could be anything, so the above could fail cls_name = str(cls) assert callable(cls), f"_target_ {cls} does not define a callable object" try: return cls(**cfg) except TypeError: logger = logging.getLogger(__name__) logger.error(f"Error when instantiating {cls_name}!") raise return cfg # return as-is if don't know what to do The provided code snippet includes necessary dependencies for implementing the `get` function. Write a Python function `def get(config_path, trained: bool = False, device: Optional[str] = None)` to solve the following problem: 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 device in config, if given. Returns: nn.Module: a detectron2 model. Will be in training mode. Example: :: from detectron2 import model_zoo model = model_zoo.get("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml", trained=True) Here is the function: def get(config_path, trained: bool = False, device: Optional[str] = None): """ 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 device in config, if given. Returns: nn.Module: a detectron2 model. Will be in training mode. Example: :: from detectron2 import model_zoo model = model_zoo.get("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml", trained=True) """ cfg = get_config(config_path, trained) if device is None and not torch.cuda.is_available(): device = "cpu" if device is not None and isinstance(cfg, CfgNode): cfg.MODEL.DEVICE = device if isinstance(cfg, CfgNode): model = build_model(cfg) DetectionCheckpointer(model).load(cfg.MODEL.WEIGHTS) else: model = instantiate(cfg.model) if device is not None: model = model.to(device) if "train" in cfg and "init_checkpoint" in cfg.train: DetectionCheckpointer(model).load(cfg.train.init_checkpoint) return model
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 device in config, if given. Returns: nn.Module: a detectron2 model. Will be in training mode. Example: :: from detectron2 import model_zoo model = model_zoo.get("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml", trained=True)
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 the following problem: 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. Here is the function: def shapes_to_tensor(x: List[int], device: Optional[torch.device] = None) -> torch.Tensor: """ 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. """ if torch.jit.is_scripting(): return torch.as_tensor(x, device=device) if torch.jit.is_tracing(): assert all( [isinstance(t, torch.Tensor) for t in x] ), "Shape should be tensor during tracing!" # as_tensor should not be used in tracing because it records a constant ret = torch.stack(x) if ret.device != device: # avoid recording a hard-coded device if not necessary ret = ret.to(device=device) return ret return torch.as_tensor(x, device=device)
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 that avoids a copy if there is only a single element in a list Here is the function: def cat(tensors: List[torch.Tensor], dim: int = 0): """ Efficient version of torch.cat that avoids a copy if there is only a single element in a list """ assert isinstance(tensors, (list, tuple)) if len(tensors) == 1: return tensors[0] return torch.cat(tensors, dim)
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 `torch.nn.functional.cross_entropy`, but returns 0 (instead of nan) for empty inputs. Here is the function: def cross_entropy(input, target, *, reduction="mean", **kwargs): """ Same as `torch.nn.functional.cross_entropy`, but returns 0 (instead of nan) for empty inputs. """ if target.numel() == 0 and reduction == "mean": return input.sum() * 0.0 # connect the gradient return F.cross_entropy(input, target, reduction=reduction, **kwargs)
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 support torchscript. because of https://github.com/pytorch/pytorch/issues/38718 Here is the 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 """ if torch.jit.is_scripting(): if x.dim() == 0: return x.unsqueeze(0).nonzero().unbind(1) return x.nonzero().unbind(1) else: return x.nonzero(as_tuple=True)
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 will be summed. eps (float): small number to prevent division by zero Here is the function: def diou_loss( boxes1: torch.Tensor, boxes2: torch.Tensor, reduction: str = "none", eps: float = 1e-7, ) -> torch.Tensor: """ 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 will be summed. eps (float): small number to prevent division by zero """ x1, y1, x2, y2 = boxes1.unbind(dim=-1) x1g, y1g, x2g, y2g = boxes2.unbind(dim=-1) # TODO: use torch._assert_async() when pytorch 1.8 support is dropped assert (x2 >= x1).all(), "bad box: x1 larger than x2" assert (y2 >= y1).all(), "bad box: y1 larger than y2" # Intersection keypoints xkis1 = torch.max(x1, x1g) ykis1 = torch.max(y1, y1g) xkis2 = torch.min(x2, x2g) ykis2 = torch.min(y2, y2g) intsct = torch.zeros_like(x1) mask = (ykis2 > ykis1) & (xkis2 > xkis1) intsct[mask] = (xkis2[mask] - xkis1[mask]) * (ykis2[mask] - ykis1[mask]) union = (x2 - x1) * (y2 - y1) + (x2g - x1g) * (y2g - y1g) - intsct + eps iou = intsct / union # smallest enclosing box xc1 = torch.min(x1, x1g) yc1 = torch.min(y1, y1g) xc2 = torch.max(x2, x2g) yc2 = torch.max(y2, y2g) diag_len = ((xc2 - xc1) ** 2) + ((yc2 - yc1) ** 2) + eps # centers of boxes x_p = (x2 + x1) / 2 y_p = (y2 + y1) / 2 x_g = (x1g + x2g) / 2 y_g = (y1g + y2g) / 2 distance = ((x_p - x_g) ** 2) + ((y_p - y_g) ** 2) # Eqn. (7) loss = 1 - iou + (distance / diag_len) if reduction == "mean": loss = loss.mean() if loss.numel() > 0 else 0.0 * loss.sum() elif reduction == "sum": loss = loss.sum() return loss
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 will be summed. eps (float): small number to prevent division by zero
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 will be summed. eps (float): small number to prevent division by zero Here is the function: def ciou_loss( boxes1: torch.Tensor, boxes2: torch.Tensor, reduction: str = "none", eps: float = 1e-7, ) -> torch.Tensor: """ 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 will be summed. eps (float): small number to prevent division by zero """ x1, y1, x2, y2 = boxes1.unbind(dim=-1) x1g, y1g, x2g, y2g = boxes2.unbind(dim=-1) # TODO: use torch._assert_async() when pytorch 1.8 support is dropped assert (x2 >= x1).all(), "bad box: x1 larger than x2" assert (y2 >= y1).all(), "bad box: y1 larger than y2" # Intersection keypoints xkis1 = torch.max(x1, x1g) ykis1 = torch.max(y1, y1g) xkis2 = torch.min(x2, x2g) ykis2 = torch.min(y2, y2g) intsct = torch.zeros_like(x1) mask = (ykis2 > ykis1) & (xkis2 > xkis1) intsct[mask] = (xkis2[mask] - xkis1[mask]) * (ykis2[mask] - ykis1[mask]) union = (x2 - x1) * (y2 - y1) + (x2g - x1g) * (y2g - y1g) - intsct + eps iou = intsct / union # smallest enclosing box xc1 = torch.min(x1, x1g) yc1 = torch.min(y1, y1g) xc2 = torch.max(x2, x2g) yc2 = torch.max(y2, y2g) diag_len = ((xc2 - xc1) ** 2) + ((yc2 - yc1) ** 2) + eps # centers of boxes x_p = (x2 + x1) / 2 y_p = (y2 + y1) / 2 x_g = (x1g + x2g) / 2 y_g = (y1g + y2g) / 2 distance = ((x_p - x_g) ** 2) + ((y_p - y_g) ** 2) # width and height of boxes w_pred = x2 - x1 h_pred = y2 - y1 w_gt = x2g - x1g h_gt = y2g - y1g v = (4 / (math.pi ** 2)) * torch.pow((torch.atan(w_gt / h_gt) - torch.atan(w_pred / h_pred)), 2) with torch.no_grad(): alpha = v / (1 - iou + v + eps) # Eqn. (10) loss = 1 - iou + (distance / diag_len) + alpha * v if reduction == "mean": loss = loss.mean() if loss.numel() > 0 else 0.0 * loss.sum() elif reduction == "sum": loss = loss.sum() return loss
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 will be summed. eps (float): small number to prevent division by zero
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: float )` to solve the following problem: Same as torchvision.ops.boxes.batched_nms, but with float(). Here is the function: def batched_nms( boxes: torch.Tensor, scores: torch.Tensor, idxs: torch.Tensor, iou_threshold: float ): """ Same as torchvision.ops.boxes.batched_nms, but with float(). """ assert boxes.shape[-1] == 4 # Note: Torchvision already has a strategy (https://github.com/pytorch/vision/issues/1311) # to decide whether to use coordinate trick or for loop to implement batched_nms. So we # just call it directly. # Fp16 does not have enough range for batched NMS, so adding float(). return box_ops.batched_nms(boxes.float(), scores, idxs, iou_threshold)
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 rotated boxes which have an IoU greater than iou_threshold with another (higher scoring) rotated box. Note that RotatedBox (5, 3, 4, 2, -90) covers exactly the same region as RotatedBox (5, 3, 4, 2, 90) does, and their IoU will be 1. However, they can be representing completely different objects in certain tasks, e.g., OCR. As for the question of whether rotated-NMS should treat them as faraway boxes even though their IOU is 1, it depends on the application and/or ground truth annotation. As an extreme example, consider a single character v and the square box around it. If the angle is 0 degree, the object (text) would be read as 'v'; If the angle is 90 degrees, the object (text) would become '>'; If the angle is 180 degrees, the object (text) would become '^'; If the angle is 270/-90 degrees, the object (text) would become '<' All of these cases have IoU of 1 to each other, and rotated NMS that only uses IoU as criterion would only keep one of them with the highest score - which, practically, still makes sense in most cases because typically only one of theses orientations is the correct one. Also, it does not matter as much if the box is only used to classify the object (instead of transcribing them with a sequential OCR recognition model) later. On the other hand, when we use IoU to filter proposals that are close to the ground truth during training, we should definitely take the angle into account if we know the ground truth is labeled with the strictly correct orientation (as in, upside-down words are annotated with -180 degrees even though they can be covered with a 0/90/-90 degree box, etc.) The way the original dataset is annotated also matters. For example, if the dataset is a 4-point polygon dataset that does not enforce ordering of vertices/orientation, we can estimate a minimum rotated bounding box to this polygon, but there's no way we can tell the correct angle with 100% confidence (as shown above, there could be 4 different rotated boxes, with angles differed by 90 degrees to each other, covering the exactly same region). In that case we have to just use IoU to determine the box proximity (as many detection benchmarks (even for text) do) unless there're other assumptions we can make (like width is always larger than height, or the object is not rotated by more than 90 degrees CCW/CW, etc.) In summary, not considering angles in rotated NMS seems to be a good option for now, but we should be aware of its implications. Args: boxes (Tensor[N, 5]): Rotated boxes to perform NMS on. They are expected to be in (x_center, y_center, width, height, angle_degrees) format. scores (Tensor[N]): Scores for each one of the rotated boxes iou_threshold (float): Discards all overlapping rotated boxes with IoU < iou_threshold Returns: keep (Tensor): int64 tensor with the indices of the elements that have been kept by Rotated NMS, sorted in decreasing order of scores """ return torch.ops.detectron2.nms_rotated(boxes, scores, iou_threshold) The provided code snippet includes necessary dependencies for implementing the `batched_nms_rotated` function. Write a Python function `def batched_nms_rotated(boxes, scores, idxs, iou_threshold)` to solve the following problem: 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 (Tensor[N]): scores for each one of the boxes idxs (Tensor[N]): indices of the categories for each one of the boxes. iou_threshold (float): discards all overlapping boxes with IoU < iou_threshold Returns: Tensor: int64 tensor with the indices of the elements that have been kept by NMS, sorted in decreasing order of scores Here is the function: def batched_nms_rotated(boxes, scores, idxs, iou_threshold): """ 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 (Tensor[N]): scores for each one of the boxes idxs (Tensor[N]): indices of the categories for each one of the boxes. iou_threshold (float): discards all overlapping boxes with IoU < iou_threshold Returns: Tensor: int64 tensor with the indices of the elements that have been kept by NMS, sorted in decreasing order of scores """ assert boxes.shape[-1] == 5 if boxes.numel() == 0: return torch.empty((0,), dtype=torch.int64, device=boxes.device) boxes = boxes.float() # fp16 does not have enough range for batched NMS # Strategy: in order to perform NMS independently per class, # we add an offset to all the boxes. The offset is dependent # only on the class idx, and is large enough so that boxes # from different classes do not overlap # Note that batched_nms in torchvision/ops/boxes.py only uses max_coordinate, # which won't handle negative coordinates correctly. # Here by using min_coordinate we can make sure the negative coordinates are # correctly handled. max_coordinate = ( torch.max(boxes[:, 0], boxes[:, 1]) + torch.max(boxes[:, 2], boxes[:, 3]) / 2 ).max() min_coordinate = ( torch.min(boxes[:, 0], boxes[:, 1]) - torch.max(boxes[:, 2], boxes[:, 3]) / 2 ).min() offsets = idxs.to(boxes) * (max_coordinate - min_coordinate + 1) boxes_for_nms = boxes.clone() # avoid modifying the original values in boxes boxes_for_nms[:, :2] += offsets[:, None] keep = nms_rotated(boxes_for_nms, scores, iou_threshold) return keep
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 (Tensor[N]): scores for each one of the boxes idxs (Tensor[N]): indices of the categories for each one of the boxes. iou_threshold (float): discards all overlapping boxes with IoU < iou_threshold Returns: Tensor: int64 tensor with the indices of the elements that have been kept by NMS, sorted in decreasing order of scores
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)` to solve the following problem: 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]. box (Tensor): A tensor of shape (4, ) storing the x0, y0, x1, y1 box corners of the object instance. img_h, img_w (int): Image height and width. threshold (float): Mask binarization threshold in [0, 1]. Returns: im_mask (Tensor): The resized and binarized object mask pasted into the original image plane (a tensor of shape (img_h, img_w)). Here is the 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]. box (Tensor): A tensor of shape (4, ) storing the x0, y0, x1, y1 box corners of the object instance. img_h, img_w (int): Image height and width. threshold (float): Mask binarization threshold in [0, 1]. Returns: im_mask (Tensor): The resized and binarized object mask pasted into the original image plane (a tensor of shape (img_h, img_w)). """ # Conversion from continuous box coordinates to discrete pixel coordinates # via truncation (cast to int32). This determines which pixels to paste the # mask onto. box = box.to(dtype=torch.int32) # Continuous to discrete coordinate conversion # An example (1D) box with continuous coordinates (x0=0.7, x1=4.3) will map to # a discrete coordinates (x0=0, x1=4). Note that box is mapped to 5 = x1 - x0 + 1 # pixels (not x1 - x0 pixels). samples_w = box[2] - box[0] + 1 # Number of pixel samples, *not* geometric width samples_h = box[3] - box[1] + 1 # Number of pixel samples, *not* geometric height # Resample the mask from it's original grid to the new samples_w x samples_h grid mask = Image.fromarray(mask.cpu().numpy()) mask = mask.resize((samples_w, samples_h), resample=Image.BILINEAR) mask = np.array(mask, copy=False) if threshold >= 0: mask = np.array(mask > threshold, dtype=np.uint8) mask = torch.from_numpy(mask) else: # for visualization and debugging, we also # allow it to return an unmodified mask mask = torch.from_numpy(mask * 255).to(torch.uint8) im_mask = torch.zeros((img_h, img_w), dtype=torch.uint8) x_0 = max(box[0], 0) x_1 = min(box[2] + 1, img_w) y_0 = max(box[1], 0) y_1 = min(box[3] + 1, img_h) im_mask[y_0:y_1, x_0:x_1] = mask[ (y_0 - box[1]) : (y_1 - box[1]), (x_0 - box[0]) : (x_1 - box[0]) ] return im_mask
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]. box (Tensor): A tensor of shape (4, ) storing the x0, y0, x1, y1 box corners of the object instance. img_h, img_w (int): Image height and width. threshold (float): Mask binarization threshold in [0, 1]. Returns: im_mask (Tensor): The resized and binarized object mask pasted into the original image plane (a tensor of shape (img_h, img_w)).
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 (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. Here is the function: def pad_masks(masks, padding): """ 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. """ B = masks.shape[0] M = masks.shape[-1] pad2 = 2 * padding scale = float(M + pad2) / M padded_masks = masks.new_zeros((B, M + pad2, M + pad2)) padded_masks[:, padding:-padding, padding:-padding] = masks return padded_masks, scale
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 (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. Here is the function: def scale_boxes(boxes, scale): """ 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. """ w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5 h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5 x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5 y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5 w_half *= scale h_half *= scale scaled_boxes = torch.zeros_like(boxes) scaled_boxes[:, 0] = x_c - w_half scaled_boxes[:, 2] = x_c + w_half scaled_boxes[:, 1] = y_c - h_half scaled_boxes[:, 3] = y_c + h_half return scaled_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 28) into an image. The location, height, and width for pasting each mask is determined by their corresponding bounding boxes in boxes. Note: This is a complicated but more accurate implementation. In actual deployment, it is often enough to use a faster but less accurate implementation. See :func:`paste_mask_in_image_old` in this file for an alternative implementation. Args: masks (tensor): Tensor of shape (Bimg, Hmask, Wmask), where Bimg is the number of detected object instances in the image and Hmask, Wmask are the mask width and mask height of the predicted mask (e.g., Hmask = Wmask = 28). Values are in [0, 1]. boxes (Boxes or Tensor): A Boxes of length Bimg or Tensor of shape (Bimg, 4). boxes[i] and masks[i] correspond to the same object instance. image_shape (tuple): height, width threshold (float): A threshold in [0, 1] for converting the (soft) masks to binary masks. Returns: img_masks (Tensor): A tensor of shape (Bimg, Himage, Wimage), where Bimg is the number of detected object instances and Himage, Wimage are the image width and height. img_masks[i] is a binary mask for object instance i. """ assert masks.shape[-1] == masks.shape[-2], "Only square mask predictions are supported" N = len(masks) if N == 0: return masks.new_empty((0,) + image_shape, dtype=torch.uint8) if not isinstance(boxes, torch.Tensor): boxes = boxes.tensor device = boxes.device assert len(boxes) == N, boxes.shape img_h, img_w = image_shape # The actual implementation split the input into chunks, # and paste them chunk by chunk. if device.type == "cpu" or torch.jit.is_scripting(): # CPU is most efficient when they are pasted one by one with skip_empty=True # so that it performs minimal number of operations. num_chunks = N else: # GPU benefits from parallelism for larger chunks, but may have memory issue # int(img_h) because shape may be tensors in tracing num_chunks = int(np.ceil(N * int(img_h) * int(img_w) * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert ( num_chunks <= N ), "Default GPU_MEM_LIMIT in mask_ops.py is too small; try increasing it" chunks = torch.chunk(torch.arange(N, device=device), num_chunks) img_masks = torch.zeros( N, img_h, img_w, device=device, dtype=torch.bool if threshold >= 0 else torch.uint8 ) for inds in chunks: masks_chunk, spatial_inds = _do_paste_mask( masks[inds, None, :, :], boxes[inds], img_h, img_w, skip_empty=device.type == "cpu" ) if threshold >= 0: masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) else: # for visualization and debugging masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) if torch.jit.is_scripting(): # Scripting does not use the optimized codepath img_masks[inds] = masks_chunk else: img_masks[(inds,) + spatial_inds] = masks_chunk return img_masks The provided code snippet includes necessary dependencies for implementing the `_paste_masks_tensor_shape` function. Write a Python function `def _paste_masks_tensor_shape( masks: torch.Tensor, boxes: torch.Tensor, image_shape: Tuple[torch.Tensor, torch.Tensor], threshold: float = 0.5, )` to solve the following problem: 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. Here is the function: def _paste_masks_tensor_shape( masks: torch.Tensor, boxes: torch.Tensor, image_shape: Tuple[torch.Tensor, torch.Tensor], threshold: float = 0.5, ): """ 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. """ return paste_masks_in_image(masks, boxes, (int(image_shape[0]), int(image_shape[1])), threshold)
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 statistics and the affine parameters are fixed. It contains non-trainable buffers called "weight" and "bias", "running_mean", "running_var", initialized to perform identity transformation. The pre-trained backbone models from Caffe2 only contain "weight" and "bias", which are computed from the original four parameters of BN. The affine transform `x * weight + bias` will perform the equivalent computation of `(x - running_mean) / sqrt(running_var) * weight + bias`. When loading a backbone model from Caffe2, "running_mean" and "running_var" will be left unchanged as identity transformation. Other pre-trained backbone models may contain all 4 parameters. The forward is implemented by `F.batch_norm(..., training=False)`. """ _version = 3 def __init__(self, num_features, eps=1e-5): super().__init__() self.num_features = num_features self.eps = eps self.register_buffer("weight", torch.ones(num_features)) self.register_buffer("bias", torch.zeros(num_features)) self.register_buffer("running_mean", torch.zeros(num_features)) self.register_buffer("running_var", torch.ones(num_features) - eps) def forward(self, x): if x.requires_grad: # When gradients are needed, F.batch_norm will use extra memory # because its backward op computes gradients for weight/bias as well. scale = self.weight * (self.running_var + self.eps).rsqrt() bias = self.bias - self.running_mean * scale scale = scale.reshape(1, -1, 1, 1) bias = bias.reshape(1, -1, 1, 1) out_dtype = x.dtype # may be half return x * scale.to(out_dtype) + bias.to(out_dtype) else: # When gradients are not needed, F.batch_norm is a single fused op # and provide more optimization opportunities. return F.batch_norm( x, self.running_mean, self.running_var, self.weight, self.bias, training=False, eps=self.eps, ) def _load_from_state_dict( self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs ): version = local_metadata.get("version", None) if version is None or version < 2: # No running_mean/var in early versions # This will silent the warnings if prefix + "running_mean" not in state_dict: state_dict[prefix + "running_mean"] = torch.zeros_like(self.running_mean) if prefix + "running_var" not in state_dict: state_dict[prefix + "running_var"] = torch.ones_like(self.running_var) super()._load_from_state_dict( state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs ) def __repr__(self): return "FrozenBatchNorm2d(num_features={}, eps={})".format(self.num_features, self.eps) def convert_frozen_batchnorm(cls, module): """ Convert all BatchNorm/SyncBatchNorm in module into FrozenBatchNorm. Args: module (torch.nn.Module): Returns: If module is BatchNorm/SyncBatchNorm, returns a new module. Otherwise, in-place convert module and return it. Similar to convert_sync_batchnorm in https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/batchnorm.py """ bn_module = nn.modules.batchnorm bn_module = (bn_module.BatchNorm2d, bn_module.SyncBatchNorm) res = module if isinstance(module, bn_module): res = cls(module.num_features) if module.affine: res.weight.data = module.weight.data.clone().detach() res.bias.data = module.bias.data.clone().detach() res.running_mean.data = module.running_mean.data res.running_var.data = module.running_var.data res.eps = module.eps else: for name, child in module.named_children(): new_child = cls.convert_frozen_batchnorm(child) if new_child is not child: res.add_module(name, new_child) return res class NaiveSyncBatchNorm(BatchNorm2d): """ In PyTorch<=1.5, ``nn.SyncBatchNorm`` has incorrect gradient when the batch size on each worker is different. (e.g., when scale augmentation is used, or when it is applied to mask head). This is a slower but correct alternative to `nn.SyncBatchNorm`. Note: There isn't a single definition of Sync BatchNorm. When ``stats_mode==""``, this module computes overall statistics by using statistics of each worker with equal weight. The result is true statistics of all samples (as if they are all on one worker) only when all workers have the same (N, H, W). This mode does not support inputs with zero batch size. When ``stats_mode=="N"``, this module computes overall statistics by weighting the statistics of each worker by their ``N``. The result is true statistics of all samples (as if they are all on one worker) only when all workers have the same (H, W). It is slower than ``stats_mode==""``. Even though the result of this module may not be the true statistics of all samples, it may still be reasonable because it might be preferrable to assign equal weights to all workers, regardless of their (H, W) dimension, instead of putting larger weight on larger images. From preliminary experiments, little difference is found between such a simplified implementation and an accurate computation of overall mean & variance. """ def __init__(self, *args, stats_mode="", **kwargs): super().__init__(*args, **kwargs) assert stats_mode in ["", "N"] self._stats_mode = stats_mode def forward(self, input): if comm.get_world_size() == 1 or not self.training: return super().forward(input) B, C = input.shape[0], input.shape[1] half_input = input.dtype == torch.float16 if half_input: # fp16 does not have good enough numerics for the reduction here input = input.float() mean = torch.mean(input, dim=[0, 2, 3]) meansqr = torch.mean(input * input, dim=[0, 2, 3]) if self._stats_mode == "": assert B > 0, 'SyncBatchNorm(stats_mode="") does not support zero batch size.' vec = torch.cat([mean, meansqr], dim=0) vec = differentiable_all_reduce(vec) * (1.0 / dist.get_world_size()) mean, meansqr = torch.split(vec, C) momentum = self.momentum else: if B == 0: vec = torch.zeros([2 * C + 1], device=mean.device, dtype=mean.dtype) vec = vec + input.sum() # make sure there is gradient w.r.t input else: vec = torch.cat( [mean, meansqr, torch.ones([1], device=mean.device, dtype=mean.dtype)], dim=0 ) vec = differentiable_all_reduce(vec * B) total_batch = vec[-1].detach() momentum = total_batch.clamp(max=1) * self.momentum # no update if total_batch is 0 mean, meansqr, _ = torch.split(vec / total_batch.clamp(min=1), C) # avoid div-by-zero var = meansqr - mean * mean invstd = torch.rsqrt(var + self.eps) scale = self.weight * invstd bias = self.bias - mean * scale scale = scale.reshape(1, -1, 1, 1) bias = bias.reshape(1, -1, 1, 1) self.running_mean += momentum * (mean.detach() - self.running_mean) self.running_var += momentum * (var.detach() - self.running_var) ret = input * scale + bias if half_input: ret = ret.half() return ret BatchNorm2d = torch.nn.BatchNorm2d The provided code snippet includes necessary dependencies for implementing the `get_norm` function. Write a Python function `def get_norm(norm, out_channels)` to solve the following problem: 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 Here is the function: def get_norm(norm, out_channels): """ 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 """ if norm is None: return None if isinstance(norm, str): if len(norm) == 0: return None norm = { "BN": BatchNorm2d, # Fixed in https://github.com/pytorch/pytorch/pull/36382 "SyncBN": NaiveSyncBatchNorm if env.TORCH_VERSION <= (1, 5) else nn.SyncBatchNorm, "FrozenBN": FrozenBatchNorm2d, "GN": lambda channels: nn.GroupNorm(32, channels), # for debugging: "nnSyncBN": nn.SyncBatchNorm, "naiveSyncBN": NaiveSyncBatchNorm, # expose stats_mode N as an option to caller, required for zero-len inputs "naiveSyncBN_N": lambda channels: NaiveSyncBatchNorm(channels, stats_mode="N"), }[norm] return norm(out_channels)
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 The provided code snippet includes necessary dependencies for implementing the `iter_benchmark` function. Write a Python function `def iter_benchmark( iterator, num_iter: int, warmup: int = 5, max_time_seconds: float = 60 ) -> Tuple[float, List[float]]` to solve the following problem: 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. Here is the function: def iter_benchmark( iterator, num_iter: int, warmup: int = 5, max_time_seconds: float = 60 ) -> Tuple[float, List[float]]: """ 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. """ num_iter, warmup = int(num_iter), int(warmup) iterator = iter(iterator) for _ in range(warmup): next(iterator) timer = Timer() all_times = [] for curr_iter in tqdm.trange(num_iter): start = timer.seconds() if start > max_time_seconds: num_iter = curr_iter break next(iterator) all_times.append(timer.seconds() - start) avg = timer.seconds() / num_iter return avg, all_times
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 inside pytorch dataloader worker. worker_info = data.get_worker_info() if worker_info is None or worker_info.num_workers == 1: # do nothing yield from iterable else: yield from itertools.islice(iterable, worker_info.id, None, worker_info.num_workers)
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.utils.file_io import PathManager from . import transforms as T from .catalog import MetadataCatalog _M_YUV2RGB = [[1.0, 0.0, 1.13983], [1.0, -0.39465, -0.58060], [1.0, 2.03211, 0.0]] The provided code snippet includes necessary dependencies for implementing the `convert_image_to_rgb` function. Write a Python function `def convert_image_to_rgb(image, format)` to solve the following problem: 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 Here is the function: def convert_image_to_rgb(image, format): """ 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 """ if isinstance(image, torch.Tensor): image = image.cpu().numpy() if format == "BGR": image = image[:, :, [2, 1, 0]] elif format == "YUV-BT.601": image = np.dot(image, np.array(_M_YUV2RGB).T) image = image * 255.0 else: if format == "L": image = image[:, :, 0] image = image.astype(np.uint8) image = np.asarray(Image.fromarray(image, mode=format).convert("RGB")) return image
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.utils.file_io import PathManager from . import transforms as T from .catalog import MetadataCatalog class SizeMismatchError(ValueError): """ When loaded image has difference width/height compared with annotation. """ The provided code snippet includes necessary dependencies for implementing the `check_image_size` function. Write a Python function `def check_image_size(dataset_dict, image)` to solve the following problem: Raise an error if the image does not match the size specified in the dict. Here is the function: def check_image_size(dataset_dict, image): """ Raise an error if the image does not match the size specified in the dict. """ if "width" in dataset_dict or "height" in dataset_dict: image_wh = (image.shape[1], image.shape[0]) expected_wh = (dataset_dict["width"], dataset_dict["height"]) if not image_wh == expected_wh: raise SizeMismatchError( "Mismatched image shape{}, got {}, expect {}.".format( " for image " + dataset_dict["file_name"] if "file_name" in dataset_dict else "", image_wh, expected_wh, ) + " Please check the width/height in your annotation." ) # To ensure bbox always remap to original image size if "width" not in dataset_dict: dataset_dict["width"] = image.shape[1] if "height" not in dataset_dict: dataset_dict["height"] = image.shape[0]
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.utils.file_io import PathManager from . import transforms as T from .catalog import MetadataCatalog The provided code snippet includes necessary dependencies for implementing the `transform_proposals` function. Write a Python function `def transform_proposals(dataset_dict, image_shape, transforms, *, proposal_topk, min_box_size=0)` to solve the following problem: 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 scoring proposals min_box_size (int): proposals with either side smaller than this threshold are removed The input dict is modified in-place, with abovementioned keys removed. A new key "proposals" will be added. Its value is an `Instances` object which contains the transformed proposals in its field "proposal_boxes" and "objectness_logits". Here is the function: def transform_proposals(dataset_dict, image_shape, transforms, *, proposal_topk, min_box_size=0): """ 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 scoring proposals min_box_size (int): proposals with either side smaller than this threshold are removed The input dict is modified in-place, with abovementioned keys removed. A new key "proposals" will be added. Its value is an `Instances` object which contains the transformed proposals in its field "proposal_boxes" and "objectness_logits". """ if "proposal_boxes" in dataset_dict: # Transform proposal boxes boxes = transforms.apply_box( BoxMode.convert( dataset_dict.pop("proposal_boxes"), dataset_dict.pop("proposal_bbox_mode"), BoxMode.XYXY_ABS, ) ) boxes = Boxes(boxes) objectness_logits = torch.as_tensor( dataset_dict.pop("proposal_objectness_logits").astype("float32") ) boxes.clip(image_shape) keep = boxes.nonempty(threshold=min_box_size) boxes = boxes[keep] objectness_logits = objectness_logits[keep] proposals = Instances(image_shape) proposals.proposal_boxes = boxes[:proposal_topk] proposals.objectness_logits = objectness_logits[:proposal_topk] dataset_dict["proposals"] = proposals
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 scoring proposals min_box_size (int): proposals with either side smaller than this threshold are removed The input dict is modified in-place, with abovementioned keys removed. A new key "proposals" will be added. Its value is an `Instances` object which contains the transformed proposals in its field "proposal_boxes" and "objectness_logits".
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.utils.file_io import PathManager from . import transforms as T from .catalog import MetadataCatalog def transform_keypoint_annotations(keypoints, transforms, image_size, keypoint_hflip_indices=None): """ Transform keypoint annotations of an image. If a keypoint is transformed out of image boundary, it will be marked "unlabeled" (visibility=0) Args: keypoints (list[float]): Nx3 float in Detectron2's Dataset format. Each point is represented by (x, y, visibility). transforms (TransformList): image_size (tuple): the height, width of the transformed image keypoint_hflip_indices (ndarray[int]): see `create_keypoint_hflip_indices`. When `transforms` includes horizontal flip, will use the index mapping to flip keypoints. """ # (N*3,) -> (N, 3) keypoints = np.asarray(keypoints, dtype="float64").reshape(-1, 3) keypoints_xy = transforms.apply_coords(keypoints[:, :2]) # Set all out-of-boundary points to "unlabeled" inside = (keypoints_xy >= np.array([0, 0])) & (keypoints_xy <= np.array(image_size[::-1])) inside = inside.all(axis=1) keypoints[:, :2] = keypoints_xy keypoints[:, 2][~inside] = 0 # This assumes that HorizFlipTransform is the only one that does flip do_hflip = sum(isinstance(t, T.HFlipTransform) for t in transforms.transforms) % 2 == 1 # Alternative way: check if probe points was horizontally flipped. # probe = np.asarray([[0.0, 0.0], [image_width, 0.0]]) # probe_aug = transforms.apply_coords(probe.copy()) # do_hflip = np.sign(probe[1][0] - probe[0][0]) != np.sign(probe_aug[1][0] - probe_aug[0][0]) # noqa # If flipped, swap each keypoint with its opposite-handed equivalent if do_hflip: if keypoint_hflip_indices is None: raise ValueError("Cannot flip keypoints without providing flip indices!") if len(keypoints) != len(keypoint_hflip_indices): raise ValueError( "Keypoint data has {} points, but metadata " "contains {} points!".format(len(keypoints), len(keypoint_hflip_indices)) ) keypoints = keypoints[np.asarray(keypoint_hflip_indices, dtype=np.int32), :] # Maintain COCO convention that if visibility == 0 (unlabeled), then x, y = 0 keypoints[keypoints[:, 2] == 0] = 0 return keypoints The provided code snippet includes necessary dependencies for implementing the `transform_instance_annotations` function. Write a Python function `def transform_instance_annotations( annotation, transforms, image_size, *, keypoint_hflip_indices=None )` to solve the following problem: 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 this function or the transforms. Args: annotation (dict): dict of instance annotations for a single instance. It will be modified in-place. transforms (TransformList or list[Transform]): image_size (tuple): the height, width of the transformed image keypoint_hflip_indices (ndarray[int]): see `create_keypoint_hflip_indices`. Returns: dict: the same input dict with fields "bbox", "segmentation", "keypoints" transformed according to `transforms`. The "bbox_mode" field will be set to XYXY_ABS. Here is the function: def transform_instance_annotations( annotation, transforms, image_size, *, keypoint_hflip_indices=None ): """ 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 this function or the transforms. Args: annotation (dict): dict of instance annotations for a single instance. It will be modified in-place. transforms (TransformList or list[Transform]): image_size (tuple): the height, width of the transformed image keypoint_hflip_indices (ndarray[int]): see `create_keypoint_hflip_indices`. Returns: dict: the same input dict with fields "bbox", "segmentation", "keypoints" transformed according to `transforms`. The "bbox_mode" field will be set to XYXY_ABS. """ if isinstance(transforms, (tuple, list)): transforms = T.TransformList(transforms) # bbox is 1d (per-instance bounding box) bbox = BoxMode.convert(annotation["bbox"], annotation["bbox_mode"], BoxMode.XYXY_ABS) # clip transformed bbox to image size bbox = transforms.apply_box(np.array([bbox]))[0].clip(min=0) annotation["bbox"] = np.minimum(bbox, list(image_size + image_size)[::-1]) annotation["bbox_mode"] = BoxMode.XYXY_ABS if "segmentation" in annotation: # each instance contains 1 or more polygons segm = annotation["segmentation"] if isinstance(segm, list): # polygons polygons = [np.asarray(p).reshape(-1, 2) for p in segm] annotation["segmentation"] = [ p.reshape(-1) for p in transforms.apply_polygons(polygons) ] elif isinstance(segm, dict): # RLE mask = mask_util.decode(segm) mask = transforms.apply_segmentation(mask) assert tuple(mask.shape[:2]) == image_size annotation["segmentation"] = mask else: raise ValueError( "Cannot transform segmentation of type '{}'!" "Supported types are: polygons as list[list[float] or ndarray]," " COCO-style RLE as a dict.".format(type(segm)) ) if "keypoints" in annotation: keypoints = transform_keypoint_annotations( annotation["keypoints"], transforms, image_size, keypoint_hflip_indices ) annotation["keypoints"] = keypoints return annotation
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 this function or the transforms. Args: annotation (dict): dict of instance annotations for a single instance. It will be modified in-place. transforms (TransformList or list[Transform]): image_size (tuple): the height, width of the transformed image keypoint_hflip_indices (ndarray[int]): see `create_keypoint_hflip_indices`. Returns: dict: the same input dict with fields "bbox", "segmentation", "keypoints" transformed according to `transforms`. The "bbox_mode" field will be set to XYXY_ABS.