id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
37,052 | from collections import OrderedDict
from mmcv.runner.checkpoint import _load_checkpoint, load_state_dict
The provided code snippet includes necessary dependencies for implementing the `get_state_dict` function. Write a Python function `def get_state_dict(filename, map_location='cpu')` to solve the following problem:
G... | Get state_dict from a file or URI. Args: filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. map_location (str): Same as :func:`torch.load`. Returns: OrderedDict: The state_dict. |
37,053 |
The provided code snippet includes necessary dependencies for implementing the `make_divisible` function. Write a Python function `def make_divisible(value, divisor, min_value=None, min_ratio=0.9)` to solve the following problem:
Make divisible function. This function rounds the channel number down to the nearest val... | Make divisible function. This function rounds the channel number down to the nearest value that can be divisible by the divisor. Args: value (int): The original channel number. divisor (int): The divisor to fully divide the channel number. min_value (int, optional): The minimum value of the output channel. Default: Non... |
37,054 | import torch
The provided code snippet includes necessary dependencies for implementing the `channel_shuffle` function. Write a Python function `def channel_shuffle(x, groups)` to solve the following problem:
Channel Shuffle operation. This function enables cross-group information flow for multiple groups convolution ... | Channel Shuffle operation. This function enables cross-group information flow for multiple groups convolution layers. Args: x (Tensor): The input tensor. groups (int): The number of groups to divide the input tensor in the channel dimension. Returns: Tensor: The output tensor after channel shuffle operation. |
37,055 | from mmcv.cnn import MODELS as MMCV_MODELS
from mmcv.cnn import build_model_from_cfg
from mmcv.utils import Registry
BACKBONES = MODELS
The provided code snippet includes necessary dependencies for implementing the `build_backbone` function. Write a Python function `def build_backbone(cfg)` to solve the following prob... | Build backbone. |
37,056 | from mmcv.cnn import MODELS as MMCV_MODELS
from mmcv.cnn import build_model_from_cfg
from mmcv.utils import Registry
NECKS = MODELS
The provided code snippet includes necessary dependencies for implementing the `build_neck` function. Write a Python function `def build_neck(cfg)` to solve the following problem:
Build n... | Build neck. |
37,057 | from mmcv.cnn import MODELS as MMCV_MODELS
from mmcv.cnn import build_model_from_cfg
from mmcv.utils import Registry
HEADS = MODELS
The provided code snippet includes necessary dependencies for implementing the `build_head` function. Write a Python function `def build_head(cfg)` to solve the following problem:
Build h... | Build head. |
37,058 | from mmcv.cnn import MODELS as MMCV_MODELS
from mmcv.cnn import build_model_from_cfg
from mmcv.utils import Registry
LOSSES = MODELS
The provided code snippet includes necessary dependencies for implementing the `build_loss` function. Write a Python function `def build_loss(cfg)` to solve the following problem:
Build ... | Build loss. |
37,059 | from mmcv.cnn import MODELS as MMCV_MODELS
from mmcv.cnn import build_model_from_cfg
from mmcv.utils import Registry
POSENETS = MODELS
The provided code snippet includes necessary dependencies for implementing the `build_posenet` function. Write a Python function `def build_posenet(cfg)` to solve the following problem... | Build posenet. |
37,060 | from mmcv.cnn import MODELS as MMCV_MODELS
from mmcv.cnn import build_model_from_cfg
from mmcv.utils import Registry
MESH_MODELS = MODELS
The provided code snippet includes necessary dependencies for implementing the `build_mesh_model` function. Write a Python function `def build_mesh_model(cfg)` to solve the followin... | Build mesh model. |
37,061 | import cv2
import mmcv
import numpy as np
import torch
from mmpose.core.visualization.image import imshow_mesh_3d
from mmpose.models.misc.discriminator import SMPLDiscriminator
from .. import builder
from ..builder import POSENETS
from .base import BasePose
The provided code snippet includes necessary dependencies for... | Set requies_grad for all the networks. Args: nets (nn.Module | list[nn.Module]): A list of networks or a single network. requires_grad (bool): Whether the networks require gradients or not |
37,062 | import torch
from torch.nn import functional as F
The provided code snippet includes necessary dependencies for implementing the `rot6d_to_rotmat` function. Write a Python function `def rot6d_to_rotmat(x)` to solve the following problem:
Convert 6D rotation representation to 3x3 rotation matrix. Based on Zhou et al., ... | Convert 6D rotation representation to 3x3 rotation matrix. Based on Zhou et al., "On the Continuity of Rotation Representations in Neural Networks", CVPR 2019 Input: (B,6) Batch of 6-D rotation representations Output: (B,3,3) Batch of corresponding rotation matrices |
37,063 | import torch
from torch.nn import functional as F
def quat_to_rotmat(quat):
"""Convert quaternion coefficients to rotation matrix.
Args:
quat: size = [B, 4] 4 <===>(w, x, y, z)
Returns:
Rotation matrix corresponding to the quaternion
-- size = [B, 3, 3]
"""
norm_quat = qu... | Convert axis-angle representation to rotation matrix. Args: theta: size = [B, 3] Returns: Rotation matrix corresponding to the quaternion -- size = [B, 3, 3] |
37,064 | import warnings
import torch
import torch.nn.functional as F
def resize(input,
size=None,
scale_factor=None,
mode='nearest',
align_corners=None,
warning=True):
if warning:
if size is not None and align_corners:
input_h, input_w = tuple(int(... | null |
37,065 | import os
import platform
import warnings
import cv2
import torch.multiprocessing as mp
The provided code snippet includes necessary dependencies for implementing the `setup_multi_processes` function. Write a Python function `def setup_multi_processes(cfg)` to solve the following problem:
Setup multi-processing enviro... | Setup multi-processing environment variables. |
37,066 | from mmcv.utils import collect_env as collect_basic_env
from mmcv.utils import get_git_hash
import mmpose
def collect_env():
env_info = collect_basic_env()
env_info['MMPose'] = (mmpose.__version__ + '+' + get_git_hash(digits=7))
return env_info | null |
37,067 | import functools
def rgetattr(obj, attr, *args):
def _getattr(obj, attr):
return getattr(obj, attr, *args)
return functools.reduce(_getattr, [obj] + attr.split('.')) | null |
37,068 | import logging
from mmcv.utils import get_logger
The provided code snippet includes necessary dependencies for implementing the `get_root_logger` function. Write a Python function `def get_root_logger(log_file=None, log_level=logging.INFO)` to solve the following problem:
Use `get_logger` method in mmcv to get the roo... | Use `get_logger` method in mmcv to get the root logger. The logger will be initialized if it has not been initialized. By default a StreamHandler will be added. If `log_file` is specified, a FileHandler will also be added. The name of the root logger is the top-level package name, e.g., "mmpose". Args: log_file (str | ... |
37,069 | import argparse
import copy
import os
import os.path as osp
import time
import warnings
import mmcv
import torch
from mmcv import Config, DictAction
from mmcv.runner import get_dist_info, init_dist, set_random_seed
from mmcv.utils import get_git_hash
from mmpose import __version__
from mmpose.apis import init_random_se... | null |
37,070 | from argparse import ArgumentParser
from mmcv import Config, DictAction
from webcam_apis import WebcamRunner
def parse_args():
parser = ArgumentParser('Lauch webcam runner')
parser.add_argument(
'--config',
type=str,
default='tools/webcam/configs/meow_dwen_dwen/meow_dwen_dwen.py')
pa... | null |
37,071 | from typing import List, Tuple
from mmcv import Config
from mmpose.datasets.dataset_info import DatasetInfo
class DatasetInfo:
def __init__(self, dataset_info):
self._dataset_info = dataset_info
self.dataset_name = self._dataset_info['dataset_name']
self.paper_info = self._dataset_info['pa... | A helpfer function to get the keypoint indices of left and right eyes from the model config. Args: model_cfg (Config): pose model config. Returns: int: left eye keypoint index. int: right eye keypoint index. |
37,072 | from typing import List, Tuple
from mmcv import Config
from mmpose.datasets.dataset_info import DatasetInfo
class DatasetInfo:
def __init__(self, dataset_info):
self._dataset_info = dataset_info
self.dataset_name = self._dataset_info['dataset_name']
self.paper_info = self._dataset_info['pa... | A helpfer function to get the keypoint indices of the face from the model config. Args: model_cfg (Config): pose model config. Returns: list[int]: face keypoint index. |
37,073 | from typing import List, Tuple
from mmcv import Config
from mmpose.datasets.dataset_info import DatasetInfo
class DatasetInfo:
def __init__(self, dataset_info):
self._dataset_info = dataset_info
self.dataset_name = self._dataset_info['dataset_name']
self.paper_info = self._dataset_info['pa... | A helpfer function to get the keypoint indices of left and right wrist from the model config. Args: model_cfg (Config): pose model config. Returns: int: left wrist keypoint index. int: right wrist keypoint index. |
37,074 | from typing import List, Tuple
from mmcv import Config
from mmpose.datasets.dataset_info import DatasetInfo
class DatasetInfo:
def __init__(self, dataset_info):
self._dataset_info = dataset_info
self.dataset_name = self._dataset_info['dataset_name']
self.paper_info = self._dataset_info['pa... | A helpfer function to get the keypoint indices of the left and right part of mouth from the model config. Args: model_cfg (Config): pose model config. Returns: int: left-part mouth keypoint index. int: right-part mouth keypoint index. |
37,075 | from typing import List, Tuple
from mmcv import Config
from mmpose.datasets.dataset_info import DatasetInfo
class DatasetInfo:
def __init__(self, dataset_info):
self._dataset_info = dataset_info
self.dataset_name = self._dataset_info['dataset_name']
self.paper_info = self._dataset_info['pa... | A helpfer function to get the keypoint indices of left and right hand from the model config. Args: model_cfg (Config): pose model config. Returns: list[int]: hand keypoint indices. |
37,076 | import os
import os.path as osp
import sys
import time
from contextlib import contextmanager
from typing import Optional
from urllib.parse import urlparse
from urllib.request import urlopen
import cv2
import numpy as np
from torch.hub import HASH_REGEX, download_url_to_file
def limit_max_fps(fps: Optional[float]):
... | null |
37,077 | import os
import os.path as osp
import sys
import time
from contextlib import contextmanager
from typing import Optional
from urllib.parse import urlparse
from urllib.request import urlopen
import cv2
import numpy as np
from torch.hub import HASH_REGEX, download_url_to_file
def _is_url(filename):
"""Check if the fi... | Load an image file, from disk or url. Args: filename (str): file name on the disk or url link. readFlag (int): readFlag for imdecode. Returns: np.ndarray: A loaded image |
37,078 | import os
import os.path as osp
import sys
import time
from contextlib import contextmanager
from typing import Optional
from urllib.parse import urlparse
from urllib.request import urlopen
import cv2
import numpy as np
from torch.hub import HASH_REGEX, download_url_to_file
def mkdir_or_exist(dir_name, mode=0o777):
... | r"""Loads the Torch serialized object at the given URL. If downloaded file is a zip file, it will be automatically decompressed If the object is already present in `model_dir`, it's deserialized and returned. The default value of ``model_dir`` is ``<hub_dir>/checkpoints`` where ``hub_dir`` is the directory returned by ... |
37,079 | import os
import os.path as osp
import sys
import time
from contextlib import contextmanager
from typing import Optional
from urllib.parse import urlparse
from urllib.request import urlopen
import cv2
import numpy as np
from torch.hub import HASH_REGEX, download_url_to_file
The provided code snippet includes necessary... | Screen Matting. Args: img (np.ndarray): Image data. color_low (tuple): Lower limit (b, g, r). color_high (tuple): Higher limit (b, g, r). color (str): Support colors include: - 'green' or 'g' - 'blue' or 'b' - 'black' or 'k' - 'white' or 'w' |
37,080 | import os
import os.path as osp
import sys
import time
from contextlib import contextmanager
from typing import Optional
from urllib.parse import urlparse
from urllib.request import urlopen
import cv2
import numpy as np
from torch.hub import HASH_REGEX, download_url_to_file
The provided code snippet includes necessary... | Expand the bbox and clip it to fit the image shape. Args: box (list): x1, y1, x2, y2 im_shape (ndarray): image shape (h, w, c) s (float): expand ratio Returns: list: x1, y1, x2, y2 |
37,081 | import os
import os.path as osp
import sys
import time
from contextlib import contextmanager
from typing import Optional
from urllib.parse import urlparse
from urllib.request import urlopen
import cv2
import numpy as np
from torch.hub import HASH_REGEX, download_url_to_file
The provided code snippet includes necessary... | Find connected components and sort with areas. Args: mask (ndarray): instance segmentation result. Returns: ndarray (N, 5): Each item contains (x, y, w, h, area). |
37,082 | import os
import os.path as osp
import sys
import time
from contextlib import contextmanager
from typing import Optional
from urllib.parse import urlparse
from urllib.request import urlopen
import cv2
import numpy as np
from torch.hub import HASH_REGEX, download_url_to_file
def _find_bbox(mask):
"""Find the boundin... | Copy the image region and paste to the background. Args: img (np.ndarray): Image data. background_img (np.ndarray): Background image data. mask (ndarray): instance segmentation result. bbox (ndarray): instance bbox, (x1, y1, x2, y2). effect_region (tuple(4, )): The region to apply mask, the coordinates are normalized (... |
37,083 | import os
import os.path as osp
import sys
import time
from contextlib import contextmanager
from typing import Optional
from urllib.parse import urlparse
from urllib.request import urlopen
import cv2
import numpy as np
from torch.hub import HASH_REGEX, download_url_to_file
def is_image_file(path):
if isinstance(p... | null |
37,084 | from functools import wraps
from queue import Queue
from typing import Dict, List, Optional
from mmcv import is_seq_of
def check_buffer_registered(exist=True):
def wrapper(func):
@wraps(func)
def wrapped(manager, name, *args, **kwargs):
if exist:
# Assert buffer exist
... | null |
37,085 | import csv
import json
import os
import time
import cv2
import numpy as np
np.random.seed(0)
def get_seg_area(segmentations):
area = 0
for segmentation in segmentations:
area += get_poly_area(segmentation[:, 0], segmentation[:, 1])
return area
with open(os.path.join(dataset_dir, 'annotations.csv'), ... | Save annotations in coco-format. :param data_annotation: list of data annotation. :param img_root: the root dir to load images. :param save_path: the path to save transformed annotation file. :param start_img_id: the starting point to count the image id. :param start_ann_id: the starting point to count the annotation i... |
37,086 | import argparse
import os.path as osp
from functools import wraps
import mmcv
import numpy as np
from PIL import Image
from mmpose.core import SimpleCamera
def mmcv_track_func(func):
@wraps(func)
def wrapped_func(args):
return func(*args)
return wrapped_func | null |
37,087 | import argparse
import os.path as osp
from functools import wraps
import mmcv
import numpy as np
from PIL import Image
from mmpose.core import SimpleCamera
def _get_img_info(img_idx, img_name, img_root):
try:
im = Image.open(osp.join(img_root, img_name))
w, h = im.size
except: # noqa: E722
... | null |
37,088 | import argparse
import os.path as osp
from functools import wraps
import mmcv
import numpy as np
from PIL import Image
from mmpose.core import SimpleCamera
def _keypoint_camera_to_world(keypoints,
camera_params,
image_name=None,
d... | null |
37,089 | import argparse
import os
import pickle
import tarfile
import xml.etree.ElementTree as ET
from os.path import join
import cv2
import numpy as np
from spacepy import pycdf
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'--metadata', type=str, required=True, help='Path to metad... | null |
37,090 | import json
import os
import time
import cv2
import h5py
import numpy as np
np.random.seed(0)
The provided code snippet includes necessary dependencies for implementing the `save_coco_anno` function. Write a Python function `def save_coco_anno(keypoints_all, annotated_all, imgs_al... | Save annotations in coco-format. :param keypoints_all: keypoint annotations. :param annotated_all: images annotated or not. :param imgs_all: the array of images. :param keypoints_info: information about keypoint name. :param skeleton_info: information about skeleton connection. :param dataset: information about dataset... |
37,091 | import argparse
import json
import time
from scipy.io import loadmat
def parse_args():
parser = argparse.ArgumentParser(
description='Converting the predicted .mat file to .json file.')
parser.add_argument('pred_mat_file', help='input prediction mat file.')
parser.add_argument(
'gt_json_fil... | null |
37,092 | import argparse
import json
import time
from scipy.io import loadmat
def save_json(list_file, path):
with open(path, 'w') as f:
json.dump(list_file, f, indent=4)
return 0
def convert_mat(pred_mat_file, gt_json_file, output_json_file):
res = loadmat(pred_mat_file)
preds = res['preds']
N = pr... | null |
37,093 | import json
import os
import re
import time
import warnings
import cv2
import numpy as np
import xmltodict
from xtcocotools.coco import COCO
The provided code snippet includes necessary dependencies for implementing the `list_all_files` function. Write a Python function `def list_all_files(root_dir, ext='.xml')` to so... | List all files in the root directory and all its sub directories. :param root_dir: root directory :param ext: filename extension :return: list of files |
37,094 | import json
import os
import re
import time
import warnings
import cv2
import numpy as np
import xmltodict
from xtcocotools.coco import COCO
np.random.seed(0)
def get_anno_info():
keypoints_info = [
'L_Eye',
'R_Eye',
'L_EarBase',
'R_EarBase',
'Nose',
'Throat',
... | Save annotations in coco-format. :param file_list: list of data annotation files. :param img_root: the root dir to load images. :param save_path: the path to save transformed annotation file. :param start_ann_id: the starting point to count the annotation id. :param val_num: the number of annotated objects for validati... |
37,095 | import json
import os
import re
import time
import warnings
import cv2
import numpy as np
import xmltodict
from xtcocotools.coco import COCO
np.random.seed(0)
def get_anno_info():
keypoints_info = [
'L_Eye',
'R_Eye',
'L_EarBase',
'R_EarBase',
'Nose',
'Throat',
... | Save annotations in coco-format. :param file_list: list of data annotation files. :param img_root: the root dir to load images. :param save_path: the path to save transformed annotation file. :param start_ann_id: the starting point to count the annotation id. |
37,096 | import json
import os
import re
import time
import warnings
import cv2
import numpy as np
import xmltodict
from xtcocotools.coco import COCO
np.random.seed(0)
def get_anno_info():
keypoints_info = [
'L_Eye',
'R_Eye',
'L_EarBase',
'R_EarBase',
'Nose',
'Throat',
... | Split train-val json file into training and validation files. :param work_dir: path to load train-val json file, and save split files. :param trainval_file: The input json file combining both train and val. :param trainval_file: The output json file for training. :param trainval_file: The output json file for validatio... |
37,097 | import argparse
import os
import pickle
import shutil
from os.path import join
import cv2
import h5py
import mmcv
import numpy as np
from scipy.io import loadmat
train_subjects = [i for i in range(1, 9)]
train_seqs = [1, 2]
train_cams = [0, 1, 2, 4, 5, 6, 7, 8]
train_frame_nums = {
(1, 1): 6416,
(1, 2): 12430,
... | Load training data, create annotation file and camera file. Args: data_root: Directory of dataset, which is organized in the following hierarchy: data_root |-- train |-- S1 |-- Seq1 |-- Seq2 |-- S2 |-- ... |-- test |-- TS1 |-- TS2 |-- ... out_dir: Directory to save annotation file. |
37,098 | import argparse
import os
import pickle
import shutil
from os.path import join
import cv2
import h5py
import mmcv
import numpy as np
from scipy.io import loadmat
test_subjects = [i for i in range(1, 7)]
test_frame_nums = {1: 6151, 2: 6080, 3: 5838, 4: 6007, 5: 320, 6: 492}
def get_annotations(joints_2d, joints_3d, scal... | Load testing data, create annotation file and camera file. Args: data_root: Directory of dataset. out_dir: Directory to save annotation file. valid_only: Only keep frames with valid_label == 1. |
37,101 | import torch
import os
import argparse
import copy
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--source', type=str)
parser.add_argument('--target', type=str, default=None)
args = parser.parse_args()
return args | null |
37,102 | import argparse
import warnings
import numpy as np
import torch
from mmpose.apis import init_pose_model
The provided code snippet includes necessary dependencies for implementing the `_convert_batchnorm` function. Write a Python function `def _convert_batchnorm(module)` to solve the following problem:
Convert the sync... | Convert the syncBNs into normal BN3ds. |
37,103 | import argparse
import warnings
import numpy as np
import torch
from mmpose.apis import init_pose_model
try:
import onnx
import onnxruntime as rt
except ImportError as e:
raise ImportError(f'Please install onnx and onnxruntime first. {e}')
The provided code snippet includes necessary dependencies for imple... | Convert pytorch model to onnx model. Args: model (:obj:`nn.Module`): The pytorch model to be exported. input_shape (tuple[int]): The input tensor shape of the model. opset_version (int): Opset version of onnx used. Default: 11. show (bool): Determines whether to print the onnx model architecture. Default: False. output... |
37,104 | import argparse
import warnings
import numpy as np
import torch
from mmpose.apis import init_pose_model
def parse_args():
parser = argparse.ArgumentParser(
description='Convert MMPose models to ONNX')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help... | null |
37,105 | import os.path as osp
import warnings
from argparse import ArgumentParser, Namespace
from tempfile import TemporaryDirectory
import mmcv
import torch
from mmcv.runner import CheckpointLoader
The provided code snippet includes necessary dependencies for implementing the `mmpose2torchserve` function. Write a Python func... | Converts MMPose model (config + checkpoint) to TorchServe `.mar`. Args: config_file: In MMPose config format. The contents vary for each task repository. checkpoint_file: In MMPose checkpoint format. The contents vary for each task repository. output_folder: Folder where `{model_name}.mar` will be created. The file cre... |
37,106 | import os.path as osp
import warnings
from argparse import ArgumentParser, Namespace
from tempfile import TemporaryDirectory
import mmcv
import torch
from mmcv.runner import CheckpointLoader
def parse_args():
parser = ArgumentParser(
description='Convert MMPose models to TorchServe `.mar` format.')
par... | null |
37,107 | import argparse
from functools import partial
import torch
from mmpose.apis.inference import init_pose_model
def parse_args():
parser = argparse.ArgumentParser(description='Train a recognizer')
parser.add_argument('config', help='train config file path')
parser.add_argument(
'--shape',
type... | null |
37,108 | import argparse
from functools import partial
import torch
from mmpose.apis.inference import init_pose_model
The provided code snippet includes necessary dependencies for implementing the `batch_constructor` function. Write a Python function `def batch_constructor(flops_model, batch_size, input_shape)` to solve the fo... | Generate a batch of tensors to the model. |
37,110 | import argparse
import json
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
def plot_curve(log_dicts, args):
if args.backend is not None:
plt.switch_backend(args.backend)
sns.set_style(args.style)
# if legend is None, use {filename}_{key}... | null |
37,111 | import argparse
import json
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
def add_plot_parser(subparsers):
parser_plt = subparsers.add_parser(
'plot_curve', help='parser for plotting curves')
parser_plt.add_argument(
'json_logs',
... | null |
37,112 | import argparse
import json
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
def load_json_logs(json_logs):
# load and convert json_logs to log_dict, key is epoch, value is a sub dict
# keys of sub dict is different metrics, e.g. memory, top1_acc
... | null |
37,113 | import argparse
import time
import torch
from mmcv import Config
from mmcv.cnn import fuse_conv_bn
from mmcv.parallel import MMDataParallel
from mmcv.runner.fp16_utils import wrap_fp16_model
from mmpose.datasets import build_dataloader, build_dataset
from mmpose.models import build_posenet
def parse_args():
parser... | null |
37,115 | import json
from mmcv.runner import OPTIMIZER_BUILDERS, DefaultOptimizerConstructor
from mmcv.runner import get_dist_info
def get_num_layer_for_vit(var_name, num_max_layer):
if var_name in ("backbone.cls_token", "backbone.mask_token", "backbone.pos_embed"):
return 0
elif var_name.startswith("backbone.p... | null |
37,116 | import io
import os
import os.path as osp
import pkgutil
import time
import warnings
from collections import OrderedDict
from importlib import import_module
from tempfile import TemporaryDirectory
import torch
import torchvision
from torch.optim import Optimizer
from torch.utils import model_zoo
from torch.nn import fu... | null |
37,117 | import io
import os
import os.path as osp
import pkgutil
import time
import warnings
from collections import OrderedDict
from importlib import import_module
from tempfile import TemporaryDirectory
import torch
import torchvision
from torch.optim import Optimizer
from torch.utils import model_zoo
from torch.nn import fu... | Load checkpoint from a file or URI. Args: model (Module): Module to load checkpoint. filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for details. map_location (str): Same as :func:`torch.load`. strict (bool): Whether to allow different param... |
37,118 | import io
import os
import os.path as osp
import pkgutil
import time
import warnings
from collections import OrderedDict
from importlib import import_module
from tempfile import TemporaryDirectory
import torch
import torchvision
from torch.optim import Optimizer
from torch.utils import model_zoo
from torch.nn import fu... | Save checkpoint to file. The checkpoint will have 3 fields: ``meta``, ``state_dict`` and ``optimizer``. By default ``meta`` will contain version and time info. Args: model (Module): Module whose params are to be saved. filename (str): Checkpoint filename. optimizer (:obj:`Optimizer`, optional): Optimizer to be saved. m... |
37,119 | import os.path as osp
import time
from tempfile import TemporaryDirectory
import torch
from torch.optim import Optimizer
import mmcv
from mmcv.parallel import is_module_wrapper
from mmcv.runner.checkpoint import weights_to_cpu, get_state_dict
try:
import apex
except:
print('apex is not installed')
The provided... | Save checkpoint to file. The checkpoint will have 4 fields: ``meta``, ``state_dict`` and ``optimizer``, ``amp``. By default ``meta`` will contain version and time info. Args: model (Module): Module whose params are to be saved. filename (str): Checkpoint filename. optimizer (:obj:`Optimizer`, optional): Optimizer to be... |
37,120 | from pathlib import Path
import bpy
output_path = '/repository_name/results'
def load(path):
"""Load a BVH file to Blender.
Args:
path (str or pathlib.Path): The path to the input file.
"""
# Reset objects.
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(True)
bpy.o... | Load the BVH file and save motion as an MP4 file. Args: path (str or pathlib.Path): The path to the input file. |
37,121 | import numpy as np
import torch
def embedded_dropout(embed, words, dropout=0.1, scale=None):
if dropout:
mask = embed.weight.data.new().resize_((embed.weight.size(0), 1)).bernoulli_(1 - dropout).expand_as(embed.weight) / (1 - dropout)
masked_embed_weight = mask * embed.weight
else:
masked_embed_weight ... | null |
37,122 | import torch
def repackage_hidden(h):
"""Wraps hidden states in new Tensors,
to detach them from their history."""
if h is None:
return None
if isinstance(h, torch.Tensor):
return h.detach()
else:
return tuple(repackage_hidden(v) for v in h)
The provided code snippet include... | Wraps hidden states in new Tensors, to detach them from their history. |
37,123 | import torch
def batchify(data, bsz, args):
# Work out how cleanly we can divide the dataset into bsz parts.
nbatch = data.size(0) // bsz
# Trim off any extra elements that wouldn't cleanly fit (remainders).
data = data.narrow(0, 0, nbatch * bsz)
# Evenly divide the data across the bsz batches.
... | null |
37,124 | import argparse
import functools
import time
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
import data
import model
from utils import batchify, get_batch, repackage_hidden, zero_hidden
torch.manual_seed(args.seed)
if torch.c... | null |
37,125 | import argparse
import functools
import time
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
import data
import model
from utils import batchify, get_batch, repackage_hidden, zero_hidden
torch.manual_seed(args.seed)
if torch.c... | null |
37,126 | import argparse
import functools
import time
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
import data
import model
from utils import batchify, get_batch, repackage_hidden, zero_hidden
args = parser.parse_args()
args.tied = ... | null |
37,127 | import argparse
import functools
import time
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
import data
import model
from utils import batchify, get_batch, repackage_hidden, zero_hidden
args = parser.parse_args()
args.tied = ... | null |
37,128 | import math
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from apex.normalization.fused_layer_norm import FusedLayerNorm as LayerNorm
import torch.utils
import torch.utils.checkpoint
def attention(query, key, value, attn_mask=None, need_weights=True, dropout=None):... | null |
37,129 | import argparse
import sys
import torch
import torch.nn.functional as F
import data
model, criterion = torch.load(args.checkpoint)
model.eval()
import os
import hashlib
with open(args.outf, 'w') as outf:
#outf.write(str(orig.decode('utf8')))
outf.write(orig)
outf.write('||||')
for i in range(args.words)... | null |
37,130 | import argparse
import sys
import torch
import torch.nn.functional as F
import data
model, criterion = torch.load(args.checkpoint)
model.eval()
import os
import hashlib
with open(args.outf, 'w') as outf:
#outf.write(str(orig.decode('utf8')))
outf.write(orig)
outf.write('||||')
for i in range(args.words)... | null |
37,131 | import argparse
import sys
import torch
import torch.nn.functional as F
import data
import os
import hashlib
def produce_vocab_logits(head_weight, head_bias, hiddens):
head_res = torch.nn.functional.linear(hiddens, head_weight, bias=head_bias)
#softmaxed_head_res = torch.nn.functional.log_softmax(head_res, dim... | null |
37,132 | import argparse
import sys
import torch
import torch.nn.functional as F
import data
import os
import hashlib
The provided code snippet includes necessary dependencies for implementing the `top_k_top_p_filtering` function. Write a Python function `def top_k_top_p_filtering(logits, top_k=0, top_p=0.0, filter_value=-floa... | Filter a distribution of logits using top-k and/or nucleus (top-p) filtering Args: logits: logits distribution shape (vocabulary size) top_k > 0: keep only top k tokens with highest probability (top-k filtering). top_p > 0.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering). Nucleus filterin... |
37,133 | def download_dict():
return {
"vec768l12": {
"url": "https://ibm.ent.box.com/shared/static/z1wgl1stco8ffooyatzdwsqn2psd9lrr",
"output": "./pretrain/checkpoint_best_legacy_500.pt"
},
"vec256l9": {
"url": "https://ibm.ent.box.com/shared/static/z1wgl1stco8ffo... | null |
37,135 | import torch
from torch import nn
from torch.nn import functional as F
import modules.attentions as attentions
import modules.commons as commons
from modules.commons import get_padding, init_weights
from modules.DSConv import (
Depthwise_Separable_Conv1D,
remove_weight_norm_modules,
weight_norm_modules,
)
C... | null |
37,136 | import torch.nn as nn
from torch.nn.utils import remove_weight_norm, weight_norm
class Depthwise_Separable_Conv1D(nn.Module):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride = 1,
padding = 0,
dilation = 1,
bias = True,
paddin... | null |
37,137 | import torch.nn as nn
from torch.nn.utils import remove_weight_norm, weight_norm
class Depthwise_Separable_Conv1D(nn.Module):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride = 1,
padding = 0,
dilation = 1,
bias = True,
paddin... | null |
37,139 | import math
import torch
from torch.nn import functional as F
def init_weights(m, mean=0.0, std=0.01):
classname = m.__class__.__name__
if "Depthwise_Separable" in classname:
m.depth_conv.weight.data.normal_(mean, std)
m.point_conv.weight.data.normal_(mean, std)
elif classname.find("Conv") != -1:
m.... | null |
37,140 | import math
import torch
from torch.nn import functional as F
def get_padding(kernel_size, dilation=1):
return int((kernel_size*dilation - dilation)/2) | null |
37,142 | import math
import torch
from torch.nn import functional as F
The provided code snippet includes necessary dependencies for implementing the `kl_divergence` function. Write a Python function `def kl_divergence(m_p, logs_p, m_q, logs_q)` to solve the following problem:
KL(P||Q)
Here is the function:
def kl_divergence... | KL(P||Q) |
37,146 | import math
import torch
from torch.nn import functional as F
def get_timing_signal_1d(
length, channels, min_timescale=1.0, max_timescale=1.0e4):
position = torch.arange(length, dtype=torch.float)
num_timescales = channels // 2
log_timescale_increment = (
math.log(float(max_timescale) / float(min_times... | null |
37,147 | import math
import torch
from torch.nn import functional as F
def get_timing_signal_1d(
length, channels, min_timescale=1.0, max_timescale=1.0e4):
def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
b, channels, length = x.size()
signal = get_timing_signal_1d(length, channels, min_time... | null |
37,150 | import math
import torch
from torch.nn import functional as F
def convert_pad_shape(pad_shape):
def shift_1d(x):
x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
return x | null |
37,151 | import math
import torch
from torch.nn import functional as F
def convert_pad_shape(pad_shape):
l = pad_shape[::-1]
pad_shape = [item for sublist in l for item in sublist]
return pad_shape
def sequence_mask(length, max_length=None):
if max_length is None:
max_length = length.max()
x = torch.arange(max_len... | duration: [b, 1, t_x] mask: [b, 1, t_y, t_x] |
37,152 | from typing import Optional, Union
import numpy as np
import torch
import torchcrepe
from torch import nn
from torch.nn import functional as F
The provided code snippet includes necessary dependencies for implementing the `repeat_expand` function. Write a Python function `def repeat_expand( content: Union[torch.Te... | Repeat content to target length. This is a wrapper of torch.nn.functional.interpolate. Args: content (torch.Tensor): tensor target_len (int): target length mode (str, optional): interpolation mode. Defaults to "nearest". Returns: torch.Tensor: tensor |
37,153 | import sys
from functools import reduce
import librosa
import numpy as np
import torch
from torch.nn.modules.module import _addindent
from .constants import *
def cycle(iterable):
while True:
for item in iterable:
yield item | null |
37,154 | import sys
from functools import reduce
import librosa
import numpy as np
import torch
from torch.nn.modules.module import _addindent
from .constants import *
def summary(model, file=sys.stdout):
def repr(model):
# We treat the extra repr like the sub-module, one item per line
extra_lines = []
... | null |
37,155 | import sys
from functools import reduce
import librosa
import numpy as np
import torch
from torch.nn.modules.module import _addindent
from .constants import *
def to_local_average_cents(salience, center=None, thred=0.05):
"""
find the weighted average cents near the argmax bin
"""
if not hasattr(to_loc... | null |
37,156 | import math
from functools import partial
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
from local_attention import LocalAttention
from torch import nn
def softmax_kernel(data, *, projection_matrix, is_query, normalize_data=True, eps=1e-4, device = None):
b, h, *_ = data.shape
... | null |
37,157 | import math
from functools import partial
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
from local_attention import LocalAttention
from torch import nn
def empty(tensor):
return tensor.numel() == 0 | null |
37,158 | import math
from functools import partial
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
from local_attention import LocalAttention
from torch import nn
def exists(val):
return val is not None
def default(val, d):
return val if exists(val) else d | null |
37,159 | import math
from functools import partial
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
from local_attention import LocalAttention
from torch import nn
def cast_tuple(val):
return (val,) if not isinstance(val, tuple) else val | null |
37,160 | import math
from functools import partial
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
from local_attention import LocalAttention
from torch import nn
def calc_same_padding(kernel_size):
pad = kernel_size // 2
return (pad, pad - (kernel_size + 1) % 2) | null |
37,161 | import math
from functools import partial
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
from local_attention import LocalAttention
from torch import nn
def linear_attention(q, k, v):
if v is None:
#print (k.size(), q.size())
out = torch.einsum('...ed,...nd->...ne... | null |
37,162 | import math
from functools import partial
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
from local_attention import LocalAttention
from torch import nn
def orthogonal_matrix_chunk(cols, qr_uniform_q = False, device = None):
def gaussian_orthogonal_random_matrix(nb_rows, nb_columns, ... | null |
37,163 | import os
import librosa
import numpy as np
import soundfile as sf
import torch
import torch.nn.functional as F
import torch.utils.data
from librosa.filters import mel as librosa_mel_fn
def load_wav_to_torch(full_path, target_sr=None, return_empty_on_exception=False):
sampling_rate = None
try:
data, sa... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.