python_code
stringlengths
0
83.2k
# data # models # constants FEATURES = "esm" # one of ["esm", "msa", "msa_transformer", None] DEVICE = None # defaults to cuda if available, else cpu NUM_BATCHES = int(1e5) GRADIENT_ACCUMULATE_EVERY = 16 LEARNING_RATE = 3e-4 IGNORE_INDEX = -100 THRESHOLD_LENGTH = 250 TO_PDB = False SAVE_DIR = "" # set device ...
# helpers def exists(val): return val is not None @contextmanager def null_context(): yield def split_at_index(dim, index, t): pre_slices = (slice(None),) * dim l = (*pre_slices, slice(None, index)) r = (*pre_slices, slice(index, None)) return t[l], t[r] # function wrapper for determinism ...
# MSA MLM def get_mask_subset_with_prob(mask, prob): batch, seq_len, device = *mask.shape, mask.device max_masked = math.ceil(prob * seq_len) num_tokens = mask.sum(dim=-1, keepdim=True) mask_excess = (mask.cumsum(dim=-1) > (num_tokens * prob).ceil()) mask_excess = mask_excess[:, :max_masked] ...
# constants MAX_NUM_MSA = 20 MAX_NUM_TEMPLATES = 10 NUM_AMINO_ACIDS = 21 NUM_EMBEDDS_TR = 1280 # best esm model NUM_EMBEDDS_T5 = 1024 # best t5 model NUM_COORDS_PER_RES = 14 DISTOGRAM_BUCKETS = 37 THETA_BUCKETS = 25 PHI_BUCKETS = 13 OMEGA_BUCKETS = 25 # embedding related constants MSA_EMBED_DIM = 768 MSA_MODEL_P...
# utils for working with 3d-protein structures # import torch_sparse # only needed for sparse nth_deg adj calculation # bio # sidechainnet # custom # build vocabulary VOCAB = ProteinVocabulary() # constants # helpers def exists(val): return val is not None # constants: same as in alphafold2.py DISTANCE...
# structure module # constants @dataclass class Recyclables: coords: torch.Tensor single_msa_repr_row: torch.Tensor pairwise_repr: torch.Tensor @dataclass class ReturnValues: distance: torch.Tensor = None theta: torch.Tensor = None phi: torch.Tensor = None omega: torch.Tensor = None ...
class ProtTranEmbedWrapper(nn.Module): def __init__(self, *, alphafold2): super().__init__() from transformers import AutoTokenizer, AutoModel self.alphafold2 = alphafold2 self.project_embed = nn.Linear(PROTTRAN_EMBED_DIM, alphafold2.dim) self.tokenizer = AutoTokenizer.fr...
# rotary embedding helpers def rotate_every_two(x): x = rearrange(x, '... (d j) -> ... d j', j = 2) x1, x2 = x.unbind(dim = -1) x = torch.stack((-x2, x1), dim = -1) return rearrange(x, '... d j -> ... (d j)') def apply_rotary_pos_emb(x, sinu_pos): sin, cos = map(lambda t: rearrange(t, 'b ... -> ...
def test_mat_to_masked(): # nodes x = torch.ones(19, 3) x_mask = torch.randn(19) > -0.3 # edges edges_mat = torch.randn(19, 19) < 1 edges = torch.nonzero(edges_mat, as_tuple=False).t() # test normal edges / nodes cleaned = mat_input_to_masked(x, x_mask, edges=edges) cleaned_2 = mat...
def test_main(): model = Alphafold2( dim = 32, depth = 2, heads = 2, dim_head = 32 ) seq = torch.randint(0, 21, (2, 128)) msa = torch.randint(0, 21, (2, 5, 128)) mask = torch.ones_like(seq).bool() msa_mask = torch.ones_like(msa).bool() distogram = model( ...
try: import pytorch_lightning as pl LightningDataModule = pl.LightningDataModule except ImportError: LightningDataModule = object CACHE_PATH = Path("~/.cache/alphafold2_pytorch").expanduser() DATA_DIR = CACHE_PATH / "trrosetta" / "trrosetta" URL = "http://s3.amazonaws.com/proteindata/data_pytorch/trrose...
# will use FastRelax routine to refine structure # science # pyrosetta installation instructs in readme try: import pyrosetta except ModuleNotFoundError: msg = "Unable to find an existing installation of the PyRosetta module. " +\ "Functions involving this module such as the FastRelax pipeline " +\ ...
# following example for saving and setting rng here https://pytorch.org/docs/stable/_modules/torch/utils/checkpoint.html class Deterministic(nn.Module): def __init__(self, net): super().__init__() self.net = net self.cpu_state = None self.cuda_in_fwd = None self.gpu_devices ...
# helper functions def exists(val): return val is not None def map_el_ind(arr, ind): return list(map(itemgetter(ind), arr)) def sort_and_return_indices(arr): indices = [ind for ind in range(len(arr))] arr = zip(arr, indices) arr = sorted(arr) return map_el_ind(arr, 0), map_el_ind(arr, 1) # ...
# constants BITS = 8 # helpers functions def exists(x): return x is not None def default(val, d): if exists(val): return val return d() if callable(d) else d def cycle(dl): while True: for data in dl: yield data def has_int_squareroot(num): return (math.sqrt(n...
from .adamod import AdaMod
class AdaMod(Optimizer): """Implements AdaMod algorithm with Decoupled Weight Decay (arxiv.org/abs/1711.05101) It has been proposed in `Adaptive and Momental Bounds for Adaptive Learning Rate Methods`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining p...
#%matplotlib notebook LABELS = ['SGD','Adam', 'AdaMod'] def get_folder_path(use_pretrained=True): if use_pretrained: path = 'pretrained' else: path = 'curve' return path def get_curve_data(use_pretrained=True, model='ResNet'): folder_path = get_folder_path(use_pretrained) filename...
"""Train CIFAR100 with PyTorch.""" def get_parser(): parser = argparse.ArgumentParser(description='PyTorch CIFAR100 Training') parser.add_argument('--model', default='resnet', type=str, help='model', choices=['resnet', 'densenet']) parser.add_argument('--optim', default='adamod',...
""" .. Densely Connected Convolutional Networks: https://arxiv.org/abs/1608.06993 """ class Bottleneck(nn.Module): def __init__(self, in_planes, growth_rate): super(Bottleneck, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.conv1 = nn.Conv2d(in_planes, 4 * growth_rate, ker...
""" .. Deep Residual Learning for Image Recognition: https://arxiv.org/abs/1512.03385 """ 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, ...
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. LR_SCHEDULER_REGISTRY = {} de...
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. @register_lr_scheduler('cold_sta...
# constants MAX_TOKEN_LENGTH = 256 DATA_DIR = './data' NUM_MEL = 80 TSV_FILE_NAME = 'subset.tsv' # helpers def tsv_to_dict(path): with open(path) as fd: rd = csv.DictReader(fd, delimiter = "\t", quotechar = '"') return [row for row in rd] # script voice_clips = tsv_to_dict(f'{DATA_DIR}/{TSV_F...
# data @click.command() @optgroup.group('Model settings') @optgroup.option('--text_vocab', default = 256, type = int) @optgroup.option('--text_dim', default = 512, type = int) @optgroup.option('--text_depth', default = 1, type = int) @optgroup.option('--text_heads', default = 8, type = int) @optgroup.option('--aud...
# einsum and einops # flax # constants LARGE_NEG_VALUE = -1e10 # config config.enable_omnistaging() # Linen requires enabling omnistaging # helpers def cross_entropy(logits, targets, axis=-1): logprobs = nn.log_softmax(logits, axis=axis) nll = np.take_along_axis(logprobs, np.expand_dims(targets, ax...
class CaptionedAudioMetadataset(IterableDataset): def __init__(self, path_pairs, lazy=False): self.datasets = [ CaptionedAudioDataset(captions_path, spectrograms_path, lazy=lazy) for (captions_path, spectrograms_path) in path_pairs ] def __iter__(self): def r...
# Modified from Google's Vision Transformer repo, whose notice is reproduced below. # # Copyright 2021 Google LLC. # # 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.or...
p = torch.nn.Parameter(torch.rand(10,10).cuda()) a = torch.rand(10,10).cuda() p1 = p.data.sum().item() adam = bnb.optim.Adam([p]) out = a*p loss = out.sum() loss.backward() adam.step() p2 = p.data.sum().item() assert p1 != p2 print('SUCCESS!') print('Installation was successful!')
torch.set_printoptions( precision=5, sci_mode=False, linewidth=120, edgeitems=20, threshold=10000 ) k = 20 def assert_all_approx_close(a, b, rtol=1e-3, atol=1e-3, count=0): idx = torch.isclose(a, b, rtol, atol) sumval = (idx == 0).sum().item() if sumval > count: print(f"Too many values not ...
# import apex k = 20 def get_temp_dir(): path = f"/tmp/autoswap/{str(uuid.uuid4())}" os.makedirs(path, exist_ok=True) return path def rm_path(path): shutil.rmtree(path) str2optimizers = {} str2optimizers["adam_pytorch"] = (None, torch.optim.Adam, bnb.optim.Adam) # str2optimizers['adam_apex'] ...
CUDA_RUNTIME_LIB, determine_cuda_runtime_lib_path, evaluate_cuda_setup, extract_candidate_paths, ) """ 'LD_LIBRARY_PATH': ':/mnt/D/titus/local/cuda-11.1/lib64/' 'CONDA_EXE': '/mnt/D/titus/miniconda/bin/conda' 'LESSCLOSE': '/usr/bin/lesspipe %s %s' 'OLDPWD': '/mnt/D/titus/src' 'CONDA_PREFIX': '/mnt/D/...
# contributed by Alex Borzunov, see: # https://github.com/bigscience-workshop/petals/blob/main/tests/test_linear8bitlt.py @pytest.mark.skipif( not torch.cuda.is_available() or torch.cuda.get_device_capability() < (7, 5), reason="this test requires a turing-generation or newer GPU, see bitsandbytes docs", ) d...
n = 1 k = 25 dim1 = torch.randint(16, 64, size=(n,)).tolist() dim2 = torch.randint(32, 96, size=(n,)).tolist() dim3 = torch.randint(32, 96, size=(n,)).tolist() dim4 = torch.randint(32, 96, size=(n,)).tolist() funcs = [(torch.bmm, bnb.bmm_cublas), (torch.matmul, bnb.matmul_cublas)] str_funcs = ["bmm", "matmul"] req_g...
class MockArgs: def __init__(self, initial_data): for key in initial_data: setattr(self, key, initial_data[key]) class MLP8bit(torch.nn.Module): def __init__(self, dim1, dim2, has_fp16_weights=True, memory_efficient_backward=False, threshold=0.0): super().__init__() sel...
setup = CUDASetup.get_instance() if setup.initialized != True: setup.run_cuda_setup() if 'BITSANDBYTES_NOWELCOME' not in os.environ or str(os.environ['BITSANDBYTES_NOWELCOME']) == '0': setup.print_log_stack() lib = setup.lib try: if lib is None and torch.cuda.is_available(): CUDASetup.g...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. MatmulLtState, bmm_cublas, matmul, matmul_cublas, mm_cublas, ) if COMPILED_WITH_CUDA: from .optim import adam __pdoc...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # math.prod not compatible with python < 3.8 def prod(iterable): return reduce(operator.mul, iterable, 1) name2qmap = {} if COMPILED_...
def execute_and_return(command_string: str) -> Tuple[str, str]: def _decode(subprocess_err_out_tuple): return tuple( to_decode.decode("UTF-8").strip() for to_decode in subprocess_err_out_tuple ) def execute_and_return_decoded_std_streams(command_string): return...
HEADER_WIDTH = 60 def print_header( txt: str, width: int = HEADER_WIDTH, filler: str = "+" ) -> None: txt = f" {txt} " if txt else "" print(txt.center(width, filler)) def print_debug_info() -> None: print( "\nAbove we output some debug information. Please provide this info when " f...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree.
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. T = TypeVar("T", bound="torch.nn.Module") class StableEmbedding(torch.nn.Embedding): def __init__( self, num_embedding...
# math.prod not compatible with python < 3.8 def prod(iterable): return reduce(operator.mul, iterable, 1) tensor = torch.Tensor # The inverse transformation for the colTuring and colAmpere format were contributed by Alex Borzunov: # https://github.com/bigscience-workshop/petals/blob/main/src/petals/utils/lin...
def to_be_ignored(env_var: str, value: str) -> bool: ignorable = { "PWD", # PWD: this is how the shell keeps track of the current working dir "OLDPWD", "SSH_AUTH_SOCK", # SSH stuff, therefore unrelated "SSH_TTY", "HOME", # Linux shell default "TMUX", # Terminal ...
""" extract factors the build is dependent on: [X] compute capability [ ] TODO: Q - What if we have multiple GPUs of different makes? - CUDA version - Software: - CPU-only: only CPU quantization functions (no optimizer, no matrix multipl) - CuBLAS-LT: full-build 8-bit optimizer - no CuBLAS-LT: no 8-bit ...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. class RMSprop(Optimizer1State): def __init__( self, params, lr=1e-2, alpha=0.99, eps=1e-8, ...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. class Lion(Optimizer1State): def __init__( self, params, lr=1e-4, betas=(0.9, 0.99), weight_decay...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. class LAMB(Optimizer2State): def __init__( self, params, lr=1e-3, bias_correction=True, betas=(0....
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. class SGD(Optimizer1State): def __init__( self, params, lr, momentum=0, dampening=0, weig...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. class LARS(Optimizer1State): def __init__( self, params, lr, momentum=0, dampening=0, we...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree.
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. class Adagrad(Optimizer1State): def __init__( self, params, lr=1e-2, lr_decay=0, weight_decay=0, ...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. class AdamW(Optimizer2State): def __init__( self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, ...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. class Adam(Optimizer2State): def __init__( self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. class MockArgs: def __init__(self, initial_data): for key in initial_data: setattr(self, key, initial_data[key]) ...
# helper functions def exists(val): return val is not None # freezing of neural networks (teacher needs to be frozen) def set_module_requires_grad_(module, requires_grad): for param in module.parameters(): param.requires_grad = requires_grad def freeze_all_layers_(module): set_module_requires...
class ExperienceDataset(Dataset): def __init__(self, data): super().__init__() self.data = data def __len__(self): return len(self.data[0]) def __getitem__(self, ind): return tuple(map(lambda t: t[ind], self.data)) def create_dataloader(data, batch_size): ds = Exper...
# they use basic PPO for training the teacher with privileged information # then they used noisy student training, using the trained "oracle" teacher as guide # ppo data Memory = namedtuple('Memory', ['state', 'action', 'action_log_prob', 'reward', 'done', 'value']) class ExperienceDataset(Dataset): def __in...
class RunningStats(nn.Module): def __init__(self, shape, eps = 1e-5): super().__init__() shape = shape if isinstance(shape, tuple) else (shape,) self.shape = shape self.eps = eps self.n = 0 self.register_buffer('old_mean', torch.zeros(shape), persistent = False) ...
# translated from tensorflow code # https://gist.github.com/aravindsrinivas/56359b79f0ce4449bcb04ab4b56a57a2 # positional embedding helpers def pair(x): return (x, x) if not isinstance(x, tuple) else x def expand_dim(t, dim, k): t = t.unsqueeze(dim = dim) expand_shape = [-1] * len(t.shape) expand_s...
# constants NUM_BATCHES = int(1e5) BATCH_SIZE = 4 GRADIENT_ACCUMULATE_EVERY = 4 LEARNING_RATE = 1e-4 VALIDATE_EVERY = 100 PRIME_LENGTH = 128 GENERATE_EVERY = 250 GENERATE_LENGTH = 2048 SEQ_LEN = 2048 # helpers def cycle(loader): while True: for data in loader: yield data def decode_token(...
if version.parse(torch.__version__) >= version.parse('2.0.0'): from einops._torch_specific import allow_ops_in_compiled_graph allow_ops_in_compiled_graph()
# helpers def exists(val): return val is not None def default(val, d): return val if exists(val) else d def is_empty(t: torch.Tensor): return t.numel() == 0 def cast_tuple(t, length = 1): return t if isinstance(t, tuple) else ((t,) * length) def all_unique(arr): return len(arr) == len(set(...
def exists(val): return val is not None class Adan(Optimizer): def __init__( self, params, lr = 1e-3, betas = (0.02, 0.08, 0.01), eps = 1e-8, weight_decay = 0, restart_cond: callable = None ): assert len(betas) == 3 defaults = dict( ...
def exists(val): return val is not None def default(val, d): return val if exists(val) else d def stable_softmax(t, dim = -1): t = t - t.amax(dim = dim, keepdim = True) return t.softmax(dim = dim) # bidirectional cross attention - have two sequences attend to each other with 1 attention step class ...
# helper functions def default(val, def_val): return def_val if val is None else val def flatten(t): return t.reshape(t.shape[0], -1) def singleton(cache_key): def inner_fn(fn): @wraps(fn) def wrapper(self, *args, **kwargs): instance = getattr(self, cache_key) i...
# test model, a resnet 50 resnet = models.resnet50(pretrained=True) # arguments parser = argparse.ArgumentParser(description='byol-lightning-test') parser.add_argument('--image_folder', type=str, required = True, help='path to your folder of images for self-supervised learning') args = pa...
# constants NUM_BATCHES = int(1e5) BATCH_SIZE = 4 GRADIENT_ACCUMULATE_EVERY = 4 LEARNING_RATE = 3e-4 VALIDATE_EVERY = 100 GENERATE_EVERY = 500 GENERATE_LENGTH = 512 SEQ_LEN = 512 # helpers def cycle(loader): while True: for data in loader: yield data def decode_token(token): return s...
def default(value, default): return value if value is not None else default def log(t, eps=1e-9): return torch.log(t + eps) def top_p(logits, thres = 0.9): sorted_logits, sorted_indices = torch.sort(logits, descending=True) cum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1) sorte...
# helpers def cum_mean(t): device = t.device running_num = torch.arange(t.shape[-1], device=t.device) + 1 return t.cumsum(dim=-1) / running_num def normalize(t, eps=1e-8): t -= t.mean(dim=-1, keepdim=True) s = (t ** 2).mean(dim=-1, keepdim=True) return t * torch.rsqrt(s + eps) def causal_nor...
__version__ = '1.4.1'
# less warning messages since only using encoder transformers.logging.set_verbosity_error() # helper functions def exists(val): return val is not None # config MAX_LENGTH = 256 DEFAULT_T5_NAME = 'google/t5-v1_1-base' T5_CONFIGS = {} # singleton globals def get_tokenizer(name): tokenizer = T5Tokenizer...
# suppress a few warnings def noop(*args, **kwargs): pass logging.root.setLevel(logging.ERROR) warnings.warn = noop # import fairseq and joblib for hubert # helper functions def exists(val): return val is not None def default(val, d): return val if exists(val) else d class HubertWithKmeans(nn...
if version.parse(torch.__version__) >= version.parse('2.0.0'): from einops._torch_specific import allow_ops_in_compiled_graph allow_ops_in_compiled_graph()
parsed_version = version.parse(__version__) # helper functions def exists(val): return val is not None def default(val, d): return val if exists(val) else d def cast_tuple(t, l = 1): return ((t,) * l) if not isinstance(t, tuple) else t def filter_by_keys(fn, d): return {k: v for k, v in d....
# constants Config = namedtuple('Config', ['enable_flash', 'enable_math', 'enable_mem_efficient']) # helpers def exists(val): return val is not None def once(fn): called = False @wraps(fn) def inner(x): nonlocal called if called: return called = True re...
# functions def round_down_nearest_multiple(num, divisor): return num // divisor * divisor def curtail_to_multiple(t, mult, from_left = False): data_len = t.shape[-1] rounded_seq_len = round_down_nearest_multiple(data_len, mult) seq_slice = slice(None, rounded_seq_len) if not from_left else slice(-ro...
logging.root.setLevel(logging.ERROR) def exists(val): return val is not None class FairseqVQWav2Vec(nn.Module): """ checkpoint path can be found at https://github.com/facebookresearch/fairseq/blob/main/examples/wav2vec/README.md#vq-wav2vec specifically download the kmeans model for now $ wge...
def separate_weight_decayable_params(params): wd_params, no_wd_params = [], [] for param in params: param_list = no_wd_params if param.ndim < 2 else wd_params param_list.append(param) return wd_params, no_wd_params def get_optimizer( params, lr = 1e-4, wd = 1e-2, betas = (0...
# helper functions def exists(val): return val is not None def default(val, d): return val if exists(val) else d def always(val): def inner(*args, **kwargs): return val return inner def maybe(fn): if not exists(fn): return always(None) @wraps(fn) def inner(x, *...
SemanticTransformer, SemanticTransformerWrapper, CoarseTransformer, CoarseTransformerWrapper, FineTransformer, FineTransformerWrapper, FairseqVQWav2Vec, HubertWithKmeans ) # constants DEFAULT_SAMPLE_RATE = 16000 # make sure only one trainer is instantiated ONE_TRAINER_INST...
# helper functions def exists(val): return val is not None # hacky way to get num quantizers def get_num_quantizers(model: EncodecModel, audio_length = 512): out = model.encode(torch.randn(1, 1, audio_length)) return out[0][0].shape[1] class EncodecWrapper(nn.Module): """ Support pretrained...
# helper functions def exists(val): return val is not None def cast_tuple(val, length = 1): return val if isinstance(val, tuple) else ((val,) * length) def is_unique(arr): return len(set(arr)) == len(arr) # dataset functions class SoundDataset(Dataset): @beartype def __init__( sel...
# standard imports # non-standard imports # local imports num_recommendations = 500 # papers to recommend per user # ----------------------------------------------------------------------------- if not os.path.isfile(Config.database_path): print("the database file as.db should exist. You can create an empty databas...