id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
21,000
from typing import Union, Optional import torch import torch.nn as nn import numpy as np import inspect from bert4torch.snippets import take_along_dim, torch_div, sequence_padding, create_position_ids_start_at_padding from bert4torch.snippets import log_info, log_warn, log_warn_once from bert4torch.tokenizers import To...
null
21,001
from bert4torch.models.transformer import Decoder from bert4torch.snippets import delete_arguments from bert4torch.layers import MultiHeadAttentionLayer, BertLayer, BlockIdentity import math import torch from torch import nn import copy The provided code snippet includes necessary dependencies for implementing the `ap...
执行alibi相对位置编码,单独拎出来主要是falcon是在+之后再执行attention_scale的
21,002
import torch from torch import nn from bert4torch.layers import LayerNorm from bert4torch.snippets import log_warn, load_state_dict_into_meta_model, find_tied_parameters, JsonConfig from bert4torch.snippets import get_parameter_device, load_checkpoint, save_checkpoint, copytree import warnings from typing import Union,...
添加torch4keras的BaseModel, 可以使用.compile, .fit等Trainer的功能
21,003
import torch from torch import nn from bert4torch.layers import LayerNorm from bert4torch.snippets import log_warn, load_state_dict_into_meta_model, find_tied_parameters, JsonConfig from bert4torch.snippets import get_parameter_device, load_checkpoint, save_checkpoint, copytree import warnings from typing import Union,...
添加下三角的Attention Mask(语言模型用)
21,004
import torch from torch import nn from bert4torch.layers import LayerNorm from bert4torch.snippets import log_warn, load_state_dict_into_meta_model, find_tied_parameters, JsonConfig from bert4torch.snippets import get_parameter_device, load_checkpoint, save_checkpoint, copytree import warnings from typing import Union,...
添加UniLM的Attention Mask(Seq2Seq模型用)
21,005
import torch import torch.nn.functional as F import numpy as np import random from multiprocessing import Process, Queue import os from os import path, listdir import argparse import json import subprocess import sys from typing import List, Dict import itertools from warnings import warn from datetime import datetime ...
null
21,006
import torch import torch.nn.functional as F import numpy as np import random from multiprocessing import Process, Queue import os from os import path, listdir import argparse import json import subprocess import sys from typing import List, Dict import itertools from warnings import warn from datetime import datetime ...
null
21,007
import torch import torch.nn.functional as F import numpy as np import random from multiprocessing import Process, Queue import os from os import path, listdir import argparse import json import subprocess import sys from typing import List, Dict import itertools from warnings import warn from datetime import datetime ...
null
21,008
import torch import torch.nn.functional as F import numpy as np import random from multiprocessing import Process, Queue import os from os import path, listdir import argparse import json import subprocess import sys from typing import List, Dict import itertools from warnings import warn from datetime import datetime ...
null
21,009
import torch import torch.nn.functional as F import numpy as np import random from multiprocessing import Process, Queue import os from os import path, listdir import argparse import json import subprocess import sys from typing import List, Dict import itertools from warnings import warn from datetime import datetime ...
null
21,010
import torch import torch.nn.functional as F import numpy as np import random from multiprocessing import Process, Queue import os from os import path, listdir import argparse import json import subprocess import sys from typing import List, Dict import itertools from warnings import warn from datetime import datetime ...
Create a dict for each setting of variable values (product across lists)
21,011
import torch import torch.nn.functional as F import numpy as np import random from multiprocessing import Process, Queue import os from os import path, listdir import argparse import json import subprocess import sys from typing import List, Dict import itertools from warnings import warn from datetime import datetime ...
null
21,012
import torch import torch.cuda import torch.optim import torch.nn.functional as F import svox2 import json import imageio import os from os import path import shutil import gc import numpy as np import math import argparse import cv2 from util.dataset import datasets from util.util import Timing, get_expon_lr_func, gen...
null
21,013
import torch import torch.cuda import torch.optim import torch.nn.functional as F import svox2 import json import imageio import os from os import path import shutil import gc import numpy as np import math import argparse import cv2 from util.dataset import datasets from util.util import Timing, get_expon_lr_func, gen...
null
21,014
import os import os.path as osp from typing import NamedTuple, List import argparse import random class Dir(NamedTuple): name: str valid_exts: List[str] dirs, dir_idx = list_filter_dirs(args.root_dir) def list_filter_dirs(base): all_dirs = [x for x in os.listdir(base) if osp.isdir(osp.join(base, x))] i...
null
21,015
import os import os.path as osp import click from typing import NamedTuple, List import argparse class Dir(NamedTuple): name: str valid_exts: List[str] dirs, dir_idx = list_filter_dirs(args.root_dir) def list_filter_dirs(base): all_dirs = [x for x in os.listdir(base) if osp.isdir(osp.join(base, x))] im...
null
21,016
import sys import os from os import path import warnings import numpy as np import math from argparse import ArgumentParser from nerfvis import Scene from scipy.spatial.transform import Rotation def align_umeyama(model, data, known_scale=False, yaw_only=False): """Implementation of the paper: S. Umeyama, Least-Squ...
Align translation + rotation :param t_a: camera translations to align (N, 3) :param q_a: camera rotations to align (xyz axis-angle, xyzw quaternion, or rotation matrix) (N, {3, 4, 9}) :param t_ref: reference camera translations (N, 3) :param use_first_k: int, if set, uses only first k number of cameras to align :param ...
21,017
import sys import os from os import path import warnings import numpy as np import math from argparse import ArgumentParser from nerfvis import Scene from scipy.spatial.transform import Rotation The provided code snippet includes necessary dependencies for implementing the `get_image_size` function. Write a Python fu...
Get image size without loading it
21,018
import sys import os from os import path import warnings import numpy as np import math from argparse import ArgumentParser from nerfvis import Scene from scipy.spatial.transform import Rotation def sort_key(x): if len(x) > 2 and x[1] == "_": return x[2:] return x
null
21,019
import os import os.path as osp import numpy as np import struct import collections import argparse import shutil 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...
null
21,020
import os import os.path as osp import numpy as np import struct import collections import argparse import shutil Camera = collections.namedtuple("Camera", ["id", "model", "width", "height", "params"]) Point3D = collections.namedtuple( "Point3D", ["id", "xyz", "rgb", "error", "image_ids", "point2D_idxs"] ) class Im...
null
21,021
import os import collections import numpy as np import struct import argparse def read_cameras_text(path): """ see: src/base/reconstruction.cc void Reconstruction::WriteCamerasText(const std::string& path) void Reconstruction::ReadCamerasText(const std::string& path) """ cameras = {} ...
null
21,022
import os import collections import numpy as np import struct import argparse def write_cameras_text(cameras, path): def write_cameras_binary(cameras, path_to_model_file): def write_images_text(images, path): def write_images_binary(images, path_to_model_file): def write_points3D_text(points3D, path): def write_points3...
null
21,023
import os import collections import numpy as np import struct import argparse def rotmat2qvec(R): Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat K = np.array([ [Rxx - Ryy - Rzz, 0, 0, 0], [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0], [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0], [Ryz ...
null
21,024
import os import shutil from glob import glob import json import numpy as np from PIL import Image import argparse The provided code snippet includes necessary dependencies for implementing the `convert` function. Write a Python function `def convert(data_dir : str, out_data_dir : str)` to solve the following problem:...
Convert Instant-NGP (modified NeRF) data to NSVF :param data_dir: the dataset dir (NeRF-NGP format) to convert :param out_data_dir: output dataset directory NSVF
21,025
import cv2 import moviepy import moviepy.editor import numpy import argparse import os import random import shutil import sys import tempfile import torch import torchvision import glob import numpy as np from tqdm import tqdm from warnings import warn def compute_poses(vid_root, args, overwrite=False): vid_name =...
null
21,026
import cv2 import moviepy import moviepy.editor import numpy import argparse import os import random import shutil import sys import tempfile import torch import torchvision import glob import numpy as np from tqdm import tqdm from warnings import warn def generate_masks(vid_root, args, overwrite=False): print('com...
null
21,027
import numpy as np import os import imageio def ptstocam(pts, c2w): tt = np.matmul(c2w[:3, :3].T, (pts - c2w[:3, 3])[..., np.newaxis])[..., 0] return tt
null
21,028
import numpy as np import os import imageio def normalize(x): return x / np.linalg.norm(x) def viewmatrix(z, up, pos): vec2 = normalize(z) vec1_avg = up vec0 = normalize(np.cross(vec1_avg, vec2)) vec1 = normalize(np.cross(vec2, vec0)) m = np.stack([vec0, vec1, vec2, pos], 1) return m def re...
null
21,029
import numpy as np import os import imageio def _load_data(basedir, factor=None, width=None, height=None, load_imgs=True): def normalize(x): def poses_avg(poses): def render_path_spiral(c2w, up, rads, focal, zrate, rots, N): def recenter_poses(poses): def spherify_poses(poses, bds): def load_llff_data( basedir, ...
null
21,030
import torch import torch.cuda import torch.nn.functional as F from typing import Optional, Union, List from dataclasses import dataclass import numpy as np import cv2 from scipy.spatial.transform import Rotation from scipy.interpolate import CubicSpline from matplotlib import pyplot as plt from warnings import warn T...
Continuous learning rate decay function. Adapted from JaxNeRF The returned rate is lr_init when step=0 and lr_final when step=max_steps, and is log-linearly interpolated elsewhere (equivalent to exponential decay). If lr_delay_steps>0 then the learning rate will be scaled by some smooth function of lr_delay_mult, such ...
21,031
import torch import torch.cuda import torch.nn.functional as F from typing import Optional, Union, List from dataclasses import dataclass import numpy as np import cv2 from scipy.spatial.transform import Rotation from scipy.interpolate import CubicSpline from matplotlib import pyplot as plt from warnings import warn T...
Save an image to disk. Image should have values in [0,1].
21,032
import torch import torch.cuda import torch.nn.functional as F from typing import Optional, Union, List from dataclasses import dataclass import numpy as np import cv2 from scipy.spatial.transform import Rotation from scipy.interpolate import CubicSpline from matplotlib import pyplot as plt from warnings import warn T...
Convert ray direction vectors into equirectangular pixel coordinates. Inverse of equirect2xyz. Taken from Vickie Ye
21,033
import torch import torch.cuda import torch.nn.functional as F from typing import Optional, Union, List from dataclasses import dataclass import numpy as np import cv2 from scipy.spatial.transform import Rotation from scipy.interpolate import CubicSpline from matplotlib import pyplot as plt from warnings import warn cl...
null
21,034
import torch import torch.cuda import torch.nn.functional as F from typing import Optional, Union, List from dataclasses import dataclass import numpy as np import cv2 from scipy.spatial.transform import Rotation from scipy.interpolate import CubicSpline from matplotlib import pyplot as plt from warnings import warn T...
Computes SSIM from two images. This function was modeled after tf.image.ssim, and should produce comparable output. Args: img0: torch.tensor. An image of size [..., width, height, num_channels]. img1: torch.tensor. An image of size [..., width, height, num_channels]. max_val: float > 0. The maximum magnitude that `img0...
21,035
import torch import torch.cuda import torch.nn.functional as F from typing import Optional, Union, List from dataclasses import dataclass import numpy as np import cv2 from scipy.spatial.transform import Rotation from scipy.interpolate import CubicSpline from matplotlib import pyplot as plt from warnings import warn cl...
Generate perspective camera rays. Principal point is at center. Args: w: int image width h: int image heigth focal: float real focal length camtoworlds: jnp.ndarray [B, 4, 4] c2w homogeneous poses equirect: if true, generates spherical rays instead of pinhole Returns: rays: Rays a namedtuple(origins [B, 3], directions ...
21,036
import torch import torch.cuda import torch.nn.functional as F from typing import Optional, Union, List from dataclasses import dataclass import numpy as np import cv2 from scipy.spatial.transform import Rotation from scipy.interpolate import CubicSpline from matplotlib import pyplot as plt from warnings import warn T...
Get a similarity transform to normalize dataset from c2w (OpenCV convention) cameras :param c2w: (N, 4) :return T (4,4) , scale (float)
21,037
import torch import torch.cuda import torch.nn.functional as F from typing import Optional, Union, List from dataclasses import dataclass import numpy as np import cv2 from scipy.spatial.transform import Rotation from scipy.interpolate import CubicSpline from matplotlib import pyplot as plt from warnings import warn T...
For generating a novel trajectory close to known trajectory :param poses: torch.Tensor (B, 4, 4) :param n_inter: int, number of views to interpolate in total :param noise_std: float, default 0
21,038
import torch import torch.cuda import torch.nn.functional as F from typing import Optional, Union, List from dataclasses import dataclass import numpy as np import cv2 from scipy.spatial.transform import Rotation from scipy.interpolate import CubicSpline from matplotlib import pyplot as plt from warnings import warn de...
Generate spherical rendering poses, from NeRF. Forgive the code horror :return: r (3,), t (3,)
21,039
from scipy.spatial.transform import Rotation import struct import json import glob import copy import numpy as np import os import torch import torch.nn.functional as F from collections import deque from tqdm import tqdm import imageio import cv2 from .util import Rays, Intrin from .dataset_base import DatasetBase from...
null
21,040
from scipy.spatial.transform import Rotation import struct import json import glob import copy import numpy as np import os import torch import torch.nn.functional as F from collections import deque from tqdm import tqdm import imageio import cv2 from .util import Rays, Intrin from .dataset_base import DatasetBase from...
null
21,041
from scipy.spatial.transform import Rotation import struct import json import glob import copy import numpy as np import os import torch import torch.nn.functional as F from collections import deque from tqdm import tqdm import imageio import cv2 from .util import Rays, Intrin from .dataset_base import DatasetBase from...
null
21,042
from scipy.spatial.transform import Rotation import struct import json import glob import copy import numpy as np import os import torch import torch.nn.functional as F from collections import deque from tqdm import tqdm import imageio import cv2 from .util import Rays, Intrin from .dataset_base import DatasetBase from...
null
21,043
from scipy.spatial.transform import Rotation import struct import json import glob import copy import numpy as np import os import torch import torch.nn.functional as F from collections import deque from tqdm import tqdm import imageio import cv2 from .util import Rays, Intrin from .dataset_base import DatasetBase from...
null
21,044
import torch import argparse from util.dataset import datasets import json datasets = { 'nerf': NeRFDataset, 'llff': LLFFDataset, 'nsvf': NSVFDataset, 'co3d': CO3DDataset, 'auto': auto_dataset } def define_common_args(parser : argparse.ArgumentParser): parser.add_argument('data_dir', type=str)...
null
21,045
import torch import argparse from util.dataset import datasets import json The provided code snippet includes necessary dependencies for implementing the `build_data_options` function. Write a Python function `def build_data_options(args)` to solve the following problem: Arguments to pass as kwargs to the dataset cons...
Arguments to pass as kwargs to the dataset constructor
21,046
import torch import argparse from util.dataset import datasets import json The provided code snippet includes necessary dependencies for implementing the `maybe_merge_config_file` function. Write a Python function `def maybe_merge_config_file(args, allow_invalid=False)` to solve the following problem: Load json config...
Load json config file if specified and merge the arguments
21,047
import torch import argparse from util.dataset import datasets import json The provided code snippet includes necessary dependencies for implementing the `setup_render_opts` function. Write a Python function `def setup_render_opts(opt, args)` to solve the following problem: Pass render arguments to the SparseGrid rend...
Pass render arguments to the SparseGrid renderer options
21,048
from .nerf_dataset import NeRFDataset from .llff_dataset import LLFFDataset from .nsvf_dataset import NSVFDataset from .co3d_dataset import CO3DDataset from os import path class NeRFDataset(DatasetBase): def __init__( self, root, split, epoch_size : Optional[int] = ...
null
21,049
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math def inthroot(x : int, n : int): if x <= 0: return None lo, hi = 1, x while lo <= hi: mi = lo + (hi - lo) // 2 p = mi **...
null
21,050
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math def _get_c_extension(): from warnings import warn try: import svox2.csrc as _C if not hasattr(_C, "sample_grid"): _C = ...
null
21,051
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math def _unexpand_bits(v): v &= 0x49249249 v = (v | (v >> 2)) & 0xc30c30c3 v = (v | (v >> 4)) & 0xf00f00f v = (v | (v >> 8)) & 0xff0000ff v ...
null
21,052
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math def is_pow2(x : int): def morton_code_3(x, y, z): def gen_morton(D, device='cpu', dtype=torch.long): assert is_pow2(D), "Morton code requires power of ...
null
21,053
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math SH_C0 = 0.28209479177387814 SH_C1 = 0.4886025119029199 SH_C2 = [ 1.0925484305920792, -1.0925484305920792, 0.31539156525252005, -1.0925484305...
Evaluate spherical harmonics bases at unit directions, without taking linear combination. At each point, the final result may the be obtained through simple multiplication. :param basis_dim: int SH basis dim. Currently, 1-25 square numbers supported :param dirs: torch.Tensor (..., 3) unit directions :return: torch.Tens...
21,054
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math class CubemapCoord: ax : torch.Tensor ori : torch.Tensor u : torch.Tensor v : torch.Tensor def query_in(self, cubemap : torch.Tensor): ...
Convert a direction on a sphere (not necessarily normalized) :param xyz: direction (not necessarily normalized) :param face_reso: int, resolution of cubemap face :param eac: bool, if true (default) then uses equi-angular cubemaps (EAC) instead of standard cubemap; see https://blog.google/products/google-ar-vr/bringing-...
21,055
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math class CubemapCoord: ax : torch.Tensor ori : torch.Tensor u : torch.Tensor v : torch.Tensor def query_in(self, cubemap : torch.Tensor): ...
Compute the points on the cubemap for bilinear sampling given a cubemap coordinate from dir_to_cubemap_coord; to be used with cubemap_sample. :param idx: CubemapCoord, cube map coordinate from dir_to_cubemap_coord :param face_reso: int, resolution of cubemap face :param mode: str, interpolation mode; one of nearest, li...
21,056
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math class CubemapBilerpQuery: i00: CubemapCoord i01: CubemapCoord i10: CubemapCoord i11: CubemapCoord du: torch.Tensor dv: torch.Tensor ...
Perform bilinear sampling on a cubemap given a query from cubemap_build_query :param cubemap: torch.Tensor float (6, face_reso, face_reso, C) or (B, 6, face_reso, face_reso, C) :param idx4: CubemapBilerpQuery from cubemap_build_query where each tensor has batch size B :return: (B, C)
21,057
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math def memlog(device='cuda'): # Memory debugging print(torch.cuda.memory_summary(device)) import gc for obj in gc.get_objects(): try: ...
null
21,058
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math The provided code snippet includes necessary dependencies for implementing the `spher2cart` function. Write a Python function `def spher2cart(theta : torch...
Convert spherical coordinates into Cartesian coordinates on unit sphere.
21,059
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math The provided code snippet includes necessary dependencies for implementing the `eval_sg_at_dirs` function. Write a Python function `def eval_sg_at_dirs(sg_...
Evaluate spherical Gaussian functions at unit directions using learnable SG basis, without taking linear combination Works with torch. ... Can be 0 or more batch dimensions. N is the number of SG basis we use. :math:`Output = \sigma_{i}{exp ^ {\lambda_i * (\dot(\mu_i, \dirs) - 1)}` :param sg_lambda: The sharpness of th...
21,060
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math def init_weights(m): if type(m) == nn.Linear: nn.init.xavier_uniform_(m.weight) m.bias.data.fill_(0.0)
null
21,061
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math The provided code snippet includes necessary dependencies for implementing the `cross_broadcast` function. Write a Python function `def cross_broadcast(x :...
Cross broadcasting for 2 tensors :param x: torch.Tensor :param y: torch.Tensor, should have the same ndim as x :return: tuple of cross-broadcasted tensors x, y. Any dimension where the size of x or y is 1 is expanded to the maximum size in that dimension among the 2. Formally, say the shape of x is (a1, ... an) and of ...
21,062
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math The provided code snippet includes necessary dependencies for implementing the `posenc` function. Write a Python function `def posenc( x: torch.Tensor,...
Positional encoding function. Adapted from jaxNeRF (https://github.com/google-research/google-research/tree/master/jaxnerf). With support for mip-NeFF IPE (by passing cov_diag != 0, keeping enable_ipe=True). And BARF-nerfies frequency attenuation (setting cutoff) Cat x with a positional encoding of x with scales 2^[min...
21,063
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math def net_to_dict(out_dict : dict, prefix : str, model : nn.Module): for child in model.named_children(): layer_n...
null
21,064
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math def net_from_dict(in_dict, prefix : str, model : nn.Module): for child in model.named_children(): layer_nam...
null
21,065
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math The provided code snippet includes necessary dependencies for implementing the `convert_to_ndc` function. Write a Python function `def convert_to_ndc(origi...
Convert a set of rays to NDC coordinates.
21,066
from functools import partial import torch from torch import nn from typing import Optional, Tuple import numpy as np from dataclasses import dataclass import math The provided code snippet includes necessary dependencies for implementing the `xyz2equirect` function. Write a Python function `def xyz2equirect(bearings,...
Convert ray direction vectors into equirectangular pixel coordinates. Inverse of equirect2xyz. Taken from Vickie Ye
21,067
def setup(app): import sphinx.search as search import zh search.languages["zh_CN"] = zh.SearchChinese
null
21,068
import os import subprocess import platform base_link = "http://python.iswbm.com/en/latest/" def get_file_info(filename): with open(filename, 'r', encoding="utf-8") as file: first_line = file.readline().replace("#", "").strip() return first_line.split(' ', 1) def make_line(chapter, file): page_name...
null
21,069
import os import subprocess import platform index_path = os.path.join(pwd, "README.md") readme_header = ''' ![](http://image.iswbm.com/20200607120940.png) <p align="center"> <img src='https://img.shields.io/badge/language-Python-blue.svg' alt="Build Status"> <img src='https://img.shields.io/badge/framwork-Sphin...
生成 readme.md 索引文件,包含所有文件目录
21,070
import os import subprocess import platform The provided code snippet includes necessary dependencies for implementing the `convert_md5_to_rst` function. Write a Python function `def convert_md5_to_rst(file)` to solve the following problem: 转换格式:md5转换成rst Here is the function: def convert_md5_to_rst(file): ''' ...
转换格式:md5转换成rst
21,071
import os import subprocess import platform blog_path = os.path.join(pwd, "source") The provided code snippet includes necessary dependencies for implementing the `get_all_dir` function. Write a Python function `def get_all_dir()` to solve the following problem: 获取所有的目录 Here is the function: def get_all_dir(): '...
获取所有的目录
21,072
import os import subprocess import platform blog_path = os.path.join(pwd, "source") The provided code snippet includes necessary dependencies for implementing the `init_index_info` function. Write a Python function `def init_index_info()` to solve the following problem: 初始化索引 Here is the function: def init_index_inf...
初始化索引
21,073
import os import re import linecache from glob import glob source_dir = os.path.join(pwd, "source") def get_all_chapter(): all_chapters_path = [] os.chdir(source_dir) for dir_name in glob("c*"): if dir_name == "chapters" or dir_name == "conf.py": continue all_chapters_path.appen...
null
21,074
import os import re import linecache from glob import glob pwd = os.getcwd() def get_chapter_name(file): return linecache.getline(file, 2).strip() def generate_mapping(all_chapters_path): mapping = dict.fromkeys([os.path.basename(chapter_path) for chapter_path in all_chapters_path]) for key in mapping.keys...
null
21,075
import os import re import linecache from glob import glob source_dir = os.path.join(pwd, "source") def get_title(file): first_line = linecache.getline(file, 1) if first_line.startswith("#"): return first_line.strip() def get_toc_info(all_chapters_path): toc = {} for dir_name in all_chapters_pa...
null
21,076
import os import re import linecache from glob import glob def print_md_toc(toc_info, mapping): for chapter in sorted(toc_info.items(), key=lambda item: item[0]): posts = chapter[1] chapter_name = mapping[chapter[0]] print(f"- **{chapter_name}**") for post in sorted(posts.items(), k...
null
21,077
import json import os import argparse import deepspeed import deepspeed.comm as dist import numpy as np import sentencepiece as spm import torch from models.configuration_baichuan import BaiChuanConfig from models.modeling_baichuan import BaiChuanForCausalLM def get_argument_parser(): parser = argparse.ArgumentPar...
null
21,078
import json import os import argparse import deepspeed import deepspeed.comm as dist import numpy as np import sentencepiece as spm import torch from models.configuration_baichuan import BaiChuanConfig from models.modeling_baichuan import BaiChuanForCausalLM args = arg_parser.parse_args() class DataEngine(): def __...
null
21,079
import json import os import argparse import deepspeed import deepspeed.comm as dist import numpy as np import sentencepiece as spm import torch from models.configuration_baichuan import BaiChuanConfig from models.modeling_baichuan import BaiChuanForCausalLM args = arg_parser.parse_args() deepspeed.init_distributed() ...
null
21,080
import json import os import argparse import deepspeed import deepspeed.comm as dist import numpy as np import sentencepiece as spm import torch from models.configuration_baichuan import BaiChuanConfig from models.modeling_baichuan import BaiChuanForCausalLM args = arg_parser.parse_args() def train(data_engine, model_...
null
21,081
import argparse import json import os from tqdm import tqdm import numpy as np import torch from datasets import load_dataset from transformers import ( AutoModelForCausalLM, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerBase, ) def parse_argument(): parser = argparse.ArgumentParser() pars...
null
21,082
import argparse import os import torch import numpy as np import pandas as pd from categories import subcategories, categories from transformers import AutoTokenizer,AutoModelForCausalLM import time choices = ["A", "B", "C", "D"] def format_example(df, idx, include_answer=True): prompt = df.iloc[idx, 0] k = df....
null
21,083
import math from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss import torch.utils.checkpoint from transformers import PreTrainedModel, add_start_docstrings from transformers.activations import ACT2FN from transformers.model...
Make causal mask used for bi-directional self-attention.
21,084
import math from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss import torch.utils.checkpoint from transformers import PreTrainedModel, add_start_docstrings from transformers.activations import ACT2FN from transformers.model...
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
21,085
import math from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss import torch.utils.checkpoint from transformers import PreTrainedModel, add_start_docstrings from transformers.activations import ACT2FN from transformers.model...
null
21,086
import os from typing import Dict, List, Tuple from setuptools import find_packages, setup def _setup_packages() -> List: return find_packages( "src", include=["sparseml", "sparseml.*"], exclude=["*.__pycache__.*"] )
null
21,087
import os from typing import Dict, List, Tuple from setuptools import find_packages, setup def _setup_package_dir() -> Dict: return {"": "src"}
null
21,088
import os from typing import Dict, List, Tuple from setuptools import find_packages, setup _deps = [ "setuptools<=59.5.0", "pyyaml>=5.0.0", "numpy>=1.0.0", "matplotlib>=3.0.0", "merge-args>=0.1.0", "onnx>=1.5.0,<1.15.0", "pandas>=0.25.0", "packaging>=20.0", "psutil>=5.0.0", "pyda...
null
21,089
import os from typing import Dict, List, Tuple from setuptools import find_packages, setup _deepsparse_deps = [ f"{'deepsparse' if is_release else 'deepsparse-nightly'}~={version_nm_deps}" ] _deepsparse_ent_deps = [f"deepsparse-ent~={version_nm_deps}"] _onnxruntime_deps = ["onnxruntime>=1.0.0"] _clip_deps = ["open_...
null
21,090
import os from typing import Dict, List, Tuple from setuptools import find_packages, setup def _setup_entry_points() -> Dict: entry_points = { "console_scripts": [ # export "sparseml.export=sparseml.export.export:main", # sparsification "sparseml.framework=sp...
null
21,091
import os from typing import Dict, List, Tuple from setuptools import find_packages, setup def _setup_long_description() -> Tuple[str, str]: return open("README.md", "r", encoding="utf-8").read(), "text/markdown"
null
21,092
from datetime import date version_base = "1.7.0" is_release = False is_dev = False dev_number = None def _generate_version(): if is_release: return version_base elif is_dev: return f"{version_base}.dev{dev_number}" else: return f"{version_base}.{date.today().strftime('%Y%m%d')}"
null
21,093
import logging import os import shutil from pathlib import Path from typing import Any, List, Optional, Union import numpy import click import sparseml.core.session as session_manager from sparseml.export.helpers import ( AVAILABLE_DEPLOYMENT_TARGETS, ONNX_MODEL_NAME, create_deployment_folder, create_ex...
Export a PyTorch model that is either: - located in source_path (and will be loaded) - passed directly to the function to target_path. The deployment files will be located at target_path/deployment_directory_name The exporting logic consists of the following steps: 1. Create the model (if required) and the data loader ...
21,094
import logging import os import shutil from pathlib import Path from typing import Any, List, Optional, Union import numpy import click import sparseml.core.session as session_manager from sparseml.export.helpers import ( AVAILABLE_DEPLOYMENT_TARGETS, ONNX_MODEL_NAME, create_deployment_folder, create_ex...
null
21,095
import logging import os import shutil from pathlib import Path from typing import Any, List, Optional, Union import numpy import click import sparseml.core.session as session_manager from sparseml.export.helpers import ( AVAILABLE_DEPLOYMENT_TARGETS, ONNX_MODEL_NAME, create_deployment_folder, create_ex...
null
21,096
import os from pathlib import Path from typing import Union import onnx import torch from sparseml.exporters import ExportTargets from sparseml.exporters.onnx_to_deepsparse import ONNXToDeepsparse from sparseml.pytorch.opset import TORCH_DEFAULT_ONNX_OPSET from sparseml.pytorch.torch_to_onnx_exporter import TorchToONNX...
Exports the torch model to the deployment target :param model: The torch model to export :param sample_data: The sample data to use for the export :param target_path: The path to export the model to :param onnx_model_name: The name to save the exported ONNX model as :param deployment_target: The deployment target to ex...
21,097
import glob import logging import os.path from collections import OrderedDict from pathlib import Path from typing import Callable, List, Optional, Union import numpy from sparseml.export.export_data import InputsNames, LabelNames, OutputsNames from sparseml.export.helpers import ONNX_MODEL_NAME, onnx_data_files from s...
Validates the structure of the targe_path by checking if the expected files, that should exist as a result of the export, are present. :param target_path: The directory where the exported files are stored. :param deployment_directory_name: The name of the deployment directory. :param onnx_model_name: The name of the ON...
21,098
import glob import logging import os.path from collections import OrderedDict from pathlib import Path from typing import Callable, List, Optional, Union import numpy from sparseml.export.export_data import InputsNames, LabelNames, OutputsNames from sparseml.export.helpers import ONNX_MODEL_NAME, onnx_data_files from s...
Validates the correctness of the exported ONNX model by running it on a set of sample inputs and comparing the resulting outputs using a validation function. :param target_path: The directory where the sample inputs and outputs are stored. :param directory: The directory where the ONNX model is stored. :param onnx_mode...
21,099
from typing import Optional from sparseml.pytorch import recipe_template The provided code snippet includes necessary dependencies for implementing the `create_recipe` function. Write a Python function `def create_recipe( model: Optional["Module"] = None, # noqa: F821 pruning: str = "true", quant: bool = ...
Convenience function to create a recipe based on supplied args and kwargs :param model: an instantiated PyTorch Module, or the local path to a torch.jit loadable *.pt file, if supplied then the recipe is built according to this architecture :param pruning: optional pruning algorithm to use in the recipe, can be any of ...