python_code
stringlengths
0
229k
from torchbenchmark.tasks import NLP from torchbenchmark.util.framework.huggingface.model_factory import HuggingFaceModel class Model(HuggingFaceModel): task = NLP.LANGUAGE_MODELING DEFAULT_TRAIN_BSIZE = 2 DEFAULT_EVAL_BSIZE = 1 def __init__(self, test, device, batch_size=None, extra_args=[]): ...
import subprocess import sys import os from torchbenchmark.util.framework.huggingface.patch_hf import patch_transformers, cache_model def pip_install_requirements(): subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', '-r', 'requirements.txt']) if __name__ == '__main__': pip_install_requirem...
""" HuggingFace Stable Diffusion model. It requires users to specify "HUGGINGFACE_AUTH_TOKEN" in environment variable to authorize login and agree HuggingFace terms and conditions. """ from torchbenchmark.tasks import COMPUTER_VISION from torchbenchmark.util.model import BenchmarkModel from torchbenchmark.util.framewor...
from torchbenchmark.util.framework.diffusers import install_diffusers from torchbenchmark.util.framework.huggingface.model_factory import HuggingFaceAuthMixin import torch import os import warnings MODEL_NAME = "stabilityai/stable-diffusion-2" def load_model_checkpoint(): from diffusers import StableDiffusionPipel...
import os from torchbenchmark.tasks import COMPUTER_VISION from torchbenchmark.util.framework.detectron2.model_factory import Detectron2Model MODEL_NAME = os.path.basename(os.path.dirname(os.path.abspath(__file__))) MODEL_DIR = os.path.abspath(os.path.dirname(__file__)) class Model(Detectron2Model): task = COMPUT...
import os from torchbenchmark.util.framework.detectron2 import install_detectron2 MODEL_NAME = os.path.basename(os.path.dirname(os.path.abspath(__file__))) MODEL_DIR = os.path.abspath(os.path.dirname(__file__)) if __name__ == '__main__': install_detectron2(MODEL_NAME, MODEL_DIR)
import matplotlib matplotlib.use("Agg") import matplotlib.pylab as plt import numpy as np def save_figure_to_numpy(fig): # save it to a numpy array. data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) return data def...
import os import time import argparse import math from numpy import finfo import torch from .distributed import apply_gradient_allreduce import torch.distributed as dist from torch.utils.data.distributed import DistributedSampler from torch.utils.data import DataLoader from .model import Tacotron2 from .data_utils im...
import tensorflow as tf from text import symbols def create_hparams(hparams_string=None, verbose=False): """Create model hyperparameters. Parse nondefault from given string.""" hparams = tf.contrib.training.HParams( ################################ # Experiment Parameters # ###...
from .train_tacotron2 import load_model, prepare_dataloaders import torch from .loss_function import Tacotron2Loss from argparse import Namespace from .text import symbols from pathlib import Path from ...util.model import BenchmarkModel from typing import Tuple from contextlib import nullcontext from torchbenchmark.ta...
import torch import numpy as np from scipy.signal import get_window import librosa.util as librosa_util def window_sumsquare(window, n_frames, hop_length=200, win_length=800, n_fft=800, dtype=np.float32, norm=None): """ # from librosa 0.6 Compute the sum-square envelope of a window fu...
import random import torch from torch.utils.tensorboard import SummaryWriter from plotting_utils import plot_alignment_to_numpy, plot_spectrogram_to_numpy from plotting_utils import plot_gate_outputs_to_numpy class Tacotron2Logger(SummaryWriter): def __init__(self, logdir): super(Tacotron2Logger, self).__...
from math import sqrt import torch from torch.autograd import Variable from torch import nn from torch.nn import functional as F from .layers import ConvNorm, LinearNorm from .tacotron2_utils import to_gpu, get_mask_from_lengths class LocationLayer(nn.Module): def __init__(self, attention_n_filters, attention_ker...
""" BSD 3-Clause License Copyright (c) 2017, Prem Seetharaman All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of...
import torch import torch.distributed as dist from torch.nn.modules import Module from torch.autograd import Variable def _flatten_dense_tensors(tensors): """Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of same dense type. Since inputs are dense, the resulting tensor will be a conc...
import random import numpy as np import torch import torch.utils.data from .layers import TacotronSTFT from .tacotron2_utils import load_wav_to_torch, load_filepaths_and_text from .text import text_to_sequence class TextMelLoader(torch.utils.data.Dataset): """ 1) loads audio,text pairs 2) normali...
from torch import nn class Tacotron2Loss(nn.Module): def __init__(self): super(Tacotron2Loss, self).__init__() def forward(self, model_output, targets): mel_target, gate_target = targets[0], targets[1] mel_target.requires_grad = False gate_target.requires_grad = False ...
import os from pathlib import Path import subprocess import sys from utils import s3_utils def check_data_dir(): current_dir = Path(os.path.dirname(os.path.realpath(__file__))) tacotron2_data_dir = os.path.join(current_dir.parent.parent, "data", ".data", "tacotron2-minimal") assert os.path.exists(tacotron...
import torch from librosa.filters import mel as librosa_mel_fn from .audio_processing import dynamic_range_compression from .audio_processing import dynamic_range_decompression from .stft import STFT class LinearNorm(torch.nn.Module): def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'): s...
import time import torch import sys import subprocess argslist = list(sys.argv)[1:] num_gpus = torch.cuda.device_count() argslist.append('--n_gpus={}'.format(num_gpus)) workers = [] job_id = time.strftime("%Y_%m_%d-%H%M%S") argslist.append("--group_name=group_{}".format(job_id)) for i in range(num_gpus): argslist...
import numpy as np from scipy.io.wavfile import read import torch from pathlib import Path def get_mask_from_lengths(lengths): max_len = torch.max(lengths).item() ids = torch.arange(0, max_len, device=lengths.device) mask = (ids < lengths.unsqueeze(1)).bool() return mask def load_wav_to_torch(full_p...
import torch class LossScaler: def __init__(self, scale=1): self.cur_scale = scale # `params` is a list / generator of torch.Variable def has_overflow(self, params): return False # `x` is a torch.Tensor def _has_inf_or_nan(x): return False # `overflow` is boolean ind...
# ***************************************************************************** # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions...
import copy import torch from glow import Invertible1x1Conv, remove @torch.jit.script def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): n_channels_int = n_channels[0] in_act = input_a+input_b t_act = torch.tanh(in_act[:, :n_channels_int, :]) s_act = torch.sigmoid(in_act[:, n_channels_...
import sys sys.path.append('tacotron2') import torch from layers import STFT class Denoiser(torch.nn.Module): """ Removes model bias from audio produced with waveglow """ def __init__(self, waveglow, filter_length=1024, n_overlap=4, win_length=1024, mode='zeros'): super(Denoiser, sel...
# ***************************************************************************** # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions...
# ***************************************************************************** # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions...
# ***************************************************************************** # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions...
# ***************************************************************************** # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions...
import sys import copy import torch def _check_model_old_version(model): if hasattr(model.WN[0], 'res_layers') or hasattr(model.WN[0], 'cond_layers'): return True else: return False def _update_model_res_skip(old_model, new_model): for idx in range(0, len(new_model.WN)): wavenet =...
import matplotlib matplotlib.use("Agg") import matplotlib.pylab as plt import numpy as np def save_figure_to_numpy(fig): # save it to a numpy array. data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) return data def...
import tensorflow as tf from text import symbols def create_hparams(hparams_string=None, verbose=False): """Create model hyperparameters. Parse nondefault from given string.""" hparams = tf.contrib.training.HParams( ################################ # Experiment Parameters # ###...
import torch import numpy as np from scipy.signal import get_window import librosa.util as librosa_util def window_sumsquare(window, n_frames, hop_length=200, win_length=800, n_fft=800, dtype=np.float32, norm=None): """ # from librosa 0.6 Compute the sum-square envelope of a window fu...
import random import torch.nn.functional as F from tensorboardX import SummaryWriter from plotting_utils import plot_alignment_to_numpy, plot_spectrogram_to_numpy from plotting_utils import plot_gate_outputs_to_numpy class Tacotron2Logger(SummaryWriter): def __init__(self, logdir): super(Tacotron2Logger, ...
import torch from torch import nn from torch.autograd import Variable from torch.nn.parameter import Parameter from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors from loss_scaler import DynamicLossScaler, LossScaler FLOAT_TYPES = (torch.FloatTensor, torch.cuda.FloatTensor) HALF_TYPES = (torch.H...
import torch from torch.autograd import Variable from torch import nn from torch.nn import functional as F from layers import ConvNorm, LinearNorm from utils import to_gpu, get_mask_from_lengths from fp16_optimizer import fp32_to_fp16, fp16_to_fp32 class LocationLayer(nn.Module): def __init__(self, attention_n_fi...
""" BSD 3-Clause License Copyright (c) 2017, Prem Seetharaman All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of...
import torch import torch.distributed as dist from torch.nn.modules import Module def _flatten_dense_tensors(tensors): """Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of same dense type. Since inputs are dense, the resulting tensor will be a concatenated 1D buffer. Element-wise...
import random import numpy as np import torch import torch.utils.data import layers from utils import load_wav_to_torch, load_filepaths_and_text from text import text_to_sequence class TextMelLoader(torch.utils.data.Dataset): """ 1) loads audio,text pairs 2) normalizes text and converts them to s...
from torch import nn class Tacotron2Loss(nn.Module): def __init__(self): super(Tacotron2Loss, self).__init__() def forward(self, model_output, targets): mel_target, gate_target = targets[0], targets[1] mel_target.requires_grad = False gate_target.requires_grad = False ...
import numpy as np from scipy.io.wavfile import read import torch def get_mask_from_lengths(lengths): max_len = torch.max(lengths) ids = torch.arange(0, max_len).long().cuda() mask = (ids < lengths.unsqueeze(1)).byte() return mask def load_wav_to_torch(full_path, sr): sampling_rate, data = read(...
import os import time import argparse import math from numpy import finfo import torch from distributed import DistributedDataParallel from torch.utils.data.distributed import DistributedSampler from torch.nn import DataParallel from torch.utils.data import DataLoader from fp16_optimizer import FP16_Optimizer from m...
import torch from librosa.filters import mel as librosa_mel_fn from audio_processing import dynamic_range_compression from audio_processing import dynamic_range_decompression from stft import STFT class LinearNorm(torch.nn.Module): def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'): supe...
import time import torch import sys import subprocess argslist = list(sys.argv)[1:] num_gpus = torch.cuda.device_count() argslist.append('--n_gpus={}'.format(num_gpus)) workers = [] job_id = time.strftime("%Y_%m_%d-%H%M%S") argslist.append("--group_name=group_{}".format(job_id)) for i in range(num_gpus): argslist...
import torch class LossScaler: def __init__(self, scale=1): self.cur_scale = scale # `params` is a list / generator of torch.Variable def has_overflow(self, params): return False # `x` is a torch.Tensor def _has_inf_or_nan(x): return False # `overflow` is boolean ind...
""" from https://github.com/keithito/tacotron """ import re valid_symbols = [ 'AA', 'AA0', 'AA1', 'AA2', 'AE', 'AE0', 'AE1', 'AE2', 'AH', 'AH0', 'AH1', 'AH2', 'AO', 'AO0', 'AO1', 'AO2', 'AW', 'AW0', 'AW1', 'AW2', 'AY', 'AY0', 'AY1', 'AY2', 'B', 'CH', 'D', 'DH', 'EH', 'EH0', 'EH1', 'EH2', 'ER', 'ER0', 'ER1', 'E...
""" from https://github.com/keithito/tacotron """ import re from text import cleaners from text.symbols import symbols # Mappings from symbol to numeric ID and vice versa: _symbol_to_id = {s: i for i, s in enumerate(symbols)} _id_to_symbol = {i: s for i, s in enumerate(symbols)} # Regular expression matching text en...
""" from https://github.com/keithito/tacotron """ import inflect import re _inflect = inflect.engine() _comma_number_re = re.compile(r'([0-9][0-9\,]+[0-9])') _decimal_number_re = re.compile(r'([0-9]+\.[0-9]+)') _pounds_re = re.compile(r'£([0-9\,]*[0-9]+)') _dollars_re = re.compile(r'\$([0-9\.\,]*[0-9]+)') _ordinal_r...
""" from https://github.com/keithito/tacotron """ ''' Defines the set of symbols used in text input to the model. The default is a set of ASCII characters that works well for English or text that has been run through Unidecode. For other data, you can modify _characters. See TRAINING_DATA.md for details. ''' from tex...
""" from https://github.com/keithito/tacotron """ ''' Cleaners are transformations that run over the input text at both training and eval time. Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners" hyperparameter. Some cleaners are English-specific. You'll typically want to use...
""" from https://github.com/keithito/tacotron """ import re valid_symbols = [ 'AA', 'AA0', 'AA1', 'AA2', 'AE', 'AE0', 'AE1', 'AE2', 'AH', 'AH0', 'AH1', 'AH2', 'AO', 'AO0', 'AO1', 'AO2', 'AW', 'AW0', 'AW1', 'AW2', 'AY', 'AY0', 'AY1', 'AY2', 'B', 'CH', 'D', 'DH', 'EH', 'EH0', 'EH1', 'EH2', 'ER', 'ER0', 'ER1', 'E...
""" from https://github.com/keithito/tacotron """ import re from . import cleaners from .symbols import symbols # Mappings from symbol to numeric ID and vice versa: _symbol_to_id = {s: i for i, s in enumerate(symbols)} _id_to_symbol = {i: s for i, s in enumerate(symbols)} # Regular expression matching text enclosed ...
""" from https://github.com/keithito/tacotron """ import inflect import re _inflect = inflect.engine() _comma_number_re = re.compile(r'([0-9][0-9\,]+[0-9])') _decimal_number_re = re.compile(r'([0-9]+\.[0-9]+)') _pounds_re = re.compile(r'£([0-9\,]*[0-9]+)') _dollars_re = re.compile(r'\$([0-9\.\,]*[0-9]+)') _ordinal_r...
""" from https://github.com/keithito/tacotron """ ''' Defines the set of symbols used in text input to the model. The default is a set of ASCII characters that works well for English or text that has been run through Unidecode. For other data, you can modify _characters. See TRAINING_DATA.md for details. ''' from . i...
""" from https://github.com/keithito/tacotron """ ''' Cleaners are transformations that run over the input text at both training and eval time. Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners" hyperparameter. Some cleaners are English-specific. You'll typically want to use...
import os import json import torch import kaldi_io import dataclasses from .speech_transformer.transformer.decoder import Decoder from .speech_transformer.transformer.encoder import Encoder from .speech_transformer.transformer import Transformer from .speech_transformer.transformer.optimizer import TransformerOptimize...
#!/usr/bin/env python # # The SpeechTransformer model copied from https://github.com/kaituoxu/Speech-Transformer, commit e684777. # The model only supports CUDA and eager mode. # The input data files in the input_data/ directory are generated with a minimized aishell data # containing the following files in the origina...
import sys import subprocess from utils import s3_utils def pip_install_requirements(): subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', '-r', 'requirements.txt']) if __name__ == '__main__': s3_utils.checkout_s3_data("INPUT_TARBALLS", "speech_transformer_inputs.tar.gz", decompress=True) ...
import torch import torch.nn as nn import torch.nn.functional as F from .attention import MultiHeadAttention from .module import PositionalEncoding, PositionwiseFeedForward from ..utils import (IGNORE_ID, get_attn_key_pad_mask, get_attn_pad_mask, get_non_pad_mask, get_subsequent_mask, pad_list) cl...
import numpy as np import torch import torch.nn as nn class MultiHeadAttention(nn.Module): ''' Multi-Head Attention module ''' def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1): super().__init__() self.n_head = n_head self.d_k = d_k self.d_v = d_v self.w_qs ...
from .transformer import *
import torch.nn as nn from .attention import MultiHeadAttention from .module import PositionalEncoding, PositionwiseFeedForward from ..utils import get_non_pad_mask, get_attn_pad_mask class Encoder(nn.Module): """Encoder of Transformer including self-attention and feed forward. """ def __init__(self, d_...
import torch import torch.nn.functional as F from ..utils import IGNORE_ID def cal_performance(pred, gold, smoothing=0.0): """Calculate cross entropy loss, apply label smoothing if needed. Args: pred: N x T x C, score before softmax gold: N x T """ pred = pred.view(-1, pred.size(2)) ...
import torch import torch.nn as nn from .decoder import Decoder from .encoder import Encoder class Transformer(nn.Module): """An encoder-decoder framework only includes attention. """ def __init__(self, encoder, decoder): super(Transformer, self).__init__() self.encoder = encoder ...
"""A wrapper class for optimizer""" import torch class TransformerOptimizer: """A simple wrapper class for learning rate scheduling""" def __init__(self, optimizer, k, d_model, warmup_steps=4000): self.optimizer = optimizer self.k = k self.init_lr = d_model ** (-0.5) self.warm...
import math import torch import torch.nn as nn import torch.nn.functional as F class PositionalEncoding(nn.Module): """Implement the positional encoding (PE) function. PE(pos, 2i) = sin(pos/(10000^(2i/dmodel))) PE(pos, 2i+1) = cos(pos/(10000^(2i/dmodel))) """ def __init__(self, d_model, max_l...
#!/usr/bin/env python # encoding: utf-8 # Copyright 2017 Johns Hopkins University (Shinji Watanabe) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import json import argparse import logging from utils import process_dict if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_ar...
#!/usr/bin/env python2 # encoding: utf-8 # Copyright 2017 Johns Hopkins University (Shinji Watanabe) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import sys import json import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--key', '-k', type=str, ...
#!/usr/bin/env python # Apache 2.0 import sys import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--exclude', '-v', dest='exclude', action='store_true', help='exclude filter words') parser.add_argument('filt', type=str, help='filter l...
#!/usr/bin/env python2 # encoding: utf-8 # Copyright 2017 Johns Hopkins University (Shinji Watanabe) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import argparse import json import logging if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('jsons', type=str, nar...
from .utils import *
#!/usr/bin/env python3 IGNORE_ID = -1 def pad_list(xs, pad_value): # From: espnet/src/nets/e2e_asr_th.py: pad_list() n_batch = len(xs) max_len = max(x.size(0) for x in xs) pad = xs[0].new(n_batch, max_len, * xs[0].size()[1:]).fill_(pad_value) for i in range(n_batch): pad[i, :xs[i].size(0)]...
from .data import *
""" Logic: 1. AudioDataLoader generate a minibatch from AudioDataset, the size of this minibatch is AudioDataLoader's batchsize. For now, we always set AudioDataLoader's batchsize as 1. The real minibatch size we care about is set in AudioDataset's __init__(...). So actually, we generate the information of...
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed according to the terms of the GNU General Public License version 3. from typing import List import torch from .tokenizer import Tokenizer from .model import Transformer class LLaMA: def __init__(self, model: Transf...
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed according to the terms of the GNU General Public License version 3. from ...util.model import BenchmarkModel from torchbenchmark.tasks import NLP import torch from .model import ModelArgs, Transformer import torch class...
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed according to the terms of the GNU General Public License version 3. from typing import Optional, Tuple from dataclasses import dataclass import math import torch from torch import nn import torch.nn.functional as F @dat...
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed according to the terms of the GNU General Public License version 3. from sentencepiece import SentencePieceProcessor from logging import getLogger from typing import List import os logger = getLogger() class Tokenizer:...
import subprocess import sys def pip_install_requirements(): subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', '-r', 'requirements.txt']) if __name__ == '__main__': pip_install_requirements()
from torchbenchmark.util.framework.timm.model_factory import TimmModel from torchbenchmark.tasks import COMPUTER_VISION class Model(TimmModel): task = COMPUTER_VISION.CLASSIFICATION DEFAULT_TRAIN_BSIZE = 32 DEFAULT_EVAL_BSIZE = 32 def __init__(self, test, device, batch_size=None, extra_args=[]): ...
""" Generate a fully specified benchmark configuration file, given a lightweight specification and a complete source of benchmark data. Specification File ------------------ Score hierarchy input intended to be as easy to construct as possible, relying on automatic inference of unspecified weights, benchmark configs, ...
""" Compute TorchBench Score V2. """ import re import math import yaml import importlib import itertools from pathlib import Path from typing import List, Optional TORCHBENCH_V2_REF_DATA = Path(__file__).parent.joinpath("configs/v2/config-v2.yaml") TORCHBENCH_V2_DEFAULT_THRESHOLD = 0.07 TORCHBENCH_V2_DEFAULT_TARGET = ...
""" Compute the benchmark score given a frozen score configuration and current benchmark data. """ import argparse import json import math import sys import os import re import yaml import importlib from tabulate import tabulate from pathlib import Path from collections import defaultdict TARGET_SCORE_DEFAULT = 1000 ...
""" Compute the benchmark score given a frozen score configuration and current benchmark data. """ import argparse import json import math import sys import os import re import yaml import importlib from enum import Enum from tabulate import tabulate from pathlib import Path from collections import defaultdict from ty...
""" Compute the benchmark score given a frozen score configuration and current benchmark data. """ import argparse import json import math import sys import os import re import yaml import importlib from tabulate import tabulate from pathlib import Path from collections import defaultdict from .generate_score_config ...
from accelerate.utils.dataclasses import DeepSpeedPlugin import torch import math import os from pathlib import Path from torch.nn.parallel import DistributedDataParallel as DDP from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.utils.data import DataLoader from torchbenchmark.util.e2emodel ...
import subprocess import sys def pip_install_requirements(): subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', '-r', 'requirements.txt']) if __name__ == '__main__': pip_install_requirements()
import torch import math import os from pathlib import Path from torch.utils.data import DataLoader from ...util.model import BenchmarkModel from torchbenchmark.tasks import NLP from accelerate import Accelerator from transformers import ( AdamW, AutoConfig, AutoModelForSequenceClassification, AutoToken...
from accelerate.utils.dataclasses import DeepSpeedPlugin import functools import torch import numpy as np import math import os from pathlib import Path from torch.nn.parallel import DistributedDataParallel as DDP from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.wrap impor...
import subprocess import sys def pip_install_requirements(): subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', '-r', 'requirements.txt']) if __name__ == '__main__': pip_install_requirements()
# upstream repo: https://github.com/kuangliu/pytorch-cifar import torch import torchvision import torchvision.transforms as transforms from torchbenchmark.util.e2emodel import E2EBenchmarkModel from torchbenchmark.tasks import COMPUTER_VISION import os from tqdm import tqdm from pathlib import Path # setup environmen...
import torch.nn as nn import torch.nn.functional as F class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d( in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) ...
import os import sys import torch import subprocess from pathlib import Path from dataclasses import dataclass from torchbenchmark.util.e2emodel import E2EBenchmarkModel from typing import Optional, List CURRENT_DIR = Path(os.path.dirname(os.path.realpath(__file__))) FAMBENCH_ROOT = CURRENT_DIR.parent.parent.parent....
import sys import subprocess def pip_install_requirements(): subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', '-r', 'requirements.txt']) if __name__ == '__main__': pip_install_requirements()
import importlib import sys from urllib import request from typing import List, Dict TORCH_DEPS = ['torch', 'torchvision', 'torchaudio'] proxy_suggestion = "Unable to verify https connectivity, " \ "required for setup.\n" \ "Do you need to use a proxy?" class add_path(): def...
"""gitutils.py Utils for getting git-related information. """ import git import re import os import time import subprocess from datetime import datetime from typing import Optional, List # Assume the nightly branch commit message is in the following format # Hash in the parentheses links to the commit on the master ...
from typing import Any, List, Optional import boto3 import os import json import yaml from pathlib import Path USERBENCHMARK_S3_BUCKET = "ossci-metrics" USERBENCHMARK_S3_OBJECT = "torchbench-userbenchmark" REPO_ROOT = Path(__file__).parent.parent class S3Client: def __init__(self, bucket, object): self.s3...
""" Utilities for building pytorch and torch* domain packages """ import os import sys import shutil import subprocess from dataclasses import dataclass from pathlib import Path from typing import List, Dict CLEANUP_ROUND = 5 @dataclass class TorchRepo: name: str origin_url: str main_branch: str src_p...