instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings that explain logic
import functools import torch.nn as nn from ..modules.conv import CausalConv3d from einops import rearrange def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm') != -1: nn.init.normal...
--- +++ @@ -22,7 +22,17 @@ nn.init.constant_(m.bias.data, 0) class NLayerDiscriminator3D(nn.Module): + """Defines a 3D PatchGAN discriminator as in Pix2Pix but for 3D inputs.""" def __init__(self, input_nc=1, ndf=64, n_layers=3, use_actnorm=False): + """ + Construct a 3D PatchGAN di...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/models/causalvideovae/model/losses/discriminator.py
Document this code for team use
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team from collections import OrderedDict import torch import sys import os from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors from deepspeed import comm as dist from deepspeed.runtime.constants import PIPE_...
--- +++ @@ -210,6 +210,12 @@ dp_group=self.real_dp_process_group[i]) def initialize_optimizer_states(self): + """Take an optimizer step with zero-valued gradients to allocate internal + optimizer state. + + This helps prevent memory fragmentation by allocating opti...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/adaptor/bf16_optimizer.py
Improve my code by adding docstrings
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team from collections.abc import Iterable from deepspeed.moe.utils import is_moe_param import os import psutil import gc from math import sqrt from packaging import version as pkg_version import torch from deepspeed import comm ...
--- +++ @@ -2,6 +2,11 @@ # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team +""" +Copyright NVIDIA/Megatron + +Helper functions and classes from multiple sources. +""" from collections.abc import Iterable from deepspeed.moe.utils import is_moe_param @@ -32,6 +37,10 @@ class DummyOptim(): + """ + Du...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/adaptor/utils.py
Add well-formatted docstrings
import numpy as np import torch from PIL import ImageFile import torch.nn.functional as F ImageFile.LOAD_TRUNCATED_IMAGES = True def warp(img, flow): B, _, H, W = flow.shape xx = torch.linspace(-1.0, 1.0, W).view(1, 1, 1, W).expand(B, -1, H, -1) yy = torch.linspace(-1.0, 1.0, H).view(1, 1, H, 1).expand(B,...
--- +++ @@ -17,6 +17,15 @@ def make_colorwheel(): + """ + Generates a color wheel for optical flow visualization as presented in: + Baker et al. "A Database and Evaluation Methodology for Optical Flow" (ICCV, 2007) + URL: http://vision.middlebury.edu/flow/flowEval-iccv07.pdf + Code follows th...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/models/frame_interpolation/utils/flow_utils.py
Document my Python code with docstrings
import math from einops import rearrange import decord from torch.nn import functional as F import torch IMG_EXTENSIONS = ['.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG'] def is_image_file(filename): return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) class DecordInit(object): def __...
--- +++ @@ -11,12 +11,18 @@ return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) class DecordInit(object): + """Using Decord(https://github.com/dmlc/decord) to initialize the video_reader.""" def __init__(self, num_threads=1): self.num_threads = num_threads self.ct...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/models/causalvideovae/utils/dataset_utils.py
Add docstrings to improve code quality
import os import torch def get_world_size(): if os.environ.get('PMI_SIZE') is not None: return int(os.environ.get('PMI_SIZE') or 1) elif os.environ.get('OMPI_COMM_WORLD_SIZE') is not None: return int(os.environ.get('OMPI_COMM_WORLD_SIZE') or 1) else: return torch.cuda.device_count(...
--- +++ @@ -3,6 +3,9 @@ def get_world_size(): + """Find OMPI world size without calling mpi functions + :rtype: int + """ if os.environ.get('PMI_SIZE') is not None: return int(os.environ.get('PMI_SIZE') or 1) elif os.environ.get('OMPI_COMM_WORLD_SIZE') is not None: @@ -12,6 +15,9 @@ ...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/models/frame_interpolation/utils/dist_utils.py
Please document this code using docstrings
import subprocess import json import pickle from collections import OrderedDict from opensora.npu_config import npu_config import sys import os class SuppressStdout: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super(SuppressStdout, cls).__...
--- +++ @@ -27,6 +27,11 @@ class ObsConnection: + """ + AK, SK, STS_TOKEN临时密钥有效时效云计算网站最长为24h + buckets & object: https://uconsole.ccaicc.com/#/mgt/modelarts -> 对象控制台 + keys & tokens: https://uconsole.ccaicc.com/#/mgt/modelarts -> 对象控制台 -> 获取访问密匙(AK 和 SK) + """ def __init__(self): with o...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/dataset/virtual_disk.py
Add structured docstrings to improve clarity
import torch from einops import rearrange, repeat from typing import Any, Dict, Optional, Tuple import torch.nn.functional as F from torch import nn from typing import Optional, Tuple from diffusers.utils import logging from diffusers.utils.torch_utils import maybe_allow_in_graph from diffusers.models.attention import ...
--- +++ @@ -88,6 +88,22 @@ def prepare_attention_mask( self, attention_mask: torch.Tensor, target_length: int, batch_size: int, out_dim: int = 3 ) -> torch.Tensor: + r""" + Prepare the attention mask for the attention computation. + + Args: + attention_mask (`torch.Tens...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/models/diffusion/opensora_v1_3/modules.py
Add docstrings that explain purpose and usage
import torch.nn as nn import torch.nn.functional as F from .normalize import Normalize from .conv import CausalConv3d import torch from .block import Block try: import torch_npu from opensora.npu_config import npu_config, set_run_dtype except: torch_npu = None npu_config = None # from xformers impo...
--- +++ @@ -14,6 +14,7 @@ # from xformers import ops as xops class AttnBlock3D(Block): + """Compatible with old versions, there are issues, use with caution.""" def __init__(self, in_channels): super().__init__() self.in_channels = in_channels @@ -51,6 +52,9 @@ return x + h_ ...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/models/causalvideovae/model/modules/attention.py
Add docstrings to improve readability
# Original code from https://github.com/piergiaj/pytorch-i3d import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class MaxPool3dSamePadding(nn.MaxPool3d): def compute_pad(self, dim, s): if s % self.stride[dim] == 0: return max(self.kernel_size[dim] - self.stri...
--- +++ @@ -46,6 +46,7 @@ use_bias=False, name='unit_3d'): + """Initializes Unit3D module.""" super(Unit3D, self).__init__() self._output_channels = output_channels @@ -132,6 +133,17 @@ class InceptionI3d(nn.Module): + """Inception-v1 I3D architectu...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/models/causalvideovae/eval/fvd/videogpt/pytorch_i3d.py
Help me comply with documentation standards
import torch import random import numbers from torchvision.transforms import RandomCrop, RandomResizedCrop def _is_tensor_video_clip(clip): if not torch.is_tensor(clip): raise TypeError("clip should be Tensor. Got %s" % type(clip)) if not clip.ndimension() == 4: raise ValueError("clip should ...
--- +++ @@ -15,6 +15,10 @@ def center_crop_arr(pil_image, image_size): + """ + Center cropping implementation from ADM. + https://github.com/openai/guided-diffusion/blob/8fb3ad9197f16bbc40620447b2742e13458d2831/guided_diffusion/image_datasets.py#L126 + """ while min(*pil_image.size) >= 2 * image_si...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/models/causalvideovae/dataset/transform.py
Generate consistent documentation across files
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import argparse import logging import math import os import shutil from pathlib import Path from typing import Optional im...
--- +++ @@ -4,6 +4,9 @@ # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. +""" +A minimal training script for DiT using PyTorch DDP. +""" import argparse import logging import math @@ -156,6 +159,9 @@ # `from_pretrained` So CLIPTextModel an...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/train/train_inpaint.py
Add docstrings to improve readability
import os, hashlib import requests from tqdm import tqdm URL_MAP = { "vgg_lpips": "https://heibox.uni-heidelberg.de/f/607503859c864bc1b30b/?dl=1" } CKPT_MAP = { "vgg_lpips": "vgg.pth" } MD5_MAP = { "vgg_lpips": "d507d7349b931f0638a25a48a722f98a" } def download(url, local_path, chunk_size=1024): os...
--- +++ @@ -1,3 +1,4 @@+"""Modified from https://github.com/CompVis/taming-transformers.git""" import os, hashlib import requests @@ -63,6 +64,36 @@ def retrieve( list_or_dict, key, splitval="/", default=None, expand=True, pass_success=False ): + """Given a nested list or dict return the desired value at k...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/utils/taming_download.py
Add clean documentation to messy code
import torch import torch.distributed as dist import os class COMM_INFO: def __init__(self): self.group = None self.world_size = 0 self.rank = -1 nccl_info = COMM_INFO() _SEQUENCE_PARALLEL_STATE = False def initialize_sequence_parallel_state(sequence_parallel_size): global _SEQUENCE_PA...
--- +++ @@ -24,6 +24,7 @@ return _SEQUENCE_PARALLEL_STATE def initialize_sequence_parallel_group(sequence_parallel_size): + """Initialize the sequence parallel group.""" rank = int(os.getenv('RANK', '0')) world_size = int(os.getenv("WORLD_SIZE", '1')) assert world_size % sequence_parallel_size ...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/utils/parallel_states.py
Add concise docstrings to each method
import torch import torch.fft as fft import math def freq_mix_3d(x, noise, LPF): # FFT x_freq = fft.fftn(x, dim=(-3, -2, -1)) x_freq = fft.fftshift(x_freq, dim=(-3, -2, -1)) noise_freq = fft.fftn(noise, dim=(-3, -2, -1)) noise_freq = fft.fftshift(noise_freq, dim=(-3, -2, -1)) # frequency mix ...
--- +++ @@ -4,6 +4,14 @@ def freq_mix_3d(x, noise, LPF): + """ + Noise reinitialization. + + Args: + x: diffused latent + noise: randomly sampled noise + LPF: low pass filter + """ # FFT x_freq = fft.fftn(x, dim=(-3, -2, -1)) x_freq = fft.fftshift(x_freq, dim=(-3, -2,...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/utils/freeinit_utils.py
Document all endpoints with docstrings
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import argparse import logging import math import os import shutil from pathlib import Path from typing import Optional im...
--- +++ @@ -4,6 +4,9 @@ # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. +""" +A minimal training script for DiT using PyTorch DDP. +""" import argparse import logging import math @@ -228,6 +231,9 @@ # `from_pretrained` So CLIPTextModel an...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/train/train_t2v_diffusers.py
Add missing documentation to my Python functions
import math from einops import rearrange import decord from torch.nn import functional as F import torch from typing import Optional import torch.utils import torch.utils.data import torch from torch.utils.data import Sampler from typing import List from collections import Counter, defaultdict import random IMG_EXTEN...
--- +++ @@ -19,12 +19,18 @@ return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) class DecordInit(object): + """Using Decord(https://github.com/dmlc/decord) to initialize the video_reader.""" def __init__(self, num_threads=1): self.num_threads = num_threads self.ct...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/utils/dataset_utils.py
Improve my code by adding docstrings
import os import torch import os import math import torch import logging import random import subprocess import numpy as np import torch.distributed as dist # from torch._six import inf import accelerate from torch import inf from PIL import Image from typing import Union, Iterable import collections from collection...
--- +++ @@ -45,6 +45,19 @@ def explicit_uniform_sampling(T, n, rank, bsz, device): + """ + Explicit Uniform Sampling with integer timesteps and PyTorch. + + Args: + T (int): Maximum timestep value. + n (int): Number of ranks (data parallel processes). + rank (int): The rank of the curr...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/utils/utils.py
Add inline docstrings for readability
import contextlib import copy import random from typing import Any, Dict, Iterable, List, Optional, Union from diffusers.utils import ( deprecate, is_torchvision_available, is_transformers_available, ) if is_transformers_available(): import transformers if is_torchvision_available(): from torchvi...
--- +++ @@ -21,6 +21,9 @@ # Adapted from diffusers-style ema https://github.com/huggingface/diffusers/blob/main/src/diffusers/training_utils.py#L263 class EMAModel: + """ + Exponential Moving Average of models weights + """ def __init__( self, @@ -35,6 +38,25 @@ model_config: Dict[st...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/utils/ema.py
Add docstrings for better understanding
from torch.nn import functional as F from transformers.models.llama.modeling_llama import LlamaAttention from .quant_linear import * import triton import triton.language as tl @triton.jit def rotate_half_kernel( qk_seq_ptr, position_ids_ptr, qk_seq_stride, position_ids_batch_stride, seq_len, H...
--- +++ @@ -110,6 +110,7 @@ class QuantLlamaAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, hidden_size, num_heads, qkv_proj, o_proj): super().__init__() @@ -134,6 +135,7 @@ output_attentions=False, use_cache=False, ...
https://raw.githubusercontent.com/RUCAIBox/LLMSurvey/HEAD/Experiments/InstructTuning/mmlu/quant/fused_attn.py
Add minimal docstrings for each function
import numpy as np import torch import torch.nn as nn from torch.cuda.amp import custom_bwd, custom_fwd from transformers.models.llama.modeling_llama import LlamaMLP try: import triton import triton.language as tl from . import custom_autotune # code based https://github.com/fpgaminer/GPTQ-triton ...
--- +++ @@ -151,6 +151,14 @@ BLOCK_SIZE_K: tl.constexpr, GROUP_SIZE_M: tl.constexpr, ): + """ + Computes: C = silu(A * B1) * (A * B2) + A is of shape (M, K) float16 + B is of shape (K//8, N) int32 + C is of shape (M, N) float16 + scales is of shape (1, N) ...
https://raw.githubusercontent.com/RUCAIBox/LLMSurvey/HEAD/Experiments/InstructTuning/mmlu/quant/fused_mlp.py
Write docstrings describing each step
#!/usr/bin/env python # coding=utf-8 # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE...
--- +++ @@ -13,6 +13,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Fine-tuning the library models for sequence to sequence. +""" # You can also adapt this script on your own ...
https://raw.githubusercontent.com/RUCAIBox/LLMSurvey/HEAD/Experiments/MathematicalReasoning/do_math.py
Write docstrings for this repository
#!/usr/bin/env python # coding=utf-8 # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE...
--- +++ @@ -13,6 +13,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Fine-tuning the library models for sequence to sequence. +""" # You can also adapt this script on your own ...
https://raw.githubusercontent.com/RUCAIBox/LLMSurvey/HEAD/Experiments/MathematicalReasoning/do_gsm8k.py
Add docstrings that explain inputs and outputs
import torch from torch import nn import triton import triton.language as tl from transformers.models.llama.modeling_llama import LlamaRMSNorm @triton.jit def rms_norm_fwd_fused( X, # pointer to the input Y, # pointer to the output W, # pointer to the weights stride, # how much to increase the poi...
--- +++ @@ -42,6 +42,9 @@ class TritonLlamaRMSNorm(nn.Module): def __init__(self, weight, eps=1e-6): + """ + LlamaRMSNorm is equivalent to T5LayerNorm + """ super().__init__() self.weight = weight self.variance_epsilon = eps @@ -73,6 +76,9 @@ def make_quant_nor...
https://raw.githubusercontent.com/RUCAIBox/LLMSurvey/HEAD/Experiments/InstructTuning/mmlu/quant/triton_norm.py
Add docstrings following best practices
import argparse import json import re import string def normalize_text(text: str) -> str: def remove_articles(text: str) -> str: return re.sub(r"\b(a|an|the)\b", " ", text) def white_space_fix(text: str) -> str: return " ".join(text.split()) def remove_punc(text: str) -> str: ex...
--- +++ @@ -5,6 +5,9 @@ def normalize_text(text: str) -> str: + """Lower text and remove punctuation, articles and extra whitespace. + Copied from the [QuAC](http://quac.ai/) evaluation script found at + https://s3.amazonaws.com/my89public/quac/scorer.py""" def remove_articles(text: str) -> str: ...
https://raw.githubusercontent.com/RUCAIBox/LLMSurvey/HEAD/Experiments/KnowledgeUtilization/WikiFact/em.py
Write docstrings describing each step
#!/usr/bin/env python # coding=utf-8 # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE...
--- +++ @@ -13,6 +13,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Fine-tuning the library models for sequence to sequence. +""" # You can also adapt this script on your own ...
https://raw.githubusercontent.com/RUCAIBox/LLMSurvey/HEAD/Experiments/SymbolicReasoning/do_penguins.py
Add return value explanations in docstrings
#!/usr/bin/env python # coding=utf-8 # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE...
--- +++ @@ -13,6 +13,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Fine-tuning the library models for sequence to sequence. +""" # You can also adapt this script on your own ...
https://raw.githubusercontent.com/RUCAIBox/LLMSurvey/HEAD/Experiments/SymbolicReasoning/do_color.py
Add docstrings including usage examples
# https://github.com/fpgaminer/GPTQ-triton import builtins import math import time from typing import Dict import triton class Autotuner(triton.KernelInterface): def __init__( self, fn, arg_names, configs, key, reset_to_zero, prune_configs_by: Dict = None,...
--- +++ @@ -1,4 +1,7 @@ # https://github.com/fpgaminer/GPTQ-triton +""" +Mostly the same as the autotuner in Triton, but with a few changes like using 40 runs instead of 100. +""" import builtins import math @@ -19,6 +22,13 @@ prune_configs_by: Dict = None, nearest_power_of_two: bool = False, ...
https://raw.githubusercontent.com/RUCAIBox/LLMSurvey/HEAD/Experiments/InstructTuning/mmlu/quant/custom_autotune.py
Please document this code using docstrings
# -*- coding: utf-8 -*- # Natural Language Toolkit: BLEU Score # # Copyright (C) 2001-2020 NLTK Project # Authors: Chin Yee Lee, Hengfeng Li, Ruxin Hou, Calvin Tanujaya Lim # Contributors: Björn Mattsson, Dmitrijs Milajevs, Liling Tan # URL: <http://nltk.org/> # For license information, see LICENSE.TXT import math im...
--- +++ @@ -1,242 +1,590 @@-# -*- coding: utf-8 -*- -# Natural Language Toolkit: BLEU Score -# -# Copyright (C) 2001-2020 NLTK Project -# Authors: Chin Yee Lee, Hengfeng Li, Ruxin Hou, Calvin Tanujaya Lim -# Contributors: Björn Mattsson, Dmitrijs Milajevs, Liling Tan -# URL: <http://nltk.org/> -# For license informatio...
https://raw.githubusercontent.com/RUCAIBox/LLMSurvey/HEAD/Experiments/ToolManipulation/Gorilla/eval/eval-scripts/codebleu/bleu.py
Document this code for team use
import argparse import copy import json import os import re import random import time import typing import numpy as np import pandas as pd import warnings import tiktoken from collections import defaultdict import openai import nltk from loguru import logger from thefuzz import fuzz from tenacity import Retrying, retr...
--- +++ @@ -63,6 +63,7 @@ class my_stop_after_attempt(stop_base): + """Stop when the previous attempt >= max_attempt.""" def __init__(self, max_attempt_number: int) -> None: self.max_attempt_number = max_attempt_number @@ -99,6 +100,7 @@ def format_ft_comp(q, a1, a2, context): + """Formats...
https://raw.githubusercontent.com/RUCAIBox/LLMSurvey/HEAD/Experiments/HumanAlignment/metric/eval_truthfulqa.py
Write beginner-friendly docstrings
# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LIC...
--- +++ @@ -73,6 +73,10 @@ tokenizer: transformers.PreTrainedTokenizer, model: transformers.PreTrainedModel, ): + """Resize tokenizer and embedding. + + Note: This is the unoptimized version that may make your embedding size not be divisible by 64. + """ num_new_tokens = tokenizer.add_special_to...
https://raw.githubusercontent.com/RUCAIBox/LLMSurvey/HEAD/Experiments/InstructTuning/train.py
Add documentation for all methods
import math import numpy as np import torch import torch.nn as nn from torch.cuda.amp import custom_bwd, custom_fwd try: import triton import triton.language as tl from . import custom_autotune # code based https://github.com/fpgaminer/GPTQ-triton @custom_autotune.autotune( configs=[ ...
--- +++ @@ -127,6 +127,15 @@ BLOCK_SIZE_K: tl.constexpr, GROUP_SIZE_M: tl.constexpr, ): + """ + Compute the matrix multiplication C = A x B. + A is of shape (M, K) float16 + B is of shape (K//8, N) int32 + C is of shape (M, N) float16 + scales is of shape ...
https://raw.githubusercontent.com/RUCAIBox/LLMSurvey/HEAD/Experiments/InstructTuning/mmlu/quant/quant_linear.py
Add docstrings to improve readability
# -*- coding: utf-8 -*- # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # Natural Language Toolkit: BLEU Score # # Copyright (C) 2001-2020 NLTK Project # Authors: Chin Yee Lee, Hengfeng Li, Ruxin Hou, Calvin Tanujaya Lim # Contributors: Björn Mattsson, Dmitrijs Milajevs, Liling Tan # URL: <ht...
--- +++ @@ -1,269 +1,558 @@-# -*- coding: utf-8 -*- -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. - -# Natural Language Toolkit: BLEU Score -# -# Copyright (C) 2001-2020 NLTK Project -# Authors: Chin Yee Lee, Hengfeng Li, Ruxin Hou, Calvin Tanujaya Lim -# Contributors: Björn Mattsson, Dmit...
https://raw.githubusercontent.com/RUCAIBox/LLMSurvey/HEAD/Experiments/ToolManipulation/Gorilla/eval/eval-scripts/codebleu/weighted_ngram_match.py
Write docstrings describing functionality
# Natural Language Toolkit: Utility functions # # Copyright (C) 2001-2020 NLTK Project # Author: Steven Bird <stevenbird1@gmail.com> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT from itertools import chain def pad_sequence( sequence, n, pad_left=False, pad_right=False, left...
--- +++ @@ -1,54 +1,106 @@-# Natural Language Toolkit: Utility functions -# -# Copyright (C) 2001-2020 NLTK Project -# Author: Steven Bird <stevenbird1@gmail.com> -# URL: <http://nltk.org/> -# For license information, see LICENSE.TXT - -from itertools import chain - -def pad_sequence( - sequence, - n, - pad_le...
https://raw.githubusercontent.com/RUCAIBox/LLMSurvey/HEAD/Experiments/ToolManipulation/Gorilla/eval/eval-scripts/codebleu/utils.py
Generate docstrings with parameter types
import numpy as np import torch import torch.nn as nn from torch.cuda.amp import custom_bwd, custom_fwd import math import triton import triton.language as tl from models.custom_autotune import * def find_layers(module, layers=[nn.Conv2d, nn.Linear], name=''): if type(module) in layers: return {name: modu...
--- +++ @@ -63,6 +63,15 @@ stride_scales, stride_zeros, BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr, GROUP_SIZE_M: tl.constexpr): + """ + Compute the matrix multiplication C = A x B. + A is of shape (M, K...
https://raw.githubusercontent.com/OpenMOSS/MOSS/HEAD/models/quantization.py
Write beginner-friendly docstrings
import json import os import numpy as np import regex as re from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple, Union from transformers.utils import is_tf_available, is_torch_available, logging from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer if TYPE_...
--- +++ @@ -1,3 +1,4 @@+"""Tokenization classes for Moss""" import json import os @@ -59,6 +60,15 @@ @lru_cache() def bytes_to_unicode(): + """ + Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control + characters the bpe code barfs on. + + T...
https://raw.githubusercontent.com/OpenMOSS/MOSS/HEAD/models/tokenization_moss.py
Write beginner-friendly docstrings
#https://github.com/fpgaminer/GPTQ-triton import builtins import math import time from typing import Dict import triton class Autotuner(triton.KernelInterface): def __init__(self, fn, arg_names, configs, key, reset_to_zero, prune_configs_by: Dict = None, nearest_power_of_two: bool = False): if not configs: se...
--- +++ @@ -1,4 +1,7 @@ #https://github.com/fpgaminer/GPTQ-triton +""" +Mostly the same as the autotuner in Triton, but with a few changes like using 40 runs instead of 100. +""" import builtins import math @@ -10,6 +13,13 @@ class Autotuner(triton.KernelInterface): def __init__(self, fn, arg_names, configs, ke...
https://raw.githubusercontent.com/OpenMOSS/MOSS/HEAD/models/custom_autotune.py
Write docstrings describing each step
import math import jittor as jt import jittor.nn as nn class NewGELUActivation(jt.Module): def execute(self, input): output = (input + 0.044715 * jt.pow(input.float(), 3)) if jt.flags.amp_level >= 1: output = output.half() return 0.5 * input * (1.0 + jt.tanh(math.sqrt(2.0 /...
--- +++ @@ -32,6 +32,9 @@ return x.flatten(-2) # in einsum notation: rearrange(x, '... d j -> ... (d j)') def duplicate_interleave(m): + """ + A simple version of `jt.repeat_interleave` for duplicating a matrix while interleaving the copy. + """ dim0 = m.shape[0] m = m.view(-1, 1) # flatten ...
https://raw.githubusercontent.com/OpenMOSS/MOSS/HEAD/models_jittor/utils.py
Add docstrings for production code
import time import statistics import json import re from typing import Union, List, Tuple, Optional, Dict import torch try: from transformers import MossForCausalLM, MossTokenizer, MossConfig except (ImportError, ModuleNotFoundError): from models.modeling_moss import MossForCausalLM from models.tokenizatio...
--- +++ @@ -49,6 +49,15 @@ parallelism: bool = True, device_map: Optional[Union[str, List[int]]] = None, ) -> None: + """ + Initializes the MossModel with a given model or loads a model from the specified directory. + + Args: + model (Optional[MossForCausalLM], opti...
https://raw.githubusercontent.com/OpenMOSS/MOSS/HEAD/moss_inference.py
Add docstrings to clarify complex logic
from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss import transformers from transformers.activations import ACT2FN from transformers.modeling_utils import PreTrainedModel from transformers.modeling_outputs import BaseModelOut...
--- +++ @@ -1,3 +1,4 @@+""" PyTorch Moss model.""" from typing import Optional, Tuple, Union @@ -94,6 +95,9 @@ return reshaped def _merge_heads(self, tensor, num_attention_heads, attn_head_size): + """ + Merges attn_head_size dim and num_attn_heads dim into n_ctx + """ ...
https://raw.githubusercontent.com/OpenMOSS/MOSS/HEAD/models/modeling_moss.py