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(torchvi... | 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,... | 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... | 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... | 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 th... |
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 fo... | 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.float3... | 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 ... | 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 an... |
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_foc... | 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_foc... | 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.cla... | 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 i... |
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 de... | 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,
... | 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_p... | 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_r... | 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=Fa... | 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 uti... | 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 flo... |
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 uti... | 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 uti... | 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 uti... | 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 uti... | 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 uti... | 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 uti... | 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 uti... | 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 tha... |
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 uti... | 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 obje... |
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 uti... | 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 ... |
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 uti... | 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 o... |
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 uti... | 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 uti... | 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 uti... | 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 uti... | 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... | 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... | 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.':
... | 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 oth... | 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['i... | 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/... | 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:
>>> c... | 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)).s... | 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.
... | 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(... |
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.sha... | 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.sha... | 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(f... | 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.
... | [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
... | [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... | 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 th... |
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... | 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... |
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... | 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]
int... | 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... | 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.par... | 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... | 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
d... | 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
de... | 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
de... | 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
de... | 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
T... | 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_bbo... | 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 col... |
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):
... | 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 logge... |
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,
... | 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):
ret... | 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 ... | 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 * ... | 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_audioset6... | 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_pretrain... | 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)
... | 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_sis... | 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 ... | 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_len... | 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""... | 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` fun... | 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 Loudnes... |
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_ya... | 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 co... | 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 =... | 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("Inpu... | 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... | 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
war... | 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):
p... | 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 followin... | 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 ... |
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_... | 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 imp... | 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_nor... | 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 ... | 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 impor... | 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/CLA... | 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.datas... | 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.datas... | 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.datas... | 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.datas... | 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.datas... | 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.datas... | 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, data... | 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 ... | 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. |
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:
Initializ... | 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 p... | Initialize a Linear or Convolutional layer. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.