id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
14,554
import os import h5py import logging import tqdm import subprocess import os.path as osp import numpy as np from pathlib import Path from src.utils.colmap.read_write_model import CAMERA_MODEL_NAMES, Image, read_cameras_binary, read_images_binary from src.utils.colmap.database import COLMAPDatabase class COLMAPDatabase...
Import keypoints info into COLMAP database.
14,555
import os import h5py import logging import tqdm import subprocess import os.path as osp import numpy as np from pathlib import Path from src.utils.colmap.read_write_model import CAMERA_MODEL_NAMES, Image, read_cameras_binary, read_images_binary from src.utils.colmap.database import COLMAPDatabase def names_to_pair(nam...
Import matches info into COLMAP database.
14,556
import os import h5py import logging import tqdm import subprocess import os.path as osp import numpy as np from pathlib import Path from src.utils.colmap.read_write_model import CAMERA_MODEL_NAMES, Image, read_cameras_binary, read_images_binary from src.utils.colmap.database import COLMAPDatabase The provided code sn...
run triangulation on given database
14,557
import h5py import torch import logging import tqdm import os.path as osp confs = { 'superglue': { 'output': 'matches-spg', 'conf': { 'descriptor_dim': 256, 'weights': 'outdoor', 'match_threshold': 0.7 } } } def names_to_pair(name0, name1): return ...
Match features by SuperGlue
14,558
import h5py import json import os.path as osp import numpy as np from collections import defaultdict from pathlib import Path from src.utils.colmap import read_write_model from src.utils import path_utils The provided code snippet includes necessary dependencies for implementing the `average_3d_ann` function. Write a ...
average position, descriptors and scores for 3d points new_point_feature = avg(all merged 3d points features) = avg(all matched 2d points features)
14,559
import h5py import tqdm import torch import logging from torch.utils.data import DataLoader confs = { 'superpoint': { 'output': 'feats-spp', 'model': { 'name': 'spp_det', }, 'preprocessing': { 'grayscale': True, 'resize_h': 512, 'resize...
extract keypoints info by superpoint
14,560
import numpy as np import torch def compute_epipolar_error(kpts0, kpts1, T_0to1, K0, K1): def to_homogeneous(points): return np.concatenate([points, np.ones_like(points[:, :1])], axis=-1) kpts0 = (kpts0 - K0[[0, 1], [2, 2]][None]) / K0[[0, 1], [0, 1]][None] kpts1 = (kpts1 - K1[[0, 1], [2, 2]][None...
null
14,561
import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `project` function. Write a Python function `def project(xyz, K, RT, need_depth=False)` to solve the following problem: xyz: [N, 3] K: [3, 3] RT: [3, 4] Here is the function: def project(xyz, K, RT, need_de...
xyz: [N, 3] K: [3, 3] RT: [3, 4]
14,562
import numpy as np import torch def AngleAxisRotatePoint(angleAxis, pt): theta2 = (angleAxis * angleAxis).sum(dim=1) mask = (theta2 > 0).float() theta = torch.sqrt(theta2 + (1 - mask)) mask = mask.reshape((mask.shape[0], 1)) mask = torch.cat([mask, mask, mask], dim=1) costheta = torch.cos(theta)...
null
14,563
import numpy as np import torch def put_text(img, inform_text, color=None): import cv2 fontScale = 1 if color is None: color = (255, 0, 0) org = (50, 50) font = cv2.FONT_HERSHEY_SIMPLEX thickness = 2 img = cv2.putText(img, inform_text, org, font, fontScale, col...
null
14,564
import numpy as np import torch def draw_kpt2d(image, kpt2d, color=(0, 0, 255), radius=2, thikness=1): import cv2 for coord in kpt2d: cv2.circle(image, (int(coord[0]), int(coord[1])), radius, color, thikness, 1) # cv2.circle(image, (int(coord[0]), int(coord[1])), 7, color, 1, 1) return imag...
null
14,565
from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F from .GATs import GraphAttentionLayer def arange_like(x, dim: int): return x.new_ones(x.shape[dim]).cumsum(0) - 1
null
14,566
from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F from .GATs import GraphAttentionLayer def buildAdjMatrix(num_2d, num_3d): num_leaf = int(num_2d / num_3d) adj_matrix = torch.zeros(num_3d, num_2d) for i in range(num_3d): adj_matrix[i, num_leaf*i: num_leaf...
null
14,567
from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F from .GATs import GraphAttentionLayer def linear_attention(query, key, value): eps = 1e-6 query = F.elu(query) + 1 key = F.elu(key) + 1 v_length = value.size(3) value = value / v_length KV = torch.ein...
null
14,568
from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F from .GATs import GraphAttentionLayer The provided code snippet includes necessary dependencies for implementing the `MLP` function. Write a Python function `def MLP(channels: list, do_bn=True)` to solve the following problem:...
Multi-layer perceptron
14,569
from pathlib import Path import torch from torch import nn The provided code snippet includes necessary dependencies for implementing the `simple_nms` function. Write a Python function `def simple_nms(scores, nms_radius: int)` to solve the following problem: Fast Non-maximum suppression to remove nearby points Here i...
Fast Non-maximum suppression to remove nearby points
14,570
from pathlib import Path import torch from torch import nn The provided code snippet includes necessary dependencies for implementing the `remove_borders` function. Write a Python function `def remove_borders(keypoints, scores, border: int, height: int, width: int)` to solve the following problem: Removes keypoints to...
Removes keypoints too close to the border
14,571
from pathlib import Path import torch from torch import nn def top_k_keypoints(keypoints, scores, k: int): if k >= len(keypoints): return keypoints, scores scores, indices = torch.topk(scores, k, dim=0) return keypoints[indices], scores
null
14,572
from pathlib import Path import torch from torch import nn The provided code snippet includes necessary dependencies for implementing the `sample_descriptors` function. Write a Python function `def sample_descriptors(keypoints, descriptors, s: int = 8)` to solve the following problem: Interpolate descriptors at keypoi...
Interpolate descriptors at keypoint locations
14,573
import torch import torch.nn as nn def find_nn(sim, ratio_thresh, distance_thresh): sim_nn, ind_nn = sim.topk(2 if ratio_thresh else 1, dim=-1, largest=True) dist_nn = 2 * (1 - sim_nn) mask = torch.ones(ind_nn.shape[:-1], dtype=torch.bool, device=sim.device) if ratio_thresh: mask = mask & (dist...
null
14,574
import torch import torch.nn as nn def mutual_check(m0, m1): inds0 = torch.arange(m0.shape[-1], device=m0.device) loop = torch.gather(m1, -1, torch.where(m0 > -1, m0, m0.new_tensor(0))) ok = (m0 > -1) & (inds0 == loop) m0_new = torch.where(ok, m0, m0.new_tensor(-1)) return m0_new
null
14,575
from copy import deepcopy from pathlib import Path import torch from torch import nn The provided code snippet includes necessary dependencies for implementing the `MLP` function. Write a Python function `def MLP(channels: list, do_bn=True)` to solve the following problem: Multi-layer perceptron Here is the function:...
Multi-layer perceptron
14,576
from copy import deepcopy from pathlib import Path import torch from torch import nn The provided code snippet includes necessary dependencies for implementing the `normalize_keypoints` function. Write a Python function `def normalize_keypoints(kpts, image_shape)` to solve the following problem: Normalize keypoints lo...
Normalize keypoints locations based on image image_shape
14,577
from copy import deepcopy from pathlib import Path import torch from torch import nn def attention(query, key, value): dim = query.shape[1] scores = torch.einsum('bdhn,bdhm->bhnm', query, key) / dim**.5 prob = torch.nn.functional.softmax(scores, dim=-1) return torch.einsum('bhnm,bdhm->bdhn', prob, valu...
null
14,578
from copy import deepcopy from pathlib import Path import torch from torch import nn def log_sinkhorn_iterations(Z, log_mu, log_nu, iters: int): """ Perform Sinkhorn Normalization in Log-space for stability""" u, v = torch.zeros_like(log_mu), torch.zeros_like(log_nu) for _ in range(iters): u = log_m...
Perform Differentiable Optimal Transport in Log-space for stability
14,579
from copy import deepcopy from pathlib import Path import torch from torch import nn def arange_like(x, dim: int): return x.new_ones(x.shape[dim]).cumsum(0) - 1 # traceable in 1.1
null
14,580
import cv2 import torch import numpy as np import os.path as osp from loguru import logger from pathlib import Path def pad_keypoints2d_random(keypoints, features, scores, img_h, img_w, n_target_kpts): dtype = keypoints.dtype n_pad = n_target_kpts - keypoints.shape[0] if n_pad < 0: keypoints =...
null
14,581
import cv2 import torch import numpy as np import os.path as osp from loguru import logger from pathlib import Path def pad_features(features, num_leaf): num_features = features.shape[0] feature_dim = features.shape[1] n_pad = num_leaf - num_features if n_pad <= 0: features = features[:num_lea...
null
14,582
import cv2 import torch import numpy as np import os.path as osp from loguru import logger from pathlib import Path def pad_scores(scores, num_leaf): num_scores = scores.shape[0] n_pad = num_leaf - num_scores if n_pad <= 0: scores = scores[:num_leaf] else: scores = torch.cat([scores, t...
null
14,583
import cv2 import torch import numpy as np import os.path as osp from loguru import logger from pathlib import Path def avg_features(features): ret_features = torch.mean(features, dim=0).reshape(-1, 1) return ret_features
null
14,584
import cv2 import torch import numpy as np import os.path as osp from loguru import logger from pathlib import Path def avg_scores(scores): ret_scores = torch.mean(scores, dim=0).reshape(-1, 1) return ret_scores
null
14,585
import cv2 import torch import numpy as np import os.path as osp from loguru import logger from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `pad_keypoints3d_random` function. Write a Python function `def pad_keypoints3d_random(keypoints, n_target_kpts)` to solve t...
Pad or truncate orig 3d keypoints to fixed size.
14,586
import cv2 import torch import numpy as np import os.path as osp from loguru import logger from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `reshape_assign_matrix` function. Write a Python function `def reshape_assign_matrix(assign_matrix, orig_shape2d, orig_shape...
Reshape assign matrix (from 2xk to nxm)
14,587
import cv2 import torch import numpy as np import os.path as osp from loguru import logger from pathlib import Path def read_gray_scale(img_file): image = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE) image = image.astype(np.float32) image = image[None] return image
null
14,588
import torch import os from collections import OrderedDict def save_model(net, optim, scheduler, recorder, epoch, model_dir): os.system('mkdir -p {}'.format(model_dir)) torch.save({ 'net': net.state_dict(), 'optim': optim.state_dict(), 'scheduler': scheduler.state_dict(), 'recor...
null
14,589
import torch import os from collections import OrderedDict def remove_net_prefix(net, prefix): net_ = OrderedDict() for k in net.keys(): if k.startswith(prefix): net_[k[len(prefix):]] = net[k] else: net_[k] = net[k] return net_ def remove_net_layer(net, layers): k...
null
14,590
import torch import os from collections import OrderedDict def add_net_prefix(net, prefix): net_ = OrderedDict() for k in net.keys(): net_[prefix + k] = net[k] return net_
null
14,591
import torch import os from collections import OrderedDict def replace_net_prefix(net, orig_prefix, prefix): net_ = OrderedDict() for k in net.keys(): if k.startswith(orig_prefix): net_[prefix + k[len(orig_prefix):]] = net[k] else: net_[k] = net[k] return net_
null
14,592
import torch import os from collections import OrderedDict def to_cuda(data): if type(data).__name__ == "Tensor": data = data.cuda() elif type(data).__name__ == 'list': data = [d.cuda() for d in data] elif type(data).__name__ == 'dict': data = {k: v.cuda() for k, v in data.items()} ...
null
14,593
import cv2 import os from pathlib import Path from PIL import Image import os.path as osp import numpy as np import matplotlib import matplotlib.cm as cm import matplotlib.pyplot as plt import natsort from loguru import logger The provided code snippet includes necessary dependencies for implementing the `draw_2d_box`...
Draw 2d box corners @param corners_2d: [x_left, y_top, x_right, y_bottom]
14,594
import cv2 import os from pathlib import Path from PIL import Image import os.path as osp import numpy as np import matplotlib import matplotlib.cm as cm import matplotlib.pyplot as plt import natsort from loguru import logger jet = cm.get_cmap("jet") def make_matching_plot( image0, image1, kpts0, kpts1...
null
14,595
import functools import logging import numpy as np import pickle import torch import torch.distributed as dist _LOCAL_PROCESS_GROUP = None def get_rank() -> int: if not dist.is_available(): return 0 if not dist.is_initialized(): return 0 return dist.get_rank() The provided code snippet incl...
Returns: The rank of the current process within the local (per-machine) process group.
14,596
import functools import logging import numpy as np import pickle import torch import torch.distributed as dist _LOCAL_PROCESS_GROUP = None def get_world_size() -> int: if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() The provided code ...
Returns: The size of the per-machine process group, i.e. the number of processes per machine.
14,597
import functools import logging import numpy as np import pickle import torch import torch.distributed as dist def get_rank() -> int: if not dist.is_available(): return 0 if not dist.is_initialized(): return 0 return dist.get_rank() def is_main_process() -> bool: return get_rank() == 0
null
14,598
import functools import logging import numpy as np import pickle import torch import torch.distributed as dist def get_world_size() -> int: if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() The provided code snippet includes necessary d...
Helper function to synchronize (barrier) among all processes when using distributed training
14,599
import functools import logging import numpy as np import pickle import torch import torch.distributed as dist def get_world_size() -> int: if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() def get_rank() -> int: if not dist.is_avail...
Run gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object dst (int): destination rank group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Returns: list[data]: on dst, a list of data gathered from each rank. Otherwise, an empty lis...
14,600
import functools import logging import numpy as np import pickle import torch import torch.distributed as dist def all_gather(data, group=None): """ Run all_gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object group: a torch process group. By default...
Returns: int: a random number that is the same across all workers. If workers need a shared RNG, they can use this shared seed to create one. All workers must call this function, otherwise it will deadlock.
14,601
import functools import logging import numpy as np import pickle import torch import torch.distributed as dist def get_world_size() -> int: if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() def get_rank() -> int: if not dist.is_avail...
Reduce the values in the dictionary from all processes so that process with rank 0 has the reduced results. Args: input_dict (dict): inputs to be reduced. All the values must be scalar CUDA Tensor. average (bool): whether to do average or sum Returns: a dict with the same keys as input_dict, after reduction.
14,602
import sys import sqlite3 import numpy as np IS_PYTHON3 = sys.version_info[0] >= 3 def array_to_blob(array): if IS_PYTHON3: return array.tostring() else: return np.getbuffer(array)
null
14,603
import sys import sqlite3 import numpy as np def image_ids_to_pair_id(image_id1, image_id2): if image_id1 > image_id2: image_id1, image_id2 = image_id2, image_id1 return image_id1 * MAX_IMAGE_ID + image_id2 def pair_id_to_image_ids(pair_id): image_id2 = pair_id % MAX_IMAGE_ID image_id1 = (pair_i...
null
14,604
import os import sys import collections import numpy as np import struct import argparse def qvec2rotmat(qvec): return np.array([ [1 - 2 * qvec[2]**2 - 2 * qvec[3]**2, 2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3], 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]], [2 * qvec[1] * qve...
null
14,605
import cv2 import numpy as np import os.path as osp from pathlib import Path def ransac_PnP(K, pts_2d, pts_3d, scale=1): """ solve pnp """ dist_coeffs = np.zeros(shape=[8, 1], dtype='float64') pts_2d = np.ascontiguousarray(pts_2d.astype(np.float64)) pts_3d = np.ascontiguousarray(pts_3d.astype(np.float64...
null
14,606
import cv2 import numpy as np import os.path as osp from pathlib import Path The provided code snippet includes necessary dependencies for implementing the `aggregate_metrics` function. Write a Python function `def aggregate_metrics(metrics, thres=[1, 3, 5])` to solve the following problem: Aggregate metrics for the w...
Aggregate metrics for the whole dataset: (This method should be called once per dataset) 1. AUC of the pose error (angular) at the threshold [5, 10, 20] 2. Mean matching precision at the threshold 5e-4
14,607
import json import os import glob import hydra import os.path as osp from loguru import logger from pathlib import Path from omegaconf import DictConfig def merge_(anno_2d_file, avg_anno_3d_file, collect_anno_3d_file, idxs_file, img_id, ann_id, images, annotations): """ To prepare training and test objec...
Merge different objects' anno file into one anno file
14,608
import glob import torch import hydra from tqdm import tqdm import os.path as osp import numpy as np from PIL import Image from loguru import logger from torch.utils.data import DataLoader from src.utils import data_utils, path_utils, eval_utils, vis_utils from pytorch_lightning import seed_everything def inference_cor...
null
14,609
import glob import torch import hydra from tqdm import tqdm import os import os.path as osp import natsort from loguru import logger from torch.utils.data import DataLoader from src.utils import data_utils from src.utils.model_io import load_network from src.local_feature_2D_detector import LocalFeatureObjectDetector f...
Prepare data for OnePose inference
14,610
import glob import torch import hydra from tqdm import tqdm import os import os.path as osp import natsort from loguru import logger from torch.utils.data import DataLoader from src.utils import data_utils from src.utils.model_io import load_network from src.local_feature_2D_detector import LocalFeatureObjectDetector f...
null
14,611
import os import cv2 import tqdm import numpy as np import os.path as osp import argparse from pathlib import Path from transforms3d import affines, quaternions from src.utils import data_utils def get_arkit_default_path(data_dir): video_file = osp.join(data_dir, 'Frames.m4v') color_dir = osp.join(data_dir, 'co...
null
14,612
import os import cv2 import tqdm import numpy as np import os.path as osp import argparse from pathlib import Path from transforms3d import affines, quaternions from src.utils import data_utils def get_test_default_path(data_dir): video_file = osp.join(data_dir, 'Frames.m4v') # box_file = osp.join(data_dir, 'Re...
null
14,613
import os import cv2 import tqdm import numpy as np import os.path as osp import argparse from pathlib import Path from transforms3d import affines, quaternions from src.utils import data_utils def parse_args(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) ...
null
14,614
import glob import torch import hydra from tqdm import tqdm import os import os.path as osp import numpy as np import natsort from loguru import logger from torch.utils.data import DataLoader from src.utils import data_utils, path_utils, eval_utils, vis_utils from src.utils.model_io import load_network from src.local_f...
null
14,615
from typing import Optional import fire import torch import tqdm import transformers from train_ppo import LlamaRewardModel class LlamaRewardModel(LlamaForCausalLM): def __init__(self, config, opt, tokenizer): super().__init__(config) self.opt = opt self.tokenizer = tokenizer self.r...
Make the weight diff. This function is given to present full transparency of how the weight diff was created. Run: python weight_diff.py make_diff --path_raw decapoda-research/llama-7b-hf --path_tuned <your_path_tuned> --path_diff <your_path_diff>
14,616
from typing import Optional import fire import torch import tqdm import transformers from train_ppo import LlamaRewardModel class LlamaRewardModel(LlamaForCausalLM): def __init__(self, config, opt, tokenizer): super().__init__(config) self.opt = opt self.tokenizer = tokenizer self.r...
Recover the original weights from the released weight diff. This function is given for you to run. Things to do before running this: 1. Convert Meta's released weights into huggingface format. Follow this guide: https://huggingface.co/docs/transformers/main/model_doc/llama 2. Make sure you cloned the released weight di...
14,617
import argparse def parse_args(): parser = argparse.ArgumentParser(description='MOSS-RLHF @Fudan NLP Group') # Path parser.add_argument('--model_save_path', type=str, default='', help='checkpoint path, used for save model and training') parser.add_argument('--policy_model_path', type=str, default='', ...
null
14,618
import torch import torch.nn.functional as F import logging from accelerate import Accelerator from accelerate.state import AcceleratorState from typing import Tuple, Callable accelerator = None def setup_accelerator(): global accelerator if accelerator is None: accelerator = Accelerator(split_batches=...
null
14,619
import torch import torch.nn.functional as F import logging from accelerate import Accelerator from accelerate.state import AcceleratorState from typing import Tuple, Callable accelerator = None def synchronize_if_distributed(): if accelerator.use_distributed: accelerator.wait_for_everyone()
null
14,620
import torch import torch.nn.functional as F import logging from accelerate import Accelerator from accelerate.state import AcceleratorState from typing import Tuple, Callable accelerator = None def synchronize_forward_on_stage3(done: bool, fake_forward_fn: Callable, **kwargs): # synchronize to avoid deadlock on d...
null
14,621
import torch import torch.nn.functional as F import logging from accelerate import Accelerator from accelerate.state import AcceleratorState from typing import Tuple, Callable accelerator = None def to_cuda(batch): for k, v in batch.items(): if isinstance(v, torch.Tensor): batch[k] = v.to(accel...
null
14,622
import torch import torch.nn.functional as F import logging from accelerate import Accelerator from accelerate.state import AcceleratorState from typing import Tuple, Callable def get_eval_ds_config(offload=None, stage=3): deepspeed_states = AcceleratorState().deepspeed_plugin device = "cpu" if offload else "...
null
14,623
import torch import torch.nn.functional as F import logging from accelerate import Accelerator from accelerate.state import AcceleratorState from typing import Tuple, Callable def get_global_statistics(accelerator, xs: torch.Tensor, mask=None, device='cpu') -> Tuple[float, float, int]: """ Computes element-wise...
Whitens values
14,624
import torch import torch.nn.functional as F import logging from accelerate import Accelerator from accelerate.state import AcceleratorState from typing import Tuple, Callable The provided code snippet includes necessary dependencies for implementing the `top_p_logits` function. Write a Python function `def top_p_logi...
Filter a distribution of logits using nucleus (top-p) filtering https://github.com/OpenLMLab/MOSS/blob/e088f438d1a95d424c6dffef0d73134ebe62cb72/models_jittor/generation.py#L146
14,625
import torch import torch.nn.functional as F import logging from accelerate import Accelerator from accelerate.state import AcceleratorState from typing import Tuple, Callable The provided code snippet includes necessary dependencies for implementing the `logprobs_from_logits` function. Write a Python function `def lo...
See: https://github.com/pytorch/pytorch/issues/563#issuecomment-330103591
14,626
import torch import torch.nn.functional as F import logging from accelerate import Accelerator from accelerate.state import AcceleratorState from typing import Tuple, Callable The provided code snippet includes necessary dependencies for implementing the `get_category_distribution_entropy` function. Write a Python fun...
Compute category distribution entropy
14,627
import torch import torch.nn.functional as F import logging from accelerate import Accelerator from accelerate.state import AcceleratorState from typing import Tuple, Callable The provided code snippet includes necessary dependencies for implementing the `pad_sequences` function. Write a Python function `def pad_seque...
Padding sequence to the same length
14,628
import argparse def parse_args(*args): parser = argparse.ArgumentParser(description='MOSS-RLHF Reward Model @Fudan NLP Group') # training settings parser.add_argument('--seed', type=int, default=42, help='seed') parser.add_argument('--lr', type=float, default=5e-6, help='learning rate of reward model')...
null
14,629
import os import random import logging import torch import json import copy from typing import List, Dict, Any, Tuple from transformers.models.llama.tokenization_llama import LlamaTokenizer from torch.utils.data import get_worker_info, IterableDataset from utils import print_rank_0, pad_sequences def get_human_prompt(o...
null
14,630
import os import random import logging import torch import json import copy from typing import List, Dict, Any, Tuple from transformers.models.llama.tokenization_llama import LlamaTokenizer from torch.utils.data import get_worker_info, IterableDataset from utils import print_rank_0, pad_sequences def get_human_prompt(o...
null
14,631
import os import random import logging import torch import json import copy from typing import List, Dict, Any, Tuple from transformers.models.llama.tokenization_llama import LlamaTokenizer from torch.utils.data import get_worker_info, IterableDataset from utils import print_rank_0, pad_sequences def get_human_prompt(o...
null
14,632
from typing import Optional import fire import torch import tqdm import transformers from train_ppo import LlamaRewardModel, Llama class Llama(LlamaForCausalLM): def __init__(self, config, opt, tokenizer): super().__init__(config) self.opt = opt self.tokenizer = tokenizer def f...
Make the weight diff. This function is given to present full transparency of how the weight diff was created. Run: python weight_diff.py make_diff --path_raw decapoda-research/llama-7b-hf --path_tuned <your_path_tuned> --path_diff <your_path_diff> --model_type
14,633
from typing import Optional import fire import torch import tqdm import transformers from train_ppo import LlamaRewardModel, Llama class Llama(LlamaForCausalLM): def __init__(self, config, opt, tokenizer): super().__init__(config) self.opt = opt self.tokenizer = tokenizer def f...
Recover the original weights from the released weight diff. This function is given for you to run. Things to do before running this: 1. Convert Meta's released weights into huggingface format. Follow this guide: https://huggingface.co/docs/transformers/main/model_doc/llama 2. Make sure you cloned the released weight di...
14,634
from torch.utils.data import get_worker_info, IterableDataset from transformers.models.llama.tokenization_llama import LlamaTokenizer from typing import Dict, Any, List, Tuple, Union, Generator import json, logging, torch, random import os from utils import * def get_human_prompt(): return "Human:" def get_assista...
null
14,635
from torch.utils.data import get_worker_info, IterableDataset from transformers.models.llama.tokenization_llama import LlamaTokenizer from typing import Dict, Any, List, Tuple, Union, Generator import json, logging, torch, random import os from utils import * def get_tokenizer(opt): tokenizer_name_or_path = opt.h...
null
14,636
import argparse import logging import math import os import random import time from pathlib import Path from threading import Thread from warnings import warn import numpy as np import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.optim.lr_sched...
null
14,637
import os import cv2 import numpy as np import shutil import sys from tqdm import tqdm def xywh2xxyy(box): x1 = box[0] y1 = box[1] x2 = box[0] + box[2] y2 = box[1] + box[3] return x1, x2, y1, y2 def convert(size, box): dw = 1. / (size[0]) dh = 1. / (size[1]) x = (box[0] + box[1]) / 2.0 -...
null
14,638
import os.path import sys import torch import torch.utils.data as data import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `detection_collate` function. Write a Python function `def detection_collate(batch)` to solve the following problem: Custom collate fn for ...
Custom collate fn for dealing with batches of images that have a different number of associated object annotations (bounding boxes). Arguments: batch: (tuple) A tuple of tensor images and lists of annotations Return: A tuple containing: 1) (tensor) batch of images stacked on their 0 dim 2) (list of tensors) annotations...
14,640
import argparse import time from pathlib import Path import sys import os import numpy as np import cv2 import torch import torch.backends.cudnn as cudnn from numpy import random import copy from models.experimental import attempt_load from utils.datasets import letterbox, img_formats, vid_formats, LoadImages, LoadStre...
null
14,641
import argparse import time from pathlib import Path import sys import os import numpy as np import cv2 import torch import torch.backends.cudnn as cudnn from numpy import random import copy from models.experimental import attempt_load from utils.datasets import letterbox, img_formats, vid_formats, LoadImages, LoadStre...
null
14,642
import pycuda.autoinit import pycuda.driver as cuda import tensorrt as trt import numpy as np EXPLICIT_BATCH = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) TRT_LOGGER = trt.Logger(trt.Logger.WARNING) def GiB(val): return val * 1 << 30 The provided code snippet includes necessary dependencies for im...
仅适用TensorRT V8版本 生成cudaEngine,并保存引擎文件(仅支持固定输入尺度) fp16_mode: True则fp16预测 onnx_model_path: 将加载的onnx权重路径 trt_engine_path: trt引擎文件保存路径
14,643
import os import sys import cv2 import copy import torch import argparse from utils.datasets import letterbox from detect_face import scale_coords_landmarks,show_results from torch2trt.trt_model import TrtModel def check_img_size(img_size, s=32): # Verify img_size is a multiple of stride s new_size = make_divi...
图像预处理
14,644
import os import sys import cv2 import copy import torch import argparse from utils.datasets import letterbox from detect_face import scale_coords_landmarks,show_results from torch2trt.trt_model import TrtModel cur_path=os.path.abspath(os.path.dirname(__file__)) def xyxy2xywh(x): # Convert nx4 boxes from [x1, y1, ...
预测可视化 vis_thres: 可视化阈值
14,645
from models.experimental import attempt_load from torch2trt.trt_model import TrtModel import argparse import torch import time from tqdm import tqdm def run(model,img,warmup_iter,iter): print('start warm up...') for _ in tqdm(range(warmup_iter)): model(img) print('start calculat...
null
14,646
import os import tqdm import pickle import argparse import numpy as np from scipy.io import loadmat from bbox import bbox_overlaps from IPython import embed def get_gt_boxes_from_txt(gt_path, cache_dir): cache_file = os.path.join(cache_dir, 'gt_cache.pkl') if os.path.exists(cache_file): f = open(cache...
null
14,647
import os import tqdm import pickle import argparse import numpy as np from scipy.io import loadmat from bbox import bbox_overlaps from IPython import embed def get_gt_boxes(gt_dir): """ gt dir: (wider_face_val.mat, wider_easy_val.mat, wider_medium_val.mat, wider_hard_val.mat)""" gt_mat = loadmat(os.path.join(g...
null
14,648
from pathlib import Path import torch from models.yolo import Model from utils.general import set_logging from utils.google_utils import attempt_download def create(name, pretrained, channels, classes, autoshape): """Creates a specified YOLOv5 model Arguments: name (str): name of model, i.e. 'yolov5s' ...
YOLOv5-small model from https://github.com/ultralytics/yolov5 Arguments: pretrained (bool): load pretrained weights into the model, default=False channels (int): number of input channels, default=3 classes (int): number of model classes, default=80 Returns: pytorch model
14,649
from pathlib import Path import torch from models.yolo import Model from utils.general import set_logging from utils.google_utils import attempt_download def create(name, pretrained, channels, classes, autoshape): """Creates a specified YOLOv5 model Arguments: name (str): name of model, i.e. 'yolov5s' ...
YOLOv5-medium model from https://github.com/ultralytics/yolov5 Arguments: pretrained (bool): load pretrained weights into the model, default=False channels (int): number of input channels, default=3 classes (int): number of model classes, default=80 Returns: pytorch model
14,650
from pathlib import Path import torch from models.yolo import Model from utils.general import set_logging from utils.google_utils import attempt_download def create(name, pretrained, channels, classes, autoshape): """Creates a specified YOLOv5 model Arguments: name (str): name of model, i.e. 'yolov5s' ...
YOLOv5-large model from https://github.com/ultralytics/yolov5 Arguments: pretrained (bool): load pretrained weights into the model, default=False channels (int): number of input channels, default=3 classes (int): number of model classes, default=80 Returns: pytorch model
14,651
from pathlib import Path import torch from models.yolo import Model from utils.general import set_logging from utils.google_utils import attempt_download def create(name, pretrained, channels, classes, autoshape): """Creates a specified YOLOv5 model Arguments: name (str): name of model, i.e. 'yolov5s' ...
YOLOv5-xlarge model from https://github.com/ultralytics/yolov5 Arguments: pretrained (bool): load pretrained weights into the model, default=False channels (int): number of input channels, default=3 classes (int): number of model classes, default=80 Returns: pytorch model
14,652
from pathlib import Path import torch from models.yolo import Model from utils.general import set_logging from utils.google_utils import attempt_download class Model(nn.Module): def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None): # model, input channels, number of classes super(Model, self).__init__() ...
YOLOv5-custom model from https://github.com/ultralytics/yolov5 Arguments (3 options): path_or_model (str): 'path/to/model.pt' path_or_model (dict): torch.load('path/to/model.pt') path_or_model (nn.Module): torch.load('path/to/model.pt')['model'] Returns: pytorch model
14,653
import argparse import logging import math import sys from copy import deepcopy from pathlib import Path import torch import torch.nn as nn logger = logging.getLogger(__name__) from models.common import Conv, Bottleneck, SPP, DWConv, Focus, BottleneckCSP, C3, ShuffleV2Block, Concat, NMS, autoShape, StemBlock, BlazeBloc...
null
14,654
import math import numpy as np import requests import torch import torch.nn as nn from PIL import Image, ImageDraw from utils.datasets import letterbox from utils.general import non_max_suppression, make_divisible, scale_coords, xyxy2xywh from utils.plots import color_list def autopad(k, p=None): # kernel, padding ...
null