id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
167,210
import json from pathlib import Path import random import os import torch import torch.utils.data import torchvision from pycocotools import mask as coco_mask from datasets.data_util import preparing_dataset import datasets.transforms as T from util.box_ops import box_cxcywh_to_xyxy, box_iou class CocoDetection(torchvision.datasets.CocoDetection): def __init__(self, img_folder, ann_file, transforms, return_masks, aux_target_hacks=None): super(CocoDetection, self).__init__(img_folder, ann_file) self._transforms = transforms self.prepare = ConvertCocoPolysToMask(return_masks) self.aux_target_hacks = aux_target_hacks def change_hack_attr(self, hackclassname, attrkv_dict): target_class = dataset_hook_register[hackclassname] for item in self.aux_target_hacks: if isinstance(item, target_class): for k,v in attrkv_dict.items(): setattr(item, k, v) def get_hack(self, hackclassname): target_class = dataset_hook_register[hackclassname] for item in self.aux_target_hacks: if isinstance(item, target_class): return item def __getitem__(self, idx): """ Output: - target: dict of multiple items - boxes: Tensor[num_box, 4]. \ Init type: x0,y0,x1,y1. unnormalized data. Final type: cx,cy,w,h. normalized data. """ try: img, target = super(CocoDetection, self).__getitem__(idx) except: print("Error idx: {}".format(idx)) idx += 1 img, target = super(CocoDetection, self).__getitem__(idx) image_id = self.ids[idx] target = {'image_id': image_id, 'annotations': target} img, target = self.prepare(img, target) if self._transforms is not None: img, target = self._transforms(img, target) # convert to needed format if self.aux_target_hacks is not None: for hack_runner in self.aux_target_hacks: target, img = hack_runner(target, img=img) return img, target def make_coco_transforms(image_set, fix_size=False, strong_aug=False, args=None): normalize = T.Compose([ T.ToTensor(), T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) # config the params for data aug scales = [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800] max_size = 1333 scales2_resize = [400, 500, 600] scales2_crop = [384, 600] # update args from config files scales = getattr(args, 'data_aug_scales', scales) max_size = getattr(args, 'data_aug_max_size', max_size) scales2_resize = getattr(args, 'data_aug_scales2_resize', scales2_resize) scales2_crop = getattr(args, 'data_aug_scales2_crop', scales2_crop) # resize them data_aug_scale_overlap = getattr(args, 'data_aug_scale_overlap', None) if data_aug_scale_overlap is not None and data_aug_scale_overlap > 0: data_aug_scale_overlap = float(data_aug_scale_overlap) scales = [int(i*data_aug_scale_overlap) for i in scales] max_size = int(max_size*data_aug_scale_overlap) scales2_resize = [int(i*data_aug_scale_overlap) for i in scales2_resize] scales2_crop = [int(i*data_aug_scale_overlap) for i in scales2_crop] datadict_for_print = { 'scales': scales, 'max_size': max_size, 'scales2_resize': scales2_resize, 'scales2_crop': scales2_crop } print("data_aug_params:", json.dumps(datadict_for_print, indent=2)) if image_set == 'train': if fix_size: return T.Compose([ T.RandomHorizontalFlip(), T.RandomResize([(max_size, max(scales))]), # T.RandomResize([(512, 512)]), normalize, ]) if strong_aug: import datasets.sltransform as SLT return T.Compose([ T.RandomHorizontalFlip(), T.RandomSelect( T.RandomResize(scales, max_size=max_size), T.Compose([ T.RandomResize(scales2_resize), T.RandomSizeCrop(*scales2_crop), T.RandomResize(scales, max_size=max_size), ]) ), SLT.RandomSelectMulti([ SLT.RandomCrop(), SLT.LightingNoise(), SLT.AdjustBrightness(2), SLT.AdjustContrast(2), ]), normalize, ]) return T.Compose([ T.RandomHorizontalFlip(), T.RandomSelect( T.RandomResize(scales, max_size=max_size), T.Compose([ T.RandomResize(scales2_resize), T.RandomSizeCrop(*scales2_crop), T.RandomResize(scales, max_size=max_size), ]) ), normalize, ]) if image_set in ['val', 'eval_debug', 'train_reg', 'test']: if os.environ.get("GFLOPS_DEBUG_SHILONG", False) == 'INFO': print("Under debug mode for flops calculation only!!!!!!!!!!!!!!!!") return T.Compose([ T.ResizeDebug((1280, 800)), normalize, ]) return T.Compose([ T.RandomResize([max(scales)], max_size=max_size), normalize, ]) raise ValueError(f'unknown {image_set}') def get_aux_target_hacks_list(image_set, args): if args.modelname in ['q2bs_mask', 'q2bs']: aux_target_hacks_list = [ label2compat(), label_compat2onehot(), RandomSelectBoxes(num_class=args.num_classes) ] if args.masked_data and image_set == 'train': # aux_target_hacks_list.append() aux_target_hacks_list.append(MaskCrop()) elif args.modelname in ['q2bm_v2', 'q2bs_ce', 'q2op', 'q2ofocal', 'q2opclip', 'q2ocqonly']: aux_target_hacks_list = [ label2compat(), label_compat2onehot(), box_label_catter(), RandomSelectBoxlabels(num_classes=args.num_classes, prob_first_item=args.prob_first_item, prob_random_item=args.prob_random_item, prob_last_item=args.prob_last_item, prob_stop_sign=args.prob_stop_sign, ), BboxPertuber(max_ratio=0.02, generate_samples=1000), ] elif args.modelname in ['q2omask', 'q2osa']: if args.coco_aug: aux_target_hacks_list = [ label2compat(), label_compat2onehot(), box_label_catter(), RandomSelectBoxlabels(num_classes=args.num_classes, prob_first_item=args.prob_first_item, prob_random_item=args.prob_random_item, prob_last_item=args.prob_last_item, prob_stop_sign=args.prob_stop_sign, ), RandomDrop(p=0.2), BboxPertuber(max_ratio=0.02, generate_samples=1000), RandomCutout(factor=0.5) ] else: aux_target_hacks_list = [ label2compat(), label_compat2onehot(), box_label_catter(), RandomSelectBoxlabels(num_classes=args.num_classes, prob_first_item=args.prob_first_item, prob_random_item=args.prob_random_item, prob_last_item=args.prob_last_item, prob_stop_sign=args.prob_stop_sign, ), BboxPertuber(max_ratio=0.02, generate_samples=1000), ] else: aux_target_hacks_list = None return aux_target_hacks_list def preparing_dataset(pathdict, image_set, args): start_time = time.time() dataset_file = args.dataset_file data_static_info = SLConfig.fromfile('util/static_data_path.py') static_dict = data_static_info[dataset_file][image_set] copyfilelist = [] for k,tgt_v in pathdict.items(): if os.path.exists(tgt_v): if args.local_rank == 0: print("path <{}> exist. remove it!".format(tgt_v)) remove(tgt_v) # continue if args.local_rank == 0: src_v = static_dict[k] assert isinstance(src_v, str) if src_v.endswith('.zip'): # copy cp_tgt_dir = os.path.dirname(tgt_v) filename = os.path.basename(src_v) cp_tgt_path = os.path.join(cp_tgt_dir, filename) print('Copy from <{}> to <{}>.'.format(src_v, cp_tgt_path)) os.makedirs(cp_tgt_dir, exist_ok=True) check_and_copy(src_v, cp_tgt_path) # unzip import zipfile print("Starting unzip <{}>".format(cp_tgt_path)) with zipfile.ZipFile(cp_tgt_path, 'r') as zip_ref: zip_ref.extractall(os.path.dirname(cp_tgt_path)) copyfilelist.append(cp_tgt_path) copyfilelist.append(tgt_v) else: print('Copy from <{}> to <{}>.'.format(src_v, tgt_v)) os.makedirs(os.path.dirname(tgt_v), exist_ok=True) check_and_copy(src_v, tgt_v) copyfilelist.append(tgt_v) if len(copyfilelist) == 0: copyfilelist = None args.copyfilelist = copyfilelist if args.distributed: torch.distributed.barrier() total_time = time.time() - start_time if copyfilelist: total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('Data copy time {}'.format(total_time_str)) return copyfilelist def build(image_set, args): root = Path(args.coco_path) mode = 'instances' PATHS = { "train": (root / "train2017", root / "annotations" / f'{mode}_train2017.json'), "train_reg": (root / "train2017", root / "annotations" / f'{mode}_train2017.json'), "val": (root / "val2017", root / "annotations" / f'{mode}_val2017.json'), "eval_debug": (root / "val2017", root / "annotations" / f'{mode}_val2017.json'), "test": (root / "test2017", root / "annotations" / 'image_info_test-dev2017.json' ), } # add some hooks to datasets aux_target_hacks_list = get_aux_target_hacks_list(image_set, args) img_folder, ann_file = PATHS[image_set] # copy to local path if os.environ.get('DATA_COPY_SHILONG') == 'INFO': preparing_dataset(dict(img_folder=img_folder, ann_file=ann_file), image_set, args) try: strong_aug = args.strong_aug except: strong_aug = False dataset = CocoDetection(img_folder, ann_file, transforms=make_coco_transforms(image_set, fix_size=args.fix_size, strong_aug=strong_aug, args=args), return_masks=args.masks, aux_target_hacks=aux_target_hacks_list, ) return dataset
null
167,211
import PIL import torch import os import torchvision.transforms.functional as F import numpy as np import random def find_IoU(boxes1, boxes2): ''' Find IoU between every boxes set of boxes boxes1: a tensor of dimensions (n1, 4) (left, top, right , bottom) boxes2: a tensor of dimensions (n2, 4) Out: IoU each of boxes1 with respect to each of boxes2, a tensor of dimensions (n1, n2) Formula: (box1 ∩ box2) / (box1 u box2) = (box1 ∩ box2) / (area(box1) + area(box2) - (box1 ∩ box2 )) ''' inter = intersect(boxes1, boxes2) area_boxes1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1]) area_boxes2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1]) area_boxes1 = area_boxes1.unsqueeze(1).expand_as(inter) #(n1, n2) area_boxes2 = area_boxes2.unsqueeze(0).expand_as(inter) #(n1, n2) union = (area_boxes1 + area_boxes2 - inter) return inter / union The provided code snippet includes necessary dependencies for implementing the `random_crop` function. Write a Python function `def random_crop(image, boxes, labels, difficulties=None)` to solve the following problem: image: A PIL image boxes: Bounding boxes, a tensor of dimensions (#objects, 4) labels: labels of object, a tensor of dimensions (#objects) difficulties: difficulties of detect object, a tensor of dimensions (#objects) Out: cropped image , new boxes, new labels, new difficulties Here is the function: def random_crop(image, boxes, labels, difficulties=None): ''' image: A PIL image boxes: Bounding boxes, a tensor of dimensions (#objects, 4) labels: labels of object, a tensor of dimensions (#objects) difficulties: difficulties of detect object, a tensor of dimensions (#objects) Out: cropped image , new boxes, new labels, new difficulties ''' if type(image) == PIL.Image.Image: image = F.to_tensor(image) original_h = image.size(1) original_w = image.size(2) while True: mode = random.choice([0.1, 0.3, 0.5, 0.9, None]) if mode is None: return F.to_pil_image(image), boxes, labels, difficulties new_image = image new_boxes = boxes new_difficulties = difficulties new_labels = labels for _ in range(50): # Crop dimensions: [0.3, 1] of original dimensions new_h = random.uniform(0.3*original_h, original_h) new_w = random.uniform(0.3*original_w, original_w) # Aspect ratio constraint b/t .5 & 2 if new_h/new_w < 0.5 or new_h/new_w > 2: continue #Crop coordinate left = random.uniform(0, original_w - new_w) right = left + new_w top = random.uniform(0, original_h - new_h) bottom = top + new_h crop = torch.FloatTensor([int(left), int(top), int(right), int(bottom)]) # Calculate IoU between the crop and the bounding boxes overlap = find_IoU(crop.unsqueeze(0), boxes) #(1, #objects) overlap = overlap.squeeze(0) # If not a single bounding box has a IoU of greater than the minimum, try again if overlap.shape[0] == 0: continue if overlap.max().item() < mode: continue #Crop new_image = image[:, int(top):int(bottom), int(left):int(right)] #(3, new_h, new_w) #Center of bounding boxes center_bb = (boxes[:, :2] + boxes[:, 2:])/2.0 #Find bounding box has been had center in crop center_in_crop = (center_bb[:, 0] >left) * (center_bb[:, 0] < right ) *(center_bb[:, 1] > top) * (center_bb[:, 1] < bottom) #( #objects) if not center_in_crop.any(): continue #take matching bounding box new_boxes = boxes[center_in_crop, :] #take matching labels new_labels = labels[center_in_crop] #take matching difficulities if difficulties is not None: new_difficulties = difficulties[center_in_crop] else: new_difficulties = None #Use the box left and top corner or the crop's new_boxes[:, :2] = torch.max(new_boxes[:, :2], crop[:2]) #adjust to crop new_boxes[:, :2] -= crop[:2] new_boxes[:, 2:] = torch.min(new_boxes[:, 2:],crop[2:]) #adjust to crop new_boxes[:, 2:] -= crop[:2] return F.to_pil_image(new_image), new_boxes, new_labels, new_difficulties
image: A PIL image boxes: Bounding boxes, a tensor of dimensions (#objects, 4) labels: labels of object, a tensor of dimensions (#objects) difficulties: difficulties of detect object, a tensor of dimensions (#objects) Out: cropped image , new boxes, new labels, new difficulties
167,212
import torch from torch import nn, Tensor import math import torch.nn.functional as F from torch import nn The provided code snippet includes necessary dependencies for implementing the `gen_encoder_output_proposals` function. Write a Python function `def gen_encoder_output_proposals(memory:Tensor, memory_padding_mask:Tensor, spatial_shapes:Tensor, learnedwh=None)` to solve the following problem: Input: - memory: bs, \sum{hw}, d_model - memory_padding_mask: bs, \sum{hw} - spatial_shapes: nlevel, 2 - learnedwh: 2 Output: - output_memory: bs, \sum{hw}, d_model - output_proposals: bs, \sum{hw}, 4 Here is the function: def gen_encoder_output_proposals(memory:Tensor, memory_padding_mask:Tensor, spatial_shapes:Tensor, learnedwh=None): """ Input: - memory: bs, \sum{hw}, d_model - memory_padding_mask: bs, \sum{hw} - spatial_shapes: nlevel, 2 - learnedwh: 2 Output: - output_memory: bs, \sum{hw}, d_model - output_proposals: bs, \sum{hw}, 4 """ N_, S_, C_ = memory.shape base_scale = 4.0 proposals = [] _cur = 0 for lvl, (H_, W_) in enumerate(spatial_shapes): mask_flatten_ = memory_padding_mask[:, _cur:(_cur + H_ * W_)].view(N_, H_, W_, 1) valid_H = torch.sum(~mask_flatten_[:, :, 0, 0], 1) valid_W = torch.sum(~mask_flatten_[:, 0, :, 0], 1) grid_y, grid_x = torch.meshgrid(torch.linspace(0, H_ - 1, H_, dtype=torch.float32, device=memory.device), torch.linspace(0, W_ - 1, W_, dtype=torch.float32, device=memory.device)) grid = torch.cat([grid_x.unsqueeze(-1), grid_y.unsqueeze(-1)], -1) # H_, W_, 2 scale = torch.cat([valid_W.unsqueeze(-1), valid_H.unsqueeze(-1)], 1).view(N_, 1, 1, 2) grid = (grid.unsqueeze(0).expand(N_, -1, -1, -1) + 0.5) / scale if learnedwh is not None: wh = torch.ones_like(grid) * learnedwh.sigmoid() * (2.0 ** lvl) else: wh = torch.ones_like(grid) * 0.05 * (2.0 ** lvl) proposal = torch.cat((grid, wh), -1).view(N_, -1, 4) proposals.append(proposal) _cur += (H_ * W_) output_proposals = torch.cat(proposals, 1) output_proposals_valid = ((output_proposals > 0.01) & (output_proposals < 0.99)).all(-1, keepdim=True) output_proposals = torch.log(output_proposals / (1 - output_proposals)) # unsigmoid output_proposals = output_proposals.masked_fill(memory_padding_mask.unsqueeze(-1), float('inf')) output_proposals = output_proposals.masked_fill(~output_proposals_valid, float('inf')) output_memory = memory output_memory = output_memory.masked_fill(memory_padding_mask.unsqueeze(-1), float(0)) output_memory = output_memory.masked_fill(~output_proposals_valid, float(0)) return output_memory, output_proposals
Input: - memory: bs, \sum{hw}, d_model - memory_padding_mask: bs, \sum{hw} - spatial_shapes: nlevel, 2 - learnedwh: 2 Output: - output_memory: bs, \sum{hw}, d_model - output_proposals: bs, \sum{hw}, 4
167,213
import torch from torch import nn, Tensor import math import torch.nn.functional as F from torch import nn The provided code snippet includes necessary dependencies for implementing the `sigmoid_focal_loss` function. Write a Python function `def sigmoid_focal_loss(inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2)` to solve the following problem: Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class). alpha: (optional) Weighting factor in range (0,1) to balance positive vs negative examples. Default = -1 (no weighting). gamma: Exponent of the modulating factor (1 - p_t) to balance easy vs hard examples. Returns: Loss tensor Here is the function: def sigmoid_focal_loss(inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2): """ Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class). alpha: (optional) Weighting factor in range (0,1) to balance positive vs negative examples. Default = -1 (no weighting). gamma: Exponent of the modulating factor (1 - p_t) to balance easy vs hard examples. Returns: Loss tensor """ prob = inputs.sigmoid() ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") p_t = prob * targets + (1 - prob) * (1 - targets) loss = ce_loss * ((1 - p_t) ** gamma) if alpha >= 0: alpha_t = alpha * targets + (1 - alpha) * (1 - targets) loss = alpha_t * loss return loss.mean(1).sum() / num_boxes
Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class). alpha: (optional) Weighting factor in range (0,1) to balance positive vs negative examples. Default = -1 (no weighting). gamma: Exponent of the modulating factor (1 - p_t) to balance easy vs hard examples. Returns: Loss tensor
167,214
import torch from torch import nn, Tensor import math import torch.nn.functional as F from torch import nn The provided code snippet includes necessary dependencies for implementing the `_get_activation_fn` function. Write a Python function `def _get_activation_fn(activation, d_model=256, batch_dim=0)` to solve the following problem: Return an activation function given a string Here is the function: def _get_activation_fn(activation, d_model=256, batch_dim=0): """Return an activation function given a string""" if activation == "relu": return F.relu if activation == "gelu": return F.gelu if activation == "glu": return F.glu if activation == "prelu": return nn.PReLU() if activation == "selu": return F.selu raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
Return an activation function given a string
167,215
import torch from torch import nn, Tensor import math import torch.nn.functional as F from torch import nn def gen_sineembed_for_position(pos_tensor): # n_query, bs, _ = pos_tensor.size() # sineembed_tensor = torch.zeros(n_query, bs, 256) scale = 2 * math.pi dim_t = torch.arange(128, dtype=torch.float32, device=pos_tensor.device) dim_t = 10000 ** (2 * (dim_t // 2) / 128) x_embed = pos_tensor[:, :, 0] * scale y_embed = pos_tensor[:, :, 1] * scale pos_x = x_embed[:, :, None] / dim_t pos_y = y_embed[:, :, None] / dim_t pos_x = torch.stack((pos_x[:, :, 0::2].sin(), pos_x[:, :, 1::2].cos()), dim=3).flatten(2) pos_y = torch.stack((pos_y[:, :, 0::2].sin(), pos_y[:, :, 1::2].cos()), dim=3).flatten(2) if pos_tensor.size(-1) == 2: pos = torch.cat((pos_y, pos_x), dim=2) elif pos_tensor.size(-1) == 4: w_embed = pos_tensor[:, :, 2] * scale pos_w = w_embed[:, :, None] / dim_t pos_w = torch.stack((pos_w[:, :, 0::2].sin(), pos_w[:, :, 1::2].cos()), dim=3).flatten(2) h_embed = pos_tensor[:, :, 3] * scale pos_h = h_embed[:, :, None] / dim_t pos_h = torch.stack((pos_h[:, :, 0::2].sin(), pos_h[:, :, 1::2].cos()), dim=3).flatten(2) pos = torch.cat((pos_y, pos_x, pos_w, pos_h), dim=2) else: raise ValueError("Unknown pos_tensor shape(-1):{}".format(pos_tensor.size(-1))) return pos
null
167,216
import copy from typing import Optional, List import torch import torch.nn.functional as F from torch import nn, Tensor import warnings from typing import Tuple, Optional import torch from torch import Tensor from torch.nn.modules.linear import Linear from torch.nn.init import xavier_uniform_ from torch.nn.init import constant_ from torch.nn.init import xavier_normal_ from torch.nn.parameter import Parameter from torch.nn.modules.module import Module from torch.nn import functional as F import warnings import math from torch._C import _infer_size, _add_docstr from torch.nn import _reduction as _Reduction from torch.nn.modules import utils from torch.nn.modules.utils import _single, _pair, _triple, _list_with_default from torch.nn import grad from torch import _VF from torch._jit_internal import boolean_dispatch, List, Optional, _overload, Tuple try: from torch.overrides import has_torch_function, handle_torch_function except: from torch._overrides import has_torch_function, handle_torch_function Tensor = torch.Tensor from torch.nn.functional import linear, pad, softmax, dropout The provided code snippet includes necessary dependencies for implementing the `multi_head_attention_forward` function. Write a Python function `def multi_head_attention_forward(query: Tensor, key: Tensor, value: Tensor, embed_dim_to_check: int, num_heads: int, in_proj_weight: Tensor, in_proj_bias: Tensor, bias_k: Optional[Tensor], bias_v: Optional[Tensor], add_zero_attn: bool, dropout_p: float, out_proj_weight: Tensor, out_proj_bias: Tensor, training: bool = True, key_padding_mask: Optional[Tensor] = None, need_weights: bool = True, attn_mask: Optional[Tensor] = None, use_separate_proj_weight: bool = False, q_proj_weight: Optional[Tensor] = None, k_proj_weight: Optional[Tensor] = None, v_proj_weight: Optional[Tensor] = None, static_k: Optional[Tensor] = None, static_v: Optional[Tensor] = None, out_dim: Optional[Tensor] = None ) -> Tuple[Tensor, Optional[Tensor]]` to solve the following problem: r""" Args: query, key, value: map a query and a set of key-value pairs to an output. See "Attention Is All You Need" for more details. embed_dim_to_check: total dimension of the model. num_heads: parallel attention heads. in_proj_weight, in_proj_bias: input projection weight and bias. bias_k, bias_v: bias of the key and value sequences to be added at dim=0. add_zero_attn: add a new batch of zeros to the key and value sequences at dim=1. dropout_p: probability of an element to be zeroed. out_proj_weight, out_proj_bias: the output projection weight and bias. training: apply dropout if is ``True``. key_padding_mask: if provided, specified padding elements in the key will be ignored by the attention. This is an binary mask. When the value is True, the corresponding value on the attention layer will be filled with -inf. need_weights: output attn_output_weights. attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all the batches while a 3D mask allows to specify a different mask for the entries of each batch. use_separate_proj_weight: the function accept the proj. weights for query, key, and value in different forms. If false, in_proj_weight will be used, which is a combination of q_proj_weight, k_proj_weight, v_proj_weight. q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias. static_k, static_v: static key and value used for attention operators. Shape: Inputs: - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is the embedding dimension. - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is the embedding dimension. - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length. If a ByteTensor is provided, the non-zero positions will be ignored while the zero positions will be unchanged. If a BoolTensor is provided, the positions with the value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged. - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length. 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length, S is the source sequence length. attn_mask ensures that position i is allowed to attend the unmasked positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True`` are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor is provided, it will be added to the attention weight. - static_k: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. E/num_heads is the head dimension. - static_v: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. E/num_heads is the head dimension. Outputs: - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is the embedding dimension. - attn_output_weights: :math:`(N, L, S)` where N is the batch size, L is the target sequence length, S is the source sequence length. Here is the function: def multi_head_attention_forward(query: Tensor, key: Tensor, value: Tensor, embed_dim_to_check: int, num_heads: int, in_proj_weight: Tensor, in_proj_bias: Tensor, bias_k: Optional[Tensor], bias_v: Optional[Tensor], add_zero_attn: bool, dropout_p: float, out_proj_weight: Tensor, out_proj_bias: Tensor, training: bool = True, key_padding_mask: Optional[Tensor] = None, need_weights: bool = True, attn_mask: Optional[Tensor] = None, use_separate_proj_weight: bool = False, q_proj_weight: Optional[Tensor] = None, k_proj_weight: Optional[Tensor] = None, v_proj_weight: Optional[Tensor] = None, static_k: Optional[Tensor] = None, static_v: Optional[Tensor] = None, out_dim: Optional[Tensor] = None ) -> Tuple[Tensor, Optional[Tensor]]: r""" Args: query, key, value: map a query and a set of key-value pairs to an output. See "Attention Is All You Need" for more details. embed_dim_to_check: total dimension of the model. num_heads: parallel attention heads. in_proj_weight, in_proj_bias: input projection weight and bias. bias_k, bias_v: bias of the key and value sequences to be added at dim=0. add_zero_attn: add a new batch of zeros to the key and value sequences at dim=1. dropout_p: probability of an element to be zeroed. out_proj_weight, out_proj_bias: the output projection weight and bias. training: apply dropout if is ``True``. key_padding_mask: if provided, specified padding elements in the key will be ignored by the attention. This is an binary mask. When the value is True, the corresponding value on the attention layer will be filled with -inf. need_weights: output attn_output_weights. attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all the batches while a 3D mask allows to specify a different mask for the entries of each batch. use_separate_proj_weight: the function accept the proj. weights for query, key, and value in different forms. If false, in_proj_weight will be used, which is a combination of q_proj_weight, k_proj_weight, v_proj_weight. q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias. static_k, static_v: static key and value used for attention operators. Shape: Inputs: - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is the embedding dimension. - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is the embedding dimension. - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length. If a ByteTensor is provided, the non-zero positions will be ignored while the zero positions will be unchanged. If a BoolTensor is provided, the positions with the value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged. - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length. 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length, S is the source sequence length. attn_mask ensures that position i is allowed to attend the unmasked positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True`` are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor is provided, it will be added to the attention weight. - static_k: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. E/num_heads is the head dimension. - static_v: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. E/num_heads is the head dimension. Outputs: - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is the embedding dimension. - attn_output_weights: :math:`(N, L, S)` where N is the batch size, L is the target sequence length, S is the source sequence length. """ if not torch.jit.is_scripting(): tens_ops = (query, key, value, in_proj_weight, in_proj_bias, bias_k, bias_v, out_proj_weight, out_proj_bias) if any([type(t) is not Tensor for t in tens_ops]) and has_torch_function(tens_ops): return handle_torch_function( multi_head_attention_forward, tens_ops, query, key, value, embed_dim_to_check, num_heads, in_proj_weight, in_proj_bias, bias_k, bias_v, add_zero_attn, dropout_p, out_proj_weight, out_proj_bias, training=training, key_padding_mask=key_padding_mask, need_weights=need_weights, attn_mask=attn_mask, use_separate_proj_weight=use_separate_proj_weight, q_proj_weight=q_proj_weight, k_proj_weight=k_proj_weight, v_proj_weight=v_proj_weight, static_k=static_k, static_v=static_v) tgt_len, bsz, embed_dim = query.size() assert embed_dim == embed_dim_to_check # allow MHA to have different sizes for the feature dimension assert key.size(0) == value.size(0) and key.size(1) == value.size(1) head_dim = embed_dim // num_heads v_head_dim = out_dim // num_heads assert head_dim * num_heads == embed_dim, "embed_dim must be divisible by num_heads" scaling = float(head_dim) ** -0.5 q = query * scaling k = key v = value if attn_mask is not None: assert attn_mask.dtype == torch.float32 or attn_mask.dtype == torch.float64 or \ attn_mask.dtype == torch.float16 or attn_mask.dtype == torch.uint8 or attn_mask.dtype == torch.bool, \ 'Only float, byte, and bool types are supported for attn_mask, not {}'.format(attn_mask.dtype) if attn_mask.dtype == torch.uint8: warnings.warn("Byte tensor for attn_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.") attn_mask = attn_mask.to(torch.bool) if attn_mask.dim() == 2: attn_mask = attn_mask.unsqueeze(0) if list(attn_mask.size()) != [1, query.size(0), key.size(0)]: raise RuntimeError('The size of the 2D attn_mask is not correct.') elif attn_mask.dim() == 3: if list(attn_mask.size()) != [bsz * num_heads, query.size(0), key.size(0)]: raise RuntimeError('The size of the 3D attn_mask is not correct.') else: raise RuntimeError("attn_mask's dimension {} is not supported".format(attn_mask.dim())) # attn_mask's dim is 3 now. # convert ByteTensor key_padding_mask to bool if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8: warnings.warn("Byte tensor for key_padding_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.") key_padding_mask = key_padding_mask.to(torch.bool) if bias_k is not None and bias_v is not None: if static_k is None and static_v is None: k = torch.cat([k, bias_k.repeat(1, bsz, 1)]) v = torch.cat([v, bias_v.repeat(1, bsz, 1)]) if attn_mask is not None: attn_mask = pad(attn_mask, (0, 1)) if key_padding_mask is not None: key_padding_mask = pad(key_padding_mask, (0, 1)) else: assert static_k is None, "bias cannot be added to static key." assert static_v is None, "bias cannot be added to static value." else: assert bias_k is None assert bias_v is None q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1) if k is not None: k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) if v is not None: v = v.contiguous().view(-1, bsz * num_heads, v_head_dim).transpose(0, 1) if static_k is not None: assert static_k.size(0) == bsz * num_heads assert static_k.size(2) == head_dim k = static_k if static_v is not None: assert static_v.size(0) == bsz * num_heads assert static_v.size(2) == v_head_dim v = static_v src_len = k.size(1) if key_padding_mask is not None: assert key_padding_mask.size(0) == bsz assert key_padding_mask.size(1) == src_len if add_zero_attn: src_len += 1 k = torch.cat([k, torch.zeros((k.size(0), 1) + k.size()[2:], dtype=k.dtype, device=k.device)], dim=1) v = torch.cat([v, torch.zeros((v.size(0), 1) + v.size()[2:], dtype=v.dtype, device=v.device)], dim=1) if attn_mask is not None: attn_mask = pad(attn_mask, (0, 1)) if key_padding_mask is not None: key_padding_mask = pad(key_padding_mask, (0, 1)) attn_output_weights = torch.bmm(q, k.transpose(1, 2)) assert list(attn_output_weights.size()) == [bsz * num_heads, tgt_len, src_len] if attn_mask is not None: if attn_mask.dtype == torch.bool: attn_output_weights.masked_fill_(attn_mask, float('-inf')) else: attn_output_weights += attn_mask if key_padding_mask is not None: attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len) attn_output_weights = attn_output_weights.masked_fill( key_padding_mask.unsqueeze(1).unsqueeze(2), float('-inf'), ) attn_output_weights = attn_output_weights.view(bsz * num_heads, tgt_len, src_len) # attn_output_weights = softmax( # attn_output_weights, dim=-1) attn_output_weights = softmax( attn_output_weights - attn_output_weights.max(dim=-1, keepdim=True)[0], dim=-1) attn_output_weights = dropout(attn_output_weights, p=dropout_p, training=training) attn_output = torch.bmm(attn_output_weights, v) assert list(attn_output.size()) == [bsz * num_heads, tgt_len, v_head_dim] attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, out_dim) attn_output = linear(attn_output, out_proj_weight, out_proj_bias) if need_weights: # average attention weights over heads attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len) return attn_output, attn_output_weights.sum(dim=1) / num_heads else: return attn_output, None
r""" Args: query, key, value: map a query and a set of key-value pairs to an output. See "Attention Is All You Need" for more details. embed_dim_to_check: total dimension of the model. num_heads: parallel attention heads. in_proj_weight, in_proj_bias: input projection weight and bias. bias_k, bias_v: bias of the key and value sequences to be added at dim=0. add_zero_attn: add a new batch of zeros to the key and value sequences at dim=1. dropout_p: probability of an element to be zeroed. out_proj_weight, out_proj_bias: the output projection weight and bias. training: apply dropout if is ``True``. key_padding_mask: if provided, specified padding elements in the key will be ignored by the attention. This is an binary mask. When the value is True, the corresponding value on the attention layer will be filled with -inf. need_weights: output attn_output_weights. attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all the batches while a 3D mask allows to specify a different mask for the entries of each batch. use_separate_proj_weight: the function accept the proj. weights for query, key, and value in different forms. If false, in_proj_weight will be used, which is a combination of q_proj_weight, k_proj_weight, v_proj_weight. q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias. static_k, static_v: static key and value used for attention operators. Shape: Inputs: - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is the embedding dimension. - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is the embedding dimension. - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length. If a ByteTensor is provided, the non-zero positions will be ignored while the zero positions will be unchanged. If a BoolTensor is provided, the positions with the value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged. - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length. 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length, S is the source sequence length. attn_mask ensures that position i is allowed to attend the unmasked positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True`` are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor is provided, it will be added to the attention weight. - static_k: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. E/num_heads is the head dimension. - static_v: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. E/num_heads is the head dimension. Outputs: - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is the embedding dimension. - attn_output_weights: :math:`(N, L, S)` where N is the batch size, L is the target sequence length, S is the source sequence length.
167,217
import copy import os from typing import Optional, List import math import torch import torch.nn.functional as F from torch import nn, Tensor from torch.nn.init import xavier_uniform_, constant_, uniform_, normal_ from util.misc import inverse_sigmoid from .ops.modules import MSDeformAttn from .utils import sigmoid_focal_loss, MLP, _get_activation_fn, gen_sineembed_for_position def _get_clones(module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
null
167,218
import copy import os from typing import Optional, List import math import torch import torch.nn.functional as F from torch import nn, Tensor from torch.nn.init import xavier_uniform_, constant_, uniform_, normal_ from util.misc import inverse_sigmoid from .ops.modules import MSDeformAttn from .utils import sigmoid_focal_loss, MLP, _get_activation_fn, gen_sineembed_for_position class DeformableTransformer(nn.Module): def __init__(self, d_model=256, nhead=8, num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=1024, dropout=0.1, activation="relu", return_intermediate_dec=False, num_feature_levels=4, dec_n_points=4, enc_n_points=4, two_stage=False, two_stage_num_proposals=300, use_dab=False, high_dim_query_update=False, no_sine_embed=False): def _reset_parameters(self): def get_proposal_pos_embed(self, proposals): def gen_encoder_output_proposals(self, memory, memory_padding_mask, spatial_shapes): def get_valid_ratio(self, mask): def forward(self, srcs, masks, pos_embeds, query_embed=None): def build_deforamble_transformer(args): return DeformableTransformer( d_model=args.hidden_dim, nhead=args.nheads, num_encoder_layers=args.enc_layers, num_decoder_layers=args.dec_layers, dim_feedforward=args.dim_feedforward, dropout=args.dropout, activation="relu", return_intermediate_dec=True, num_feature_levels=args.ddetr_num_feature_levels, dec_n_points=args.ddetr_dec_n_points, enc_n_points=args.ddetr_enc_n_points, two_stage=args.ddetr_two_stage, two_stage_num_proposals=args.num_queries, use_dab=args.ddetr_use_dab, high_dim_query_update=args.ddetr_high_dim_query_update, no_sine_embed=args.ddetr_no_sine_embed)
null
167,219
import torch from util.misc import (NestedTensor, nested_tensor_from_tensor_list, accuracy, get_world_size, interpolate, is_dist_avail_and_initialized, inverse_sigmoid) from util import box_ops import torch.nn.functional as F def inverse_sigmoid(x, eps=1e-3): x = x.clamp(min=0, max=1) x1 = x.clamp(min=eps) x2 = (1 - x).clamp(min=eps) return torch.log(x1/x2) The provided code snippet includes necessary dependencies for implementing the `prepare_for_cdn` function. Write a Python function `def prepare_for_cdn(dn_args, training, num_queries, num_classes, hidden_dim, label_enc)` to solve the following problem: A major difference of DINO from DN-DETR is that the author process pattern embedding pattern embedding in its detector forward function and use learnable tgt embedding, so we change this function a little bit. :param dn_args: targets, dn_number, label_noise_ratio, box_noise_scale :param training: if it is training or inference :param num_queries: number of queires :param num_classes: number of classes :param hidden_dim: transformer hidden dim :param label_enc: encode labels in dn :return: Here is the function: def prepare_for_cdn(dn_args, training, num_queries, num_classes, hidden_dim, label_enc): """ A major difference of DINO from DN-DETR is that the author process pattern embedding pattern embedding in its detector forward function and use learnable tgt embedding, so we change this function a little bit. :param dn_args: targets, dn_number, label_noise_ratio, box_noise_scale :param training: if it is training or inference :param num_queries: number of queires :param num_classes: number of classes :param hidden_dim: transformer hidden dim :param label_enc: encode labels in dn :return: """ if training: targets, dn_number, label_noise_ratio, box_noise_scale = dn_args # positive and negative dn queries dn_number = dn_number * 2 known = [(torch.ones_like(t['labels'])).cuda() for t in targets] batch_size = len(known) known_num = [sum(k) for k in known] if int(max(known_num)) == 0: dn_number = 1 else: if dn_number >= 100: dn_number = dn_number // (int(max(known_num) * 2)) elif dn_number < 1: dn_number = 1 if dn_number == 0: dn_number = 1 unmask_bbox = unmask_label = torch.cat(known) labels = torch.cat([t['labels'] for t in targets]) boxes = torch.cat([t['boxes'] for t in targets]) batch_idx = torch.cat([torch.full_like(t['labels'].long(), i) for i, t in enumerate(targets)]) known_indice = torch.nonzero(unmask_label + unmask_bbox) known_indice = known_indice.view(-1) known_indice = known_indice.repeat(2 * dn_number, 1).view(-1) known_labels = labels.repeat(2 * dn_number, 1).view(-1) known_bid = batch_idx.repeat(2 * dn_number, 1).view(-1) known_bboxs = boxes.repeat(2 * dn_number, 1) known_labels_expaned = known_labels.clone() known_bbox_expand = known_bboxs.clone() if label_noise_ratio > 0: p = torch.rand_like(known_labels_expaned.float()) chosen_indice = torch.nonzero(p < (label_noise_ratio * 0.5)).view(-1) # half of bbox prob new_label = torch.randint_like(chosen_indice, 0, num_classes) # randomly put a new one here known_labels_expaned.scatter_(0, chosen_indice, new_label) single_pad = int(max(known_num)) pad_size = int(single_pad * 2 * dn_number) positive_idx = torch.tensor(range(len(boxes))).long().cuda().unsqueeze(0).repeat(dn_number, 1) positive_idx += (torch.tensor(range(dn_number)) * len(boxes) * 2).long().cuda().unsqueeze(1) positive_idx = positive_idx.flatten() negative_idx = positive_idx + len(boxes) if box_noise_scale > 0: known_bbox_ = torch.zeros_like(known_bboxs) known_bbox_[:, :2] = known_bboxs[:, :2] - known_bboxs[:, 2:] / 2 known_bbox_[:, 2:] = known_bboxs[:, :2] + known_bboxs[:, 2:] / 2 diff = torch.zeros_like(known_bboxs) diff[:, :2] = known_bboxs[:, 2:] / 2 diff[:, 2:] = known_bboxs[:, 2:] / 2 rand_sign = torch.randint_like(known_bboxs, low=0, high=2, dtype=torch.float32) * 2.0 - 1.0 rand_part = torch.rand_like(known_bboxs) rand_part[negative_idx] += 1.0 rand_part *= rand_sign known_bbox_ = known_bbox_ + torch.mul(rand_part, diff).cuda() * box_noise_scale known_bbox_ = known_bbox_.clamp(min=0.0, max=1.0) known_bbox_expand[:, :2] = (known_bbox_[:, :2] + known_bbox_[:, 2:]) / 2 known_bbox_expand[:, 2:] = known_bbox_[:, 2:] - known_bbox_[:, :2] m = known_labels_expaned.long().to('cuda') input_label_embed = label_enc(m) input_bbox_embed = inverse_sigmoid(known_bbox_expand) padding_label = torch.zeros(pad_size, hidden_dim).cuda() padding_bbox = torch.zeros(pad_size, 4).cuda() input_query_label = padding_label.repeat(batch_size, 1, 1) input_query_bbox = padding_bbox.repeat(batch_size, 1, 1) map_known_indice = torch.tensor([]).to('cuda') if len(known_num): map_known_indice = torch.cat([torch.tensor(range(num)) for num in known_num]) # [1,2, 1,2,3] map_known_indice = torch.cat([map_known_indice + single_pad * i for i in range(2 * dn_number)]).long() if len(known_bid): input_query_label[(known_bid.long(), map_known_indice)] = input_label_embed input_query_bbox[(known_bid.long(), map_known_indice)] = input_bbox_embed tgt_size = pad_size + num_queries attn_mask = torch.ones(tgt_size, tgt_size).to('cuda') < 0 # match query cannot see the reconstruct attn_mask[pad_size:, :pad_size] = True # reconstruct cannot see each other for i in range(dn_number): if i == 0: attn_mask[single_pad * 2 * i:single_pad * 2 * (i + 1), single_pad * 2 * (i + 1):pad_size] = True if i == dn_number - 1: attn_mask[single_pad * 2 * i:single_pad * 2 * (i + 1), :single_pad * i * 2] = True else: attn_mask[single_pad * 2 * i:single_pad * 2 * (i + 1), single_pad * 2 * (i + 1):pad_size] = True attn_mask[single_pad * 2 * i:single_pad * 2 * (i + 1), :single_pad * 2 * i] = True dn_meta = { 'pad_size': pad_size, 'num_dn_group': dn_number, } else: input_query_label = None input_query_bbox = None attn_mask = None dn_meta = None return input_query_label, input_query_bbox, attn_mask, dn_meta
A major difference of DINO from DN-DETR is that the author process pattern embedding pattern embedding in its detector forward function and use learnable tgt embedding, so we change this function a little bit. :param dn_args: targets, dn_number, label_noise_ratio, box_noise_scale :param training: if it is training or inference :param num_queries: number of queires :param num_classes: number of classes :param hidden_dim: transformer hidden dim :param label_enc: encode labels in dn :return:
167,220
import torch from util.misc import (NestedTensor, nested_tensor_from_tensor_list, accuracy, get_world_size, interpolate, is_dist_avail_and_initialized, inverse_sigmoid) from util import box_ops import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `dn_post_process` function. Write a Python function `def dn_post_process(outputs_class, outputs_coord, dn_meta, aux_loss, _set_aux_loss)` to solve the following problem: post process of dn after output from the transformer put the dn part in the dn_meta Here is the function: def dn_post_process(outputs_class, outputs_coord, dn_meta, aux_loss, _set_aux_loss): """ post process of dn after output from the transformer put the dn part in the dn_meta """ if dn_meta and dn_meta['pad_size'] > 0: output_known_class = outputs_class[:, :, :dn_meta['pad_size'], :] output_known_coord = outputs_coord[:, :, :dn_meta['pad_size'], :] outputs_class = outputs_class[:, :, dn_meta['pad_size']:, :] outputs_coord = outputs_coord[:, :, dn_meta['pad_size']:, :] out = {'pred_logits': output_known_class[-1], 'pred_boxes': output_known_coord[-1]} if aux_loss: out['aux_outputs'] = _set_aux_loss(output_known_class, output_known_coord) dn_meta['output_known_lbs_bboxes'] = out return outputs_class, outputs_coord
post process of dn after output from the transformer put the dn part in the dn_meta
167,227
import copy import math from typing import List import torch import torch.nn.functional as F from torch import nn from torchvision.ops.boxes import nms from util import box_ops from util.misc import (NestedTensor, nested_tensor_from_tensor_list, accuracy, get_world_size, interpolate, is_dist_avail_and_initialized, inverse_sigmoid) from .backbone import build_backbone from .matcher import build_matcher from .segmentation import (DETRsegm, PostProcessPanoptic, PostProcessSegm, dice_loss) from .deformable_transformer import build_deformable_transformer from .utils import sigmoid_focal_loss, MLP from ..registry import MODULE_BUILD_FUNCS from .dn_components import prepare_for_cdn,dn_post_process class DINO(nn.Module): def __init__(self, backbone, transformer, num_classes, num_queries, aux_loss=False, iter_update=False, query_dim=2, random_refpoints_xy=False, fix_refpoints_hw=-1, num_feature_levels=1, nheads=8, # two stage two_stage_type='no', # ['no', 'standard'] two_stage_add_query_num=0, dec_pred_class_embed_share=True, dec_pred_bbox_embed_share=True, two_stage_class_embed_share=True, two_stage_bbox_embed_share=True, decoder_sa_type = 'sa', num_patterns = 0, dn_number = 100, dn_box_noise_scale = 0.4, dn_label_noise_ratio = 0.5, dn_labelbook_size = 100, ): def _reset_parameters(self): def init_ref_points(self, use_num_queries): def forward(self, samples: NestedTensor, targets:List=None): def _set_aux_loss(self, outputs_class, outputs_coord): class SetCriterion(nn.Module): def __init__(self, num_classes, matcher, weight_dict, focal_alpha, losses): def loss_labels(self, outputs, targets, indices, num_boxes, log=True): def loss_cardinality(self, outputs, targets, indices, num_boxes): def loss_boxes(self, outputs, targets, indices, num_boxes): def loss_masks(self, outputs, targets, indices, num_boxes): def _get_src_permutation_idx(self, indices): def _get_tgt_permutation_idx(self, indices): def get_loss(self, loss, outputs, targets, indices, num_boxes, **kwargs): def forward(self, outputs, targets, return_indices=False): def prep_for_dn(self,dn_meta): class PostProcess(nn.Module): def __init__(self, num_select=100, nms_iou_threshold=-1) -> None: def forward(self, outputs, target_sizes, not_to_xyxy=False, test=False): def build_backbone(args): def build_matcher(args): class DETRsegm(nn.Module): def __init__(self, detr, freeze_detr=False): def forward(self, samples: NestedTensor): class PostProcessSegm(nn.Module): def __init__(self, threshold=0.5): def forward(self, results, outputs, orig_target_sizes, max_target_sizes): class PostProcessPanoptic(nn.Module): def __init__(self, is_thing_map, threshold=0.85): def forward(self, outputs, processed_sizes, target_sizes=None): def to_tuple(tup): def get_ids_area(masks, scores, dedup=False): def build_deformable_transformer(args): def build_dino(args): # the `num_classes` naming here is somewhat misleading. # it indeed corresponds to `max_obj_id + 1`, where max_obj_id # is the maximum id for a class in your dataset. For example, # COCO has a max_obj_id of 90, so we pass `num_classes` to be 91. # As another example, for a dataset that has a single class with id 1, # you should pass `num_classes` to be 2 (max_obj_id + 1). # For more details on this, check the following discussion # https://github.com/facebookresearch/detr/issues/108#issuecomment-650269223 # num_classes = 20 if args.dataset_file != 'coco' else 91 # if args.dataset_file == "coco_panoptic": # # for panoptic, we just add a num_classes that is large enough to hold # # max_obj_id + 1, but the exact value doesn't really matter # num_classes = 250 # if args.dataset_file == 'o365': # num_classes = 366 # if args.dataset_file == 'vanke': # num_classes = 51 num_classes = args.num_classes device = torch.device(args.device) backbone = build_backbone(args) transformer = build_deformable_transformer(args) try: match_unstable_error = args.match_unstable_error dn_labelbook_size = args.dn_labelbook_size except: match_unstable_error = True dn_labelbook_size = num_classes try: dec_pred_class_embed_share = args.dec_pred_class_embed_share except: dec_pred_class_embed_share = True try: dec_pred_bbox_embed_share = args.dec_pred_bbox_embed_share except: dec_pred_bbox_embed_share = True model = DINO( backbone, transformer, num_classes=num_classes, num_queries=args.num_queries, aux_loss=True, iter_update=True, query_dim=4, random_refpoints_xy=args.random_refpoints_xy, fix_refpoints_hw=args.fix_refpoints_hw, num_feature_levels=args.num_feature_levels, nheads=args.nheads, dec_pred_class_embed_share=dec_pred_class_embed_share, dec_pred_bbox_embed_share=dec_pred_bbox_embed_share, # two stage two_stage_type=args.two_stage_type, # box_share two_stage_bbox_embed_share=args.two_stage_bbox_embed_share, two_stage_class_embed_share=args.two_stage_class_embed_share, decoder_sa_type=args.decoder_sa_type, num_patterns=args.num_patterns, dn_number = args.dn_number if args.use_dn else 0, dn_box_noise_scale = args.dn_box_noise_scale, dn_label_noise_ratio = args.dn_label_noise_ratio, dn_labelbook_size = dn_labelbook_size, ) if args.masks: model = DETRsegm(model, freeze_detr=(args.frozen_weights is not None)) matcher = build_matcher(args) # prepare weight dict weight_dict = {'loss_ce': args.cls_loss_coef, 'loss_bbox': args.bbox_loss_coef} weight_dict['loss_giou'] = args.giou_loss_coef clean_weight_dict_wo_dn = copy.deepcopy(weight_dict) # for DN training if args.use_dn: weight_dict['loss_ce_dn'] = args.cls_loss_coef weight_dict['loss_bbox_dn'] = args.bbox_loss_coef weight_dict['loss_giou_dn'] = args.giou_loss_coef if args.masks: weight_dict["loss_mask"] = args.mask_loss_coef weight_dict["loss_dice"] = args.dice_loss_coef clean_weight_dict = copy.deepcopy(weight_dict) # TODO this is a hack if args.aux_loss: aux_weight_dict = {} for i in range(args.dec_layers - 1): aux_weight_dict.update({k + f'_{i}': v for k, v in clean_weight_dict.items()}) weight_dict.update(aux_weight_dict) if args.two_stage_type != 'no': interm_weight_dict = {} try: no_interm_box_loss = args.no_interm_box_loss except: no_interm_box_loss = False _coeff_weight_dict = { 'loss_ce': 1.0, 'loss_bbox': 1.0 if not no_interm_box_loss else 0.0, 'loss_giou': 1.0 if not no_interm_box_loss else 0.0, } try: interm_loss_coef = args.interm_loss_coef except: interm_loss_coef = 1.0 interm_weight_dict.update({k + f'_interm': v * interm_loss_coef * _coeff_weight_dict[k] for k, v in clean_weight_dict_wo_dn.items()}) weight_dict.update(interm_weight_dict) losses = ['labels', 'boxes', 'cardinality'] if args.masks: losses += ["masks"] criterion = SetCriterion(num_classes, matcher=matcher, weight_dict=weight_dict, focal_alpha=args.focal_alpha, losses=losses, ) criterion.to(device) postprocessors = {'bbox': PostProcess(num_select=args.num_select, nms_iou_threshold=args.nms_iou_threshold)} if args.masks: postprocessors['segm'] = PostProcessSegm() if args.dataset_file == "coco_panoptic": is_thing_map = {i: i <= 90 for i in range(201)} postprocessors["panoptic"] = PostProcessPanoptic(is_thing_map, threshold=0.85) return model, criterion, postprocessors
null
167,228
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint import numpy as np from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from util.misc import NestedTensor 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: Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) Here is the function: def window_partition(x, window_size): """ Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) """ B, H, W, C = x.shape x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) return windows
Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C)
167,229
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint import numpy as np from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from util.misc import NestedTensor The provided code snippet includes necessary dependencies for implementing the `window_reverse` function. Write a Python function `def window_reverse(windows, window_size, H, W)` to solve the following problem: Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C) Here is the function: def window_reverse(windows, window_size, H, W): """ Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C) """ B = int(windows.shape[0] / (H * W / window_size / window_size)) x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return x
Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C)
167,230
import math, random import copy from typing import Optional import torch from torch import nn, Tensor from util.misc import inverse_sigmoid from .utils import gen_encoder_output_proposals, MLP,_get_activation_fn, gen_sineembed_for_position from .ops.modules import MSDeformAttn def _get_clones(module, N, layer_share=False): if layer_share: return nn.ModuleList([module for i in range(N)]) else: return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
null
167,231
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def get_shape(val: object) -> typing.List[int]: """ Get the shapes from a jit value object. Args: val (torch._C.Value): jit value object. Returns: list(int): return a list of ints. """ if val.isCompleteTensor(): # pyre-ignore r = val.type().sizes() # pyre-ignore if not r: r = [1] return r elif val.type().kind() in ("IntType", "FloatType"): return [1] elif val.type().kind() in ("StringType",): return [0] elif val.type().kind() in ("ListType",): return [1] elif val.type().kind() in ("BoolType", "NoneType"): return [0] else: raise ValueError() The provided code snippet includes necessary dependencies for implementing the `addmm_flop_jit` function. Write a Python function `def addmm_flop_jit( inputs: typing.List[object], outputs: typing.List[object] ) -> typing.Counter[str]` to solve the following problem: This method counts the flops for fully connected layers with torch script. Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object. outputs (list(torch._C.Value)): The output shape in the form of a list of jit object. Returns: Counter: A Counter dictionary that records the number of flops for each operation. Here is the function: def addmm_flop_jit( inputs: typing.List[object], outputs: typing.List[object] ) -> typing.Counter[str]: """ This method counts the flops for fully connected layers with torch script. Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object. outputs (list(torch._C.Value)): The output shape in the form of a list of jit object. Returns: Counter: A Counter dictionary that records the number of flops for each operation. """ # Count flop for nn.Linear # inputs is a list of length 3. input_shapes = [get_shape(v) for v in inputs[1:3]] # input_shapes[0]: [batch size, input feature dimension] # input_shapes[1]: [batch size, output feature dimension] assert len(input_shapes[0]) == 2 assert len(input_shapes[1]) == 2 batch_size, input_dim = input_shapes[0] output_dim = input_shapes[1][1] flop = batch_size * input_dim * output_dim flop_counter = Counter({"addmm": flop}) return flop_counter
This method counts the flops for fully connected layers with torch script. Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object. outputs (list(torch._C.Value)): The output shape in the form of a list of jit object. Returns: Counter: A Counter dictionary that records the number of flops for each operation.
167,232
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def get_shape(val: object) -> typing.List[int]: """ Get the shapes from a jit value object. Args: val (torch._C.Value): jit value object. Returns: list(int): return a list of ints. """ if val.isCompleteTensor(): # pyre-ignore r = val.type().sizes() # pyre-ignore if not r: r = [1] return r elif val.type().kind() in ("IntType", "FloatType"): return [1] elif val.type().kind() in ("StringType",): return [0] elif val.type().kind() in ("ListType",): return [1] elif val.type().kind() in ("BoolType", "NoneType"): return [0] else: raise ValueError() def bmm_flop_jit(inputs, outputs): # Count flop for nn.Linear # inputs is a list of length 3. input_shapes = [get_shape(v) for v in inputs] # input_shapes[0]: [batch size, input feature dimension] # input_shapes[1]: [batch size, output feature dimension] assert len(input_shapes[0]) == 3 assert len(input_shapes[1]) == 3 T, batch_size, input_dim = input_shapes[0] output_dim = input_shapes[1][2] flop = T * batch_size * input_dim * output_dim flop_counter = Counter({"bmm": flop}) return flop_counter
null
167,233
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def get_shape(val: object) -> typing.List[int]: """ Get the shapes from a jit value object. Args: val (torch._C.Value): jit value object. Returns: list(int): return a list of ints. """ if val.isCompleteTensor(): # pyre-ignore r = val.type().sizes() # pyre-ignore if not r: r = [1] return r elif val.type().kind() in ("IntType", "FloatType"): return [1] elif val.type().kind() in ("StringType",): return [0] elif val.type().kind() in ("ListType",): return [1] elif val.type().kind() in ("BoolType", "NoneType"): return [0] else: raise ValueError() def basic_binary_op_flop_jit(inputs, outputs, name): input_shapes = [get_shape(v) for v in inputs] # for broadcasting input_shapes = [s[::-1] for s in input_shapes] max_shape = np.array(list(zip_longest(*input_shapes, fillvalue=1))).max(1) flop = prod(max_shape) flop_counter = Counter({name: flop}) return flop_counter
null
167,234
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def get_shape(val: object) -> typing.List[int]: def rsqrt_flop_jit(inputs, outputs): input_shapes = [get_shape(v) for v in inputs] flop = prod(input_shapes[0]) * 2 flop_counter = Counter({"rsqrt": flop}) return flop_counter
null
167,235
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def get_shape(val: object) -> typing.List[int]: """ Get the shapes from a jit value object. Args: val (torch._C.Value): jit value object. Returns: list(int): return a list of ints. """ if val.isCompleteTensor(): # pyre-ignore r = val.type().sizes() # pyre-ignore if not r: r = [1] return r elif val.type().kind() in ("IntType", "FloatType"): return [1] elif val.type().kind() in ("StringType",): return [0] elif val.type().kind() in ("ListType",): return [1] elif val.type().kind() in ("BoolType", "NoneType"): return [0] else: raise ValueError() def dropout_flop_jit(inputs, outputs): input_shapes = [get_shape(v) for v in inputs[:1]] flop = prod(input_shapes[0]) flop_counter = Counter({"dropout": flop}) return flop_counter
null
167,236
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def get_shape(val: object) -> typing.List[int]: """ Get the shapes from a jit value object. Args: val (torch._C.Value): jit value object. Returns: list(int): return a list of ints. """ if val.isCompleteTensor(): # pyre-ignore r = val.type().sizes() # pyre-ignore if not r: r = [1] return r elif val.type().kind() in ("IntType", "FloatType"): return [1] elif val.type().kind() in ("StringType",): return [0] elif val.type().kind() in ("ListType",): return [1] elif val.type().kind() in ("BoolType", "NoneType"): return [0] else: raise ValueError() def softmax_flop_jit(inputs, outputs): # from https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/profiler/internal/flops_registry.py input_shapes = [get_shape(v) for v in inputs[:1]] flop = prod(input_shapes[0]) * 5 flop_counter = Counter({"softmax": flop}) return flop_counter
null
167,237
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def get_shape(val: object) -> typing.List[int]: """ Get the shapes from a jit value object. Args: val (torch._C.Value): jit value object. Returns: list(int): return a list of ints. """ if val.isCompleteTensor(): # pyre-ignore r = val.type().sizes() # pyre-ignore if not r: r = [1] return r elif val.type().kind() in ("IntType", "FloatType"): return [1] elif val.type().kind() in ("StringType",): return [0] elif val.type().kind() in ("ListType",): return [1] elif val.type().kind() in ("BoolType", "NoneType"): return [0] else: raise ValueError() def _reduction_op_flop_jit(inputs, outputs, reduce_flops=1, finalize_flops=0): input_shapes = [get_shape(v) for v in inputs] output_shapes = [get_shape(v) for v in outputs] in_elements = prod(input_shapes[0]) out_elements = prod(output_shapes[0]) num_flops = in_elements * reduce_flops + out_elements * ( finalize_flops - reduce_flops ) return num_flops
null
167,238
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def get_shape(val: object) -> typing.List[int]: """ Get the shapes from a jit value object. Args: val (torch._C.Value): jit value object. Returns: list(int): return a list of ints. """ if val.isCompleteTensor(): # pyre-ignore r = val.type().sizes() # pyre-ignore if not r: r = [1] return r elif val.type().kind() in ("IntType", "FloatType"): return [1] elif val.type().kind() in ("StringType",): return [0] elif val.type().kind() in ("ListType",): return [1] elif val.type().kind() in ("BoolType", "NoneType"): return [0] else: raise ValueError() def conv_flop_count( x_shape: typing.List[int], w_shape: typing.List[int], out_shape: typing.List[int], ) -> typing.Counter[str]: """ This method counts the flops for convolution. Note only multiplication is counted. Computation for addition and bias is ignored. Args: x_shape (list(int)): The input shape before convolution. w_shape (list(int)): The filter shape. out_shape (list(int)): The output shape after convolution. Returns: Counter: A Counter dictionary that records the number of flops for each operation. """ batch_size, Cin_dim, Cout_dim = x_shape[0], w_shape[1], out_shape[1] out_size = prod(out_shape[2:]) kernel_size = prod(w_shape[2:]) flop = batch_size * out_size * Cout_dim * Cin_dim * kernel_size flop_counter = Counter({"conv": flop}) return flop_counter The provided code snippet includes necessary dependencies for implementing the `conv_flop_jit` function. Write a Python function `def conv_flop_jit( inputs: typing.List[object], outputs: typing.List[object] ) -> typing.Counter[str]` to solve the following problem: This method counts the flops for convolution using torch script. Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object before convolution. outputs (list(torch._C.Value)): The output shape in the form of a list of jit object after convolution. Returns: Counter: A Counter dictionary that records the number of flops for each operation. Here is the function: def conv_flop_jit( inputs: typing.List[object], outputs: typing.List[object] ) -> typing.Counter[str]: """ This method counts the flops for convolution using torch script. Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object before convolution. outputs (list(torch._C.Value)): The output shape in the form of a list of jit object after convolution. Returns: Counter: A Counter dictionary that records the number of flops for each operation. """ # Inputs of Convolution should be a list of length 12. They represent: # 0) input tensor, 1) convolution filter, 2) bias, 3) stride, 4) padding, # 5) dilation, 6) transposed, 7) out_pad, 8) groups, 9) benchmark_cudnn, # 10) deterministic_cudnn and 11) user_enabled_cudnn. # import ipdb; ipdb.set_trace() # assert len(inputs) == 12 x, w = inputs[:2] x_shape, w_shape, out_shape = ( get_shape(x), get_shape(w), get_shape(outputs[0]), ) return conv_flop_count(x_shape, w_shape, out_shape)
This method counts the flops for convolution using torch script. Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object before convolution. outputs (list(torch._C.Value)): The output shape in the form of a list of jit object after convolution. Returns: Counter: A Counter dictionary that records the number of flops for each operation.
167,239
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def get_shape(val: object) -> typing.List[int]: """ Get the shapes from a jit value object. Args: val (torch._C.Value): jit value object. Returns: list(int): return a list of ints. """ if val.isCompleteTensor(): # pyre-ignore r = val.type().sizes() # pyre-ignore if not r: r = [1] return r elif val.type().kind() in ("IntType", "FloatType"): return [1] elif val.type().kind() in ("StringType",): return [0] elif val.type().kind() in ("ListType",): return [1] elif val.type().kind() in ("BoolType", "NoneType"): return [0] else: raise ValueError() The provided code snippet includes necessary dependencies for implementing the `einsum_flop_jit` function. Write a Python function `def einsum_flop_jit( inputs: typing.List[object], outputs: typing.List[object] ) -> typing.Counter[str]` to solve the following problem: This method counts the flops for the einsum operation. We currently support two einsum operations: "nct,ncp->ntp" and "ntg,ncg->nct". Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object before einsum. outputs (list(torch._C.Value)): The output shape in the form of a list of jit object after einsum. Returns: Counter: A Counter dictionary that records the number of flops for each operation. Here is the function: def einsum_flop_jit( inputs: typing.List[object], outputs: typing.List[object] ) -> typing.Counter[str]: """ This method counts the flops for the einsum operation. We currently support two einsum operations: "nct,ncp->ntp" and "ntg,ncg->nct". Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object before einsum. outputs (list(torch._C.Value)): The output shape in the form of a list of jit object after einsum. Returns: Counter: A Counter dictionary that records the number of flops for each operation. """ # Inputs of einsum should be a list of length 2. # Inputs[0] stores the equation used for einsum. # Inputs[1] stores the list of input shapes. assert len(inputs) == 2 equation = inputs[0].toIValue() # pyre-ignore # Get rid of white space in the equation string. equation = equation.replace(" ", "") # Re-map equation so that same equation with different alphabet # representations will look the same. letter_order = OrderedDict((k, 0) for k in equation if k.isalpha()).keys() mapping = {ord(x): 97 + i for i, x in enumerate(letter_order)} equation = equation.translate(mapping) input_shapes_jit = inputs[1].node().inputs() # pyre-ignore input_shapes = [get_shape(v) for v in input_shapes_jit] if equation == "abc,abd->acd": n, c, t = input_shapes[0] p = input_shapes[-1][-1] flop = n * c * t * p flop_counter = Counter({"einsum": flop}) return flop_counter elif equation == "abc,adc->adb": n, t, g = input_shapes[0] c = input_shapes[-1][1] flop = n * t * g * c flop_counter = Counter({"einsum": flop}) return flop_counter else: raise NotImplementedError("Unsupported einsum operation.")
This method counts the flops for the einsum operation. We currently support two einsum operations: "nct,ncp->ntp" and "ntg,ncg->nct". Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object before einsum. outputs (list(torch._C.Value)): The output shape in the form of a list of jit object after einsum. Returns: Counter: A Counter dictionary that records the number of flops for each operation.
167,240
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def get_shape(val: object) -> typing.List[int]: """ Get the shapes from a jit value object. Args: val (torch._C.Value): jit value object. Returns: list(int): return a list of ints. """ if val.isCompleteTensor(): # pyre-ignore r = val.type().sizes() # pyre-ignore if not r: r = [1] return r elif val.type().kind() in ("IntType", "FloatType"): return [1] elif val.type().kind() in ("StringType",): return [0] elif val.type().kind() in ("ListType",): return [1] elif val.type().kind() in ("BoolType", "NoneType"): return [0] else: raise ValueError() The provided code snippet includes necessary dependencies for implementing the `matmul_flop_jit` function. Write a Python function `def matmul_flop_jit( inputs: typing.List[object], outputs: typing.List[object] ) -> typing.Counter[str]` to solve the following problem: This method counts the flops for matmul. Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object before matmul. outputs (list(torch._C.Value)): The output shape in the form of a list of jit object after matmul. Returns: Counter: A Counter dictionary that records the number of flops for each operation. Here is the function: def matmul_flop_jit( inputs: typing.List[object], outputs: typing.List[object] ) -> typing.Counter[str]: """ This method counts the flops for matmul. Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object before matmul. outputs (list(torch._C.Value)): The output shape in the form of a list of jit object after matmul. Returns: Counter: A Counter dictionary that records the number of flops for each operation. """ # Inputs contains the shapes of two matrices. input_shapes = [get_shape(v) for v in inputs] assert len(input_shapes) == 2 assert input_shapes[0][-1] == input_shapes[1][-2] dim_len = len(input_shapes[1]) assert dim_len >= 2 batch = 1 for i in range(dim_len - 2): assert input_shapes[0][i] == input_shapes[1][i] batch *= input_shapes[0][i] # (b,m,c) x (b,c,n), flop = bmnc flop = batch * input_shapes[0][-2] * input_shapes[0][-1] * input_shapes[1][-1] flop_counter = Counter({"matmul": flop}) return flop_counter
This method counts the flops for matmul. Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object before matmul. outputs (list(torch._C.Value)): The output shape in the form of a list of jit object after matmul. Returns: Counter: A Counter dictionary that records the number of flops for each operation.
167,241
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def get_shape(val: object) -> typing.List[int]: """ Get the shapes from a jit value object. Args: val (torch._C.Value): jit value object. Returns: list(int): return a list of ints. """ if val.isCompleteTensor(): # pyre-ignore r = val.type().sizes() # pyre-ignore if not r: r = [1] return r elif val.type().kind() in ("IntType", "FloatType"): return [1] elif val.type().kind() in ("StringType",): return [0] elif val.type().kind() in ("ListType",): return [1] elif val.type().kind() in ("BoolType", "NoneType"): return [0] else: raise ValueError() The provided code snippet includes necessary dependencies for implementing the `batchnorm_flop_jit` function. Write a Python function `def batchnorm_flop_jit( inputs: typing.List[object], outputs: typing.List[object] ) -> typing.Counter[str]` to solve the following problem: This method counts the flops for batch norm. Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object before batch norm. outputs (list(torch._C.Value)): The output shape in the form of a list of jit object after batch norm. Returns: Counter: A Counter dictionary that records the number of flops for each operation. Here is the function: def batchnorm_flop_jit( inputs: typing.List[object], outputs: typing.List[object] ) -> typing.Counter[str]: """ This method counts the flops for batch norm. Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object before batch norm. outputs (list(torch._C.Value)): The output shape in the form of a list of jit object after batch norm. Returns: Counter: A Counter dictionary that records the number of flops for each operation. """ # Inputs[0] contains the shape of the input. input_shape = get_shape(inputs[0]) assert 2 <= len(input_shape) <= 5 flop = prod(input_shape) * 4 flop_counter = Counter({"batchnorm": flop}) return flop_counter
This method counts the flops for batch norm. Args: inputs (list(torch._C.Value)): The input shape in the form of a list of jit object before batch norm. outputs (list(torch._C.Value)): The output shape in the form of a list of jit object after batch norm. Returns: Counter: A Counter dictionary that records the number of flops for each operation.
167,242
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def get_shape(val: object) -> typing.List[int]: """ Get the shapes from a jit value object. Args: val (torch._C.Value): jit value object. Returns: list(int): return a list of ints. """ if val.isCompleteTensor(): # pyre-ignore r = val.type().sizes() # pyre-ignore if not r: r = [1] return r elif val.type().kind() in ("IntType", "FloatType"): return [1] elif val.type().kind() in ("StringType",): return [0] elif val.type().kind() in ("ListType",): return [1] elif val.type().kind() in ("BoolType", "NoneType"): return [0] else: raise ValueError() The provided code snippet includes necessary dependencies for implementing the `linear_flop_jit` function. Write a Python function `def linear_flop_jit(inputs: List[Any], outputs: List[Any]) -> Number` to solve the following problem: Count flops for the aten::linear operator. Here is the function: def linear_flop_jit(inputs: List[Any], outputs: List[Any]) -> Number: """ Count flops for the aten::linear operator. """ # Inputs is a list of length 3; unlike aten::addmm, it is the first # two elements that are relevant. input_shapes = [get_shape(v) for v in inputs[0:2]] # input_shapes[0]: [dim0, dim1, ..., input_feature_dim] # input_shapes[1]: [output_feature_dim, input_feature_dim] assert input_shapes[0][-1] == input_shapes[1][-1] flops = prod(input_shapes[0]) * input_shapes[1][0] flop_counter = Counter({"linear": flops}) return flop_counter
Count flops for the aten::linear operator.
167,243
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number Handle = Callable[[List[Any], List[Any]], Union[typing.Counter[str], Number]] from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def get_shape(val: object) -> typing.List[int]: """ Get the shapes from a jit value object. Args: val (torch._C.Value): jit value object. Returns: list(int): return a list of ints. """ if val.isCompleteTensor(): # pyre-ignore r = val.type().sizes() # pyre-ignore if not r: r = [1] return r elif val.type().kind() in ("IntType", "FloatType"): return [1] elif val.type().kind() in ("StringType",): return [0] elif val.type().kind() in ("ListType",): return [1] elif val.type().kind() in ("BoolType", "NoneType"): return [0] else: raise ValueError() The provided code snippet includes necessary dependencies for implementing the `norm_flop_counter` function. Write a Python function `def norm_flop_counter(affine_arg_index: int) -> Handle` to solve the following problem: Args: affine_arg_index: index of the affine argument in inputs Here is the function: def norm_flop_counter(affine_arg_index: int) -> Handle: """ Args: affine_arg_index: index of the affine argument in inputs """ def norm_flop_jit(inputs: List[Any], outputs: List[Any]) -> Number: """ Count flops for norm layers. """ # Inputs[0] contains the shape of the input. input_shape = get_shape(inputs[0]) has_affine = get_shape(inputs[affine_arg_index]) is not None assert 2 <= len(input_shape) <= 5, input_shape # 5 is just a rough estimate flop = prod(input_shape) * (5 if has_affine else 4) flop_counter = Counter({"norm": flop}) return flop_counter return norm_flop_jit
Args: affine_arg_index: index of the affine argument in inputs
167,244
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number Handle = Callable[[List[Any], List[Any]], Union[typing.Counter[str], Number]] from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def get_shape(val: object) -> typing.List[int]: """ Get the shapes from a jit value object. Args: val (torch._C.Value): jit value object. Returns: list(int): return a list of ints. """ if val.isCompleteTensor(): # pyre-ignore r = val.type().sizes() # pyre-ignore if not r: r = [1] return r elif val.type().kind() in ("IntType", "FloatType"): return [1] elif val.type().kind() in ("StringType",): return [0] elif val.type().kind() in ("ListType",): return [1] elif val.type().kind() in ("BoolType", "NoneType"): return [0] else: raise ValueError() The provided code snippet includes necessary dependencies for implementing the `elementwise_flop_counter` function. Write a Python function `def elementwise_flop_counter(input_scale: float = 1, output_scale: float = 0) -> Handle` to solve the following problem: Count flops by input_tensor.numel() * input_scale + output_tensor.numel() * output_scale Args: input_scale: scale of the input tensor (first argument) output_scale: scale of the output tensor (first element in outputs) Here is the function: def elementwise_flop_counter(input_scale: float = 1, output_scale: float = 0) -> Handle: """ Count flops by input_tensor.numel() * input_scale + output_tensor.numel() * output_scale Args: input_scale: scale of the input tensor (first argument) output_scale: scale of the output tensor (first element in outputs) """ def elementwise_flop(inputs: List[Any], outputs: List[Any]) -> Number: ret = 0 if input_scale != 0: shape = get_shape(inputs[0]) ret += input_scale * prod(shape) if output_scale != 0: shape = get_shape(outputs[0]) ret += output_scale * prod(shape) flop_counter = Counter({"elementwise": ret}) return flop_counter return elementwise_flop
Count flops by input_tensor.numel() * input_scale + output_tensor.numel() * output_scale Args: input_scale: scale of the input tensor (first argument) output_scale: scale of the output tensor (first element in outputs)
167,245
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def build_dataset(image_set, args): if args.dataset_file == 'coco': return build_coco(image_set, args) if args.dataset_file == 'coco_panoptic': # to avoid making panopticapi required for coco from .coco_panoptic import build as build_coco_panoptic return build_coco_panoptic(image_set, args) if args.dataset_file == 'o365': from .o365 import build_o365_combine return build_o365_combine(image_set, args) if args.dataset_file == 'vanke': from .vanke import build_vanke return build_vanke(image_set, args) raise ValueError(f'dataset {args.dataset_file} not supported') The provided code snippet includes necessary dependencies for implementing the `get_dataset` function. Write a Python function `def get_dataset(coco_path)` to solve the following problem: Gets the COCO dataset used for computing the flops on Here is the function: def get_dataset(coco_path): """ Gets the COCO dataset used for computing the flops on """ class DummyArgs: pass args = DummyArgs() args.dataset_file = "coco" args.coco_path = coco_path args.masks = False dataset = build_dataset(image_set="val", args=args) return dataset
Gets the COCO dataset used for computing the flops on
167,246
from collections import OrderedDict, Counter, defaultdict import json import os from posixpath import join import sys sys.path.append(os.path.dirname(sys.path[0])) import numpy as np from numpy import prod from itertools import zip_longest import tqdm import logging import typing import torch import torch.nn as nn from functools import partial import time from util.slconfig import SLConfig from typing import Any, Callable, List, Optional, Union from numbers import Number from main import build_model_main, get_args_parser as get_main_args_parser from datasets import build_dataset def flop_count( model: nn.Module, inputs: typing.Tuple[object, ...], whitelist: typing.Union[typing.List[str], None] = None, customized_ops: typing.Union[typing.Dict[str, typing.Callable], None] = None, ) -> typing.DefaultDict[str, float]: """ Given a model and an input to the model, compute the Gflops of the given model. Note the input should have a batch size of 1. Args: model (nn.Module): The model to compute flop counts. inputs (tuple): Inputs that are passed to `model` to count flops. Inputs need to be in a tuple. whitelist (list(str)): Whitelist of operations that will be counted. It needs to be a subset of _SUPPORTED_OPS. By default, the function computes flops for all supported operations. customized_ops (dict(str,Callable)) : A dictionary contains customized operations and their flop handles. If customized_ops contains an operation in _SUPPORTED_OPS, then the default handle in _SUPPORTED_OPS will be overwritten. Returns: defaultdict: A dictionary that records the number of gflops for each operation. """ # Copy _SUPPORTED_OPS to flop_count_ops. # If customized_ops is provided, update _SUPPORTED_OPS. flop_count_ops = _SUPPORTED_OPS.copy() if customized_ops: flop_count_ops.update(customized_ops) # If whitelist is None, count flops for all suported operations. if whitelist is None: whitelist_set = set(flop_count_ops.keys()) else: whitelist_set = set(whitelist) # Torch script does not support parallell torch models. if isinstance( model, (nn.parallel.distributed.DistributedDataParallel, nn.DataParallel), ): model = model.module # pyre-ignore assert set(whitelist_set).issubset( flop_count_ops ), "whitelist needs to be a subset of _SUPPORTED_OPS and customized_ops." assert isinstance(inputs, tuple), "Inputs need to be in a tuple." # Compatibility with torch.jit. if hasattr(torch.jit, "get_trace_graph"): trace, _ = torch.jit.get_trace_graph(model, inputs) trace_nodes = trace.graph().nodes() else: trace, _ = torch.jit._get_trace_graph(model, inputs) trace_nodes = trace.nodes() skipped_ops = Counter() total_flop_counter = Counter() for node in trace_nodes: kind = node.kind() if kind not in whitelist_set: # If the operation is not in _IGNORED_OPS, count skipped operations. if kind not in _IGNORED_OPS: skipped_ops[kind] += 1 continue handle_count = flop_count_ops.get(kind, None) if handle_count is None: continue inputs, outputs = list(node.inputs()), list(node.outputs()) flops_counter = handle_count(inputs, outputs) total_flop_counter += flops_counter global _HAS_ALREADY_SKIPPED if len(skipped_ops) > 0 and not _HAS_ALREADY_SKIPPED: _HAS_ALREADY_SKIPPED = True for op, freq in skipped_ops.items(): logging.warning("Skipped operation {} {} time(s)".format(op, freq)) # Convert flop count to gigaflops. final_count = defaultdict(float) for op in total_flop_counter: final_count[op] = total_flop_counter[op] / 1e9 return final_count def measure_time(model, inputs, N=10): warmup(model, inputs) s = time.time() for i in range(N): out = model(inputs) torch.cuda.synchronize() t = (time.time() - s) / N return t def fmt_res(data): # return data.mean(), data.std(), data.min(), data.max() return { "mean": data.mean(), "std": data.std(), "min": data.min(), "max": data.max(), } class SLConfig(object): """ config files. only support .py file as config now. ref: mmcv.utils.config Example: >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1]))) >>> cfg.a 1 >>> cfg.b {'b1': [0, 1]} >>> cfg.b.b1 [0, 1] >>> cfg = Config.fromfile('tests/data/config/a.py') >>> cfg.filename "/home/kchen/projects/mmcv/tests/data/config/a.py" >>> cfg.item4 'test' >>> cfg "Config [path: /home/kchen/projects/mmcv/tests/data/config/a.py]: " "{'item1': [1, 2], 'item2': {'a': 0}, 'item3': True, 'item4': 'test'}" """ def _validate_py_syntax(filename): with open(filename) as f: content = f.read() try: ast.parse(content) except SyntaxError: raise SyntaxError('There are syntax errors in config ' f'file {filename}') def _file2dict(filename): filename = osp.abspath(osp.expanduser(filename)) check_file_exist(filename) if filename.lower().endswith('.py'): with tempfile.TemporaryDirectory() as temp_config_dir: temp_config_file = tempfile.NamedTemporaryFile( dir=temp_config_dir, suffix='.py') temp_config_name = osp.basename(temp_config_file.name) if WINDOWS: temp_config_file.close() shutil.copyfile(filename, osp.join(temp_config_dir, temp_config_name)) temp_module_name = osp.splitext(temp_config_name)[0] sys.path.insert(0, temp_config_dir) SLConfig._validate_py_syntax(filename) mod = import_module(temp_module_name) sys.path.pop(0) cfg_dict = { name: value for name, value in mod.__dict__.items() if not name.startswith('__') } # delete imported module del sys.modules[temp_module_name] # close temp file temp_config_file.close() elif filename.lower().endswith(('.yml', '.yaml', '.json')): from .slio import slload cfg_dict = slload(filename) else: raise IOError('Only py/yml/yaml/json type are supported now!') cfg_text = filename + '\n' with open(filename, 'r') as f: cfg_text += f.read() # parse the base file if BASE_KEY in cfg_dict: cfg_dir = osp.dirname(filename) base_filename = cfg_dict.pop(BASE_KEY) base_filename = base_filename if isinstance( base_filename, list) else [base_filename] cfg_dict_list = list() cfg_text_list = list() for f in base_filename: _cfg_dict, _cfg_text = SLConfig._file2dict(osp.join(cfg_dir, f)) cfg_dict_list.append(_cfg_dict) cfg_text_list.append(_cfg_text) base_cfg_dict = dict() for c in cfg_dict_list: if len(base_cfg_dict.keys() & c.keys()) > 0: raise KeyError('Duplicate key is not allowed among bases') # TODO Allow the duplicate key while warnning user base_cfg_dict.update(c) base_cfg_dict = SLConfig._merge_a_into_b(cfg_dict, base_cfg_dict) cfg_dict = base_cfg_dict # merge cfg_text cfg_text_list.append(cfg_text) cfg_text = '\n'.join(cfg_text_list) return cfg_dict, cfg_text def _merge_a_into_b(a, b): """merge dict `a` into dict `b` (non-inplace). values in `a` will overwrite `b`. copy first to avoid inplace modification Args: a ([type]): [description] b ([type]): [description] Returns: [dict]: [description] """ if not isinstance(a, dict): return a b = b.copy() for k, v in a.items(): if isinstance(v, dict) and k in b and not v.pop(DELETE_KEY, False): if not isinstance(b[k], dict) and not isinstance(b[k], list): # if : raise TypeError( f'{k}={v} in child config cannot inherit from base ' f'because {k} is a dict in the child config but is of ' f'type {type(b[k])} in base config. You may set ' f'`{DELETE_KEY}=True` to ignore the base config') b[k] = SLConfig._merge_a_into_b(v, b[k]) elif isinstance(b, list): try: _ = int(k) except: raise TypeError( f'b is a list, ' f'index {k} should be an int when input but {type(k)}' ) b[int(k)] = SLConfig._merge_a_into_b(v, b[int(k)]) else: b[k] = v return b def fromfile(filename): cfg_dict, cfg_text = SLConfig._file2dict(filename) return SLConfig(cfg_dict, cfg_text=cfg_text, filename=filename) def __init__(self, cfg_dict=None, cfg_text=None, filename=None): if cfg_dict is None: cfg_dict = dict() elif not isinstance(cfg_dict, dict): raise TypeError('cfg_dict must be a dict, but ' f'got {type(cfg_dict)}') for key in cfg_dict: if key in RESERVED_KEYS: raise KeyError(f'{key} is reserved for config file') super(SLConfig, self).__setattr__('_cfg_dict', ConfigDict(cfg_dict)) super(SLConfig, self).__setattr__('_filename', filename) if cfg_text: text = cfg_text elif filename: with open(filename, 'r') as f: text = f.read() else: text = '' super(SLConfig, self).__setattr__('_text', text) def filename(self): return self._filename def text(self): return self._text def pretty_text(self): indent = 4 def _indent(s_, num_spaces): s = s_.split('\n') if len(s) == 1: return s_ first = s.pop(0) s = [(num_spaces * ' ') + line for line in s] s = '\n'.join(s) s = first + '\n' + s return s def _format_basic_types(k, v, use_mapping=False): if isinstance(v, str): v_str = f"'{v}'" else: v_str = str(v) if use_mapping: k_str = f"'{k}'" if isinstance(k, str) else str(k) attr_str = f'{k_str}: {v_str}' else: attr_str = f'{str(k)}={v_str}' attr_str = _indent(attr_str, indent) return attr_str def _format_list(k, v, use_mapping=False): # check if all items in the list are dict if all(isinstance(_, dict) for _ in v): v_str = '[\n' v_str += '\n'.join( f'dict({_indent(_format_dict(v_), indent)}),' for v_ in v).rstrip(',') if use_mapping: k_str = f"'{k}'" if isinstance(k, str) else str(k) attr_str = f'{k_str}: {v_str}' else: attr_str = f'{str(k)}={v_str}' attr_str = _indent(attr_str, indent) + ']' else: attr_str = _format_basic_types(k, v, use_mapping) return attr_str def _contain_invalid_identifier(dict_str): contain_invalid_identifier = False for key_name in dict_str: contain_invalid_identifier |= \ (not str(key_name).isidentifier()) return contain_invalid_identifier def _format_dict(input_dict, outest_level=False): r = '' s = [] use_mapping = _contain_invalid_identifier(input_dict) if use_mapping: r += '{' for idx, (k, v) in enumerate(input_dict.items()): is_last = idx >= len(input_dict) - 1 end = '' if outest_level or is_last else ',' if isinstance(v, dict): v_str = '\n' + _format_dict(v) if use_mapping: k_str = f"'{k}'" if isinstance(k, str) else str(k) attr_str = f'{k_str}: dict({v_str}' else: attr_str = f'{str(k)}=dict({v_str}' attr_str = _indent(attr_str, indent) + ')' + end elif isinstance(v, list): attr_str = _format_list(k, v, use_mapping) + end else: attr_str = _format_basic_types(k, v, use_mapping) + end s.append(attr_str) r += '\n'.join(s) if use_mapping: r += '}' return r cfg_dict = self._cfg_dict.to_dict() text = _format_dict(cfg_dict, outest_level=True) # copied from setup.cfg yapf_style = dict( based_on_style='pep8', blank_line_before_nested_class_or_def=True, split_before_expression_after_opening_paren=True) text, _ = FormatCode(text, style_config=yapf_style, verify=True) return text def __repr__(self): return f'Config (path: {self.filename}): {self._cfg_dict.__repr__()}' def __len__(self): return len(self._cfg_dict) def __getattr__(self, name): # # debug # print('+'*15) # print('name=%s' % name) # print("addr:", id(self)) # # print('type(self):', type(self)) # print(self.__dict__) # print('+'*15) # if self.__dict__ == {}: # raise ValueError return getattr(self._cfg_dict, name) def __getitem__(self, name): return self._cfg_dict.__getitem__(name) def __setattr__(self, name, value): if isinstance(value, dict): value = ConfigDict(value) self._cfg_dict.__setattr__(name, value) def __setitem__(self, name, value): if isinstance(value, dict): value = ConfigDict(value) self._cfg_dict.__setitem__(name, value) def __iter__(self): return iter(self._cfg_dict) def dump(self, file=None): if file is None: return self.pretty_text else: with open(file, 'w') as f: f.write(self.pretty_text) def merge_from_dict(self, options): """Merge list into cfg_dict Merge the dict parsed by MultipleKVAction into this cfg. Examples: >>> options = {'model.backbone.depth': 50, ... 'model.backbone.with_cp':True} >>> cfg = Config(dict(model=dict(backbone=dict(type='ResNet')))) >>> cfg.merge_from_dict(options) >>> cfg_dict = super(Config, self).__getattribute__('_cfg_dict') >>> assert cfg_dict == dict( ... model=dict(backbone=dict(depth=50, with_cp=True))) Args: options (dict): dict of configs to merge from. """ option_cfg_dict = {} for full_key, v in options.items(): d = option_cfg_dict key_list = full_key.split('.') for subkey in key_list[:-1]: d.setdefault(subkey, ConfigDict()) d = d[subkey] subkey = key_list[-1] d[subkey] = v cfg_dict = super(SLConfig, self).__getattribute__('_cfg_dict') super(SLConfig, self).__setattr__( '_cfg_dict', SLConfig._merge_a_into_b(option_cfg_dict, cfg_dict)) # for multiprocess def __setstate__(self, state): self.__init__(state) def copy(self): return SLConfig(self._cfg_dict.copy()) def deepcopy(self): return SLConfig(self._cfg_dict.deepcopy()) def build_model_main(args): # we use register to maintain models from catdet6 on. from models.registry import MODULE_BUILD_FUNCS assert args.modelname in MODULE_BUILD_FUNCS._module_dict build_func = MODULE_BUILD_FUNCS.get(args.modelname) model, criterion, postprocessors = build_func(args) return model, criterion, postprocessors def build_dataset(image_set, args): if args.dataset_file == 'coco': return build_coco(image_set, args) if args.dataset_file == 'coco_panoptic': # to avoid making panopticapi required for coco from .coco_panoptic import build as build_coco_panoptic return build_coco_panoptic(image_set, args) if args.dataset_file == 'o365': from .o365 import build_o365_combine return build_o365_combine(image_set, args) if args.dataset_file == 'vanke': from .vanke import build_vanke return build_vanke(image_set, args) raise ValueError(f'dataset {args.dataset_file} not supported') def benchmark(): _outputs = {} main_args = get_main_args_parser().parse_args() main_args.commad_txt = "Command: " + " ".join(sys.argv) # load cfg file and update the args print("Loading config file from {}".format(main_args.config_file)) cfg = SLConfig.fromfile(main_args.config_file) if main_args.options is not None: cfg.merge_from_dict(main_args.options) cfg_dict = cfg._cfg_dict.to_dict() args_vars = vars(main_args) for k, v in cfg_dict.items(): if k not in args_vars: setattr(main_args, k, v) else: raise ValueError("Key {} can used by args only".format(k)) dataset = build_dataset("val", main_args) model, _, _ = build_model_main(main_args) n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) _outputs.update({"nparam": n_parameters}) model.cuda() model.eval() warmup_step = 5 total_step = 20 images = [] for idx in range(total_step): img, t = dataset[idx] images.append(img) with torch.no_grad(): tmp = [] tmp2 = [] for imgid, img in enumerate(tqdm.tqdm(images)): inputs = [img.to("cuda")] res = flop_count(model, (inputs,)) t = measure_time(model, inputs) tmp.append(sum(res.values())) if imgid >= warmup_step: tmp2.append(t) _outputs.update({"detailed_flops": res}) _outputs.update({"flops": fmt_res(np.array(tmp)), "time": fmt_res(np.array(tmp2))}) mean_infer_time = float(fmt_res(np.array(tmp2))["mean"]) _outputs.update({"fps": 1 / mean_infer_time}) res = {"flops": fmt_res(np.array(tmp)), "time": fmt_res(np.array(tmp2))} # print(res) output_file = os.path.join(main_args.output_dir, "flops", "log.txt") os.makedirs(os.path.dirname(output_file), exist_ok=True) with open(output_file, "a") as f: f.write(main_args.commad_txt + "\n") f.write(json.dumps(_outputs, indent=2) + "\n") return _outputs
null
167,247
from collections import OrderedDict from copy import deepcopy import json import warnings import torch import numpy as np import argparse from util.slconfig import SLConfig def slprint(x, name='x'): if isinstance(x, (torch.Tensor, np.ndarray)): print(f'{name}.shape:', x.shape) elif isinstance(x, (tuple, list)): print('type x:', type(x)) for i in range(min(10, len(x))): slprint(x[i], f'{name}[{i}]') elif isinstance(x, dict): for k,v in x.items(): slprint(v, f'{name}[{k}]') else: print(f'{name}.type:', type(x))
null
167,248
from collections import OrderedDict from copy import deepcopy import json import warnings import torch import numpy as np import argparse from util.slconfig import SLConfig def clean_state_dict(state_dict): new_state_dict = OrderedDict() for k, v in state_dict.items(): if k[:7] == 'module.': k = k[7:] # remove `module.` new_state_dict[k] = v return new_state_dict
null
167,249
from collections import OrderedDict from copy import deepcopy import json import warnings import torch import numpy as np def get_gaussian_mean(x, axis, other_axis, softmax=True): """ Args: x (float): Input images(BxCxHxW) axis (int): The index for weighted mean other_axis (int): The other index Returns: weighted index for axis, BxC """ mat2line = torch.sum(x, axis=other_axis) # mat2line = mat2line / mat2line.mean() * 10 if softmax: u = torch.softmax(mat2line, axis=2) else: u = mat2line / (mat2line.sum(2, keepdim=True) + 1e-6) size = x.shape[axis] ind = torch.linspace(0, 1, size).to(x.device) batch = x.shape[0] channel = x.shape[1] index = ind.repeat([batch, channel, 1]) mean_position = torch.sum(index * u, dim=2) return mean_position import argparse from util.slconfig import SLConfig The provided code snippet includes necessary dependencies for implementing the `get_expected_points_from_map` function. Write a Python function `def get_expected_points_from_map(hm, softmax=True)` to solve the following problem: get_gaussian_map_from_points B,C,H,W -> B,N,2 float(0, 1) float(0, 1) softargmax function Args: hm (float): Input images(BxCxHxW) Returns: weighted index for axis, BxCx2. float between 0 and 1. Here is the function: def get_expected_points_from_map(hm, softmax=True): """get_gaussian_map_from_points B,C,H,W -> B,N,2 float(0, 1) float(0, 1) softargmax function Args: hm (float): Input images(BxCxHxW) Returns: weighted index for axis, BxCx2. float between 0 and 1. """ # hm = 10*hm B,C,H,W = hm.shape y_mean = get_gaussian_mean(hm, 2, 3, softmax=softmax) # B,C x_mean = get_gaussian_mean(hm, 3, 2, softmax=softmax) # B,C # return torch.cat((x_mean.unsqueeze(-1), y_mean.unsqueeze(-1)), 2) return torch.stack([x_mean, y_mean], dim=2)
get_gaussian_map_from_points B,C,H,W -> B,N,2 float(0, 1) float(0, 1) softargmax function Args: hm (float): Input images(BxCxHxW) Returns: weighted index for axis, BxCx2. float between 0 and 1.
167,250
from collections import OrderedDict from copy import deepcopy import json import warnings import torch import numpy as np class Embedder: def __init__(self, **kwargs): self.kwargs = kwargs self.create_embedding_fn() def create_embedding_fn(self): embed_fns = [] d = self.kwargs['input_dims'] out_dim = 0 if self.kwargs['include_input']: embed_fns.append(lambda x : x) out_dim += d max_freq = self.kwargs['max_freq_log2'] N_freqs = self.kwargs['num_freqs'] if self.kwargs['log_sampling']: freq_bands = 2.**torch.linspace(0., max_freq, steps=N_freqs) else: freq_bands = torch.linspace(2.**0., 2.**max_freq, steps=N_freqs) for freq in freq_bands: for p_fn in self.kwargs['periodic_fns']: embed_fns.append(lambda x, p_fn=p_fn, freq=freq : p_fn(x * freq)) out_dim += d self.embed_fns = embed_fns self.out_dim = out_dim def embed(self, inputs): return torch.cat([fn(inputs) for fn in self.embed_fns], -1) import argparse from util.slconfig import SLConfig def get_embedder(multires, i=0): import torch.nn as nn if i == -1: return nn.Identity(), 3 embed_kwargs = { 'include_input' : True, 'input_dims' : 3, 'max_freq_log2' : multires-1, 'num_freqs' : multires, 'log_sampling' : True, 'periodic_fns' : [torch.sin, torch.cos], } embedder_obj = Embedder(**embed_kwargs) embed = lambda x, eo=embedder_obj : eo.embed(x) return embed, embedder_obj.out_dim
null
167,251
from collections import OrderedDict from copy import deepcopy import json import warnings import torch import numpy as np import argparse from util.slconfig import SLConfig def inverse_sigmoid(x, eps=1e-5): x = x.clamp(min=0, max=1) x1 = x.clamp(min=eps) x2 = (1 - x).clamp(min=eps) return torch.log(x1/x2)
null
167,252
from collections import OrderedDict from copy import deepcopy import json import warnings import torch import numpy as np import argparse from util.slconfig import SLConfig class SLConfig(object): """ config files. only support .py file as config now. ref: mmcv.utils.config Example: >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1]))) >>> cfg.a 1 >>> cfg.b {'b1': [0, 1]} >>> cfg.b.b1 [0, 1] >>> cfg = Config.fromfile('tests/data/config/a.py') >>> cfg.filename "/home/kchen/projects/mmcv/tests/data/config/a.py" >>> cfg.item4 'test' >>> cfg "Config [path: /home/kchen/projects/mmcv/tests/data/config/a.py]: " "{'item1': [1, 2], 'item2': {'a': 0}, 'item3': True, 'item4': 'test'}" """ def _validate_py_syntax(filename): with open(filename) as f: content = f.read() try: ast.parse(content) except SyntaxError: raise SyntaxError('There are syntax errors in config ' f'file {filename}') def _file2dict(filename): filename = osp.abspath(osp.expanduser(filename)) check_file_exist(filename) if filename.lower().endswith('.py'): with tempfile.TemporaryDirectory() as temp_config_dir: temp_config_file = tempfile.NamedTemporaryFile( dir=temp_config_dir, suffix='.py') temp_config_name = osp.basename(temp_config_file.name) if WINDOWS: temp_config_file.close() shutil.copyfile(filename, osp.join(temp_config_dir, temp_config_name)) temp_module_name = osp.splitext(temp_config_name)[0] sys.path.insert(0, temp_config_dir) SLConfig._validate_py_syntax(filename) mod = import_module(temp_module_name) sys.path.pop(0) cfg_dict = { name: value for name, value in mod.__dict__.items() if not name.startswith('__') } # delete imported module del sys.modules[temp_module_name] # close temp file temp_config_file.close() elif filename.lower().endswith(('.yml', '.yaml', '.json')): from .slio import slload cfg_dict = slload(filename) else: raise IOError('Only py/yml/yaml/json type are supported now!') cfg_text = filename + '\n' with open(filename, 'r') as f: cfg_text += f.read() # parse the base file if BASE_KEY in cfg_dict: cfg_dir = osp.dirname(filename) base_filename = cfg_dict.pop(BASE_KEY) base_filename = base_filename if isinstance( base_filename, list) else [base_filename] cfg_dict_list = list() cfg_text_list = list() for f in base_filename: _cfg_dict, _cfg_text = SLConfig._file2dict(osp.join(cfg_dir, f)) cfg_dict_list.append(_cfg_dict) cfg_text_list.append(_cfg_text) base_cfg_dict = dict() for c in cfg_dict_list: if len(base_cfg_dict.keys() & c.keys()) > 0: raise KeyError('Duplicate key is not allowed among bases') # TODO Allow the duplicate key while warnning user base_cfg_dict.update(c) base_cfg_dict = SLConfig._merge_a_into_b(cfg_dict, base_cfg_dict) cfg_dict = base_cfg_dict # merge cfg_text cfg_text_list.append(cfg_text) cfg_text = '\n'.join(cfg_text_list) return cfg_dict, cfg_text def _merge_a_into_b(a, b): """merge dict `a` into dict `b` (non-inplace). values in `a` will overwrite `b`. copy first to avoid inplace modification Args: a ([type]): [description] b ([type]): [description] Returns: [dict]: [description] """ if not isinstance(a, dict): return a b = b.copy() for k, v in a.items(): if isinstance(v, dict) and k in b and not v.pop(DELETE_KEY, False): if not isinstance(b[k], dict) and not isinstance(b[k], list): # if : raise TypeError( f'{k}={v} in child config cannot inherit from base ' f'because {k} is a dict in the child config but is of ' f'type {type(b[k])} in base config. You may set ' f'`{DELETE_KEY}=True` to ignore the base config') b[k] = SLConfig._merge_a_into_b(v, b[k]) elif isinstance(b, list): try: _ = int(k) except: raise TypeError( f'b is a list, ' f'index {k} should be an int when input but {type(k)}' ) b[int(k)] = SLConfig._merge_a_into_b(v, b[int(k)]) else: b[k] = v return b def fromfile(filename): cfg_dict, cfg_text = SLConfig._file2dict(filename) return SLConfig(cfg_dict, cfg_text=cfg_text, filename=filename) def __init__(self, cfg_dict=None, cfg_text=None, filename=None): if cfg_dict is None: cfg_dict = dict() elif not isinstance(cfg_dict, dict): raise TypeError('cfg_dict must be a dict, but ' f'got {type(cfg_dict)}') for key in cfg_dict: if key in RESERVED_KEYS: raise KeyError(f'{key} is reserved for config file') super(SLConfig, self).__setattr__('_cfg_dict', ConfigDict(cfg_dict)) super(SLConfig, self).__setattr__('_filename', filename) if cfg_text: text = cfg_text elif filename: with open(filename, 'r') as f: text = f.read() else: text = '' super(SLConfig, self).__setattr__('_text', text) def filename(self): return self._filename def text(self): return self._text def pretty_text(self): indent = 4 def _indent(s_, num_spaces): s = s_.split('\n') if len(s) == 1: return s_ first = s.pop(0) s = [(num_spaces * ' ') + line for line in s] s = '\n'.join(s) s = first + '\n' + s return s def _format_basic_types(k, v, use_mapping=False): if isinstance(v, str): v_str = f"'{v}'" else: v_str = str(v) if use_mapping: k_str = f"'{k}'" if isinstance(k, str) else str(k) attr_str = f'{k_str}: {v_str}' else: attr_str = f'{str(k)}={v_str}' attr_str = _indent(attr_str, indent) return attr_str def _format_list(k, v, use_mapping=False): # check if all items in the list are dict if all(isinstance(_, dict) for _ in v): v_str = '[\n' v_str += '\n'.join( f'dict({_indent(_format_dict(v_), indent)}),' for v_ in v).rstrip(',') if use_mapping: k_str = f"'{k}'" if isinstance(k, str) else str(k) attr_str = f'{k_str}: {v_str}' else: attr_str = f'{str(k)}={v_str}' attr_str = _indent(attr_str, indent) + ']' else: attr_str = _format_basic_types(k, v, use_mapping) return attr_str def _contain_invalid_identifier(dict_str): contain_invalid_identifier = False for key_name in dict_str: contain_invalid_identifier |= \ (not str(key_name).isidentifier()) return contain_invalid_identifier def _format_dict(input_dict, outest_level=False): r = '' s = [] use_mapping = _contain_invalid_identifier(input_dict) if use_mapping: r += '{' for idx, (k, v) in enumerate(input_dict.items()): is_last = idx >= len(input_dict) - 1 end = '' if outest_level or is_last else ',' if isinstance(v, dict): v_str = '\n' + _format_dict(v) if use_mapping: k_str = f"'{k}'" if isinstance(k, str) else str(k) attr_str = f'{k_str}: dict({v_str}' else: attr_str = f'{str(k)}=dict({v_str}' attr_str = _indent(attr_str, indent) + ')' + end elif isinstance(v, list): attr_str = _format_list(k, v, use_mapping) + end else: attr_str = _format_basic_types(k, v, use_mapping) + end s.append(attr_str) r += '\n'.join(s) if use_mapping: r += '}' return r cfg_dict = self._cfg_dict.to_dict() text = _format_dict(cfg_dict, outest_level=True) # copied from setup.cfg yapf_style = dict( based_on_style='pep8', blank_line_before_nested_class_or_def=True, split_before_expression_after_opening_paren=True) text, _ = FormatCode(text, style_config=yapf_style, verify=True) return text def __repr__(self): return f'Config (path: {self.filename}): {self._cfg_dict.__repr__()}' def __len__(self): return len(self._cfg_dict) def __getattr__(self, name): # # debug # print('+'*15) # print('name=%s' % name) # print("addr:", id(self)) # # print('type(self):', type(self)) # print(self.__dict__) # print('+'*15) # if self.__dict__ == {}: # raise ValueError return getattr(self._cfg_dict, name) def __getitem__(self, name): return self._cfg_dict.__getitem__(name) def __setattr__(self, name, value): if isinstance(value, dict): value = ConfigDict(value) self._cfg_dict.__setattr__(name, value) def __setitem__(self, name, value): if isinstance(value, dict): value = ConfigDict(value) self._cfg_dict.__setitem__(name, value) def __iter__(self): return iter(self._cfg_dict) def dump(self, file=None): if file is None: return self.pretty_text else: with open(file, 'w') as f: f.write(self.pretty_text) def merge_from_dict(self, options): """Merge list into cfg_dict Merge the dict parsed by MultipleKVAction into this cfg. Examples: >>> options = {'model.backbone.depth': 50, ... 'model.backbone.with_cp':True} >>> cfg = Config(dict(model=dict(backbone=dict(type='ResNet')))) >>> cfg.merge_from_dict(options) >>> cfg_dict = super(Config, self).__getattribute__('_cfg_dict') >>> assert cfg_dict == dict( ... model=dict(backbone=dict(depth=50, with_cp=True))) Args: options (dict): dict of configs to merge from. """ option_cfg_dict = {} for full_key, v in options.items(): d = option_cfg_dict key_list = full_key.split('.') for subkey in key_list[:-1]: d.setdefault(subkey, ConfigDict()) d = d[subkey] subkey = key_list[-1] d[subkey] = v cfg_dict = super(SLConfig, self).__getattribute__('_cfg_dict') super(SLConfig, self).__setattr__( '_cfg_dict', SLConfig._merge_a_into_b(option_cfg_dict, cfg_dict)) # for multiprocess def __setstate__(self, state): self.__init__(state) def copy(self): return SLConfig(self._cfg_dict.copy()) def deepcopy(self): return SLConfig(self._cfg_dict.deepcopy()) The provided code snippet includes necessary dependencies for implementing the `get_raw_dict` function. Write a Python function `def get_raw_dict(args)` to solve the following problem: return the dicf contained in args. e.g: >>> with open(path, 'w') as f: json.dump(get_raw_dict(args), f, indent=2) Here is the function: def get_raw_dict(args): """ return the dicf contained in args. e.g: >>> with open(path, 'w') as f: json.dump(get_raw_dict(args), f, indent=2) """ if isinstance(args, argparse.Namespace): return vars(args) elif isinstance(args, dict): return args elif isinstance(args, SLConfig): return args._cfg_dict else: raise NotImplementedError("Unknown type {}".format(type(args)))
return the dicf contained in args. e.g: >>> with open(path, 'w') as f: json.dump(get_raw_dict(args), f, indent=2)
167,253
from collections import OrderedDict from copy import deepcopy import json import warnings import torch import numpy as np import argparse from util.slconfig import SLConfig def stat_tensors(tensor): assert tensor.dim() == 1 tensor_sm = tensor.softmax(0) entropy = (tensor_sm * torch.log(tensor_sm + 1e-9)).sum() return { 'max': tensor.max(), 'min': tensor.min(), 'mean': tensor.mean(), 'var': tensor.var(), 'std': tensor.var() ** 0.5, 'entropy': entropy }
null
167,254
from collections import OrderedDict from copy import deepcopy import json import warnings import torch import numpy as np import argparse from util.slconfig import SLConfig def ensure_rng(rng=None): """Coerces input into a random number generator. If the input is None, then a global random state is returned. If the input is a numeric value, then that is used as a seed to construct a random state. Otherwise the input is returned as-is. Adapted from [1]_. Args: rng (int | numpy.random.RandomState | None): if None, then defaults to the global rng. Otherwise this can be an integer or a RandomState class Returns: (numpy.random.RandomState) : rng - a numpy random number generator References: .. [1] https://gitlab.kitware.com/computer-vision/kwarray/blob/master/kwarray/util_random.py#L270 # noqa: E501 """ if rng is None: rng = np.random.mtrand._rand elif isinstance(rng, int): rng = np.random.RandomState(rng) else: rng = rng return rng The provided code snippet includes necessary dependencies for implementing the `random_boxes` function. Write a Python function `def random_boxes(num=1, scale=1, rng=None)` to solve the following problem: Simple version of ``kwimage.Boxes.random`` Returns: Tensor: shape (n, 4) in x1, y1, x2, y2 format. References: https://gitlab.kitware.com/computer-vision/kwimage/blob/master/kwimage/structs/boxes.py#L1390 Example: >>> num = 3 >>> scale = 512 >>> rng = 0 >>> boxes = random_boxes(num, scale, rng) >>> print(boxes) tensor([[280.9925, 278.9802, 308.6148, 366.1769], [216.9113, 330.6978, 224.0446, 456.5878], [405.3632, 196.3221, 493.3953, 270.7942]]) Here is the function: def random_boxes(num=1, scale=1, rng=None): """Simple version of ``kwimage.Boxes.random`` Returns: Tensor: shape (n, 4) in x1, y1, x2, y2 format. References: https://gitlab.kitware.com/computer-vision/kwimage/blob/master/kwimage/structs/boxes.py#L1390 Example: >>> num = 3 >>> scale = 512 >>> rng = 0 >>> boxes = random_boxes(num, scale, rng) >>> print(boxes) tensor([[280.9925, 278.9802, 308.6148, 366.1769], [216.9113, 330.6978, 224.0446, 456.5878], [405.3632, 196.3221, 493.3953, 270.7942]]) """ rng = ensure_rng(rng) tlbr = rng.rand(num, 4).astype(np.float32) tl_x = np.minimum(tlbr[:, 0], tlbr[:, 2]) tl_y = np.minimum(tlbr[:, 1], tlbr[:, 3]) br_x = np.maximum(tlbr[:, 0], tlbr[:, 2]) br_y = np.maximum(tlbr[:, 1], tlbr[:, 3]) tlbr[:, 0] = tl_x * scale tlbr[:, 1] = tl_y * scale tlbr[:, 2] = br_x * scale tlbr[:, 3] = br_y * scale boxes = torch.from_numpy(tlbr) return boxes
Simple version of ``kwimage.Boxes.random`` Returns: Tensor: shape (n, 4) in x1, y1, x2, y2 format. References: https://gitlab.kitware.com/computer-vision/kwimage/blob/master/kwimage/structs/boxes.py#L1390 Example: >>> num = 3 >>> scale = 512 >>> rng = 0 >>> boxes = random_boxes(num, scale, rng) >>> print(boxes) tensor([[280.9925, 278.9802, 308.6148, 366.1769], [216.9113, 330.6978, 224.0446, 456.5878], [405.3632, 196.3221, 493.3953, 270.7942]])
167,255
import torch, math def ciou(bboxes1, bboxes2): bboxes1 = torch.sigmoid(bboxes1) bboxes2 = torch.sigmoid(bboxes2) rows = bboxes1.shape[0] cols = bboxes2.shape[0] cious = torch.zeros((rows, cols)) if rows * cols == 0: return cious exchange = False if bboxes1.shape[0] > bboxes2.shape[0]: bboxes1, bboxes2 = bboxes2, bboxes1 cious = torch.zeros((cols, rows)) exchange = True w1 = torch.exp(bboxes1[:, 2]) h1 = torch.exp(bboxes1[:, 3]) w2 = torch.exp(bboxes2[:, 2]) h2 = torch.exp(bboxes2[:, 3]) area1 = w1 * h1 area2 = w2 * h2 center_x1 = bboxes1[:, 0] center_y1 = bboxes1[:, 1] center_x2 = bboxes2[:, 0] center_y2 = bboxes2[:, 1] inter_l = torch.max(center_x1 - w1 / 2,center_x2 - w2 / 2) inter_r = torch.min(center_x1 + w1 / 2,center_x2 + w2 / 2) inter_t = torch.max(center_y1 - h1 / 2,center_y2 - h2 / 2) inter_b = torch.min(center_y1 + h1 / 2,center_y2 + h2 / 2) inter_area = torch.clamp((inter_r - inter_l),min=0) * torch.clamp((inter_b - inter_t),min=0) c_l = torch.min(center_x1 - w1 / 2,center_x2 - w2 / 2) c_r = torch.max(center_x1 + w1 / 2,center_x2 + w2 / 2) c_t = torch.min(center_y1 - h1 / 2,center_y2 - h2 / 2) c_b = torch.max(center_y1 + h1 / 2,center_y2 + h2 / 2) inter_diag = (center_x2 - center_x1)**2 + (center_y2 - center_y1)**2 c_diag = torch.clamp((c_r - c_l),min=0)**2 + torch.clamp((c_b - c_t),min=0)**2 union = area1+area2-inter_area u = (inter_diag) / c_diag iou = inter_area / union v = (4 / (math.pi ** 2)) * torch.pow((torch.atan(w2 / h2) - torch.atan(w1 / h1)), 2) with torch.no_grad(): S = (iou>0.5).float() alpha= S*v/(1-iou+v) cious = iou - u - alpha * v cious = torch.clamp(cious,min=-1.0,max = 1.0) if exchange: cious = cious.T return 1-cious
null
167,256
import torch, math def diou(bboxes1, bboxes2): bboxes1 = torch.sigmoid(bboxes1) bboxes2 = torch.sigmoid(bboxes2) rows = bboxes1.shape[0] cols = bboxes2.shape[0] cious = torch.zeros((rows, cols)) if rows * cols == 0: return cious exchange = False if bboxes1.shape[0] > bboxes2.shape[0]: bboxes1, bboxes2 = bboxes2, bboxes1 cious = torch.zeros((cols, rows)) exchange = True w1 = torch.exp(bboxes1[:, 2]) h1 = torch.exp(bboxes1[:, 3]) w2 = torch.exp(bboxes2[:, 2]) h2 = torch.exp(bboxes2[:, 3]) area1 = w1 * h1 area2 = w2 * h2 center_x1 = bboxes1[:, 0] center_y1 = bboxes1[:, 1] center_x2 = bboxes2[:, 0] center_y2 = bboxes2[:, 1] inter_l = torch.max(center_x1 - w1 / 2,center_x2 - w2 / 2) inter_r = torch.min(center_x1 + w1 / 2,center_x2 + w2 / 2) inter_t = torch.max(center_y1 - h1 / 2,center_y2 - h2 / 2) inter_b = torch.min(center_y1 + h1 / 2,center_y2 + h2 / 2) inter_area = torch.clamp((inter_r - inter_l),min=0) * torch.clamp((inter_b - inter_t),min=0) c_l = torch.min(center_x1 - w1 / 2,center_x2 - w2 / 2) c_r = torch.max(center_x1 + w1 / 2,center_x2 + w2 / 2) c_t = torch.min(center_y1 - h1 / 2,center_y2 - h2 / 2) c_b = torch.max(center_y1 + h1 / 2,center_y2 + h2 / 2) inter_diag = (center_x2 - center_x1)**2 + (center_y2 - center_y1)**2 c_diag = torch.clamp((c_r - c_l),min=0)**2 + torch.clamp((c_b - c_t),min=0)**2 union = area1+area2-inter_area u = (inter_diag) / c_diag iou = inter_area / union dious = iou - u dious = torch.clamp(dious,min=-1.0,max = 1.0) if exchange: dious = dious.T return 1-dious
null
167,257
import os, sys import os.path as osp import ast import tempfile import shutil from importlib import import_module from argparse import Action from addict import Dict from yapf.yapflib.yapf_api import FormatCode import platform def check_file_exist(filename, msg_tmpl='file "{}" does not exist'): if not osp.isfile(filename): raise FileNotFoundError(msg_tmpl.format(filename))
null
167,258
import cv2 import numpy as np from util.utils import renorm from util.misc import color_sys _color_getter = color_sys(100) def add_box_to_img(img, boxes, colorlist, brands=None): """[summary] Args: img ([type]): np.array, H,W,3 boxes ([type]): list of list(4) colorlist: list of colors. brands: text. Return: img: np.array. H,W,3. """ H, W = img.shape[:2] for _i, (box, color) in enumerate(zip(boxes, colorlist)): x, y, w, h = box[0] * W, box[1] * H, box[2] * W, box[3] * H img = cv2.rectangle(img.copy(), (int(x-w/2), int(y-h/2)), (int(x+w/2), int(y+h/2)), color, 2) if brands is not None: brand = brands[_i] org = (int(x-w/2), int(y+h/2)) font = cv2.FONT_HERSHEY_SIMPLEX fontScale = 0.5 thickness = 1 img = cv2.putText(img.copy(), str(brand), org, font, fontScale, color, thickness, cv2.LINE_AA) return img def renorm(img: torch.FloatTensor, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) \ -> torch.FloatTensor: # img: tensor(3,H,W) or tensor(B,3,H,W) # return: same as img assert img.dim() == 3 or img.dim() == 4, "img.dim() should be 3 or 4 but %d" % img.dim() if img.dim() == 3: assert img.size(0) == 3, 'img.size(0) shoule be 3 but "%d". (%s)' % (img.size(0), str(img.size())) img_perm = img.permute(1,2,0) mean = torch.Tensor(mean) std = torch.Tensor(std) img_res = img_perm * std + mean return img_res.permute(2,0,1) else: # img.dim() == 4 assert img.size(1) == 3, 'img.size(1) shoule be 3 but "%d". (%s)' % (img.size(1), str(img.size())) img_perm = img.permute(0,2,3,1) mean = torch.Tensor(mean) std = torch.Tensor(std) img_res = img_perm * std + mean return img_res.permute(0,3,1,2) The provided code snippet includes necessary dependencies for implementing the `plot_dual_img` function. Write a Python function `def plot_dual_img(img, boxes, labels, idxs, probs=None)` to solve the following problem: [summary] Args: img ([type]): 3,H,W. tensor. boxes (): tensor(Kx4) or list of tensor(1x4). labels ([type]): list of ints. idxs ([type]): list of ints. probs (optional): listof floats. Returns: img_classcolor: np.array. H,W,3. img with class-wise label. img_seqcolor: np.array. H,W,3. img with seq-wise label. Here is the function: def plot_dual_img(img, boxes, labels, idxs, probs=None): """[summary] Args: img ([type]): 3,H,W. tensor. boxes (): tensor(Kx4) or list of tensor(1x4). labels ([type]): list of ints. idxs ([type]): list of ints. probs (optional): listof floats. Returns: img_classcolor: np.array. H,W,3. img with class-wise label. img_seqcolor: np.array. H,W,3. img with seq-wise label. """ boxes = [i.cpu().tolist() for i in boxes] img = (renorm(img.cpu()).permute(1,2,0).numpy() * 255).astype(np.uint8) # plot with class class_colors = [_color_getter(i) for i in labels] if probs is not None: brands = ["{},{:.2f}".format(j,k) for j,k in zip(labels, probs)] else: brands = labels img_classcolor = add_box_to_img(img, boxes, class_colors, brands=brands) # plot with seq seq_colors = [_color_getter((i * 11) % 100) for i in idxs] img_seqcolor = add_box_to_img(img, boxes, seq_colors, brands=idxs) return img_classcolor, img_seqcolor
[summary] Args: img ([type]): 3,H,W. tensor. boxes (): tensor(Kx4) or list of tensor(1x4). labels ([type]): list of ints. idxs ([type]): list of ints. probs (optional): listof floats. Returns: img_classcolor: np.array. H,W,3. img with class-wise label. img_seqcolor: np.array. H,W,3. img with seq-wise label.
167,259
import cv2 import numpy as np from util.utils import renorm from util.misc import color_sys _color_getter = color_sys(100) def renorm(img: torch.FloatTensor, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) \ -> torch.FloatTensor: # img: tensor(3,H,W) or tensor(B,3,H,W) # return: same as img assert img.dim() == 3 or img.dim() == 4, "img.dim() should be 3 or 4 but %d" % img.dim() if img.dim() == 3: assert img.size(0) == 3, 'img.size(0) shoule be 3 but "%d". (%s)' % (img.size(0), str(img.size())) img_perm = img.permute(1,2,0) mean = torch.Tensor(mean) std = torch.Tensor(std) img_res = img_perm * std + mean return img_res.permute(2,0,1) else: # img.dim() == 4 assert img.size(1) == 3, 'img.size(1) shoule be 3 but "%d". (%s)' % (img.size(1), str(img.size())) img_perm = img.permute(0,2,3,1) mean = torch.Tensor(mean) std = torch.Tensor(std) img_res = img_perm * std + mean return img_res.permute(0,3,1,2) The provided code snippet includes necessary dependencies for implementing the `plot_raw_img` function. Write a Python function `def plot_raw_img(img, boxes, labels)` to solve the following problem: [summary] Args: img ([type]): 3,H,W. tensor. boxes ([type]): Kx4. tensor labels ([type]): K. tensor. return: img: np.array. H,W,3. img with bbox annos. Here is the function: def plot_raw_img(img, boxes, labels): """[summary] Args: img ([type]): 3,H,W. tensor. boxes ([type]): Kx4. tensor labels ([type]): K. tensor. return: img: np.array. H,W,3. img with bbox annos. """ img = (renorm(img.cpu()).permute(1,2,0).numpy() * 255).astype(np.uint8) H, W = img.shape[:2] for box, label in zip(boxes.tolist(), labels.tolist()): x, y, w, h = box[0] * W, box[1] * H, box[2] * W, box[3] * H img = cv2.rectangle(img.copy(), (int(x-w/2), int(y-h/2)), (int(x+w/2), int(y+h/2)), _color_getter(label), 2) # add text org = (int(x-w/2), int(y+h/2)) font = cv2.FONT_HERSHEY_SIMPLEX fontScale = 1 thickness = 1 img = cv2.putText(img.copy(), str(label), org, font, fontScale, _color_getter(label), thickness, cv2.LINE_AA) return img
[summary] Args: img ([type]): 3,H,W. tensor. boxes ([type]): Kx4. tensor labels ([type]): K. tensor. return: img: np.array. H,W,3. img with bbox annos.
167,260
import json, pickle, yaml from pathlib import Path from abc import ABCMeta, abstractmethod file_handlers = { 'json': JsonHandler(), 'yaml': YamlHandler(), 'yml': YamlHandler(), 'pickle': PickleHandler(), 'pkl': PickleHandler() } def is_str(x): """Whether the input is an string instance. Note: This method is deprecated since python 2 is no longer supported. """ return isinstance(x, str) The provided code snippet includes necessary dependencies for implementing the `slload` function. Write a Python function `def slload(file, file_format=None, **kwargs)` to solve the following problem: Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. Args: file (str or :obj:`Path` or file-like object): Filename or a file-like object. file_format (str, optional): If not specified, the file format will be inferred from the file extension, otherwise use the specified one. Currently supported formats include "json", "yaml/yml" and "pickle/pkl". Returns: The content from the file. Here is the function: def slload(file, file_format=None, **kwargs): """Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. Args: file (str or :obj:`Path` or file-like object): Filename or a file-like object. file_format (str, optional): If not specified, the file format will be inferred from the file extension, otherwise use the specified one. Currently supported formats include "json", "yaml/yml" and "pickle/pkl". Returns: The content from the file. """ if isinstance(file, Path): file = str(file) if file_format is None and is_str(file): file_format = file.split('.')[-1] if file_format not in file_handlers: raise TypeError(f'Unsupported format: {file_format}') handler = file_handlers[file_format] if is_str(file): obj = handler.load_from_path(file, **kwargs) elif hasattr(file, 'read'): obj = handler.load_from_fileobj(file, **kwargs) else: raise TypeError('"file" must be a filepath str or a file-object') return obj
Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. Args: file (str or :obj:`Path` or file-like object): Filename or a file-like object. file_format (str, optional): If not specified, the file format will be inferred from the file extension, otherwise use the specified one. Currently supported formats include "json", "yaml/yml" and "pickle/pkl". Returns: The content from the file.
167,261
import json, pickle, yaml from pathlib import Path from abc import ABCMeta, abstractmethod file_handlers = { 'json': JsonHandler(), 'yaml': YamlHandler(), 'yml': YamlHandler(), 'pickle': PickleHandler(), 'pkl': PickleHandler() } def is_str(x): """Whether the input is an string instance. Note: This method is deprecated since python 2 is no longer supported. """ return isinstance(x, str) The provided code snippet includes necessary dependencies for implementing the `sldump` function. Write a Python function `def sldump(obj, file=None, file_format=None, **kwargs)` to solve the following problem: Dump data to json/yaml/pickle strings or files. This method provides a unified api for dumping data as strings or to files, and also supports custom arguments for each file format. Args: obj (any): The python object to be dumped. file (str or :obj:`Path` or file-like object, optional): If not specified, then the object is dump to a str, otherwise to a file specified by the filename or file-like object. file_format (str, optional): Same as :func:`load`. Returns: bool: True for success, False otherwise. Here is the function: def sldump(obj, file=None, file_format=None, **kwargs): """Dump data to json/yaml/pickle strings or files. This method provides a unified api for dumping data as strings or to files, and also supports custom arguments for each file format. Args: obj (any): The python object to be dumped. file (str or :obj:`Path` or file-like object, optional): If not specified, then the object is dump to a str, otherwise to a file specified by the filename or file-like object. file_format (str, optional): Same as :func:`load`. Returns: bool: True for success, False otherwise. """ if isinstance(file, Path): file = str(file) if file_format is None: if is_str(file): file_format = file.split('.')[-1] elif file is None: raise ValueError( 'file_format must be specified since file is None') if file_format not in file_handlers: raise TypeError(f'Unsupported format: {file_format}') handler = file_handlers[file_format] if file is None: return handler.dump_to_str(obj, **kwargs) elif is_str(file): handler.dump_to_path(obj, file, **kwargs) elif hasattr(file, 'write'): handler.dump_to_fileobj(obj, file, **kwargs) else: raise TypeError('"file" must be a filename str or a file-object')
Dump data to json/yaml/pickle strings or files. This method provides a unified api for dumping data as strings or to files, and also supports custom arguments for each file format. Args: obj (any): The python object to be dumped. file (str or :obj:`Path` or file-like object, optional): If not specified, then the object is dump to a str, otherwise to a file specified by the filename or file-like object. file_format (str, optional): Same as :func:`load`. Returns: bool: True for success, False otherwise.
167,262
import torch, os from torchvision.ops.boxes import box_area def box_cxcywh_to_xyxy(x): x_c, y_c, w, h = x.unbind(-1) b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)] return torch.stack(b, dim=-1)
null
167,263
import torch, os from torchvision.ops.boxes import box_area def box_xyxy_to_cxcywh(x): x0, y0, x1, y1 = x.unbind(-1) b = [(x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0), (y1 - y0)] return torch.stack(b, dim=-1)
null
167,264
import torch, os from torchvision.ops.boxes import box_area def box_iou(boxes1, boxes2): area1 = box_area(boxes1) area2 = box_area(boxes2) lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2] rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2] wh = (rb - lt).clamp(min=0) # [N,M,2] inter = wh[:, :, 0] * wh[:, :, 1] # [N,M] union = area1[:, None] + area2 - inter iou = inter / (union + 1e-6) return iou, union The provided code snippet includes necessary dependencies for implementing the `generalized_box_iou` function. Write a Python function `def generalized_box_iou(boxes1, boxes2)` to solve the following problem: Generalized IoU from https://giou.stanford.edu/ The boxes should be in [x0, y0, x1, y1] format Returns a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2) Here is the function: def generalized_box_iou(boxes1, boxes2): """ Generalized IoU from https://giou.stanford.edu/ The boxes should be in [x0, y0, x1, y1] format Returns a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2) """ # degenerate boxes gives inf / nan results # so do an early check assert (boxes1[:, 2:] >= boxes1[:, :2]).all() assert (boxes2[:, 2:] >= boxes2[:, :2]).all() iou, union = box_iou(boxes1, boxes2) lt = torch.min(boxes1[:, None, :2], boxes2[:, :2]) rb = torch.max(boxes1[:, None, 2:], boxes2[:, 2:]) wh = (rb - lt).clamp(min=0) # [N,M,2] area = wh[:, :, 0] * wh[:, :, 1] return iou - (area - union) / (area + 1e-6)
Generalized IoU from https://giou.stanford.edu/ The boxes should be in [x0, y0, x1, y1] format Returns a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2)
167,265
import torch, os from torchvision.ops.boxes import box_area def box_iou_pairwise(boxes1, boxes2): area1 = box_area(boxes1) area2 = box_area(boxes2) lt = torch.max(boxes1[:, :2], boxes2[:, :2]) # [N,2] rb = torch.min(boxes1[:, 2:], boxes2[:, 2:]) # [N,2] wh = (rb - lt).clamp(min=0) # [N,2] inter = wh[:, 0] * wh[:, 1] # [N] union = area1 + area2 - inter iou = inter / union return iou, union The provided code snippet includes necessary dependencies for implementing the `generalized_box_iou_pairwise` function. Write a Python function `def generalized_box_iou_pairwise(boxes1, boxes2)` to solve the following problem: Generalized IoU from https://giou.stanford.edu/ Input: - boxes1, boxes2: N,4 Output: - giou: N, 4 Here is the function: def generalized_box_iou_pairwise(boxes1, boxes2): """ Generalized IoU from https://giou.stanford.edu/ Input: - boxes1, boxes2: N,4 Output: - giou: N, 4 """ # degenerate boxes gives inf / nan results # so do an early check assert (boxes1[:, 2:] >= boxes1[:, :2]).all() assert (boxes2[:, 2:] >= boxes2[:, :2]).all() assert boxes1.shape == boxes2.shape iou, union = box_iou_pairwise(boxes1, boxes2) # N, 4 lt = torch.min(boxes1[:, :2], boxes2[:, :2]) rb = torch.max(boxes1[:, 2:], boxes2[:, 2:]) wh = (rb - lt).clamp(min=0) # [N,2] area = wh[:, 0] * wh[:, 1] return iou - (area - union) / area
Generalized IoU from https://giou.stanford.edu/ Input: - boxes1, boxes2: N,4 Output: - giou: N, 4
167,266
import torch, os from torchvision.ops.boxes import box_area The provided code snippet includes necessary dependencies for implementing the `masks_to_boxes` function. Write a Python function `def masks_to_boxes(masks)` to solve the following problem: Compute the bounding boxes around the provided masks The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions. Returns a [N, 4] tensors, with the boxes in xyxy format Here is the function: def masks_to_boxes(masks): """Compute the bounding boxes around the provided masks The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions. Returns a [N, 4] tensors, with the boxes in xyxy format """ if masks.numel() == 0: return torch.zeros((0, 4), device=masks.device) h, w = masks.shape[-2:] y = torch.arange(0, h, dtype=torch.float) x = torch.arange(0, w, dtype=torch.float) y, x = torch.meshgrid(y, x) x_mask = (masks * x.unsqueeze(0)) x_max = x_mask.flatten(1).max(-1)[0] x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0] y_mask = (masks * y.unsqueeze(0)) y_max = y_mask.flatten(1).max(-1)[0] y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0] return torch.stack([x_min, y_min, x_max, y_max], 1)
Compute the bounding boxes around the provided masks The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions. Returns a [N, 4] tensors, with the boxes in xyxy format
167,267
import json import torch import torch.nn as nn def match_name_keywords(n: str, name_keywords: list): out = False for b in name_keywords: if b in n: out = True break return out def get_param_dict(args, model_without_ddp: nn.Module): try: param_dict_type = args.param_dict_type except: param_dict_type = 'default' assert param_dict_type in ['default', 'ddetr_in_mmdet', 'large_wd'] # by default if param_dict_type == 'default': param_dicts = [ {"params": [p for n, p in model_without_ddp.named_parameters() if "backbone" not in n and p.requires_grad]}, { "params": [p for n, p in model_without_ddp.named_parameters() if "backbone" in n and p.requires_grad], "lr": args.lr_backbone, } ] return param_dicts if param_dict_type == 'ddetr_in_mmdet': param_dicts = [ { "params": [p for n, p in model_without_ddp.named_parameters() if not match_name_keywords(n, args.lr_backbone_names) and not match_name_keywords(n, args.lr_linear_proj_names) and p.requires_grad], "lr": args.lr, }, { "params": [p for n, p in model_without_ddp.named_parameters() if match_name_keywords(n, args.lr_backbone_names) and p.requires_grad], "lr": args.lr_backbone, }, { "params": [p for n, p in model_without_ddp.named_parameters() if match_name_keywords(n, args.lr_linear_proj_names) and p.requires_grad], "lr": args.lr * args.lr_linear_proj_mult, } ] return param_dicts if param_dict_type == 'large_wd': param_dicts = [ { "params": [p for n, p in model_without_ddp.named_parameters() if not match_name_keywords(n, ['backbone']) and not match_name_keywords(n, ['norm', 'bias']) and p.requires_grad], }, { "params": [p for n, p in model_without_ddp.named_parameters() if match_name_keywords(n, ['backbone']) and match_name_keywords(n, ['norm', 'bias']) and p.requires_grad], "lr": args.lr_backbone, "weight_decay": 0.0, }, { "params": [p for n, p in model_without_ddp.named_parameters() if match_name_keywords(n, ['backbone']) and not match_name_keywords(n, ['norm', 'bias']) and p.requires_grad], "lr": args.lr_backbone, "weight_decay": args.weight_decay, }, { "params": [p for n, p in model_without_ddp.named_parameters() if not match_name_keywords(n, ['backbone']) and match_name_keywords(n, ['norm', 'bias']) and p.requires_grad], "lr": args.lr, "weight_decay": 0.0, } ] # print("param_dicts: {}".format(param_dicts)) return param_dicts
null
167,268
import os, sys from textwrap import wrap import torch import numpy as np import cv2 import datetime import matplotlib.pyplot as plt from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon from pycocotools import mask as maskUtils from matplotlib import transforms def renorm(img: torch.FloatTensor, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) \ -> torch.FloatTensor: # img: tensor(3,H,W) or tensor(B,3,H,W) # return: same as img assert img.dim() == 3 or img.dim() == 4, "img.dim() should be 3 or 4 but %d" % img.dim() if img.dim() == 3: assert img.size(0) == 3, 'img.size(0) shoule be 3 but "%d". (%s)' % (img.size(0), str(img.size())) img_perm = img.permute(1,2,0) mean = torch.Tensor(mean) std = torch.Tensor(std) img_res = img_perm * std + mean return img_res.permute(2,0,1) else: # img.dim() == 4 assert img.size(1) == 3, 'img.size(1) shoule be 3 but "%d". (%s)' % (img.size(1), str(img.size())) img_perm = img.permute(0,2,3,1) mean = torch.Tensor(mean) std = torch.Tensor(std) img_res = img_perm * std + mean return img_res.permute(0,3,1,2)
null
167,269
import os import random import subprocess import time from collections import OrderedDict, defaultdict, deque import datetime import pickle from typing import Optional, List import json, time import numpy as np import torch import torch.distributed as dist from torch import Tensor import colorsys import torchvision def get_sha(): cwd = os.path.dirname(os.path.abspath(__file__)) def _run(command): return subprocess.check_output(command, cwd=cwd).decode('ascii').strip() sha = 'N/A' diff = "clean" branch = 'N/A' try: sha = _run(['git', 'rev-parse', 'HEAD']) subprocess.check_output(['git', 'diff'], cwd=cwd) diff = _run(['git', 'diff-index', 'HEAD']) diff = "has uncommited changes" if diff else "clean" branch = _run(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) except Exception: pass message = f"sha: {sha}, status: {diff}, branch: {branch}" return message
null
167,270
import os import random import subprocess import time from collections import OrderedDict, defaultdict, deque import datetime import pickle from typing import Optional, List import json, time import numpy as np import torch import torch.distributed as dist from torch import Tensor import colorsys import torchvision def nested_tensor_from_tensor_list(tensor_list: List[Tensor]): # TODO make this more general if tensor_list[0].ndim == 3: if torchvision._is_tracing(): # nested_tensor_from_tensor_list() does not export well to ONNX # call _onnx_nested_tensor_from_tensor_list() instead return _onnx_nested_tensor_from_tensor_list(tensor_list) # TODO make it support different-sized images max_size = _max_by_axis([list(img.shape) for img in tensor_list]) # min_size = tuple(min(s) for s in zip(*[img.shape for img in tensor_list])) batch_shape = [len(tensor_list)] + max_size b, c, h, w = batch_shape dtype = tensor_list[0].dtype device = tensor_list[0].device tensor = torch.zeros(batch_shape, dtype=dtype, device=device) mask = torch.ones((b, h, w), dtype=torch.bool, device=device) for img, pad_img, m in zip(tensor_list, tensor, mask): pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) m[: img.shape[1], :img.shape[2]] = False else: raise ValueError('not supported') return NestedTensor(tensor, mask) def collate_fn(batch): batch = list(zip(*batch)) batch[0] = nested_tensor_from_tensor_list(batch[0]) return tuple(batch)
null
167,271
import os import random import subprocess import time from collections import OrderedDict, defaultdict, deque import datetime import pickle from typing import Optional, List import json, time import numpy as np import torch import torch.distributed as dist from torch import Tensor import colorsys import torchvision def is_main_process(): return get_rank() == 0 def save_on_master(*args, **kwargs): if is_main_process(): torch.save(*args, **kwargs)
null
167,272
import os import random import subprocess import time from collections import OrderedDict, defaultdict, deque import datetime import pickle from typing import Optional, List import json, time import numpy as np import torch import torch.distributed as dist from torch import Tensor import colorsys import torchvision def setup_for_distributed(is_master): """ This function disables printing when not in master process """ import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs): force = kwargs.pop('force', False) if is_master or force: builtin_print(*args, **kwargs) __builtin__.print = print def init_distributed_mode(args): if 'WORLD_SIZE' in os.environ and os.environ['WORLD_SIZE'] != '': # 'RANK' in os.environ and # args.rank = int(os.environ["RANK"]) # args.world_size = int(os.environ['WORLD_SIZE']) # args.gpu = args.local_rank = int(os.environ['LOCAL_RANK']) # launch by torch.distributed.launch # Single node # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 1 --rank 0 ... # Multi nodes # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 0 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ... # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 1 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ... local_world_size = int(os.environ['WORLD_SIZE']) args.world_size = args.world_size * local_world_size args.gpu = args.local_rank = int(os.environ['LOCAL_RANK']) args.rank = args.rank * local_world_size + args.local_rank print('world size: {}, rank: {}, local rank: {}'.format(args.world_size, args.rank, args.local_rank)) print(json.dumps(dict(os.environ), indent=2)) elif 'SLURM_PROCID' in os.environ: args.rank = int(os.environ['SLURM_PROCID']) args.gpu = args.local_rank = int(os.environ['SLURM_LOCALID']) args.world_size = int(os.environ['SLURM_NPROCS']) print('world size: {}, world rank: {}, local rank: {}, device_count: {}'.format(args.world_size, args.rank, args.local_rank, torch.cuda.device_count())) else: print('Not using distributed mode') args.distributed = False args.world_size = 1 args.rank = 0 args.local_rank = 0 return print("world_size:{} rank:{} local_rank:{}".format(args.world_size, args.rank, args.local_rank)) args.distributed = True torch.cuda.set_device(args.local_rank) args.dist_backend = 'nccl' print('| distributed init (rank {}): {}'.format(args.rank, args.dist_url), flush=True) torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url, world_size=args.world_size, rank=args.rank) print("Before torch.distributed.barrier()") torch.distributed.barrier() print("End torch.distributed.barrier()") setup_for_distributed(args.rank == 0)
null
167,273
import os import random import subprocess import time from collections import OrderedDict, defaultdict, deque import datetime import pickle from typing import Optional, List import json, time import numpy as np import torch import torch.distributed as dist from torch import Tensor import colorsys import torchvision The provided code snippet includes necessary dependencies for implementing the `accuracy` function. Write a Python function `def accuracy(output, target, topk=(1,))` to solve the following problem: Computes the precision@k for the specified values of k Here is the function: def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" if target.numel() == 0: return [torch.zeros([], device=output.device)] maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append(correct_k.mul_(100.0 / batch_size)) return res
Computes the precision@k for the specified values of k
167,274
import torch import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from pathlib import Path, PurePath The provided code snippet includes necessary dependencies for implementing the `plot_logs` function. Write a Python function `def plot_logs(logs, fields=('class_error', 'loss_bbox_unscaled', 'mAP'), ewm_col=0, log_name='log.txt')` to solve the following problem: Function to plot specific fields from training log(s). Plots both training and test results. :: Inputs - logs = list containing Path objects, each pointing to individual dir with a log file - fields = which results to plot from each log file - plots both training and test for each field. - ewm_col = optional, which column to use as the exponential weighted smoothing of the plots - log_name = optional, name of log file if different than default 'log.txt'. :: Outputs - matplotlib plots of results in fields, color coded for each log file. - solid lines are training results, dashed lines are test results. Here is the function: def plot_logs(logs, fields=('class_error', 'loss_bbox_unscaled', 'mAP'), ewm_col=0, log_name='log.txt'): ''' Function to plot specific fields from training log(s). Plots both training and test results. :: Inputs - logs = list containing Path objects, each pointing to individual dir with a log file - fields = which results to plot from each log file - plots both training and test for each field. - ewm_col = optional, which column to use as the exponential weighted smoothing of the plots - log_name = optional, name of log file if different than default 'log.txt'. :: Outputs - matplotlib plots of results in fields, color coded for each log file. - solid lines are training results, dashed lines are test results. ''' func_name = "plot_utils.py::plot_logs" # verify logs is a list of Paths (list[Paths]) or single Pathlib object Path, # convert single Path to list to avoid 'not iterable' error if not isinstance(logs, list): if isinstance(logs, PurePath): logs = [logs] print(f"{func_name} info: logs param expects a list argument, converted to list[Path].") else: raise ValueError(f"{func_name} - invalid argument for logs parameter.\n \ Expect list[Path] or single Path obj, received {type(logs)}") # Quality checks - verify valid dir(s), that every item in list is Path object, and that log_name exists in each dir for i, dir in enumerate(logs): if not isinstance(dir, PurePath): raise ValueError(f"{func_name} - non-Path object in logs argument of {type(dir)}: \n{dir}") if not dir.exists(): raise ValueError(f"{func_name} - invalid directory in logs argument:\n{dir}") # verify log_name exists fn = Path(dir / log_name) if not fn.exists(): print(f"-> missing {log_name}. Have you gotten to Epoch 1 in training?") print(f"--> full path of missing log file: {fn}") return # load log file(s) and plot dfs = [pd.read_json(Path(p) / log_name, lines=True) for p in logs] fig, axs = plt.subplots(ncols=len(fields), figsize=(16, 5)) for df, color in zip(dfs, sns.color_palette(n_colors=len(logs))): for j, field in enumerate(fields): if field == 'mAP': coco_eval = pd.DataFrame( np.stack(df.test_coco_eval_bbox.dropna().values)[:, 1] ).ewm(com=ewm_col).mean() axs[j].plot(coco_eval, c=color) else: df.interpolate().ewm(com=ewm_col).mean().plot( y=[f'train_{field}', f'test_{field}'], ax=axs[j], color=[color] * 2, style=['-', '--'] ) for ax, field in zip(axs, fields): if field == 'mAP': ax.legend([Path(p).name for p in logs]) ax.set_title(field) else: ax.legend([f'train', f'test']) ax.set_title(field) return fig, axs
Function to plot specific fields from training log(s). Plots both training and test results. :: Inputs - logs = list containing Path objects, each pointing to individual dir with a log file - fields = which results to plot from each log file - plots both training and test for each field. - ewm_col = optional, which column to use as the exponential weighted smoothing of the plots - log_name = optional, name of log file if different than default 'log.txt'. :: Outputs - matplotlib plots of results in fields, color coded for each log file. - solid lines are training results, dashed lines are test results.
167,276
import functools import logging import os import sys from termcolor import colored class _ColorfulFormatter(logging.Formatter): def __init__(self, *args, **kwargs): self._root_name = kwargs.pop("root_name") + "." self._abbrev_name = kwargs.pop("abbrev_name", "") if len(self._abbrev_name): self._abbrev_name = self._abbrev_name + "." super(_ColorfulFormatter, self).__init__(*args, **kwargs) def formatMessage(self, record): record.name = record.name.replace(self._root_name, self._abbrev_name) log = super(_ColorfulFormatter, self).formatMessage(record) if record.levelno == logging.WARNING: prefix = colored("WARNING", "red", attrs=["blink"]) elif record.levelno == logging.ERROR or record.levelno == logging.CRITICAL: prefix = colored("ERROR", "red", attrs=["blink", "underline"]) else: return log return prefix + " " + log def _cached_log_stream(filename): return open(filename, "a") The provided code snippet includes necessary dependencies for implementing the `setup_logger` function. Write a Python function `def setup_logger( output=None, distributed_rank=0, *, color=True, name="imagenet", abbrev_name=None )` to solve the following problem: Initialize the detectron2 logger and set its verbosity level to "INFO". Args: output (str): a file name or a directory to save log. If None, will not save log file. If ends with ".txt" or ".log", assumed to be a file name. Otherwise, logs will be saved to `output/log.txt`. name (str): the root module name of this logger Returns: logging.Logger: a logger Here is the function: def setup_logger( output=None, distributed_rank=0, *, color=True, name="imagenet", abbrev_name=None ): """ Initialize the detectron2 logger and set its verbosity level to "INFO". Args: output (str): a file name or a directory to save log. If None, will not save log file. If ends with ".txt" or ".log", assumed to be a file name. Otherwise, logs will be saved to `output/log.txt`. name (str): the root module name of this logger Returns: logging.Logger: a logger """ logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) logger.propagate = False if abbrev_name is None: abbrev_name = name plain_formatter = logging.Formatter( '[%(asctime)s.%(msecs)03d]: %(message)s', datefmt='%m/%d %H:%M:%S' ) # stdout logging: master only if distributed_rank == 0: ch = logging.StreamHandler(stream=sys.stdout) ch.setLevel(logging.DEBUG) if color: formatter = _ColorfulFormatter( colored("[%(asctime)s.%(msecs)03d]: ", "green") + "%(message)s", datefmt="%m/%d %H:%M:%S", root_name=name, abbrev_name=str(abbrev_name), ) else: formatter = plain_formatter ch.setFormatter(formatter) logger.addHandler(ch) # file logging: all workers if output is not None: if output.endswith(".txt") or output.endswith(".log"): filename = output else: filename = os.path.join(output, "log.txt") if distributed_rank > 0: filename = filename + f".rank{distributed_rank}" os.makedirs(os.path.dirname(filename), exist_ok=True) fh = logging.StreamHandler(_cached_log_stream(filename)) fh.setLevel(logging.DEBUG) fh.setFormatter(plain_formatter) logger.addHandler(fh) return logger
Initialize the detectron2 logger and set its verbosity level to "INFO". Args: output (str): a file name or a directory to save log. If None, will not save log file. If ends with ".txt" or ".log", assumed to be a file name. Otherwise, logs will be saved to `output/log.txt`. name (str): the root module name of this logger Returns: logging.Logger: a logger
167,277
import math import os import sys from typing import Iterable from util.utils import slprint, to_device import torch import util.misc as utils from datasets.coco_eval import CocoEvaluator from datasets.panoptic_eval import PanopticEvaluator def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, max_norm: float = 0, wo_class_error=False, lr_scheduler=None, args=None, logger=None, ema_m=None): scaler = torch.cuda.amp.GradScaler(enabled=args.amp) try: need_tgt_for_training = args.use_dn except: need_tgt_for_training = False model.train() criterion.train() metric_logger = utils.MetricLogger(delimiter=" ") metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}')) if not wo_class_error: metric_logger.add_meter('class_error', utils.SmoothedValue(window_size=1, fmt='{value:.2f}')) header = 'Epoch: [{}]'.format(epoch) print_freq = 10 _cnt = 0 for samples, targets in metric_logger.log_every(data_loader, print_freq, header, logger=logger): samples = samples.to(device) targets = [{k: v.to(device) for k, v in t.items()} for t in targets] with torch.cuda.amp.autocast(enabled=args.amp): if need_tgt_for_training: outputs = model(samples, targets) else: outputs = model(samples) loss_dict = criterion(outputs, targets) weight_dict = criterion.weight_dict losses = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict) # reduce losses over all GPUs for logging purposes loss_dict_reduced = utils.reduce_dict(loss_dict) loss_dict_reduced_unscaled = {f'{k}_unscaled': v for k, v in loss_dict_reduced.items()} loss_dict_reduced_scaled = {k: v * weight_dict[k] for k, v in loss_dict_reduced.items() if k in weight_dict} losses_reduced_scaled = sum(loss_dict_reduced_scaled.values()) loss_value = losses_reduced_scaled.item() if not math.isfinite(loss_value): print("Loss is {}, stopping training".format(loss_value)) print(loss_dict_reduced) sys.exit(1) # amp backward function if args.amp: optimizer.zero_grad() scaler.scale(losses).backward() if max_norm > 0: scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm) scaler.step(optimizer) scaler.update() else: # original backward function optimizer.zero_grad() losses.backward() if max_norm > 0: torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm) optimizer.step() if args.onecyclelr: lr_scheduler.step() if args.use_ema: if epoch >= args.ema_epoch: ema_m.update(model) metric_logger.update(loss=loss_value, **loss_dict_reduced_scaled, **loss_dict_reduced_unscaled) if 'class_error' in loss_dict_reduced: metric_logger.update(class_error=loss_dict_reduced['class_error']) metric_logger.update(lr=optimizer.param_groups[0]["lr"]) _cnt += 1 if args.debug: if _cnt % 15 == 0: print("BREAK!"*5) break if getattr(criterion, 'loss_weight_decay', False): criterion.loss_weight_decay(epoch=epoch) if getattr(criterion, 'tuning_matching', False): criterion.tuning_matching(epoch) # gather the stats from all processes metric_logger.synchronize_between_processes() print("Averaged stats:", metric_logger) resstat = {k: meter.global_avg for k, meter in metric_logger.meters.items() if meter.count > 0} if getattr(criterion, 'loss_weight_decay', False): resstat.update({f'weight_{k}': v for k,v in criterion.weight_dict.items()}) return resstat
null
167,278
import math import os import sys from typing import Iterable from util.utils import slprint, to_device import torch import util.misc as utils from datasets.coco_eval import CocoEvaluator from datasets.panoptic_eval import PanopticEvaluator def to_device(item, device): if isinstance(item, torch.Tensor): return item.to(device) elif isinstance(item, list): return [to_device(i, device) for i in item] elif isinstance(item, dict): return {k: to_device(v, device) for k,v in item.items()} else: raise NotImplementedError("Call Shilong if you use other containers! type: {}".format(type(item))) class CocoEvaluator(object): def __init__(self, coco_gt, iou_types, useCats=True): assert isinstance(iou_types, (list, tuple)) coco_gt = copy.deepcopy(coco_gt) self.coco_gt = coco_gt self.iou_types = iou_types self.coco_eval = {} for iou_type in iou_types: self.coco_eval[iou_type] = COCOeval(coco_gt, iouType=iou_type) self.coco_eval[iou_type].useCats = useCats self.img_ids = [] self.eval_imgs = {k: [] for k in iou_types} self.useCats = useCats def update(self, predictions): img_ids = list(np.unique(list(predictions.keys()))) self.img_ids.extend(img_ids) for iou_type in self.iou_types: results = self.prepare(predictions, iou_type) # suppress pycocotools prints with open(os.devnull, 'w') as devnull: with contextlib.redirect_stdout(devnull): coco_dt = COCO.loadRes(self.coco_gt, results) if results else COCO() coco_eval = self.coco_eval[iou_type] coco_eval.cocoDt = coco_dt coco_eval.params.imgIds = list(img_ids) coco_eval.params.useCats = self.useCats img_ids, eval_imgs = evaluate(coco_eval) self.eval_imgs[iou_type].append(eval_imgs) def synchronize_between_processes(self): for iou_type in self.iou_types: self.eval_imgs[iou_type] = np.concatenate(self.eval_imgs[iou_type], 2) create_common_coco_eval(self.coco_eval[iou_type], self.img_ids, self.eval_imgs[iou_type]) def accumulate(self): for coco_eval in self.coco_eval.values(): coco_eval.accumulate() def summarize(self): for iou_type, coco_eval in self.coco_eval.items(): print("IoU metric: {}".format(iou_type)) coco_eval.summarize() def prepare(self, predictions, iou_type): if iou_type == "bbox": return self.prepare_for_coco_detection(predictions) elif iou_type == "segm": return self.prepare_for_coco_segmentation(predictions) elif iou_type == "keypoints": return self.prepare_for_coco_keypoint(predictions) else: raise ValueError("Unknown iou type {}".format(iou_type)) def prepare_for_coco_detection(self, predictions): coco_results = [] for original_id, prediction in predictions.items(): if len(prediction) == 0: continue boxes = prediction["boxes"] boxes = convert_to_xywh(boxes).tolist() if not isinstance(prediction["scores"], list): scores = prediction["scores"].tolist() else: scores = prediction["scores"] if not isinstance(prediction["labels"], list): labels = prediction["labels"].tolist() else: labels = prediction["labels"] try: coco_results.extend( [ { "image_id": original_id, "category_id": labels[k], "bbox": box, "score": scores[k], } for k, box in enumerate(boxes) ] ) except: import ipdb; ipdb.set_trace() return coco_results def prepare_for_coco_segmentation(self, predictions): coco_results = [] for original_id, prediction in predictions.items(): if len(prediction) == 0: continue scores = prediction["scores"] labels = prediction["labels"] masks = prediction["masks"] masks = masks > 0.5 scores = prediction["scores"].tolist() labels = prediction["labels"].tolist() rles = [ mask_util.encode(np.array(mask[0, :, :, np.newaxis], dtype=np.uint8, order="F"))[0] for mask in masks ] for rle in rles: rle["counts"] = rle["counts"].decode("utf-8") coco_results.extend( [ { "image_id": original_id, "category_id": labels[k], "segmentation": rle, "score": scores[k], } for k, rle in enumerate(rles) ] ) return coco_results def prepare_for_coco_keypoint(self, predictions): coco_results = [] for original_id, prediction in predictions.items(): if len(prediction) == 0: continue boxes = prediction["boxes"] boxes = convert_to_xywh(boxes).tolist() scores = prediction["scores"].tolist() labels = prediction["labels"].tolist() keypoints = prediction["keypoints"] keypoints = keypoints.flatten(start_dim=1).tolist() coco_results.extend( [ { "image_id": original_id, "category_id": labels[k], 'keypoints': keypoint, "score": scores[k], } for k, keypoint in enumerate(keypoints) ] ) return coco_results class PanopticEvaluator(object): def __init__(self, ann_file, ann_folder, output_dir="panoptic_eval"): self.gt_json = ann_file self.gt_folder = ann_folder if utils.is_main_process(): if not os.path.exists(output_dir): os.mkdir(output_dir) self.output_dir = output_dir self.predictions = [] def update(self, predictions): for p in predictions: with open(os.path.join(self.output_dir, p["file_name"]), "wb") as f: f.write(p.pop("png_string")) self.predictions += predictions def synchronize_between_processes(self): all_predictions = utils.all_gather(self.predictions) merged_predictions = [] for p in all_predictions: merged_predictions += p self.predictions = merged_predictions def summarize(self): if utils.is_main_process(): json_data = {"annotations": self.predictions} predictions_json = os.path.join(self.output_dir, "predictions.json") with open(predictions_json, "w") as f: f.write(json.dumps(json_data)) return pq_compute(self.gt_json, predictions_json, gt_folder=self.gt_folder, pred_folder=self.output_dir) return None def evaluate(model, criterion, postprocessors, data_loader, base_ds, device, output_dir, wo_class_error=False, args=None, logger=None): try: need_tgt_for_training = args.use_dn except: need_tgt_for_training = False model.eval() criterion.eval() metric_logger = utils.MetricLogger(delimiter=" ") if not wo_class_error: metric_logger.add_meter('class_error', utils.SmoothedValue(window_size=1, fmt='{value:.2f}')) header = 'Test:' iou_types = tuple(k for k in ('segm', 'bbox') if k in postprocessors.keys()) useCats = True try: useCats = args.useCats except: useCats = True if not useCats: print("useCats: {} !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!".format(useCats)) coco_evaluator = CocoEvaluator(base_ds, iou_types, useCats=useCats) # coco_evaluator.coco_eval[iou_types[0]].params.iouThrs = [0, 0.1, 0.5, 0.75] panoptic_evaluator = None if 'panoptic' in postprocessors.keys(): panoptic_evaluator = PanopticEvaluator( data_loader.dataset.ann_file, data_loader.dataset.ann_folder, output_dir=os.path.join(output_dir, "panoptic_eval"), ) _cnt = 0 output_state_dict = {} # for debug only for samples, targets in metric_logger.log_every(data_loader, 10, header, logger=logger): samples = samples.to(device) # targets = [{k: v.to(device) for k, v in t.items()} for t in targets] targets = [{k: to_device(v, device) for k, v in t.items()} for t in targets] with torch.cuda.amp.autocast(enabled=args.amp): if need_tgt_for_training: outputs = model(samples, targets) else: outputs = model(samples) # outputs = model(samples) loss_dict = criterion(outputs, targets) weight_dict = criterion.weight_dict # reduce losses over all GPUs for logging purposes loss_dict_reduced = utils.reduce_dict(loss_dict) loss_dict_reduced_scaled = {k: v * weight_dict[k] for k, v in loss_dict_reduced.items() if k in weight_dict} loss_dict_reduced_unscaled = {f'{k}_unscaled': v for k, v in loss_dict_reduced.items()} metric_logger.update(loss=sum(loss_dict_reduced_scaled.values()), **loss_dict_reduced_scaled, **loss_dict_reduced_unscaled) if 'class_error' in loss_dict_reduced: metric_logger.update(class_error=loss_dict_reduced['class_error']) orig_target_sizes = torch.stack([t["orig_size"] for t in targets], dim=0) results = postprocessors['bbox'](outputs, orig_target_sizes) # [scores: [100], labels: [100], boxes: [100, 4]] x B if 'segm' in postprocessors.keys(): target_sizes = torch.stack([t["size"] for t in targets], dim=0) results = postprocessors['segm'](results, outputs, orig_target_sizes, target_sizes) res = {target['image_id'].item(): output for target, output in zip(targets, results)} if coco_evaluator is not None: coco_evaluator.update(res) if panoptic_evaluator is not None: res_pano = postprocessors["panoptic"](outputs, target_sizes, orig_target_sizes) for i, target in enumerate(targets): image_id = target["image_id"].item() file_name = f"{image_id:012d}.png" res_pano[i]["image_id"] = image_id res_pano[i]["file_name"] = file_name panoptic_evaluator.update(res_pano) if args.save_results: # res_score = outputs['res_score'] # res_label = outputs['res_label'] # res_bbox = outputs['res_bbox'] # res_idx = outputs['res_idx'] for i, (tgt, res, outbbox) in enumerate(zip(targets, results, outputs['pred_boxes'])): """ pred vars: K: number of bbox pred score: Tensor(K), label: list(len: K), bbox: Tensor(K, 4) idx: list(len: K) tgt: dict. """ # compare gt and res (after postprocess) gt_bbox = tgt['boxes'] gt_label = tgt['labels'] gt_info = torch.cat((gt_bbox, gt_label.unsqueeze(-1)), 1) # img_h, img_w = tgt['orig_size'].unbind() # scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=0) # _res_bbox = res['boxes'] / scale_fct _res_bbox = outbbox _res_prob = res['scores'] _res_label = res['labels'] res_info = torch.cat((_res_bbox, _res_prob.unsqueeze(-1), _res_label.unsqueeze(-1)), 1) # import ipdb;ipdb.set_trace() if 'gt_info' not in output_state_dict: output_state_dict['gt_info'] = [] output_state_dict['gt_info'].append(gt_info.cpu()) if 'res_info' not in output_state_dict: output_state_dict['res_info'] = [] output_state_dict['res_info'].append(res_info.cpu()) # # for debug only # import random # if random.random() > 0.7: # print("Now let's break") # break _cnt += 1 if args.debug: if _cnt % 15 == 0: print("BREAK!"*5) break if args.save_results: import os.path as osp # output_state_dict['gt_info'] = torch.cat(output_state_dict['gt_info']) # output_state_dict['res_info'] = torch.cat(output_state_dict['res_info']) savepath = osp.join(args.output_dir, 'results-{}.pkl'.format(utils.get_rank())) print("Saving res to {}".format(savepath)) torch.save(output_state_dict, savepath) # gather the stats from all processes metric_logger.synchronize_between_processes() print("Averaged stats:", metric_logger) if coco_evaluator is not None: coco_evaluator.synchronize_between_processes() if panoptic_evaluator is not None: panoptic_evaluator.synchronize_between_processes() # accumulate predictions from all images if coco_evaluator is not None: coco_evaluator.accumulate() coco_evaluator.summarize() panoptic_res = None if panoptic_evaluator is not None: panoptic_res = panoptic_evaluator.summarize() stats = {k: meter.global_avg for k, meter in metric_logger.meters.items() if meter.count > 0} if coco_evaluator is not None: if 'bbox' in postprocessors.keys(): stats['coco_eval_bbox'] = coco_evaluator.coco_eval['bbox'].stats.tolist() if 'segm' in postprocessors.keys(): stats['coco_eval_masks'] = coco_evaluator.coco_eval['segm'].stats.tolist() if panoptic_res is not None: stats['PQ_all'] = panoptic_res["All"] stats['PQ_th'] = panoptic_res["Things"] stats['PQ_st'] = panoptic_res["Stuff"] return stats, coco_evaluator
null
167,279
import argparse import logging import os import pathlib from typing import List, NoReturn import lightning.pytorch as pl from lightning.pytorch.strategies import DDPStrategy from torch.utils.tensorboard import SummaryWriter from data.datamodules import * from utils import create_logging, parse_yaml from models.resunet import * from losses import get_loss_function from models.audiosep import AudioSep, get_model_class from data.waveform_mixers import SegmentMixer from models.clap_encoder import CLAP_Encoder from callbacks.base import CheckpointEveryNSteps from optimizers.lr_schedulers import get_lr_lambda def get_dirs( workspace: str, filename: str, config_yaml: str, devices_num: int ) -> List[str]: r"""Get directories and paths. Args: workspace (str): directory of workspace filename (str): filename of current .py file. config_yaml (str): config yaml path devices_num (int): 0 for cpu and 8 for training with 8 GPUs Returns: checkpoints_dir (str): directory to save checkpoints logs_dir (str), directory to save logs tf_logs_dir (str), directory to save TensorBoard logs statistics_path (str), directory to save statistics """ os.makedirs(workspace, exist_ok=True) yaml_name = pathlib.Path(config_yaml).stem # Directory to save checkpoints checkpoints_dir = os.path.join( workspace, "checkpoints", filename, "{},devices={}".format(yaml_name, devices_num), ) os.makedirs(checkpoints_dir, exist_ok=True) # Directory to save logs logs_dir = os.path.join( workspace, "logs", filename, "{},devices={}".format(yaml_name, devices_num), ) os.makedirs(logs_dir, exist_ok=True) # Directory to save TensorBoard logs create_logging(logs_dir, filemode="w") logging.info(args) tf_logs_dir = os.path.join( workspace, "tf_logs", filename, "{},devices={}".format(yaml_name, devices_num), ) # Directory to save statistics statistics_path = os.path.join( workspace, "statistics", filename, "{},devices={}".format(yaml_name, devices_num), "statistics.pkl", ) os.makedirs(os.path.dirname(statistics_path), exist_ok=True) return checkpoints_dir, logs_dir, tf_logs_dir, statistics_path def get_data_module( config_yaml: str, num_workers: int, batch_size: int, ) -> DataModule: r"""Create data_module. Mini-batch data can be obtained by: code-block:: python data_module.setup() for batch_data_dict in data_module.train_dataloader(): print(batch_data_dict.keys()) break Args: workspace: str config_yaml: str num_workers: int, e.g., 0 for non-parallel and 8 for using cpu cores for preparing data in parallel distributed: bool Returns: data_module: DataModule """ # read configurations configs = parse_yaml(config_yaml) sampling_rate = configs['data']['sampling_rate'] segment_seconds = configs['data']['segment_seconds'] # audio-text datasets datafiles = configs['data']['datafiles'] # dataset dataset = AudioTextDataset( datafiles=datafiles, sampling_rate=sampling_rate, max_clip_len=segment_seconds, ) # data module data_module = DataModule( train_dataset=dataset, num_workers=num_workers, batch_size=batch_size ) return data_module def parse_yaml(config_yaml: str) -> Dict: r"""Parse yaml file. Args: config_yaml (str): config yaml path Returns: yaml_dict (Dict): parsed yaml file """ with open(config_yaml, "r") as fr: return yaml.load(fr, Loader=yaml.FullLoader) def parse_yaml(config_yaml: str) -> Dict: r"""Parse yaml file. Args: config_yaml (str): config yaml path Returns: yaml_dict (Dict): parsed yaml file """ with open(config_yaml, "r") as fr: return yaml.load(fr, Loader=yaml.FullLoader) def get_loss_function(loss_type): if loss_type == "l1_wav": return l1_wav else: raise NotImplementedError("Error!") class AudioSep(pl.LightningModule, PyTorchModelHubMixin): def __init__( self, ss_model: nn.Module = None, waveform_mixer = None, query_encoder: nn.Module = CLAP_Encoder().eval(), loss_function = None, optimizer_type: str = None, learning_rate: float = None, lr_lambda_func = None, use_text_ratio: float =1.0, ): r"""Pytorch Lightning wrapper of PyTorch model, including forward, optimization of model, etc. Args: ss_model: nn.Module anchor_segment_detector: nn.Module loss_function: function or object learning_rate: float lr_lambda: function """ super().__init__() self.ss_model = ss_model self.waveform_mixer = waveform_mixer self.query_encoder = query_encoder self.query_encoder_type = self.query_encoder.encoder_type self.use_text_ratio = use_text_ratio self.loss_function = loss_function self.optimizer_type = optimizer_type self.learning_rate = learning_rate self.lr_lambda_func = lr_lambda_func def forward(self, x): pass def training_step(self, batch_data_dict, batch_idx): r"""Forward a mini-batch data to model, calculate loss function, and train for one step. A mini-batch data is evenly distributed to multiple devices (if there are) for parallel training. Args: batch_data_dict: e.g. 'audio_text': { 'text': ['a sound of dog', ...] 'waveform': (batch_size, 1, samples) } batch_idx: int Returns: loss: float, loss function of this mini-batch """ # [important] fix random seeds across devices random.seed(batch_idx) batch_audio_text_dict = batch_data_dict['audio_text'] batch_text = batch_audio_text_dict['text'] batch_audio = batch_audio_text_dict['waveform'] device = batch_audio.device mixtures, segments = self.waveform_mixer( waveforms=batch_audio ) # calculate text embed for audio-text data if self.query_encoder_type == 'CLAP': conditions = self.query_encoder.get_query_embed( modality='hybird', text=batch_text, audio=segments.squeeze(1), use_text_ratio=self.use_text_ratio, ) input_dict = { 'mixture': mixtures[:, None, :].squeeze(1), 'condition': conditions, } target_dict = { 'segment': segments.squeeze(1), } self.ss_model.train() sep_segment = self.ss_model(input_dict)['waveform'] sep_segment = sep_segment.squeeze() # (batch_size, 1, segment_samples) output_dict = { 'segment': sep_segment, } # Calculate loss. loss = self.loss_function(output_dict, target_dict) self.log_dict({"train_loss": loss}) return loss def test_step(self, batch, batch_idx): pass def configure_optimizers(self): r"""Configure optimizer. """ if self.optimizer_type == "AdamW": optimizer = optim.AdamW( params=self.ss_model.parameters(), lr=self.learning_rate, betas=(0.9, 0.999), eps=1e-08, weight_decay=0.0, amsgrad=True, ) else: raise NotImplementedError scheduler = LambdaLR(optimizer, self.lr_lambda_func) output_dict = { "optimizer": optimizer, "lr_scheduler": { 'scheduler': scheduler, 'interval': 'step', 'frequency': 1, } } return output_dict def get_model_class(model_type): if model_type == 'ResUNet30': from models.resunet import ResUNet30 return ResUNet30 else: raise NotImplementedError class SegmentMixer(nn.Module): def __init__(self, max_mix_num, lower_db, higher_db): super(SegmentMixer, self).__init__() self.max_mix_num = max_mix_num self.loudness_param = { 'lower_db': lower_db, 'higher_db': higher_db, } def __call__(self, waveforms): batch_size = waveforms.shape[0] data_dict = { 'segment': [], 'mixture': [], } for n in range(0, batch_size): segment = waveforms[n].clone() # create zero tensors as the background template noise = torch.zeros_like(segment) mix_num = random.randint(2, self.max_mix_num) assert mix_num >= 2 for i in range(1, mix_num): next_segment = waveforms[(n + i) % batch_size] rescaled_next_segment = dynamic_loudnorm(audio=next_segment, reference=segment, **self.loudness_param) noise += rescaled_next_segment # randomly normalize background noise noise = dynamic_loudnorm(audio=noise, reference=segment, **self.loudness_param) # create audio mixyure mixture = segment + noise # declipping if need be max_value = torch.max(torch.abs(mixture)) if max_value > 1: segment *= 0.9 / max_value mixture *= 0.9 / max_value data_dict['segment'].append(segment) data_dict['mixture'].append(mixture) for key in data_dict.keys(): data_dict[key] = torch.stack(data_dict[key], dim=0) # return data_dict return data_dict['mixture'], data_dict['segment'] class CLAP_Encoder(nn.Module): def __init__( self, pretrained_path='checkpoint/music_speech_audioset_epoch_15_esc_89.98.pt', sampling_rate=32000, amodel = "HTSAT-base", ): super().__init__() self.device = "cpu" self.precision = "fp32" self.amodel = amodel # or 'PANN-14' self.tmodel = "roberta" # the best text encoder in our training self.enable_fusion = False # False if you do not want to use the fusion model self.fusion_type = "aff_2d" self.pretrained = pretrained_path self.sampling_rate = sampling_rate self.tokenize = RobertaTokenizer.from_pretrained("roberta-base") self.model, self.model_cfg = create_model( self.amodel, self.tmodel, self.pretrained, precision=self.precision, device=self.device, enable_fusion=self.enable_fusion, fusion_type=self.fusion_type, ) for p in self.model.parameters(): p.requires_grad = False self.model.eval() self.encoder_type = 'CLAP' def batch_to_list(self, batch): ret = [] for i in range(batch.size(0)): ret.append(batch[i]) return ret def _get_audio_embed(self, batch): # batch: [B, samples] with torch.no_grad(): audio_dict_list = [] assert ( self.sampling_rate == 32000 ), "We only support 32000 sampling rate" # batch: [bs, 1, t-samples] batch = torchaudio.functional.resample( batch, orig_freq=self.sampling_rate, new_freq=48000 ) for waveform in self.batch_to_list(batch): audio_dict = {} audio_dict = get_audio_features( audio_dict, waveform, 480000, data_truncating="fusion", data_filling="repeatpad", audio_cfg=self.model_cfg["audio_cfg"], ) audio_dict_list.append(audio_dict) # [bs, 512] embed = self.model.get_audio_embedding(audio_dict_list) return embed.detach() def _get_text_embed(self, batch): double_batch = False if len(batch) == 1: batch = batch * 2 double_batch = True with torch.no_grad(): # the 'fusion' truncate mode can be changed to 'rand_trunc' if run in unfusion mode text_data = self.tokenizer(batch) embed = self.model.get_text_embedding(text_data) if double_batch: embed = embed[0].unsqueeze(0) return embed.detach() def get_query_embed(self, modality, audio=None, text=None, use_text_ratio=0.5, device=None): if modality == 'audio': embed = self._get_audio_embed(audio) elif modality == 'text': embed = self._get_text_embed(text) elif modality == 'hybird': if random.random() > use_text_ratio: embed = self._get_audio_embed(audio) else: embed = self._get_text_embed(text) else: raise NotImplementedError("Please check flag 'training_modality'.") return embed.float() def tokenizer(self, text): result = self.tokenize( text, padding="max_length", truncation=True, max_length=512, return_tensors="pt", ) return {k: v.squeeze(0) for k, v in result.items()} class CheckpointEveryNSteps(pl.Callback): def __init__( self, checkpoints_dir, save_step_frequency, ) -> None: r"""Save a checkpoint every N steps. Args: checkpoints_dir (str): directory to save checkpoints save_step_frequency (int): save checkpoint every N step """ self.checkpoints_dir = checkpoints_dir self.save_step_frequency = save_step_frequency def on_train_batch_end(self, *args, **kwargs) -> None: r"""Save a checkpoint every N steps.""" trainer = args[0] global_step = trainer.global_step if global_step == 1 or global_step % self.save_step_frequency == 0: ckpt_path = os.path.join( self.checkpoints_dir, "step={}.ckpt".format(global_step)) trainer.save_checkpoint(ckpt_path) print("Save checkpoint to {}".format(ckpt_path)) def get_lr_lambda( lr_lambda_type: str, **kwargs ) -> Callable: r"""Get learning scheduler. Args: lr_lambda_type (str), e.g., "constant_warm_up" | "linear_warm_up" Returns: lr_lambda_func (Callable) """ if lr_lambda_type == "constant_warm_up": lr_lambda_func = partial( constant_warm_up, warm_up_steps=kwargs["warm_up_steps"], reduce_lr_steps=kwargs["reduce_lr_steps"], ) elif lr_lambda_type == "linear_warm_up": lr_lambda_func = partial( linear_warm_up, warm_up_steps=kwargs["warm_up_steps"], reduce_lr_steps=kwargs["reduce_lr_steps"], ) else: raise NotImplementedError return lr_lambda_func The provided code snippet includes necessary dependencies for implementing the `train` function. Write a Python function `def train(args) -> NoReturn` to solve the following problem: r"""Train, evaluate, and save checkpoints. Args: workspace: str, directory of workspace gpus: int, number of GPUs to train config_yaml: str Here is the function: def train(args) -> NoReturn: r"""Train, evaluate, and save checkpoints. Args: workspace: str, directory of workspace gpus: int, number of GPUs to train config_yaml: str """ # arguments & parameters workspace = args.workspace config_yaml = args.config_yaml filename = args.filename devices_num = torch.cuda.device_count() # Read config file. configs = parse_yaml(config_yaml) # Configuration of data max_mix_num = configs['data']['max_mix_num'] sampling_rate = configs['data']['sampling_rate'] lower_db = configs['data']['loudness_norm']['lower_db'] higher_db = configs['data']['loudness_norm']['higher_db'] # Configuration of the separation model query_net = configs['model']['query_net'] model_type = configs['model']['model_type'] input_channels = configs['model']['input_channels'] output_channels = configs['model']['output_channels'] condition_size = configs['model']['condition_size'] use_text_ratio = configs['model']['use_text_ratio'] # Configuration of the trainer num_nodes = configs['train']['num_nodes'] batch_size = configs['train']['batch_size_per_device'] sync_batchnorm = configs['train']['sync_batchnorm'] num_workers = configs['train']['num_workers'] loss_type = configs['train']['loss_type'] optimizer_type = configs["train"]["optimizer"]["optimizer_type"] learning_rate = float(configs['train']["optimizer"]['learning_rate']) lr_lambda_type = configs['train']["optimizer"]['lr_lambda_type'] warm_up_steps = configs['train']["optimizer"]['warm_up_steps'] reduce_lr_steps = configs['train']["optimizer"]['reduce_lr_steps'] save_step_frequency = configs['train']['save_step_frequency'] resume_checkpoint_path = args.resume_checkpoint_path if resume_checkpoint_path == "": resume_checkpoint_path = None else: logging.info(f'Finetuning AudioSep with checkpoint [{resume_checkpoint_path}]') # Get directories and paths checkpoints_dir, logs_dir, tf_logs_dir, statistics_path = get_dirs( workspace, filename, config_yaml, devices_num, ) logging.info(configs) # data module data_module = get_data_module( config_yaml=config_yaml, batch_size=batch_size, num_workers=num_workers, ) # model Model = get_model_class(model_type=model_type) ss_model = Model( input_channels=input_channels, output_channels=output_channels, condition_size=condition_size, ) # loss function loss_function = get_loss_function(loss_type) segment_mixer = SegmentMixer( max_mix_num=max_mix_num, lower_db=lower_db, higher_db=higher_db ) if query_net == 'CLAP': query_encoder = CLAP_Encoder() else: raise NotImplementedError lr_lambda_func = get_lr_lambda( lr_lambda_type=lr_lambda_type, warm_up_steps=warm_up_steps, reduce_lr_steps=reduce_lr_steps, ) # pytorch-lightning model pl_model = AudioSep( ss_model=ss_model, waveform_mixer=segment_mixer, query_encoder=query_encoder, loss_function=loss_function, optimizer_type=optimizer_type, learning_rate=learning_rate, lr_lambda_func=lr_lambda_func, use_text_ratio=use_text_ratio ) checkpoint_every_n_steps = CheckpointEveryNSteps( checkpoints_dir=checkpoints_dir, save_step_frequency=save_step_frequency, ) summary_writer = SummaryWriter(log_dir=tf_logs_dir) callbacks = [checkpoint_every_n_steps] trainer = pl.Trainer( accelerator='auto', devices='auto', strategy='ddp_find_unused_parameters_true', num_nodes=num_nodes, precision="32-true", logger=None, callbacks=callbacks, fast_dev_run=False, max_epochs=-1, log_every_n_steps=50, use_distributed_sampler=True, sync_batchnorm=sync_batchnorm, num_sanity_val_steps=2, enable_checkpointing=False, enable_progress_bar=True, enable_model_summary=True, ) # Fit, evaluate, and save checkpoints. trainer.fit( model=pl_model, train_dataloaders=None, val_dataloaders=None, datamodule=data_module, ckpt_path=resume_checkpoint_path, )
r"""Train, evaluate, and save checkpoints. Args: workspace: str, directory of workspace gpus: int, number of GPUs to train config_yaml: str
167,280
import os import datetime import json import logging import librosa import pickle from typing import Dict import numpy as np import torch import torch.nn as nn import yaml from models.audiosep import AudioSep, get_model_class def float32_to_int16(x: float) -> int: x = np.clip(x, a_min=-1, a_max=1) return (x * 32767.0).astype(np.int16)
null
167,281
import os import datetime import json import logging import librosa import pickle from typing import Dict import numpy as np import torch import torch.nn as nn import yaml from models.audiosep import AudioSep, get_model_class def int16_to_float32(x: int) -> float: return (x / 32767.0).astype(np.float32)
null
167,282
import os import datetime import json import logging import librosa import pickle from typing import Dict import numpy as np import torch import torch.nn as nn import yaml from models.audiosep import AudioSep, get_model_class The provided code snippet includes necessary dependencies for implementing the `get_audioset632_id_to_lb` function. Write a Python function `def get_audioset632_id_to_lb(ontology_path: str) -> Dict` to solve the following problem: r"""Get AudioSet 632 classes ID to label mapping. Here is the function: def get_audioset632_id_to_lb(ontology_path: str) -> Dict: r"""Get AudioSet 632 classes ID to label mapping.""" audioset632_id_to_lb = {} with open(ontology_path) as f: data_list = json.load(f) for e in data_list: audioset632_id_to_lb[e["id"]] = e["name"] return audioset632_id_to_lb
r"""Get AudioSet 632 classes ID to label mapping.
167,283
import os import datetime import json import logging import librosa import pickle from typing import Dict import numpy as np import torch import torch.nn as nn import yaml from models.audiosep import AudioSep, get_model_class The provided code snippet includes necessary dependencies for implementing the `load_pretrained_panns` function. Write a Python function `def load_pretrained_panns( model_type: str, checkpoint_path: str, freeze: bool ) -> nn.Module` to solve the following problem: r"""Load pretrained pretrained audio neural networks (PANNs). Args: model_type: str, e.g., "Cnn14" checkpoint_path, str, e.g., "Cnn14_mAP=0.431.pth" freeze: bool Returns: model: nn.Module Here is the function: def load_pretrained_panns( model_type: str, checkpoint_path: str, freeze: bool ) -> nn.Module: r"""Load pretrained pretrained audio neural networks (PANNs). Args: model_type: str, e.g., "Cnn14" checkpoint_path, str, e.g., "Cnn14_mAP=0.431.pth" freeze: bool Returns: model: nn.Module """ if model_type == "Cnn14": Model = Cnn14 elif model_type == "Cnn14_DecisionLevelMax": Model = Cnn14_DecisionLevelMax else: raise NotImplementedError model = Model(sample_rate=32000, window_size=1024, hop_size=320, mel_bins=64, fmin=50, fmax=14000, classes_num=527) if checkpoint_path: checkpoint = torch.load(checkpoint_path, map_location="cpu") model.load_state_dict(checkpoint["model"]) if freeze: for param in model.parameters(): param.requires_grad = False return model
r"""Load pretrained pretrained audio neural networks (PANNs). Args: model_type: str, e.g., "Cnn14" checkpoint_path, str, e.g., "Cnn14_mAP=0.431.pth" freeze: bool Returns: model: nn.Module
167,284
import os import datetime import json import logging import librosa import pickle from typing import Dict import numpy as np import torch import torch.nn as nn import yaml from models.audiosep import AudioSep, get_model_class def magnitude_to_db(x): eps = 1e-10 return 20. * np.log10(max(x, eps))
null
167,285
import os import datetime import json import logging import librosa import pickle from typing import Dict import numpy as np import torch import torch.nn as nn import yaml from models.audiosep import AudioSep, get_model_class def db_to_magnitude(x): return 10. ** (x / 20)
null
167,286
import os import datetime import json import logging import librosa import pickle from typing import Dict import numpy as np import torch import torch.nn as nn import yaml from models.audiosep import AudioSep, get_model_class def ids_to_hots(ids, classes_num, device): hots = torch.zeros(classes_num).to(device) for id in ids: hots[id] = 1 return hots
null
167,287
import os import datetime import json import logging import librosa import pickle from typing import Dict import numpy as np import torch import torch.nn as nn import yaml from models.audiosep import AudioSep, get_model_class The provided code snippet includes necessary dependencies for implementing the `calculate_sisdr` function. Write a Python function `def calculate_sisdr(ref, est)` to solve the following problem: r"""Calculate SDR between reference and estimation. Args: ref (np.ndarray), reference signal est (np.ndarray), estimated signal Here is the function: def calculate_sisdr(ref, est): r"""Calculate SDR between reference and estimation. Args: ref (np.ndarray), reference signal est (np.ndarray), estimated signal """ eps = np.finfo(ref.dtype).eps reference = ref.copy() estimate = est.copy() reference = reference.reshape(reference.size, 1) estimate = estimate.reshape(estimate.size, 1) Rss = np.dot(reference.T, reference) # get the scaling factor for clean sources a = (eps + np.dot(reference.T, estimate)) / (Rss + eps) e_true = a * reference e_res = estimate - e_true Sss = (e_true**2).sum() Snn = (e_res**2).sum() sisdr = 10 * np.log10((eps+ Sss)/(eps + Snn)) return sisdr
r"""Calculate SDR between reference and estimation. Args: ref (np.ndarray), reference signal est (np.ndarray), estimated signal
167,288
import os import datetime import json import logging import librosa import pickle from typing import Dict import numpy as np import torch import torch.nn as nn import yaml from models.audiosep import AudioSep, get_model_class def get_active_frames(frames: np.ndarray, threshold: float) -> np.ndarray: r"""Get active frames.""" energy = np.max(np.abs(frames), axis=-1) # shape: (frames_num,) active_indexes = np.where(energy > threshold)[0] # shape: (new_frames_num,) new_frames = frames[active_indexes] # shape: (new_frames_num,) return new_frames The provided code snippet includes necessary dependencies for implementing the `remove_silence` function. Write a Python function `def remove_silence(audio: np.ndarray, sample_rate: int) -> np.ndarray` to solve the following problem: r"""Remove silent frames. Here is the function: def remove_silence(audio: np.ndarray, sample_rate: int) -> np.ndarray: r"""Remove silent frames.""" window_size = int(sample_rate * 0.1) threshold = 0.02 frames = librosa.util.frame(x=audio, frame_length=window_size, hop_length=window_size).T # shape: (frames_num, window_size) new_frames = get_active_frames(frames, threshold) # shape: (new_frames_num, window_size) new_audio = new_frames.flatten() # shape: (new_audio_samples,) return new_audio
r"""Remove silent frames.
167,289
import os import datetime import json import logging import librosa import pickle from typing import Dict import numpy as np import torch import torch.nn as nn import yaml from models.audiosep import AudioSep, get_model_class The provided code snippet includes necessary dependencies for implementing the `repeat_to_length` function. Write a Python function `def repeat_to_length(audio: np.ndarray, segment_samples: int) -> np.ndarray` to solve the following problem: r"""Repeat audio to length. Here is the function: def repeat_to_length(audio: np.ndarray, segment_samples: int) -> np.ndarray: r"""Repeat audio to length.""" repeats_num = (segment_samples // audio.shape[-1]) + 1 audio = np.tile(audio, repeats_num)[0 : segment_samples] return audio
r"""Repeat audio to length.
167,290
import os import datetime import json import logging import librosa import pickle from typing import Dict import numpy as np import torch import torch.nn as nn import yaml from models.audiosep import AudioSep, get_model_class def calculate_sdr( ref: np.ndarray, est: np.ndarray, eps=1e-10 ) -> float: r"""Calculate SDR between reference and estimation. Args: ref (np.ndarray), reference signal est (np.ndarray), estimated signal """ reference = ref noise = est - reference numerator = np.clip(a=np.mean(reference ** 2), a_min=eps, a_max=None) denominator = np.clip(a=np.mean(noise ** 2), a_min=eps, a_max=None) sdr = 10. * np.log10(numerator / denominator) return sdr def calculate_segmentwise_sdr(ref, est, hop_samples, return_sdr_list=False): min_len = min(ref.shape[-1], est.shape[-1]) pointer = 0 sdrs = [] while pointer + hop_samples < min_len: sdr = calculate_sdr( ref=ref[:, pointer : pointer + hop_samples], est=est[:, pointer : pointer + hop_samples], ) sdrs.append(sdr) pointer += hop_samples sdr = np.nanmedian(sdrs) if return_sdr_list: return sdr, sdrs else: return sdr
null
167,291
import os import datetime import json import logging import librosa import pickle from typing import Dict import numpy as np import torch import torch.nn as nn import yaml from models.audiosep import AudioSep, get_model_class The provided code snippet includes necessary dependencies for implementing the `loudness` function. Write a Python function `def loudness(data, input_loudness, target_loudness)` to solve the following problem: Loudness normalize a signal. Normalize an input signal to a user loudness in dB LKFS. Params ------- data : torch.Tensor Input multichannel audio data. input_loudness : float Loudness of the input in dB LUFS. target_loudness : float Target loudness of the output in dB LUFS. Returns ------- output : torch.Tensor Loudness normalized output data. Here is the function: def loudness(data, input_loudness, target_loudness): """ Loudness normalize a signal. Normalize an input signal to a user loudness in dB LKFS. Params ------- data : torch.Tensor Input multichannel audio data. input_loudness : float Loudness of the input in dB LUFS. target_loudness : float Target loudness of the output in dB LUFS. Returns ------- output : torch.Tensor Loudness normalized output data. """ # calculate the gain needed to scale to the desired loudness level delta_loudness = target_loudness - input_loudness gain = torch.pow(10.0, delta_loudness / 20.0) output = gain * data # check for potentially clipped samples # if torch.max(torch.abs(output)) >= 1.0: # warnings.warn("Possible clipped samples in output.") return output
Loudness normalize a signal. Normalize an input signal to a user loudness in dB LKFS. Params ------- data : torch.Tensor Input multichannel audio data. input_loudness : float Loudness of the input in dB LUFS. target_loudness : float Target loudness of the output in dB LUFS. Returns ------- output : torch.Tensor Loudness normalized output data.
167,292
import os import datetime import json import logging import librosa import pickle from typing import Dict import numpy as np import torch import torch.nn as nn import yaml from models.audiosep import AudioSep, get_model_class def parse_yaml(config_yaml: str) -> Dict: r"""Parse yaml file. Args: config_yaml (str): config yaml path Returns: yaml_dict (Dict): parsed yaml file """ with open(config_yaml, "r") as fr: return yaml.load(fr, Loader=yaml.FullLoader) def parse_yaml(config_yaml: str) -> Dict: r"""Parse yaml file. Args: config_yaml (str): config yaml path Returns: yaml_dict (Dict): parsed yaml file """ with open(config_yaml, "r") as fr: return yaml.load(fr, Loader=yaml.FullLoader) def get_model_class(model_type): if model_type == 'ResUNet30': from models.resunet import ResUNet30 return ResUNet30 else: raise NotImplementedError The provided code snippet includes necessary dependencies for implementing the `get_ss_model` function. Write a Python function `def get_ss_model(config_yaml) -> nn.Module` to solve the following problem: r"""Load trained universal source separation model. Args: configs (Dict) checkpoint_path (str): path of the checkpoint to load device (str): e.g., "cpu" | "cuda" Returns: pl_model: pl.LightningModule Here is the function: def get_ss_model(config_yaml) -> nn.Module: r"""Load trained universal source separation model. Args: configs (Dict) checkpoint_path (str): path of the checkpoint to load device (str): e.g., "cpu" | "cuda" Returns: pl_model: pl.LightningModule """ configs = parse_yaml(config_yaml) ss_model_type = configs["model"]["model_type"] input_channels = configs["model"]["input_channels"] output_channels = configs["model"]["output_channels"] condition_size = configs["model"]["condition_size"] # Initialize separation model SsModel = get_model_class(model_type=ss_model_type) ss_model = SsModel( input_channels=input_channels, output_channels=output_channels, condition_size=condition_size, ) return ss_model
r"""Load trained universal source separation model. Args: configs (Dict) checkpoint_path (str): path of the checkpoint to load device (str): e.g., "cpu" | "cuda" Returns: pl_model: pl.LightningModule
167,293
from typing import Dict, List, Optional, NoReturn import torch import lightning.pytorch as pl from torch.utils.data import DataLoader from data.audiotext_dataset import AudioTextDataset The provided code snippet includes necessary dependencies for implementing the `collate_fn` function. Write a Python function `def collate_fn(list_data_dict)` to solve the following problem: r"""Collate mini-batch data to inputs and targets for training. Args: list_data_dict: e.g., [ { 'text': 'a sound of dog', 'waveform': (1, samples), 'modality': 'audio_text' } ... ] Returns: data_dict: e.g. 'audio_text': { 'text': ['a sound of dog', ...] 'waveform': (batch_size, 1, samples) } Here is the function: def collate_fn(list_data_dict): r"""Collate mini-batch data to inputs and targets for training. Args: list_data_dict: e.g., [ { 'text': 'a sound of dog', 'waveform': (1, samples), 'modality': 'audio_text' } ... ] Returns: data_dict: e.g. 'audio_text': { 'text': ['a sound of dog', ...] 'waveform': (batch_size, 1, samples) } """ at_list_data_dict = [data_dict for data_dict in list_data_dict if data_dict['modality']=='audio_text'] at_data_dict = {} if len(at_list_data_dict) > 0: for key in at_list_data_dict[0].keys(): at_data_dict[key] = [at_data_dict[key] for at_data_dict in at_list_data_dict] if key == 'waveform': at_data_dict[key] = torch.stack(at_data_dict[key]) elif key == 'text': at_data_dict[key] = [text for text in at_data_dict[key]] data_dict = { 'audio_text': at_data_dict } return data_dict
r"""Collate mini-batch data to inputs and targets for training. Args: list_data_dict: e.g., [ { 'text': 'a sound of dog', 'waveform': (1, samples), 'modality': 'audio_text' } ... ] Returns: data_dict: e.g. 'audio_text': { 'text': ['a sound of dog', ...] 'waveform': (batch_size, 1, samples) }
167,294
import random import sre_compile import numpy as np import torch import torch.nn as nn import pyloudnorm as pyln def rescale_to_match_energy(segment1, segment2): def dynamic_loudnorm(audio, reference, lower_db=-10, higher_db=10): rescaled_audio = rescale_to_match_energy(audio, reference) delta_loudness = random.randint(lower_db, higher_db) gain = np.power(10.0, delta_loudness / 20.0) return gain * rescaled_audio
null
167,295
import random import sre_compile import numpy as np import torch import torch.nn as nn import pyloudnorm as pyln def torch_to_numpy(tensor): """Convert a PyTorch tensor to a NumPy array.""" if isinstance(tensor, torch.Tensor): return tensor.detach().cpu().numpy() else: raise ValueError("Input must be a PyTorch tensor.") def numpy_to_torch(array): """Convert a NumPy array to a PyTorch tensor.""" if isinstance(array, np.ndarray): return torch.from_numpy(array) else: raise ValueError("Input must be a NumPy array.") def random_loudness_norm(audio, lower_db=-35, higher_db=-15, sr=32000): device = audio.device audio = torch_to_numpy(audio.squeeze(0)) # randomly select a norm volume norm_vol = random.randint(lower_db, higher_db) # measure the loudness first meter = pyln.Meter(sr) # create BS.1770 meter loudness = meter.integrated_loudness(audio) # loudness normalize audio normalized_audio = pyln.normalize.loudness(audio, loudness, norm_vol) normalized_audio = numpy_to_torch(normalized_audio).unsqueeze(0) return normalized_audio.to(device)
null
167,296
import os from tqdm import tqdm import numpy as np from evaluation.evaluate_audioset import AudioSetEvaluator from evaluation.evaluate_audiocaps import AudioCapsEvaluator from evaluation.evaluate_vggsound import VGGSoundEvaluator from evaluation.evaluate_music import MUSICEvaluator from evaluation.evaluate_esc50 import ESC50Evaluator from evaluation.evaluate_clotho import ClothoEvaluator from models.clap_encoder import CLAP_Encoder from utils import ( load_ss_model, calculate_sdr, calculate_sisdr, parse_yaml, get_mean_sdr_from_dict, ) class AudioSetEvaluator: def __init__( self, audios_dir='evaluation/data/audioset', classes_num=527, sampling_rate=32000, number_per_class=10, ) -> None: r"""AudioSet evaluator. Args: audios_dir (str): directory of evaluation segments classes_num (int): the number of sound classes number_per_class (int), the number of samples to evaluate for each sound class Returns: None """ self.audios_dir = audios_dir self.classes_num = classes_num self.number_per_class = number_per_class self.sampling_rate = sampling_rate def __call__( self, pl_model: pl.LightningModule ) -> Dict: r"""Evalute.""" pl_model.eval() sisdrs_dict = {class_id: [] for class_id in range(self.classes_num)} sdris_dict = {class_id: [] for class_id in range(self.classes_num)} print('Evaluation on AudioSet with [text label] queries.') for class_id in tqdm(range(self.classes_num)): sub_dir = os.path.join( self.audios_dir, "class_id={}".format(class_id)) audio_names = self._get_audio_names(audios_dir=sub_dir) for audio_index, audio_name in enumerate(audio_names): if audio_index == self.number_per_class: break source_path = os.path.join( sub_dir, "{},source.wav".format(audio_name)) mixture_path = os.path.join( sub_dir, "{},mixture.wav".format(audio_name)) source, fs = librosa.load(source_path, sr=self.sampling_rate, mono=True) mixture, fs = librosa.load(mixture_path, sr=self.sampling_rate, mono=True) sdr_no_sep = calculate_sdr(ref=source, est=mixture) device = pl_model.device text = [IX_TO_LB[class_id]] conditions = pl_model.query_encoder.get_query_embed( modality='text', text=text, device=device ) input_dict = { "mixture": torch.Tensor(mixture)[None, None, :].to(device), "condition": conditions, } sep_segment = pl_model.ss_model(input_dict)["waveform"] # sep_segment: (batch_size=1, channels_num=1, segment_samples) sep_segment = sep_segment.squeeze(0).squeeze(0).data.cpu().numpy() # sep_segment: (segment_samples,) sdr = calculate_sdr(ref=source, est=sep_segment) sdri = sdr - sdr_no_sep sisdr = calculate_sisdr(ref=source, est=sep_segment) sisdrs_dict[class_id].append(sisdr) sdris_dict[class_id].append(sdri) stats_dict = { "sisdrs_dict": sisdrs_dict, "sdris_dict": sdris_dict, } return stats_dict def _get_audio_names(self, audios_dir: str) -> List[str]: r"""Get evaluation audio names.""" audio_names = sorted(os.listdir(audios_dir)) audio_names = [audio_name for audio_name in audio_names if '.wav' in audio_name] audio_names = [ re.search( "(.*),(mixture|source).wav", audio_name).group(1) for audio_name in audio_names] audio_names = sorted(list(set(audio_names))) return audio_names def get_median_metrics(stats_dict, metric_type): class_ids = stats_dict[metric_type].keys() median_stats_dict = { class_id: np.nanmedian( stats_dict[metric_type][class_id]) for class_id in class_ids} return median_stats_dict class AudioCapsEvaluator: def __init__( self, query='caption', sampling_rate=32000, ) -> None: r"""AudioCaps evaluator. Args: query (str): type of query, 'caption' or 'labels' Returns: None """ self.query = query self.sampling_rate = sampling_rate with open(f'evaluation/metadata/audiocaps_eval.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') eval_list = [row for row in csv_reader][1:] self.eval_list = eval_list self.audio_dir = f'evaluation/data/audiocaps' def __call__( self, pl_model: pl.LightningModule ) -> Dict: r"""Evalute.""" print(f'Evaluation on AudioCaps with [{self.query}] queries.') pl_model.eval() device = pl_model.device sisdrs_list = [] sdris_list = [] with torch.no_grad(): for eval_data in tqdm(self.eval_list): idx, caption, labels, _, _ = eval_data source_path = os.path.join(self.audio_dir, f'segment-{idx}.wav') mixture_path = os.path.join(self.audio_dir, f'mixture-{idx}.wav') source, fs = librosa.load(source_path, sr=self.sampling_rate, mono=True) mixture, fs = librosa.load(mixture_path, sr=self.sampling_rate, mono=True) sdr_no_sep = calculate_sdr(ref=source, est=mixture) if self.query == 'caption': text = [caption] elif self.query == 'labels': text = [labels] conditions = pl_model.query_encoder.get_query_embed( modality='text', text=text, device=device ) input_dict = { "mixture": torch.Tensor(mixture)[None, None, :].to(device), "condition": conditions, } sep_segment = pl_model.ss_model(input_dict)["waveform"] # sep_segment: (batch_size=1, channels_num=1, segment_samples) sep_segment = sep_segment.squeeze(0).squeeze(0).data.cpu().numpy() # sep_segment: (segment_samples,) sdr = calculate_sdr(ref=source, est=sep_segment) sdri = sdr - sdr_no_sep sisdr = calculate_sisdr(ref=source, est=sep_segment) sisdrs_list.append(sisdr) sdris_list.append(sdri) mean_sisdr = np.mean(sisdrs_list) mean_sdri = np.mean(sdris_list) return mean_sisdr, mean_sdri class VGGSoundEvaluator: def __init__( self, sampling_rate=32000 ) -> None: r"""VGGSound evaluator. Args: data_recipe (str): dataset split, 'yan' Returns: None """ self.sampling_rate = sampling_rate with open('evaluation/metadata/vggsound_eval.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') eval_list = [row for row in csv_reader][1:] self.eval_list = eval_list self.audio_dir = 'evaluation/data/vggsound' def __call__( self, pl_model: pl.LightningModule ) -> Dict: r"""Evalute.""" print(f'Evaluation on VGGSound+ with [text label] queries.') pl_model.eval() device = pl_model.device sisdrs_list = [] sdris_list = [] sisdris_list = [] with torch.no_grad(): for eval_data in tqdm(self.eval_list): # labels, source_path, mixture_path = eval_data file_id, mix_wav, s0_wav, s0_text, s1_wav, s1_text = eval_data labels = s0_text mixture_path = os.path.join(self.audio_dir, mix_wav) source_path = os.path.join(self.audio_dir, s0_wav) source, fs = librosa.load(source_path, sr=self.sampling_rate, mono=True) mixture, fs = librosa.load(mixture_path, sr=self.sampling_rate, mono=True) sdr_no_sep = calculate_sdr(ref=source, est=mixture) text = [labels] conditions = pl_model.query_encoder.get_query_embed( modality='text', text=text, device=device ) input_dict = { "mixture": torch.Tensor(mixture)[None, None, :].to(device), "condition": conditions, } sep_segment = pl_model.ss_model(input_dict)["waveform"] # sep_segment: (batch_size=1, channels_num=1, segment_samples) sep_segment = sep_segment.squeeze(0).squeeze(0).data.cpu().numpy() # sep_segment: (segment_samples,) sdr = calculate_sdr(ref=source, est=sep_segment) sdri = sdr - sdr_no_sep sisdr_no_sep = calculate_sisdr(ref=source, est=mixture) sisdr = calculate_sisdr(ref=source, est=sep_segment) sisdri = sisdr - sisdr_no_sep sisdrs_list.append(sisdr) sdris_list.append(sdri) sisdris_list.append(sisdri) mean_sisdr = np.mean(sisdrs_list) mean_sdri = np.mean(sdris_list) return mean_sisdr, mean_sdri class MUSICEvaluator: def __init__( self, sampling_rate=32000 ) -> None: self.sampling_rate = sampling_rate with open('evaluation/metadata/music_eval.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') eval_list = [row for row in csv_reader][1:] self.eval_list = eval_list self.audio_dir = 'evaluation/data/music' self.source_types = [ "acoustic guitar", "violin", "accordion", "xylophone", "erhu", "trumpet", "tuba", "cello", "flute", "saxophone"] def __call__( self, pl_model: pl.LightningModule ) -> Dict: r"""Evalute.""" print(f'Evaluation on MUSIC Test with [text label] queries.') pl_model.eval() device = pl_model.device sisdrs_list = {source_type: [] for source_type in self.source_types} sdris_list = {source_type: [] for source_type in self.source_types} with torch.no_grad(): for eval_data in tqdm(self.eval_list): idx, caption, _, _, = eval_data source_path = os.path.join(self.audio_dir, f'segment-{idx}.wav') mixture_path = os.path.join(self.audio_dir, f'mixture-{idx}.wav') source, fs = librosa.load(source_path, sr=self.sampling_rate, mono=True) mixture, fs = librosa.load(mixture_path, sr=self.sampling_rate, mono=True) sdr_no_sep = calculate_sdr(ref=source, est=mixture) text = [caption] conditions = pl_model.query_encoder.get_query_embed( modality='text', text=text, device=device ) input_dict = { "mixture": torch.Tensor(mixture)[None, None, :].to(device), "condition": conditions, } sep_segment = pl_model.ss_model(input_dict)["waveform"] # sep_segment: (batch_size=1, channels_num=1, segment_samples) sep_segment = sep_segment.squeeze(0).squeeze(0).data.cpu().numpy() # sep_segment: (segment_samples,) sdr = calculate_sdr(ref=source, est=sep_segment) sdri = sdr - sdr_no_sep sisdr = calculate_sisdr(ref=source, est=sep_segment) sisdrs_list[caption].append(sisdr) sdris_list[caption].append(sdri) mean_sisdr_list = [] mean_sdri_list = [] for source_class in self.source_types: sisdr = np.mean(sisdrs_list[source_class]) sdri = np.mean(sdris_list[source_class]) mean_sisdr_list.append(sisdr) mean_sdri_list.append(sdri) mean_sdri = np.mean(mean_sdri_list) mean_sisdr = np.mean(mean_sisdr_list) return mean_sisdr, mean_sdri class ESC50Evaluator: def __init__( self, sampling_rate=32000 ) -> None: r"""ESC-50 evaluator. Returns: None """ self.sampling_rate = sampling_rate with open('evaluation/metadata/esc50_eval.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') eval_list = [row for row in csv_reader][1:] self.eval_list = eval_list self.audio_dir = 'evaluation/data/esc50' def __call__( self, pl_model: pl.LightningModule ) -> Dict: r"""Evalute.""" print(f'Evaluation on ESC-50 with [text label] queries.') pl_model.eval() device = pl_model.device sisdrs_list = [] sdris_list = [] with torch.no_grad(): for eval_data in tqdm(self.eval_list): idx, caption, _, _, = eval_data source_path = os.path.join(self.audio_dir, f'segment-{idx}.wav') mixture_path = os.path.join(self.audio_dir, f'mixture-{idx}.wav') source, fs = librosa.load(source_path, sr=self.sampling_rate, mono=True) mixture, fs = librosa.load(mixture_path, sr=self.sampling_rate, mono=True) sdr_no_sep = calculate_sdr(ref=source, est=mixture) text = [caption] conditions = pl_model.query_encoder.get_query_embed( modality='text', text=text, device=device ) input_dict = { "mixture": torch.Tensor(mixture)[None, None, :].to(device), "condition": conditions, } sep_segment = pl_model.ss_model(input_dict)["waveform"] # sep_segment: (batch_size=1, channels_num=1, segment_samples) sep_segment = sep_segment.squeeze(0).squeeze(0).data.cpu().numpy() # sep_segment: (segment_samples,) sdr = calculate_sdr(ref=source, est=sep_segment) sdri = sdr - sdr_no_sep sisdr = calculate_sisdr(ref=source, est=sep_segment) sisdrs_list.append(sisdr) sdris_list.append(sdri) mean_sdri = np.mean(sdris_list) mean_sisdr = np.mean(sisdrs_list) return mean_sisdr, mean_sdri class ClothoEvaluator: def __init__( self, sampling_rate=32000, ) -> None: r"""Clotho evaluator. Returns: None """ self.sampling_rate = sampling_rate with open('evaluation/metadata/clotho_eval.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') eval_list = [row for row in csv_reader][1:] self.eval_list = eval_list self.audio_dir = 'evaluation/data/clotho' def __call__( self, pl_model: pl.LightningModule ) -> Dict: r"""Evalute.""" print(f'Evaluation on Clotho Evaluation with [caption] queries.') pl_model.eval() device = pl_model.device sisdrs_list = [] sdris_list = [] with torch.no_grad(): for eval_data in tqdm(self.eval_list): idx, caption, _, _, _ = eval_data source_path = os.path.join(self.audio_dir, f'segment-{idx}.wav') mixture_path = os.path.join(self.audio_dir, f'mixture-{idx}.wav') source, fs = librosa.load(source_path, sr=self.sampling_rate, mono=True) mixture, fs = librosa.load(mixture_path, sr=self.sampling_rate, mono=True) sdr_no_sep = calculate_sdr(ref=source, est=mixture) text = [caption] conditions = pl_model.query_encoder.get_query_embed( modality='text', text=text, device=device ) input_dict = { "mixture": torch.Tensor(mixture)[None, None, :].to(device), "condition": conditions, } sep_segment = pl_model.ss_model(input_dict)["waveform"] # sep_segment: (batch_size=1, channels_num=1, segment_samples) sep_segment = sep_segment.squeeze(0).squeeze(0).data.cpu().numpy() # sep_segment: (segment_samples,) sdr = calculate_sdr(ref=source, est=sep_segment) sdri = sdr - sdr_no_sep sisdr = calculate_sisdr(ref=source, est=sep_segment) sisdrs_list.append(sisdr) sdris_list.append(sdri) mean_sisdr = np.mean(sisdrs_list) mean_sdri = np.mean(sdris_list) return mean_sisdr, mean_sdri class CLAP_Encoder(nn.Module): def __init__( self, pretrained_path='checkpoint/music_speech_audioset_epoch_15_esc_89.98.pt', sampling_rate=32000, amodel = "HTSAT-base", ): super().__init__() self.device = "cpu" self.precision = "fp32" self.amodel = amodel # or 'PANN-14' self.tmodel = "roberta" # the best text encoder in our training self.enable_fusion = False # False if you do not want to use the fusion model self.fusion_type = "aff_2d" self.pretrained = pretrained_path self.sampling_rate = sampling_rate self.tokenize = RobertaTokenizer.from_pretrained("roberta-base") self.model, self.model_cfg = create_model( self.amodel, self.tmodel, self.pretrained, precision=self.precision, device=self.device, enable_fusion=self.enable_fusion, fusion_type=self.fusion_type, ) for p in self.model.parameters(): p.requires_grad = False self.model.eval() self.encoder_type = 'CLAP' def batch_to_list(self, batch): ret = [] for i in range(batch.size(0)): ret.append(batch[i]) return ret def _get_audio_embed(self, batch): # batch: [B, samples] with torch.no_grad(): audio_dict_list = [] assert ( self.sampling_rate == 32000 ), "We only support 32000 sampling rate" # batch: [bs, 1, t-samples] batch = torchaudio.functional.resample( batch, orig_freq=self.sampling_rate, new_freq=48000 ) for waveform in self.batch_to_list(batch): audio_dict = {} audio_dict = get_audio_features( audio_dict, waveform, 480000, data_truncating="fusion", data_filling="repeatpad", audio_cfg=self.model_cfg["audio_cfg"], ) audio_dict_list.append(audio_dict) # [bs, 512] embed = self.model.get_audio_embedding(audio_dict_list) return embed.detach() def _get_text_embed(self, batch): double_batch = False if len(batch) == 1: batch = batch * 2 double_batch = True with torch.no_grad(): # the 'fusion' truncate mode can be changed to 'rand_trunc' if run in unfusion mode text_data = self.tokenizer(batch) embed = self.model.get_text_embedding(text_data) if double_batch: embed = embed[0].unsqueeze(0) return embed.detach() def get_query_embed(self, modality, audio=None, text=None, use_text_ratio=0.5, device=None): if modality == 'audio': embed = self._get_audio_embed(audio) elif modality == 'text': embed = self._get_text_embed(text) elif modality == 'hybird': if random.random() > use_text_ratio: embed = self._get_audio_embed(audio) else: embed = self._get_text_embed(text) else: raise NotImplementedError("Please check flag 'training_modality'.") return embed.float() def tokenizer(self, text): result = self.tokenize( text, padding="max_length", truncation=True, max_length=512, return_tensors="pt", ) return {k: v.squeeze(0) for k, v in result.items()} def parse_yaml(config_yaml: str) -> Dict: r"""Parse yaml file. Args: config_yaml (str): config yaml path Returns: yaml_dict (Dict): parsed yaml file """ with open(config_yaml, "r") as fr: return yaml.load(fr, Loader=yaml.FullLoader) def get_mean_sdr_from_dict(sdris_dict): mean_sdr = np.nanmean(list(sdris_dict.values())) return mean_sdr def load_ss_model( configs: Dict, checkpoint_path: str, query_encoder: nn.Module ) -> nn.Module: r"""Load trained universal source separation model. Args: configs (Dict) checkpoint_path (str): path of the checkpoint to load device (str): e.g., "cpu" | "cuda" Returns: pl_model: pl.LightningModule """ ss_model_type = configs["model"]["model_type"] input_channels = configs["model"]["input_channels"] output_channels = configs["model"]["output_channels"] condition_size = configs["model"]["condition_size"] # Initialize separation model SsModel = get_model_class(model_type=ss_model_type) ss_model = SsModel( input_channels=input_channels, output_channels=output_channels, condition_size=condition_size, ) # Load PyTorch Lightning model pl_model = AudioSep.load_from_checkpoint( checkpoint_path=checkpoint_path, strict=False, ss_model=ss_model, waveform_mixer=None, query_encoder=query_encoder, loss_function=None, optimizer_type=None, learning_rate=None, lr_lambda_func=None, map_location=torch.device('cpu'), ) return pl_model def parse_yaml(config_yaml: str) -> Dict: r"""Parse yaml file. Args: config_yaml (str): config yaml path Returns: yaml_dict (Dict): parsed yaml file """ with open(config_yaml, "r") as fr: return yaml.load(fr, Loader=yaml.FullLoader) def eval(checkpoint_path, config_yaml='config/audiosep_base.yaml'): log_dir = 'eval_logs' os.makedirs(log_dir, exist_ok=True) device = "cuda" configs = parse_yaml(config_yaml) # AudioSet Evaluators audioset_evaluator = AudioSetEvaluator() # AudioCaps Evaluator audiocaps_evaluator = AudioCapsEvaluator() # VGGSound+ Evaluator vggsound_evaluator = VGGSoundEvaluator() # Clotho Evaluator clotho_evaluator = ClothoEvaluator() # MUSIC Evaluator music_evaluator = MUSICEvaluator() # ESC-50 Evaluator esc50_evaluator = ESC50Evaluator() # Load model query_encoder = CLAP_Encoder().eval() pl_model = load_ss_model( configs=configs, checkpoint_path=checkpoint_path, query_encoder=query_encoder ).to(device) print(f'------- Start Evaluation -------') # evaluation on Clotho SISDR, SDRi = clotho_evaluator(pl_model) msg_clotho = "Clotho Avg SDRi: {:.3f}, SISDR: {:.3f}".format(SDRi, SISDR) print(msg_clotho) # evaluation on VGGSound+ (YAN) SISDR, SDRi = vggsound_evaluator(pl_model) msg_vgg = "VGGSound Avg SDRi: {:.3f}, SISDR: {:.3f}".format(SDRi, SISDR) print(msg_vgg) # evaluation on MUSIC SISDR, SDRi = music_evaluator(pl_model) msg_music = "MUSIC Avg SDRi: {:.3f}, SISDR: {:.3f}".format(SDRi, SISDR) print(msg_music) # evaluation on ESC-50 SISDR, SDRi = esc50_evaluator(pl_model) msg_esc50 = "ESC-50 Avg SDRi: {:.3f}, SISDR: {:.3f}".format(SDRi, SISDR) print(msg_esc50) # evaluation on AudioSet stats_dict = audioset_evaluator(pl_model=pl_model) median_sdris = {} median_sisdrs = {} for class_id in range(527): median_sdris[class_id] = np.nanmedian(stats_dict["sdris_dict"][class_id]) median_sisdrs[class_id] = np.nanmedian(stats_dict["sisdrs_dict"][class_id]) SDRi = get_mean_sdr_from_dict(median_sdris) SISDR = get_mean_sdr_from_dict(median_sisdrs) msg_audioset = "AudioSet Avg SDRi: {:.3f}, SISDR: {:.3f}".format(SDRi, SISDR) print(msg_audioset) # evaluation on AudioCaps SISDR, SDRi = audiocaps_evaluator(pl_model) msg_audiocaps = "AudioCaps Avg SDRi: {:.3f}, SISDR: {:.3f}".format(SDRi, SISDR) print(msg_audiocaps) # evaluation on Clotho SISDR, SDRi = clotho_evaluator(pl_model) msg_clotho = "Clotho Avg SDRi: {:.3f}, SISDR: {:.3f}".format(SDRi, SISDR) print(msg_clotho) msgs = [msg_audioset, msg_vgg, msg_audiocaps, msg_clotho, msg_music, msg_esc50] # open file in write mode log_path = os.path.join(log_dir, 'eval_results.txt') with open(log_path, 'w') as fp: for msg in msgs: fp.write(msg + '\n') print(f'Eval log is written to {log_path} ...') print('------------------------- Done ---------------------------')
null
167,297
import yaml from typing import List import torch import numpy as np import librosa from scipy.io.wavfile import write from utils import ignore_warnings, parse_yaml, load_ss_model from models.clap_encoder import CLAP_Encoder def ignore_warnings(): import warnings # Ignore UserWarning from torch.meshgrid warnings.filterwarnings('ignore', category=UserWarning, module='torch.functional') # Refined regex pattern to capture variations in the warning message pattern = r"Some weights of the model checkpoint at roberta-base were not used when initializing RobertaModel: \['lm_head\..*'\].*" warnings.filterwarnings('ignore', message=pattern) def parse_yaml(config_yaml: str) -> Dict: r"""Parse yaml file. Args: config_yaml (str): config yaml path Returns: yaml_dict (Dict): parsed yaml file """ with open(config_yaml, "r") as fr: return yaml.load(fr, Loader=yaml.FullLoader) def load_ss_model( configs: Dict, checkpoint_path: str, query_encoder: nn.Module ) -> nn.Module: r"""Load trained universal source separation model. Args: configs (Dict) checkpoint_path (str): path of the checkpoint to load device (str): e.g., "cpu" | "cuda" Returns: pl_model: pl.LightningModule """ ss_model_type = configs["model"]["model_type"] input_channels = configs["model"]["input_channels"] output_channels = configs["model"]["output_channels"] condition_size = configs["model"]["condition_size"] # Initialize separation model SsModel = get_model_class(model_type=ss_model_type) ss_model = SsModel( input_channels=input_channels, output_channels=output_channels, condition_size=condition_size, ) # Load PyTorch Lightning model pl_model = AudioSep.load_from_checkpoint( checkpoint_path=checkpoint_path, strict=False, ss_model=ss_model, waveform_mixer=None, query_encoder=query_encoder, loss_function=None, optimizer_type=None, learning_rate=None, lr_lambda_func=None, map_location=torch.device('cpu'), ) return pl_model def parse_yaml(config_yaml: str) -> Dict: r"""Parse yaml file. Args: config_yaml (str): config yaml path Returns: yaml_dict (Dict): parsed yaml file """ with open(config_yaml, "r") as fr: return yaml.load(fr, Loader=yaml.FullLoader) class CLAP_Encoder(nn.Module): def __init__( self, pretrained_path='checkpoint/music_speech_audioset_epoch_15_esc_89.98.pt', sampling_rate=32000, amodel = "HTSAT-base", ): super().__init__() self.device = "cpu" self.precision = "fp32" self.amodel = amodel # or 'PANN-14' self.tmodel = "roberta" # the best text encoder in our training self.enable_fusion = False # False if you do not want to use the fusion model self.fusion_type = "aff_2d" self.pretrained = pretrained_path self.sampling_rate = sampling_rate self.tokenize = RobertaTokenizer.from_pretrained("roberta-base") self.model, self.model_cfg = create_model( self.amodel, self.tmodel, self.pretrained, precision=self.precision, device=self.device, enable_fusion=self.enable_fusion, fusion_type=self.fusion_type, ) for p in self.model.parameters(): p.requires_grad = False self.model.eval() self.encoder_type = 'CLAP' def batch_to_list(self, batch): ret = [] for i in range(batch.size(0)): ret.append(batch[i]) return ret def _get_audio_embed(self, batch): # batch: [B, samples] with torch.no_grad(): audio_dict_list = [] assert ( self.sampling_rate == 32000 ), "We only support 32000 sampling rate" # batch: [bs, 1, t-samples] batch = torchaudio.functional.resample( batch, orig_freq=self.sampling_rate, new_freq=48000 ) for waveform in self.batch_to_list(batch): audio_dict = {} audio_dict = get_audio_features( audio_dict, waveform, 480000, data_truncating="fusion", data_filling="repeatpad", audio_cfg=self.model_cfg["audio_cfg"], ) audio_dict_list.append(audio_dict) # [bs, 512] embed = self.model.get_audio_embedding(audio_dict_list) return embed.detach() def _get_text_embed(self, batch): double_batch = False if len(batch) == 1: batch = batch * 2 double_batch = True with torch.no_grad(): # the 'fusion' truncate mode can be changed to 'rand_trunc' if run in unfusion mode text_data = self.tokenizer(batch) embed = self.model.get_text_embedding(text_data) if double_batch: embed = embed[0].unsqueeze(0) return embed.detach() def get_query_embed(self, modality, audio=None, text=None, use_text_ratio=0.5, device=None): if modality == 'audio': embed = self._get_audio_embed(audio) elif modality == 'text': embed = self._get_text_embed(text) elif modality == 'hybird': if random.random() > use_text_ratio: embed = self._get_audio_embed(audio) else: embed = self._get_text_embed(text) else: raise NotImplementedError("Please check flag 'training_modality'.") return embed.float() def tokenizer(self, text): result = self.tokenize( text, padding="max_length", truncation=True, max_length=512, return_tensors="pt", ) return {k: v.squeeze(0) for k, v in result.items()} def build_audiosep(config_yaml, checkpoint_path, device): ignore_warnings() configs = parse_yaml(config_yaml) query_encoder = CLAP_Encoder().eval() model = load_ss_model(configs=configs, checkpoint_path=checkpoint_path, query_encoder=query_encoder).eval().to(device) print(f'Loaded AudioSep model from [{checkpoint_path}]') return model
null
167,298
import yaml from typing import List import torch import numpy as np import librosa from scipy.io.wavfile import write from utils import ignore_warnings, parse_yaml, load_ss_model from models.clap_encoder import CLAP_Encoder def separate_audio(model, audio_file, text, output_file, device='cuda', use_chunk=False): print(f'Separating audio from [{audio_file}] with textual query: [{text}]') mixture, fs = librosa.load(audio_file, sr=32000, mono=True) with torch.no_grad(): text = [text] conditions = model.query_encoder.get_query_embed( modality='text', text=text, device=device ) input_dict = { "mixture": torch.Tensor(mixture)[None, None, :].to(device), "condition": conditions, } if use_chunk: sep_segment = model.ss_model.chunk_inference(input_dict) sep_segment = np.squeeze(sep_segment) else: sep_segment = model.ss_model(input_dict)["waveform"] sep_segment = sep_segment.squeeze(0).squeeze(0).data.cpu().numpy() write(output_file, 32000, np.round(sep_segment * 32767).astype(np.int16)) print(f'Separated audio written to [{output_file}]')
null
167,303
import gzip import html import os from functools import lru_cache from typing import Union, List import ftfy import regex as re import torch The provided code snippet includes necessary dependencies for implementing the `bytes_to_unicode` function. Write a Python function `def bytes_to_unicode()` to solve the following problem: Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings. And avoids mapping to whitespace/control characters the bpe code barfs on. Here is the function: def bytes_to_unicode(): """ Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings. And avoids mapping to whitespace/control characters the bpe code barfs on. """ bs = ( list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1)) ) cs = bs[:] n = 0 for b in range(2**8): if b not in bs: bs.append(b) cs.append(2**8 + n) n += 1 cs = [chr(n) for n in cs] return dict(zip(bs, cs))
Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings. And avoids mapping to whitespace/control characters the bpe code barfs on.
167,309
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib dataset_split = { "audiocaps": ["train", "valid", "test"], "audioset": ["balanced_train", "unbalanced_train", "eval"], "BBCSoundEffects": ["train", "test"], "Clotho": ["train", "test", "valid"], "free_to_use_sounds": ["train", "test"], "paramount_motion": ["train", "test"], "sonniss_game_effects": ["train", "test"], "wesoundeffects": ["train", "test"], "MACS": ["train", "test"], "freesound": ["train", "test"], "FSD50K": ["train", "test", "valid"], "fsd50k_class_label": ["train", "test", "valid"], "esc50": ["train", "test"], "audiostock": ["train", "test"], "freesound_no_overlap_noesc50": ["train", "test"], "epidemic_sound_effects": ["train", "test"], "VGGSound": ["train", "test"], "urbansound8k_class_label": ["train", "test"], "audioset_t5": ["balanced_train", "unbalanced_train", "eval"], "epidemic_sound_effects_t5": ["train", "test"], "WavText5K": ["train", "test"], "esc50_no_overlap": ["train", "test"], "usd8k_no_overlap": ["train", "test"], "fsd50k_200_class_label": ["train", "test", "valid"], } from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim The provided code snippet includes necessary dependencies for implementing the `exist` function. Write a Python function `def exist(dataset_name, dataset_type)` to solve the following problem: Check if dataset exists Here is the function: def exist(dataset_name, dataset_type): """ Check if dataset exists """ if dataset_type in dataset_split[dataset_name]: return True else: return False
Check if dataset exists
167,316
import numpy as np import torch from torch import nn as nn from torchvision.ops.misc import FrozenBatchNorm2d import logging import h5py from tqdm import tqdm import random import json import os import pathlib from multiprocessing import Process, Manager from multiprocessing import Process, Value, Array from ctypes import c_wchar from torch import optim def save_json(data, name="data.json"): import json with open(name, "w") as fp: json.dump(data, fp) return
null
167,328
from collections import OrderedDict from dataclasses import dataclass from email.mime import audio from typing import Tuple, Union, Callable, Optional import numpy as np import torch import torch.nn.functional as F from torch import nn from .timm_model import TimmModel import logging from .utils import freeze_batch_norm_2d from .pann_model import create_pann_model from .htsat import create_htsat_model from transformers import BertModel, RobertaModel, BartModel, RobertaConfig from transformers.tokenization_utils_base import BatchEncoding def trace_model(model, batch_size=256, device=torch.device("cpu")): model.eval() audio_length = model.audio_cfg.audio_length example_audio = torch.ones((batch_size, audio_length), device=device) example_text = torch.zeros( (batch_size, model.context_length), dtype=torch.int, device=device ) model = torch.jit.trace_module( model, inputs=dict( forward=(example_audio, example_text), encode_text=(example_text,), encode_image=(example_audio,), ), ) model.audio_cfg.audio_length = audio_length # Question: what does this do? return model
null
167,335
import json import logging import os import pathlib import re from copy import deepcopy from pathlib import Path import torch from .model import CLAP, convert_weights_to_fp16 from .openai import load_openai_model from .pretrained import get_pretrained_url, download_pretrained from .transform import image_transform def create_model( amodel_name: str, tmodel_name: str, pretrained: str = "", precision: str = "fp32", device: torch.device = torch.device("cpu"), jit: bool = False, force_quick_gelu: bool = False, openai_model_cache_dir: str = os.path.expanduser("~/.cache/clip"), skip_params=True, pretrained_audio: str = "", pretrained_text: str = "", enable_fusion: bool = False, fusion_type: str = "None" # pretrained_image: bool = False, ): def image_transform( image_size: int, is_train: bool, mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711), ): def create_model_and_transforms( model_name: str, pretrained: str = "", precision: str = "fp32", device: torch.device = torch.device("cpu"), jit: bool = False, force_quick_gelu: bool = False, # pretrained_image: bool = False, ): model = create_model( model_name, pretrained, precision, device, jit, force_quick_gelu=force_quick_gelu, # pretrained_image=pretrained_image ) preprocess_train = image_transform(model.visual.image_size, is_train=True) preprocess_val = image_transform(model.visual.image_size, is_train=False) return model, preprocess_train, preprocess_val
null
167,340
import json import logging import math import os import time from contextlib import suppress import numpy as np import torch import torch.nn.functional as F try: import wandb except ImportError: wandb = None from open_clip import ClipLoss, gather_features from .distributed import is_master from .zero_shot import zero_shot_eval def get_metrics( audio_features, text_features, logit_scale_a, audio_features_mlp=None, text_features_mlp=None, logit_scale_t=None, mlp_loss=False, ): metrics = {} if mlp_loss: # Set up audio to text & text to audio similary matrice a_logits_per_audio = ( (logit_scale_a * audio_features @ text_features_mlp.t()).detach().cpu() ) a_logits_per_text = a_logits_per_audio.t().detach().cpu() t_logits_per_audio = ( (logit_scale_t * audio_features_mlp @ text_features.t()).detach().cpu() ) t_logits_per_text = t_logits_per_audio.t().detach().cpu() labels = torch.arange(audio_features.shape[0]).long() # Change the loss from two terms into four terms with 2x2 combined CE loss total_loss = ( F.cross_entropy(a_logits_per_audio, labels) + F.cross_entropy(a_logits_per_text, labels) + F.cross_entropy(t_logits_per_audio, labels) + F.cross_entropy(t_logits_per_text, labels) ) / 4 metrics[f"cumulative_loss"] = total_loss.item() metrics[f"num_samples"] = audio_features.shape[0] logits = { "audio_to_text": (a_logits_per_audio + t_logits_per_audio) / 2, "text_to_audio": (a_logits_per_text + t_logits_per_text) / 2, } ground_truth = torch.arange(len(text_features)).view(-1, 1) else: # print("text_features", text_features) # print("text_features.shape", text_features.shape) logits_per_audio = ( (logit_scale_a * audio_features @ text_features.t()).detach().cpu() ) logits_per_text = logits_per_audio.t().detach().cpu() labels = torch.arange(audio_features.shape[0]).long() # Change the loss from two terms into four terms with 2x2 combined CE loss total_loss = ( F.cross_entropy(logits_per_audio, labels) + F.cross_entropy(logits_per_text, labels) ) / 2 metrics[f"cumulative_loss"] = total_loss.item() metrics[f"num_samples"] = audio_features.shape[0] logits = {"audio_to_text": logits_per_audio, "text_to_audio": logits_per_text} ground_truth = torch.arange(len(text_features)).view(-1, 1) for name, logit in logits.items(): ranking = torch.argsort(logit, descending=True) preds = torch.where(ranking == ground_truth)[ 1 ] # (yusong) this line is slow because it uses single thread preds = preds.detach().cpu().numpy() metrics[f"{name}_mean_rank"] = preds.mean() + 1 metrics[f"{name}_median_rank"] = np.floor(np.median(preds)) + 1 for k in [1, 5, 10]: metrics[f"{name}_R@{k}"] = np.mean(preds < k) # map@10 metrics[f"{name}_mAP@10"] = np.mean(np.where(preds < 10, 1 / (preds + 1), 0.0)) return metrics def evaluate_clotho_audiocaps( model, data, epoch, args, autocast, device, tb_writer=None ): """ Adapted from https://github.com/XinhaoMei/audio-text_retrieval/blob/main/tools/utils.py. 1. for text-to-audio retrieval, do 5 times and average the results 2. for R@1, R@5, R@10 in audio-to-text retrieval, take the best rank among 5 text 3. for map@10 in audio-to-text retrieval: 3.1: sort the rank of 5 text 3.2: exclude the rank >=10 (0-index) 3.3: compute the map regarding the remaining ranks: np.mean(np.arange(1, len(ranks)+1) / ranks). (3.3) That is, take the top ranks of 5 text that is < 10, and assign the descending number as ground truth. (3.3) E.g.: the ground truth of first rank of the 5 text should be 1, the second rank should be 2, etc. """ # TODO: (yusong) only support single GPU evaluation and only support non-mlp case for now. dataloader = data["val"].dataloader with torch.no_grad(): eval_info = {} for i, batch in enumerate(dataloader): audios = batch # contains mel_spec, wavform, and longer list # each item in the list has 5 texts if args.tmodel == "transformer": from open_clip import tokenize texts = [tokenize(t) for t in batch["full_text"]] texts = torch.cat(texts) else: from .data import tokenizer texts = [ tokenizer(t) for t in batch["full_text"] ] # 5 texts for each audio texts = { k: torch.cat([t[k] for t in texts]) for k in texts[0].keys() } # 5 x batch # audios = audios.to(device=device, non_blocking=True) all_names = list( set(["-".join(b.split("/")[-3:-1]) for b in batch["__url__"]]) ) for name in all_names: if name not in eval_info.keys(): # we will not use mlp outputs even if args.clap_mlploss=True eval_info[name] = { "cumulative_loss": 0.0, "num_samples": 0, "all_audio_features": [], "all_text_features": [], } with autocast(): audio_features = model(audios, None, device) text_features = model(None, texts, device) audio_features = F.normalize(audio_features, dim=-1) text_features = F.normalize(text_features, dim=-1) all_names = list( set(["-".join(b.split("/")[-3:-1]) for b in batch["__url__"]]) ) for n in all_names: idx = np.where( np.array( ["-".join(b.split("/")[-3:-1]) for b in batch["__url__"]] ) == n )[0] eval_info[n]["all_audio_features"].append( audio_features.cpu().index_select(0, torch.tensor(idx).long()) ) # (yusong) please double-check. This is for selecting 5 text features at once. # because idx is a list of indices in size of num_samples, # and text_features is a tensor of size (5*num_samples, dim) # so we need to select 5 consecutive indices at once for a single index in idx. eval_info[n]["all_text_features"].append( text_features.cpu() .reshape([-1, 5, text_features.shape[1]]) .index_select(0, torch.tensor(idx).long()) .reshape([-1, text_features.shape[1]]) ) val_metrics_all = {} for n in eval_info.keys(): logit_scale_a, logit_scale_t = model(None, None, device) logit_scale_a = logit_scale_a.cpu() audio_features = torch.cat(eval_info[n]["all_audio_features"], dim=0) text_features = torch.cat(eval_info[n]["all_text_features"], dim=0) logits_per_audio = ( (logit_scale_a * audio_features @ text_features.t()).detach().cpu() ) logits_per_text = logits_per_audio.t().detach().cpu() # logits_per_audio shape: [num_samples, num_samples*5] # logits_per_text shape: [num_samples*5, num_samples] logging.info( f"dataset {n}, logits_per_audio shape: {logits_per_audio.shape}, " f"logits_per_text shape: {logits_per_text.shape}" ) metrics = {} num_samples = audio_features.shape[0] metrics[f"num_samples"] = num_samples # (yusong) the following code is very important, please double-check: # logits_per_audio.reshape(num_samples, num_samples, 5)[:, :, d] # logits_per_text.reshape(num_samples, 5, num_samples)[:, d, :] # Those two are retrieving one of the 5 text for each audio. labels = torch.arange(audio_features.shape[0]).long() audio_to_text_loss = [ F.cross_entropy( logits_per_audio.reshape(num_samples, num_samples, 5)[:, :, d], labels, ) for d in range(5) ] text_to_audio_loss = [ F.cross_entropy( logits_per_text.reshape(num_samples, 5, num_samples)[:, d, :], labels, ) for d in range(5) ] total_loss = (np.mean(audio_to_text_loss) + np.mean(text_to_audio_loss)) / 2 metrics[f"cumulative_loss"] = total_loss.item() # text to audio: do 5 times pred_text = [] for d in range(5): logit = logits_per_text.reshape(num_samples, 5, num_samples)[:, d, :] ground_truth = torch.arange(len(logit)).view(-1, 1) ranking = torch.argsort( logit, descending=True ) # [num_samples, num_samples] preds = torch.where(ranking == ground_truth)[1] pred_text.append(preds.detach().cpu().numpy()) pred_text_concat = np.concatenate(pred_text, axis=0) # [5*num_samples] metrics[f"text_to_audio_mean_rank"] = pred_text_concat.mean() + 1 metrics[f"text_to_audio_median_rank"] = ( np.floor(np.median(pred_text_concat)) + 1 ) for k in [1, 5, 10]: metrics[f"text_to_audio_R@{k}"] = np.mean(pred_text_concat < k) # map@10 metrics[f"text_to_audio_mAP@10"] = np.mean( np.where(pred_text_concat < 10, 1 / (pred_text_concat + 1), 0.0) ) # audio to text: take the best result # for audio to text map 10, sort and assign descending ground truth. # see https://github.com/XinhaoMei/audio-text_retrieval/blob/main/tools/utils.py#L103 # map@10 map_all = [] pred_audio_all = [] for d in range(num_samples): # logits_per_audio: [num_samples, num_samples*5] logit_single = logits_per_audio[d, :] # [5*num_samples] # Ground-truth index: [d*5, d*5+1, d*5+2, d*5+3, d*5+4] ranking = torch.argsort( logit_single, descending=True ) # [5*num_samples] # ranking: the index of first match, second match, ... ground_truth = torch.arange(d * 5, d * 5 + 5)[None] all_pred = torch.where( torch.stack([ranking] * 5) == ground_truth.view(-1, 1) )[1] min_pred = torch.min(all_pred) pred_audio_all.append(min_pred.detach().cpu().numpy()) all_pred_filter = all_pred[all_pred < 10].detach().cpu().numpy() # /5 because we have 5 text, so it means for the text rank >=10 we count as 0. map_single = ( np.sum( (np.arange(1, len(all_pred_filter) + 1) / (all_pred_filter + 1)) ) / 5 ) map_all.append(map_single) metrics[f"audio_to_text_mAP@10"] = np.mean(map_all) for k in [1, 5, 10]: metrics[f"audio_to_text_R@{k}"] = np.mean(np.array(pred_audio_all) < k) val_metrics_all[n] = {n + "/" + k: v for k, v in metrics.items()} return val_metrics_all def select_top_metric_clotho_audiocaps(metrics, val_metrics_per_dataset, args): # val_metrics_per_dataset: dict, key: dataset name, value: dict, key: metric name, value: metric value # metrics: dict, key: metric name, value: metric value # Hack: use args to save the top performance if not hasattr(args, "top_selection_performance"): selection_performance = calculate_selection_performance_clotho_audiocaps( val_metrics_per_dataset ) # TODO: write the if and else together metric_update = {} for n in val_metrics_per_dataset.keys(): for k in val_metrics_per_dataset[n].keys(): metric_update[ k.split("/")[0] + "-top" + "/" + k.split("/")[1] ] = val_metrics_per_dataset[n][k] metric_update["top_selection_performance"] = selection_performance metric_update["top-selection-epoch"] = metrics["epoch"] metrics.update(metric_update) args.top_metric = metric_update args.top_selection_performance = selection_performance else: selection_performance_new = calculate_selection_performance_clotho_audiocaps( val_metrics_per_dataset ) selection_performance_old = args.top_selection_performance if selection_performance_new > selection_performance_old: metric_update = {} for n in val_metrics_per_dataset.keys(): for k in val_metrics_per_dataset[n].keys(): metric_update[ k.split("/")[0] + "-top" + "/" + k.split("/")[1] ] = val_metrics_per_dataset[n][k] metric_update["top_selection_performance"] = selection_performance_new metric_update["top-selection-epoch"] = metrics["epoch"] metrics.update(metric_update) args.top_metric = metric_update args.top_selection_performance = selection_performance_new else: metrics.update(args.top_metric) return metrics def is_master(args, local=False): return is_local_master(args) if local else is_global_master(args) def evaluate(model, data, epoch, args, tb_writer=None): metrics = {} if not args.parallel_eval: if not is_master(args): return metrics device = torch.device(args.device) model.eval() # CHANGE # zero_shot_metrics = zero_shot_eval(model, data, epoch, args) # metrics.update(zero_shot_metrics) if is_master(args): print("Evaluating...") autocast = torch.cuda.amp.autocast if args.precision == "amp" else suppress if args.val_dataset_names == ["Clotho", "audiocaps"]: # if only clotho and audiocaps are used, then we will use a different evaluation function. # This is because in the Clotho and audiocaps valid and test set, there are 5 text for 1 audio. if args.parallel_eval: # (yusong): just a hack here. Don't use parallel eval when evaluating only clotho and audiocaps. raise NotImplementedError( "Parallel evaluation not supported for eval only Clotho and audiocaps." ) val_metrics_per_dataset = evaluate_clotho_audiocaps( model, data, epoch, args, autocast, device, tb_writer ) for m in val_metrics_per_dataset.values(): metrics.update(m) if "epoch" not in metrics.keys(): metrics.update({"epoch": epoch}) metrics = select_top_metric_clotho_audiocaps( metrics, val_metrics_per_dataset, args ) elif "val" in data and ( args.val_frequency and ((epoch % args.val_frequency) == 0 or epoch == args.epochs) ): dataloader = data["val"].dataloader num_samples = 0 samples_per_val = dataloader.num_samples # FIXME this does not scale past small eval datasets # all_audio_features @ all_text_features will blow up memory and compute very quickly eval_info = {} if args.clap_mlploss: eval_info["all"] = { "cumulative_loss": 0.0, "num_samples": 0, "all_audio_features": [], "all_text_features": [], "all_audio_features_mlp": [], "all_text_features_mlp": [], } # cumulative_loss = 0.0 else: eval_info["all"] = { "cumulative_loss": 0.0, "num_samples": 0, "all_audio_features": [], "all_text_features": [], } # cumu # all_audio_features, all_text_features, all_audio_features_mlp, all_text_features_mlp = [], [], [], [] with torch.no_grad(): for i, batch in enumerate(dataloader): audios = batch # contains mel_spec, wavform, and longer list texts = batch["text"] # audios = audios.to(device=device, non_blocking=True) all_names = list( set(["-".join(b.split("/")[-3:-1]) for b in batch["__url__"]]) ) for name in all_names: if name not in eval_info.keys(): if args.clap_mlploss: eval_info[name] = { "cumulative_loss": 0.0, "num_samples": 0, "all_audio_features": [], "all_text_features": [], "all_audio_features_mlp": [], "all_text_features_mlp": [], } else: eval_info[name] = { "cumulative_loss": 0.0, "num_samples": 0, "all_audio_features": [], "all_text_features": [], } with autocast(): ( audio_features, text_features, audio_features_mlp, text_features_mlp, logit_scale_a, logit_scale_t, ) = model(audios, texts, device) if args.parallel_eval: # multi-GPU eval if args.clap_mlploss: ( audio_features, text_features, audio_features_mlp, text_features_mlp, ) = gather_features( audio_features=audio_features, text_features=text_features, audio_features_mlp=audio_features_mlp, text_features_mlp=text_features_mlp, local_loss=False, gather_with_grad=False, rank=args.rank, world_size=args.world_size, use_horovod=args.horovod, mlp_loss=args.clap_mlploss, ) else: (audio_features, text_features,) = gather_features( audio_features=audio_features, text_features=text_features, local_loss=False, gather_with_grad=False, rank=args.rank, world_size=args.world_size, use_horovod=args.horovod, mlp_loss=args.clap_mlploss, ) if is_master(args): num_samples += audio_features.shape[0] for n in [*all_names, "all"]: if n == "all": eval_info[n]["all_audio_features"].append( audio_features.cpu() ) eval_info[n]["all_text_features"].append( text_features.cpu() ) if args.clap_mlploss: eval_info[n]["all_audio_features_mlp"].append( audio_features_mlp.cpu() ) eval_info[n]["all_text_features_mlp"].append( text_features_mlp.cpu() ) else: idx = np.where( np.array( [ "-".join(b.split("/")[-3:-1]) for b in batch["__url__"] ] ) == n )[0] eval_info[n]["all_audio_features"].append( audio_features.cpu().index_select( 0, torch.tensor(idx).long() ) ) eval_info[n]["all_text_features"].append( text_features.cpu().index_select( 0, torch.tensor(idx).long() ) ) if args.clap_mlploss: eval_info[n]["all_audio_features_mlp"].append( audio_features_mlp.cpu().index_select( 0, torch.tensor(idx).long() ) ) eval_info[n]["all_text_features_mlp"].append( text_features_mlp.cpu().index_select( 0, torch.tensor(idx).long() ) ) # print(f'eval step {i}') # (yusong): for debug # cumulative_loss += total_loss * batch_size # num_samples += batch_size if is_master(args) and (i % 100) == 0: # and i != 0: logging.info( f"Eval Epoch: {epoch} [{num_samples} / {samples_per_val}]" ) if is_master(args): val_metrics_per_dataset = {} for n in eval_info.keys(): if args.clap_mlploss: metrics_single_dataset = get_metrics( audio_features=torch.cat( eval_info[n]["all_audio_features"] ), text_features=torch.cat(eval_info[n]["all_text_features"]), logit_scale_a=logit_scale_a.cpu(), audio_features_mlp=torch.cat( eval_info[n]["all_audio_features_mlp"] ), text_features_mlp=torch.cat( eval_info[n]["all_text_features_mlp"] ), logit_scale_t=logit_scale_t.cpu(), mlp_loss=args.clap_mlploss, ) else: metrics_single_dataset = get_metrics( audio_features=torch.cat( eval_info[n]["all_audio_features"] ), text_features=torch.cat(eval_info[n]["all_text_features"]), logit_scale_a=logit_scale_a.cpu(), mlp_loss=args.clap_mlploss, ) val_metrics_per_dataset[n] = { n + "/" + k: v for k, v in metrics_single_dataset.items() } metrics.update(val_metrics_per_dataset[n]) if "epoch" not in metrics.keys(): metrics.update({"epoch": epoch}) if is_master(args): if not metrics: return metrics logging.info( f"Eval Epoch: {epoch} " + "\n".join( [ "\t".join([f"{k}: {round(v, 4):.4f}" for k, v in m.items()]) for m in val_metrics_per_dataset.values() ] ) ) if args.save_logs: for name, val in metrics.items(): if tb_writer is not None: tb_writer.add_scalar(f"val/{name}", val, epoch) with open(os.path.join(args.checkpoint_path, "results.jsonl"), "a+") as f: f.write(json.dumps(metrics)) f.write("\n") if args.wandb: assert wandb is not None, "Please install wandb." for name, val in metrics.items(): wandb.log({f"val/{name}": val, "epoch": epoch}) return metrics else: return metrics
null
167,342
import sys import os import torch import librosa from open_clip import create_model from training.data import get_audio_features from training.data import int16_to_float32, float32_to_int16 from transformers import RobertaTokenizer PRETRAINED_PATH = "/mnt/fast/nobackup/users/hl01486/projects/contrastive_pretraining/CLAP/assets/checkpoints/epoch_top_0_audioset_no_fusion.pt" WAVE_48k_PATH = "/mnt/fast/nobackup/users/hl01486/projects/contrastive_pretraining/CLAP/assets/audio/machine.wav" def int16_to_float32(x): return (x / 32767.0).astype(np.float32) def float32_to_int16(x): x = np.clip(x, a_min=-1.0, a_max=1.0) return (x * 32767.0).astype(np.int16) def get_audio_features( sample, audio_data, max_len, data_truncating, data_filling, audio_cfg ): """ Calculate and add audio features to sample. Sample: a dict containing all the data of current sample. audio_data: a tensor of shape (T) containing audio data. max_len: the maximum length of audio data. data_truncating: the method of truncating data. data_filling: the method of filling data. audio_cfg: a dict containing audio configuration. Comes from model_cfg['audio_cfg']. """ with torch.no_grad(): if len(audio_data) > max_len: if data_truncating == "rand_trunc": longer = torch.tensor([True]) elif data_truncating == "fusion": # fusion mel = get_mel(audio_data, audio_cfg) # split to three parts chunk_frames = ( max_len // audio_cfg["hop_size"] + 1 ) # the +1 related to how the spectrogram is computed total_frames = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is # larger than max_len but smaller than max_len+hop_size. # In this case, we just use the whole audio. mel_fusion = torch.stack([mel, mel, mel, mel], dim=0) sample["mel_fusion"] = mel_fusion longer = torch.tensor([False]) else: ranges = np.array_split( list(range(0, total_frames - chunk_frames + 1)), 3 ) # print('total_frames-chunk_frames:', total_frames-chunk_frames, # 'len(audio_data):', len(audio_data), # 'chunk_frames:', chunk_frames, # 'total_frames:', total_frames) if len(ranges[1]) == 0: # if the audio is too short, we just use the first chunk ranges[1] = [0] if len(ranges[2]) == 0: # if the audio is too short, we just use the first chunk ranges[2] = [0] # randomly choose index for each part idx_front = np.random.choice(ranges[0]) idx_middle = np.random.choice(ranges[1]) idx_back = np.random.choice(ranges[2]) # select mel mel_chunk_front = mel[idx_front : idx_front + chunk_frames, :] mel_chunk_middle = mel[idx_middle : idx_middle + chunk_frames, :] mel_chunk_back = mel[idx_back : idx_back + chunk_frames, :] # shrink the mel mel_shrink = torchvision.transforms.Resize(size=[chunk_frames, 64])( mel[None] )[0] # logging.info(f"mel_shrink.shape: {mel_shrink.shape}") # stack mel_fusion = torch.stack( [mel_chunk_front, mel_chunk_middle, mel_chunk_back, mel_shrink], dim=0, ) sample["mel_fusion"] = mel_fusion longer = torch.tensor([True]) else: raise NotImplementedError( f"data_truncating {data_truncating} not implemented" ) # random crop to max_len (for compatibility) overflow = len(audio_data) - max_len idx = np.random.randint(0, overflow + 1) audio_data = audio_data[idx : idx + max_len] else: # padding if too short if len(audio_data) < max_len: # do nothing if equal if data_filling == "repeatpad": n_repeat = int(max_len / len(audio_data)) audio_data = audio_data.repeat(n_repeat) # audio_data = audio_data.unsqueeze(0).unsqueeze(0).unsqueeze(0) # audio_data = F.interpolate(audio_data,size=max_len,mode="bicubic")[0,0,0] audio_data = F.pad( audio_data, (0, max_len - len(audio_data)), mode="constant", value=0, ) elif data_filling == "pad": audio_data = F.pad( audio_data, (0, max_len - len(audio_data)), mode="constant", value=0, ) elif data_filling == "repeat": n_repeat = int(max_len / len(audio_data)) audio_data = audio_data.repeat(n_repeat + 1)[:max_len] else: raise NotImplementedError( f"data_filling {data_filling} not implemented" ) if data_truncating == "fusion": mel = get_mel(audio_data, audio_cfg) mel_fusion = torch.stack([mel, mel, mel, mel], dim=0) sample["mel_fusion"] = mel_fusion longer = torch.tensor([False]) sample["longer"] = longer sample["waveform"] = audio_data return sample def infer_audio(): device = "cuda:0" if torch.cuda.is_available() else "cpu" precision = "fp32" amodel = "HTSAT-tiny" # or 'PANN-14' tmodel = "roberta" # the best text encoder in our training enable_fusion = False # False if you do not want to use the fusion model fusion_type = "aff_2d" pretrained = PRETRAINED_PATH model, model_cfg = create_model( amodel, tmodel, pretrained, precision=precision, device=device, enable_fusion=enable_fusion, fusion_type=fusion_type, ) # load the waveform of the shape (T,), should resample to 48000 audio_waveform, sr = librosa.load(WAVE_48k_PATH, sr=48000) # quantize audio_waveform = int16_to_float32(float32_to_int16(audio_waveform)) audio_waveform = torch.from_numpy(audio_waveform).float() audio_dict = {} # the 'fusion' truncate mode can be changed to 'rand_trunc' if run in unfusion mode import ipdb ipdb.set_trace() audio_dict = get_audio_features( audio_dict, audio_waveform, 480000, data_truncating="fusion", data_filling="repeatpad", audio_cfg=model_cfg["audio_cfg"], ) # can send a list to the model, to process many audio tracks in one time (i.e. batch size) audio_embed = model.get_audio_embedding([audio_dict]) print(audio_embed.size()) import ipdb ipdb.set_trace()
null
167,348
import ast import json import logging import math import os import random import h5py from dataclasses import dataclass from models.CLAP.training.params import parse_args import braceexpand import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torchvision.datasets as datasets import torchvision.transforms import webdataset as wds from PIL import Image from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler from torch.utils.data.distributed import DistributedSampler from functools import partial import soundfile as sf import io from pathlib import Path import wget from models.CLAP.open_clip.utils import get_tar_path_from_dataset_name, dataset_split from models.CLAP.open_clip.utils import load_p, load_class_label import tempfile import copy from models.CLAP.open_clip import tokenize from transformers import RobertaTokenizer tokenize = RobertaTokenizer.from_pretrained("roberta-base") def preprocess_txt(text): return tokenize([str(text)])[0]
null
167,349
import ast import json import logging import math import os import random import h5py from dataclasses import dataclass from models.CLAP.training.params import parse_args import braceexpand import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torchvision.datasets as datasets import torchvision.transforms import webdataset as wds from PIL import Image from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler from torch.utils.data.distributed import DistributedSampler from functools import partial import soundfile as sf import io from pathlib import Path import wget from models.CLAP.open_clip.utils import get_tar_path_from_dataset_name, dataset_split from models.CLAP.open_clip.utils import load_p, load_class_label import tempfile import copy from models.CLAP.open_clip import tokenize from transformers import RobertaTokenizer class DataInfo: dataloader: DataLoader sampler: DistributedSampler def get_imagenet(args, preprocess_fns, split): assert split in ["train", "val", "v2"] is_train = split == "train" preprocess_train, preprocess_val = preprocess_fns if split == "v2": from imagenetv2_pytorch import ImageNetV2Dataset dataset = ImageNetV2Dataset(location=args.imagenet_v2, transform=preprocess_val) else: if is_train: data_path = args.imagenet_train preprocess_fn = preprocess_train else: data_path = args.imagenet_val preprocess_fn = preprocess_val assert data_path dataset = datasets.ImageFolder(data_path, transform=preprocess_fn) if is_train: idxs = np.zeros(len(dataset.targets)) target_array = np.array(dataset.targets) k = 50 for c in range(1000): m = target_array == c n = len(idxs[m]) arr = np.zeros(n) arr[:k] = 1 np.random.shuffle(arr) idxs[m] = arr idxs = idxs.astype("int") sampler = SubsetRandomSampler(np.where(idxs)[0]) else: sampler = None dataloader = torch.utils.data.DataLoader( dataset, batch_size=args.batch_size, num_workers=args.workers, sampler=sampler, ) return DataInfo(dataloader, sampler)
null
167,350
import ast import json import logging import math import os import random import h5py from dataclasses import dataclass from models.CLAP.training.params import parse_args import braceexpand import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torchvision.datasets as datasets import torchvision.transforms import webdataset as wds from PIL import Image from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler from torch.utils.data.distributed import DistributedSampler from functools import partial import soundfile as sf import io from pathlib import Path import wget from models.CLAP.open_clip.utils import get_tar_path_from_dataset_name, dataset_split from models.CLAP.open_clip.utils import load_p, load_class_label import tempfile import copy from models.CLAP.open_clip import tokenize from transformers import RobertaTokenizer def count_samples(dataloader): os.environ["WDS_EPOCH"] = "0" n_elements, n_batches = 0, 0 for images, texts in dataloader: n_batches += 1 n_elements += len(images) assert len(images) == len(texts) return n_elements, n_batches
null
167,351
import ast import json import logging import math import os import random import h5py from dataclasses import dataclass from models.CLAP.training.params import parse_args import braceexpand import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torchvision.datasets as datasets import torchvision.transforms import webdataset as wds from PIL import Image from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler from torch.utils.data.distributed import DistributedSampler from functools import partial import soundfile as sf import io from pathlib import Path import wget from models.CLAP.open_clip.utils import get_tar_path_from_dataset_name, dataset_split from models.CLAP.open_clip.utils import load_p, load_class_label import tempfile import copy from models.CLAP.open_clip import tokenize from transformers import RobertaTokenizer def filter_no_caption(sample): return "txt" in sample
null
167,352
import ast import json import logging import math import os import random import h5py from dataclasses import dataclass from models.CLAP.training.params import parse_args import braceexpand import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torchvision.datasets as datasets import torchvision.transforms import webdataset as wds from PIL import Image from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler from torch.utils.data.distributed import DistributedSampler from functools import partial import soundfile as sf import io from pathlib import Path import wget from models.CLAP.open_clip.utils import get_tar_path_from_dataset_name, dataset_split from models.CLAP.open_clip.utils import load_p, load_class_label import tempfile import copy from models.CLAP.open_clip import tokenize from transformers import RobertaTokenizer The provided code snippet includes necessary dependencies for implementing the `wds_batch_list2dict` function. Write a Python function `def wds_batch_list2dict( batch, keys=[ "__url__", "__key__", "waveform", "text", "raw_text", "audio_name", "text_name", "audio_orig_sr", ], )` to solve the following problem: Return a dictionary of the batch, with keys as the names of the fields. Here is the function: def wds_batch_list2dict( batch, keys=[ "__url__", "__key__", "waveform", "text", "raw_text", "audio_name", "text_name", "audio_orig_sr", ], ): """ Return a dictionary of the batch, with keys as the names of the fields. """ assert len(keys) == len( batch ), "batch must have same number of keys as keys argument" return {keys[i]: batch[i] for i in range(len(batch))}
Return a dictionary of the batch, with keys as the names of the fields.
167,353
import ast import json import logging import math import os import random import h5py from dataclasses import dataclass from models.CLAP.training.params import parse_args import braceexpand import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torchvision.datasets as datasets import torchvision.transforms import webdataset as wds from PIL import Image from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler from torch.utils.data.distributed import DistributedSampler from functools import partial import soundfile as sf import io from pathlib import Path import wget from models.CLAP.open_clip.utils import get_tar_path_from_dataset_name, dataset_split from models.CLAP.open_clip.utils import load_p, load_class_label import tempfile import copy from models.CLAP.open_clip import tokenize from transformers import RobertaTokenizer def get_dataset_fn(data_path, dataset_type): if dataset_type == "webdataset": return get_wds_dataset elif dataset_type == "csv": return get_csv_dataset elif dataset_type == "auto": ext = data_path.split(".")[-1] if ext in ["csv", "tsv"]: return get_csv_dataset elif ext in ["tar"]: return get_wds_dataset else: raise ValueError( f"Tried to figure out dataset type, but failed for extention {ext}." ) elif dataset_type == "toy": return get_toy_dataset else: raise ValueError(f"Unsupported dataset type: {dataset_type}") def get_tar_path_from_dataset_name( dataset_names, dataset_types, islocal, dataset_path, proportion=1, full_dataset=None ): """ Get tar path from dataset name and type """ output = [] for n in dataset_names: if full_dataset is not None and n in full_dataset: current_dataset_types = dataset_split[n] else: current_dataset_types = dataset_types for s in current_dataset_types: tmp = [] if islocal: sizefilepath_ = f"{dataset_path}/{n}/{s}/sizes.json" if not os.path.exists(sizefilepath_): sizefilepath_ = f"./json_files/{n}/{s}/sizes.json" else: sizefilepath_ = f"./json_files/{n}/{s}/sizes.json" if not os.path.exists(sizefilepath_): continue sizes = json.load(open(sizefilepath_, "r")) for k in sizes.keys(): if islocal: tmp.append(f"{dataset_path}/{n}/{s}/{k}") else: tmp.append( f"pipe:aws s3 --cli-connect-timeout 0 cp s3://s-laion-audio/webdataset_tar/{n}/{s}/{k} -" ) if proportion != 1: tmp = random.sample(tmp, int(proportion * len(tmp))) output.append(tmp) return sum(output, []) def load_class_label(path): # https://stackoverflow.com/questions/48004243/how-to-share-large-read-only-dictionary-list-across-processes-in-multiprocessing # https://stackoverflow.com/questions/45693949/storing-strings-in-a-multiprocessing-sharedctypes-array out = None if path is not None: if pathlib.Path(path).suffix in [".pkl", ".pickle"]: out = load_p(path) elif pathlib.Path(path).suffix in [".json", ".txt"]: out = load_json(path) elif pathlib.Path(path).suffix in [".npy", ".npz"]: out = np.load(path) elif pathlib.Path(path).suffix in [".csv"]: import pandas as pd out = pd.read_csv(path) return out # if out is None: # return None # else: # key = Array(c_wchar, '\n'.join(list(out.keys())), lock=False) # val = Array('i', out.values(), lock=False) # return (key, val) def get_data(args, model_cfg): data = {} args.class_index_dict = load_class_label(args.class_label_path) if args.datasetinfos is None: args.datasetinfos = ["train", "unbalanced_train", "balanced_train"] if args.dataset_type == "webdataset": args.train_data = get_tar_path_from_dataset_name( args.datasetnames, args.datasetinfos, islocal=not args.remotedata, proportion=args.dataset_proportion, dataset_path=args.datasetpath, full_dataset=args.full_train_dataset, ) if args.full_train_dataset is None: args.full_train_dataset = [] if args.exclude_eval_dataset is None: args.exclude_eval_dataset = [] excluded_eval_datasets = args.full_train_dataset + args.exclude_eval_dataset val_dataset_names = ( [n for n in args.datasetnames if n not in excluded_eval_datasets] if excluded_eval_datasets else args.datasetnames ) args.val_dataset_names = val_dataset_names args.val_data = get_tar_path_from_dataset_name( val_dataset_names, ["valid", "test", "eval"], islocal=not args.remotedata, proportion=1, dataset_path=args.datasetpath, full_dataset=None, ) if args.train_data: data["train"] = get_dataset_fn(args.train_data, args.dataset_type)( args, model_cfg, is_train=True ) if args.val_data: data["val"] = get_dataset_fn(args.val_data, args.dataset_type)( args, model_cfg, is_train=False ) return data
null
167,358
import logging from contextlib import suppress import torch import torch.nn.functional as F from tqdm import tqdm from open_clip import tokenize from .imagenet_zeroshot_data import imagenet_classnames, openai_imagenet_template def zero_shot_classifier(model, classnames, templates, args): def run(model, classifier, dataloader, args): imagenet_classnames = [ "tench", "goldfish", "great white shark", "tiger shark", "hammerhead shark", "electric ray", "stingray", "rooster", "hen", "ostrich", "brambling", "goldfinch", "house finch", "junco", "indigo bunting", "American robin", "bulbul", "jay", "magpie", "chickadee", "American dipper", "kite (bird of prey)", "bald eagle", "vulture", "great grey owl", "fire salamander", "smooth newt", "newt", "spotted salamander", "axolotl", "American bullfrog", "tree frog", "tailed frog", "loggerhead sea turtle", "leatherback sea turtle", "mud turtle", "terrapin", "box turtle", "banded gecko", "green iguana", "Carolina anole", "desert grassland whiptail lizard", "agama", "frilled-necked lizard", "alligator lizard", "Gila monster", "European green lizard", "chameleon", "Komodo dragon", "Nile crocodile", "American alligator", "triceratops", "worm snake", "ring-necked snake", "eastern hog-nosed snake", "smooth green snake", "kingsnake", "garter snake", "water snake", "vine snake", "night snake", "boa constrictor", "African rock python", "Indian cobra", "green mamba", "sea snake", "Saharan horned viper", "eastern diamondback rattlesnake", "sidewinder rattlesnake", "trilobite", "harvestman", "scorpion", "yellow garden spider", "barn spider", "European garden spider", "southern black widow", "tarantula", "wolf spider", "tick", "centipede", "black grouse", "ptarmigan", "ruffed grouse", "prairie grouse", "peafowl", "quail", "partridge", "african grey parrot", "macaw", "sulphur-crested cockatoo", "lorikeet", "coucal", "bee eater", "hornbill", "hummingbird", "jacamar", "toucan", "duck", "red-breasted merganser", "goose", "black swan", "tusker", "echidna", "platypus", "wallaby", "koala", "wombat", "jellyfish", "sea anemone", "brain coral", "flatworm", "nematode", "conch", "snail", "slug", "sea slug", "chiton", "chambered nautilus", "Dungeness crab", "rock crab", "fiddler crab", "red king crab", "American lobster", "spiny lobster", "crayfish", "hermit crab", "isopod", "white stork", "black stork", "spoonbill", "flamingo", "little blue heron", "great egret", "bittern bird", "crane bird", "limpkin", "common gallinule", "American coot", "bustard", "ruddy turnstone", "dunlin", "common redshank", "dowitcher", "oystercatcher", "pelican", "king penguin", "albatross", "grey whale", "killer whale", "dugong", "sea lion", "Chihuahua", "Japanese Chin", "Maltese", "Pekingese", "Shih Tzu", "King Charles Spaniel", "Papillon", "toy terrier", "Rhodesian Ridgeback", "Afghan Hound", "Basset Hound", "Beagle", "Bloodhound", "Bluetick Coonhound", "Black and Tan Coonhound", "Treeing Walker Coonhound", "English foxhound", "Redbone Coonhound", "borzoi", "Irish Wolfhound", "Italian Greyhound", "Whippet", "Ibizan Hound", "Norwegian Elkhound", "Otterhound", "Saluki", "Scottish Deerhound", "Weimaraner", "Staffordshire Bull Terrier", "American Staffordshire Terrier", "Bedlington Terrier", "Border Terrier", "Kerry Blue Terrier", "Irish Terrier", "Norfolk Terrier", "Norwich Terrier", "Yorkshire Terrier", "Wire Fox Terrier", "Lakeland Terrier", "Sealyham Terrier", "Airedale Terrier", "Cairn Terrier", "Australian Terrier", "Dandie Dinmont Terrier", "Boston Terrier", "Miniature Schnauzer", "Giant Schnauzer", "Standard Schnauzer", "Scottish Terrier", "Tibetan Terrier", "Australian Silky Terrier", "Soft-coated Wheaten Terrier", "West Highland White Terrier", "Lhasa Apso", "Flat-Coated Retriever", "Curly-coated Retriever", "Golden Retriever", "Labrador Retriever", "Chesapeake Bay Retriever", "German Shorthaired Pointer", "Vizsla", "English Setter", "Irish Setter", "Gordon Setter", "Brittany dog", "Clumber Spaniel", "English Springer Spaniel", "Welsh Springer Spaniel", "Cocker Spaniel", "Sussex Spaniel", "Irish Water Spaniel", "Kuvasz", "Schipperke", "Groenendael dog", "Malinois", "Briard", "Australian Kelpie", "Komondor", "Old English Sheepdog", "Shetland Sheepdog", "collie", "Border Collie", "Bouvier des Flandres dog", "Rottweiler", "German Shepherd Dog", "Dobermann", "Miniature Pinscher", "Greater Swiss Mountain Dog", "Bernese Mountain Dog", "Appenzeller Sennenhund", "Entlebucher Sennenhund", "Boxer", "Bullmastiff", "Tibetan Mastiff", "French Bulldog", "Great Dane", "St. Bernard", "husky", "Alaskan Malamute", "Siberian Husky", "Dalmatian", "Affenpinscher", "Basenji", "pug", "Leonberger", "Newfoundland dog", "Great Pyrenees dog", "Samoyed", "Pomeranian", "Chow Chow", "Keeshond", "brussels griffon", "Pembroke Welsh Corgi", "Cardigan Welsh Corgi", "Toy Poodle", "Miniature Poodle", "Standard Poodle", "Mexican hairless dog (xoloitzcuintli)", "grey wolf", "Alaskan tundra wolf", "red wolf or maned wolf", "coyote", "dingo", "dhole", "African wild dog", "hyena", "red fox", "kit fox", "Arctic fox", "grey fox", "tabby cat", "tiger cat", "Persian cat", "Siamese cat", "Egyptian Mau", "cougar", "lynx", "leopard", "snow leopard", "jaguar", "lion", "tiger", "cheetah", "brown bear", "American black bear", "polar bear", "sloth bear", "mongoose", "meerkat", "tiger beetle", "ladybug", "ground beetle", "longhorn beetle", "leaf beetle", "dung beetle", "rhinoceros beetle", "weevil", "fly", "bee", "ant", "grasshopper", "cricket insect", "stick insect", "cockroach", "praying mantis", "cicada", "leafhopper", "lacewing", "dragonfly", "damselfly", "red admiral butterfly", "ringlet butterfly", "monarch butterfly", "small white butterfly", "sulphur butterfly", "gossamer-winged butterfly", "starfish", "sea urchin", "sea cucumber", "cottontail rabbit", "hare", "Angora rabbit", "hamster", "porcupine", "fox squirrel", "marmot", "beaver", "guinea pig", "common sorrel horse", "zebra", "pig", "wild boar", "warthog", "hippopotamus", "ox", "water buffalo", "bison", "ram (adult male sheep)", "bighorn sheep", "Alpine ibex", "hartebeest", "impala (antelope)", "gazelle", "arabian camel", "llama", "weasel", "mink", "European polecat", "black-footed ferret", "otter", "skunk", "badger", "armadillo", "three-toed sloth", "orangutan", "gorilla", "chimpanzee", "gibbon", "siamang", "guenon", "patas monkey", "baboon", "macaque", "langur", "black-and-white colobus", "proboscis monkey", "marmoset", "white-headed capuchin", "howler monkey", "titi monkey", "Geoffroy's spider monkey", "common squirrel monkey", "ring-tailed lemur", "indri", "Asian elephant", "African bush elephant", "red panda", "giant panda", "snoek fish", "eel", "silver salmon", "rock beauty fish", "clownfish", "sturgeon", "gar fish", "lionfish", "pufferfish", "abacus", "abaya", "academic gown", "accordion", "acoustic guitar", "aircraft carrier", "airliner", "airship", "altar", "ambulance", "amphibious vehicle", "analog clock", "apiary", "apron", "trash can", "assault rifle", "backpack", "bakery", "balance beam", "balloon", "ballpoint pen", "Band-Aid", "banjo", "baluster / handrail", "barbell", "barber chair", "barbershop", "barn", "barometer", "barrel", "wheelbarrow", "baseball", "basketball", "bassinet", "bassoon", "swimming cap", "bath towel", "bathtub", "station wagon", "lighthouse", "beaker", "military hat (bearskin or shako)", "beer bottle", "beer glass", "bell tower", "baby bib", "tandem bicycle", "bikini", "ring binder", "binoculars", "birdhouse", "boathouse", "bobsleigh", "bolo tie", "poke bonnet", "bookcase", "bookstore", "bottle cap", "hunting bow", "bow tie", "brass memorial plaque", "bra", "breakwater", "breastplate", "broom", "bucket", "buckle", "bulletproof vest", "high-speed train", "butcher shop", "taxicab", "cauldron", "candle", "cannon", "canoe", "can opener", "cardigan", "car mirror", "carousel", "tool kit", "cardboard box / carton", "car wheel", "automated teller machine", "cassette", "cassette player", "castle", "catamaran", "CD player", "cello", "mobile phone", "chain", "chain-link fence", "chain mail", "chainsaw", "storage chest", "chiffonier", "bell or wind chime", "china cabinet", "Christmas stocking", "church", "movie theater", "cleaver", "cliff dwelling", "cloak", "clogs", "cocktail shaker", "coffee mug", "coffeemaker", "spiral or coil", "combination lock", "computer keyboard", "candy store", "container ship", "convertible", "corkscrew", "cornet", "cowboy boot", "cowboy hat", "cradle", "construction crane", "crash helmet", "crate", "infant bed", "Crock Pot", "croquet ball", "crutch", "cuirass", "dam", "desk", "desktop computer", "rotary dial telephone", "diaper", "digital clock", "digital watch", "dining table", "dishcloth", "dishwasher", "disc brake", "dock", "dog sled", "dome", "doormat", "drilling rig", "drum", "drumstick", "dumbbell", "Dutch oven", "electric fan", "electric guitar", "electric locomotive", "entertainment center", "envelope", "espresso machine", "face powder", "feather boa", "filing cabinet", "fireboat", "fire truck", "fire screen", "flagpole", "flute", "folding chair", "football helmet", "forklift", "fountain", "fountain pen", "four-poster bed", "freight car", "French horn", "frying pan", "fur coat", "garbage truck", "gas mask or respirator", "gas pump", "goblet", "go-kart", "golf ball", "golf cart", "gondola", "gong", "gown", "grand piano", "greenhouse", "radiator grille", "grocery store", "guillotine", "hair clip", "hair spray", "half-track", "hammer", "hamper", "hair dryer", "hand-held computer", "handkerchief", "hard disk drive", "harmonica", "harp", "combine harvester", "hatchet", "holster", "home theater", "honeycomb", "hook", "hoop skirt", "gymnastic horizontal bar", "horse-drawn vehicle", "hourglass", "iPod", "clothes iron", "carved pumpkin", "jeans", "jeep", "T-shirt", "jigsaw puzzle", "rickshaw", "joystick", "kimono", "knee pad", "knot", "lab coat", "ladle", "lampshade", "laptop computer", "lawn mower", "lens cap", "letter opener", "library", "lifeboat", "lighter", "limousine", "ocean liner", "lipstick", "slip-on shoe", "lotion", "music speaker", "loupe magnifying glass", "sawmill", "magnetic compass", "messenger bag", "mailbox", "tights", "one-piece bathing suit", "manhole cover", "maraca", "marimba", "mask", "matchstick", "maypole", "maze", "measuring cup", "medicine cabinet", "megalith", "microphone", "microwave oven", "military uniform", "milk can", "minibus", "miniskirt", "minivan", "missile", "mitten", "mixing bowl", "mobile home", "ford model t", "modem", "monastery", "monitor", "moped", "mortar and pestle", "graduation cap", "mosque", "mosquito net", "vespa", "mountain bike", "tent", "computer mouse", "mousetrap", "moving van", "muzzle", "metal nail", "neck brace", "necklace", "baby pacifier", "notebook computer", "obelisk", "oboe", "ocarina", "odometer", "oil filter", "pipe organ", "oscilloscope", "overskirt", "bullock cart", "oxygen mask", "product packet / packaging", "paddle", "paddle wheel", "padlock", "paintbrush", "pajamas", "palace", "pan flute", "paper towel", "parachute", "parallel bars", "park bench", "parking meter", "railroad car", "patio", "payphone", "pedestal", "pencil case", "pencil sharpener", "perfume", "Petri dish", "photocopier", "plectrum", "Pickelhaube", "picket fence", "pickup truck", "pier", "piggy bank", "pill bottle", "pillow", "ping-pong ball", "pinwheel", "pirate ship", "drink pitcher", "block plane", "planetarium", "plastic bag", "plate rack", "farm plow", "plunger", "Polaroid camera", "pole", "police van", "poncho", "pool table", "soda bottle", "plant pot", "potter's wheel", "power drill", "prayer rug", "printer", "prison", "missile", "projector", "hockey puck", "punching bag", "purse", "quill", "quilt", "race car", "racket", "radiator", "radio", "radio telescope", "rain barrel", "recreational vehicle", "fishing casting reel", "reflex camera", "refrigerator", "remote control", "restaurant", "revolver", "rifle", "rocking chair", "rotisserie", "eraser", "rugby ball", "ruler measuring stick", "sneaker", "safe", "safety pin", "salt shaker", "sandal", "sarong", "saxophone", "scabbard", "weighing scale", "school bus", "schooner", "scoreboard", "CRT monitor", "screw", "screwdriver", "seat belt", "sewing machine", "shield", "shoe store", "shoji screen / room divider", "shopping basket", "shopping cart", "shovel", "shower cap", "shower curtain", "ski", "balaclava ski mask", "sleeping bag", "slide rule", "sliding door", "slot machine", "snorkel", "snowmobile", "snowplow", "soap dispenser", "soccer ball", "sock", "solar thermal collector", "sombrero", "soup bowl", "keyboard space bar", "space heater", "space shuttle", "spatula", "motorboat", "spider web", "spindle", "sports car", "spotlight", "stage", "steam locomotive", "through arch bridge", "steel drum", "stethoscope", "scarf", "stone wall", "stopwatch", "stove", "strainer", "tram", "stretcher", "couch", "stupa", "submarine", "suit", "sundial", "sunglasses", "sunglasses", "sunscreen", "suspension bridge", "mop", "sweatshirt", "swim trunks / shorts", "swing", "electrical switch", "syringe", "table lamp", "tank", "tape player", "teapot", "teddy bear", "television", "tennis ball", "thatched roof", "front curtain", "thimble", "threshing machine", "throne", "tile roof", "toaster", "tobacco shop", "toilet seat", "torch", "totem pole", "tow truck", "toy store", "tractor", "semi-trailer truck", "tray", "trench coat", "tricycle", "trimaran", "tripod", "triumphal arch", "trolleybus", "trombone", "hot tub", "turnstile", "typewriter keyboard", "umbrella", "unicycle", "upright piano", "vacuum cleaner", "vase", "vaulted or arched ceiling", "velvet fabric", "vending machine", "vestment", "viaduct", "violin", "volleyball", "waffle iron", "wall clock", "wallet", "wardrobe", "military aircraft", "sink", "washing machine", "water bottle", "water jug", "water tower", "whiskey jug", "whistle", "hair wig", "window screen", "window shade", "Windsor tie", "wine bottle", "airplane wing", "wok", "wooden spoon", "wool", "split-rail fence", "shipwreck", "sailboat", "yurt", "website", "comic book", "crossword", "traffic or street sign", "traffic light", "dust jacket", "menu", "plate", "guacamole", "consomme", "hot pot", "trifle", "ice cream", "popsicle", "baguette", "bagel", "pretzel", "cheeseburger", "hot dog", "mashed potatoes", "cabbage", "broccoli", "cauliflower", "zucchini", "spaghetti squash", "acorn squash", "butternut squash", "cucumber", "artichoke", "bell pepper", "cardoon", "mushroom", "Granny Smith apple", "strawberry", "orange", "lemon", "fig", "pineapple", "banana", "jackfruit", "cherimoya (custard apple)", "pomegranate", "hay", "carbonara", "chocolate syrup", "dough", "meatloaf", "pizza", "pot pie", "burrito", "red wine", "espresso", "tea cup", "eggnog", "mountain", "bubble", "cliff", "coral reef", "geyser", "lakeshore", "promontory", "sandbar", "beach", "valley", "volcano", "baseball player", "bridegroom", "scuba diver", "rapeseed", "daisy", "yellow lady's slipper", "corn", "acorn", "rose hip", "horse chestnut seed", "coral fungus", "agaric", "gyromitra", "stinkhorn mushroom", "earth star fungus", "hen of the woods mushroom", "bolete", "corn cob", "toilet paper", ] openai_imagenet_template = [ lambda c: f"a bad photo of a {c}.", lambda c: f"a photo of many {c}.", lambda c: f"a sculpture of a {c}.", lambda c: f"a photo of the hard to see {c}.", lambda c: f"a low resolution photo of the {c}.", lambda c: f"a rendering of a {c}.", lambda c: f"graffiti of a {c}.", lambda c: f"a bad photo of the {c}.", lambda c: f"a cropped photo of the {c}.", lambda c: f"a tattoo of a {c}.", lambda c: f"the embroidered {c}.", lambda c: f"a photo of a hard to see {c}.", lambda c: f"a bright photo of a {c}.", lambda c: f"a photo of a clean {c}.", lambda c: f"a photo of a dirty {c}.", lambda c: f"a dark photo of the {c}.", lambda c: f"a drawing of a {c}.", lambda c: f"a photo of my {c}.", lambda c: f"the plastic {c}.", lambda c: f"a photo of the cool {c}.", lambda c: f"a close-up photo of a {c}.", lambda c: f"a black and white photo of the {c}.", lambda c: f"a painting of the {c}.", lambda c: f"a painting of a {c}.", lambda c: f"a pixelated photo of the {c}.", lambda c: f"a sculpture of the {c}.", lambda c: f"a bright photo of the {c}.", lambda c: f"a cropped photo of a {c}.", lambda c: f"a plastic {c}.", lambda c: f"a photo of the dirty {c}.", lambda c: f"a jpeg corrupted photo of a {c}.", lambda c: f"a blurry photo of the {c}.", lambda c: f"a photo of the {c}.", lambda c: f"a good photo of the {c}.", lambda c: f"a rendering of the {c}.", lambda c: f"a {c} in a video game.", lambda c: f"a photo of one {c}.", lambda c: f"a doodle of a {c}.", lambda c: f"a close-up photo of the {c}.", lambda c: f"a photo of a {c}.", lambda c: f"the origami {c}.", lambda c: f"the {c} in a video game.", lambda c: f"a sketch of a {c}.", lambda c: f"a doodle of the {c}.", lambda c: f"a origami {c}.", lambda c: f"a low resolution photo of a {c}.", lambda c: f"the toy {c}.", lambda c: f"a rendition of the {c}.", lambda c: f"a photo of the clean {c}.", lambda c: f"a photo of a large {c}.", lambda c: f"a rendition of a {c}.", lambda c: f"a photo of a nice {c}.", lambda c: f"a photo of a weird {c}.", lambda c: f"a blurry photo of a {c}.", lambda c: f"a cartoon {c}.", lambda c: f"art of a {c}.", lambda c: f"a sketch of the {c}.", lambda c: f"a embroidered {c}.", lambda c: f"a pixelated photo of a {c}.", lambda c: f"itap of the {c}.", lambda c: f"a jpeg corrupted photo of the {c}.", lambda c: f"a good photo of a {c}.", lambda c: f"a plushie {c}.", lambda c: f"a photo of the nice {c}.", lambda c: f"a photo of the small {c}.", lambda c: f"a photo of the weird {c}.", lambda c: f"the cartoon {c}.", lambda c: f"art of the {c}.", lambda c: f"a drawing of the {c}.", lambda c: f"a photo of the large {c}.", lambda c: f"a black and white photo of a {c}.", lambda c: f"the plushie {c}.", lambda c: f"a dark photo of a {c}.", lambda c: f"itap of a {c}.", lambda c: f"graffiti of the {c}.", lambda c: f"a toy {c}.", lambda c: f"itap of my {c}.", lambda c: f"a photo of a cool {c}.", lambda c: f"a photo of a small {c}.", lambda c: f"a tattoo of the {c}.", ] def zero_shot_eval(model, data, epoch, args): if "imagenet-val" not in data and "imagenet-v2" not in data: return {} if args.zeroshot_frequency == 0: return {} if (epoch % args.zeroshot_frequency) != 0 and epoch != args.epochs: return {} logging.info("Starting zero-shot imagenet.") logging.info("Building zero-shot classifier") classifier = zero_shot_classifier( model, imagenet_classnames, openai_imagenet_template, args ) logging.info("Using classifier") results = {} if "imagenet-val" in data: top1, top5 = run(model, classifier, data["imagenet-val"].dataloader, args) results["imagenet-zeroshot-val-top1"] = top1 results["imagenet-zeroshot-val-top5"] = top5 if "imagenet-v2" in data: top1, top5 = run(model, classifier, data["imagenet-v2"].dataloader, args) results["imagenetv2-zeroshot-val-top1"] = top1 results["imagenetv2-zeroshot-val-top5"] = top5 logging.info("Finished zero-shot imagenet.") return results
null
167,360
import os import torch import socket try: import horovod.torch as hvd except ImportError: hvd = None def is_using_distributed(): if "WORLD_SIZE" in os.environ: return int(os.environ["WORLD_SIZE"]) > 1 if "SLURM_NTASKS" in os.environ: return int(os.environ["SLURM_NTASKS"]) > 1 return False def world_info_from_env(): local_rank = 0 for v in ( "SLURM_LOCALID", "MPI_LOCALRANKID", "OMPI_COMM_WORLD_LOCAL_RANK", "LOCAL_RANK", ): if v in os.environ: local_rank = int(os.environ[v]) break global_rank = 0 for v in ("SLURM_PROCID", "PMI_RANK", "OMPI_COMM_WORLD_RANK", "RANK"): if v in os.environ: global_rank = int(os.environ[v]) break world_size = 1 for v in ("SLURM_NTASKS", "PMI_SIZE", "OMPI_COMM_WORLD_SIZE", "WORLD_SIZE"): if v in os.environ: world_size = int(os.environ[v]) break return local_rank, global_rank, world_size def init_distributed_device(args): # Distributed training = training on more than one GPU. # Works in both single and multi-node scenarios. args.distributed = False args.world_size = 1 args.rank = 0 # global rank args.local_rank = 0 if args.horovod: assert hvd is not None, "Horovod is not installed" hvd.init() world_size = int(os.environ["OMPI_COMM_WORLD_SIZE"]) world_rank = int(os.environ["OMPI_COMM_WORLD_RANK"]) local_rank = int(os.environ["OMPI_COMM_WORLD_LOCAL_RANK"]) args.local_rank = local_rank args.rank = world_rank args.world_size = world_size # args.local_rank = int(hvd.local_rank()) # args.rank = hvd.rank() # args.world_size = hvd.size() args.distributed = True os.environ["LOCAL_RANK"] = str(args.local_rank) os.environ["RANK"] = str(args.rank) os.environ["WORLD_SIZE"] = str(args.world_size) print( f"Distributed training: local_rank={args.local_rank}, " f"rank={args.rank}, world_size={args.world_size}, " f"hostname={socket.gethostname()}, pid={os.getpid()}" ) elif is_using_distributed(): if "SLURM_PROCID" in os.environ: # DDP via SLURM args.local_rank, args.rank, args.world_size = world_info_from_env() # SLURM var -> torch.distributed vars in case needed os.environ["LOCAL_RANK"] = str(args.local_rank) os.environ["RANK"] = str(args.rank) os.environ["WORLD_SIZE"] = str(args.world_size) torch.distributed.init_process_group( backend=args.dist_backend, init_method=args.dist_url, world_size=args.world_size, rank=args.rank, ) elif "OMPI_COMM_WORLD_SIZE" in os.environ: # using Summit cluster world_size = int(os.environ["OMPI_COMM_WORLD_SIZE"]) world_rank = int(os.environ["OMPI_COMM_WORLD_RANK"]) local_rank = int(os.environ["OMPI_COMM_WORLD_LOCAL_RANK"]) args.local_rank = local_rank args.rank = world_rank args.world_size = world_size torch.distributed.init_process_group( backend=args.dist_backend, init_method=args.dist_url, world_size=args.world_size, rank=args.rank, ) else: # DDP via torchrun, torch.distributed.launch args.local_rank, _, _ = world_info_from_env() torch.distributed.init_process_group( backend=args.dist_backend, init_method=args.dist_url ) args.world_size = torch.distributed.get_world_size() args.rank = torch.distributed.get_rank() args.distributed = True print( f"Distributed training: local_rank={args.local_rank}, " f"rank={args.rank}, world_size={args.world_size}, " f"hostname={socket.gethostname()}, pid={os.getpid()}" ) if torch.cuda.is_available(): if args.distributed and not args.no_set_device_rank: device = "cuda:%d" % args.local_rank else: device = "cuda:0" torch.cuda.set_device(device) else: device = "cpu" args.device = device device = torch.device(device) return device
null
167,362
import torch.nn as nn import torch import numpy as np import torch.nn.functional as F import math from torchlibrosa.stft import magphase The provided code snippet includes necessary dependencies for implementing the `init_layer` function. Write a Python function `def init_layer(layer)` to solve the following problem: Initialize a Linear or Convolutional layer. Here is the function: def init_layer(layer): """Initialize a Linear or Convolutional layer. """ nn.init.xavier_uniform_(layer.weight) if hasattr(layer, "bias"): if layer.bias is not None: layer.bias.data.fill_(0.0)
Initialize a Linear or Convolutional layer.
167,363
import torch.nn as nn import torch import numpy as np import torch.nn.functional as F import math from torchlibrosa.stft import magphase The provided code snippet includes necessary dependencies for implementing the `init_bn` function. Write a Python function `def init_bn(bn)` to solve the following problem: Initialize a Batchnorm layer. Here is the function: def init_bn(bn): """Initialize a Batchnorm layer. """ bn.bias.data.fill_(0.0) bn.weight.data.fill_(1.0)
Initialize a Batchnorm layer.
167,364
import torch.nn as nn import torch import numpy as np import torch.nn.functional as F import math from torchlibrosa.stft import magphase The provided code snippet includes necessary dependencies for implementing the `init_embedding` function. Write a Python function `def init_embedding(layer)` to solve the following problem: Initialize a Linear or Convolutional layer. Here is the function: def init_embedding(layer): """Initialize a Linear or Convolutional layer. """ nn.init.uniform_(layer.weight, -1., 1.) if hasattr(layer, 'bias'): if layer.bias is not None: layer.bias.data.fill_(0.)
Initialize a Linear or Convolutional layer.