python_code stringlengths 0 1.02M | repo_name stringlengths 9 48 | file_path stringlengths 5 114 |
|---|---|---|
import torch
from torch import nn, einsum
import torch.nn.functional as F
from einops import rearrange, repeat
# helpers
def exists(val):
return val is not None
# classes
class Attention(nn.Module):
def __init__(
self,
dim,
heads = 8,
dim_head = 64,
and_self_attend =... | isab-pytorch-main | isab_pytorch/isab_pytorch.py |
from isab_pytorch.isab_pytorch import ISAB
| isab-pytorch-main | isab_pytorch/__init__.py |
from setuptools import setup, find_packages
setup(
name = 'rgn2-replica',
packages = find_packages(),
version = '0.0.1',
license='CreativeCommons4.0',
description = 'RGN2-REPLICA: Replicating a SoTA model for Protein Folding with no homologs (wip)',
author = 'Eric Alcaide',
author_email = 'ericalcaide1@g... | rgn2-replica-main | setup.py |
import torch
import numpy as numpy
from rgn2_replica.utils import *
def test_chunk_permute():
seq = torch.tensor([1,2,3,4,5,6,7,8,9]*3)
res = chunk_permute(seq)
assert True
def test_masked_lang():
seq = torch.tensor([1,2,3,4,5,6,7,8,9]*3)
res = masked_lang(seq)
assert True
def test_mask_seq():
seq = to... | rgn2-replica-main | tests/test_utils.py |
import torch
from rgn2_replica.losses import AminoBERTLoss
def test_aminobert_loss():
vocab_size = 24
bs = 20
logit_out = torch.rand(bs, 10, vocab_size)
logit_chunk_perm = torch.rand(bs, 2)
target = torch.randint(1, 20, (bs, 10))
chunk_perm = torch.randint(0, 2, (bs,))
loss_func = AminoBER... | rgn2-replica-main | tests/test_loss.py |
# Author: Eric Alcaide
import os
import sys
if __name__ == "__main__":
pass
| rgn2-replica-main | tests/tests.py |
# Author: Eric Alcaide ( @hypnopump )
import time
import gc
import random
import numpy as np
import torch
from einops import rearrange, repeat
from functools import partial
import mp_nerf
from rgn2_replica.rgn2 import *
from rgn2_replica.utils import *
from rgn2_replica.rgn2_utils import *
# logging
WANDB = True
t... | rgn2-replica-main | rgn2_replica/rgn2_trainers.py |
from rgn2_replica.rgn2 import *
from rgn2_replica.rgn2_utils import *
from rgn2_replica.utils import * | rgn2-replica-main | rgn2_replica/__init__.py |
# Author: Gurvinder Singh (@gurvindersingh)
import pytorch_lightning as pl
import torch
from torch import nn
from transformers import get_linear_schedule_with_warmup
from x_transformers import Encoder, TransformerWrapper
from transformers.optimization import AdamW
from .losses import GoPFAMLoss
from .tokenizer import... | rgn2-replica-main | rgn2_replica/lmmodel.py |
from typing import Optional
import pyrosetta
from tqdm import tqdm
"""
NOTE: Remember to initialize PyRosetta before using these functions
Example:
import pyrosetta
pyrosetta.init("-mute all")
If you need to see Rosetta outputs, remove '-mute all'
"""
def get_fa_min_mover(
max_iter: int = 1000) -> ... | rgn2-replica-main | rgn2_replica/rgn2_refine.py |
import torch
from rgn2_replica.rgn2_utils import *
class ClaspEmbedder(torch.nn.Module):
def __init__(self, config, device):
super().__init__()
from clasp import Transformer as ClaspTransformer, basic_aa_tokenizer
self.tokenizer = basic_aa_tokenizer
self.device = device
... | rgn2-replica-main | rgn2_replica/embedders.py |
# Author: Gurvinder Singh (@gurvindersingh)
import pytorch_lightning as pl
from datasets import load_from_disk
from .tokenizer import Tokenizer
from transformers import DataCollatorForLanguageModeling
import torch
from torch.utils.data.dataloader import DataLoader
from sklearn.preprocessing import MultiLabelBinarizer
... | rgn2-replica-main | rgn2_replica/dataset.py |
# Author: Gurvinder Singh (@gurvindersingh)
from transformers import PreTrainedTokenizer
import numpy as np
class Tokenizer(PreTrainedTokenizer):
# Taken from mp_nerf and extended based on ESM
ALPHABETS = "ACDEFGHIKLMNPQRSTVWY_XBUZO"
SPLTOKENS = ['<cls>','<eos>','<pad>','<mask>']
def __init__(self, ... | rgn2-replica-main | rgn2_replica/tokenizer.py |
# Author: Eric Alcaide ( @hypnopump )
import random
import math
import torch
import numpy as np
# random hacks - device utils for pyTorch - saves transfers
to_cpu = lambda x: x.cpu() if x.is_cuda else x
to_device = lambda x, device: x.to(device) if x.device != device else x
# system-wide utility functions
def expa... | rgn2-replica-main | rgn2_replica/utils.py |
import re
import torch
from sidechainnet.utils.sequence import ProteinVocabulary as VOCAB
# random hacks - device utils for pyTorch - saves transfers
to_cpu = lambda x: x.cpu() if x.is_cuda else x
to_device = lambda x, device: x.to(device) if x.device != device else x
VOCAB = VOCAB()
# data loading funcs copied from... | rgn2-replica-main | rgn2_replica/rgn2_utils.py |
import torch
from torch import nn
from typing import Optional
import torch.nn.functional as F
class AminoBERTLoss(nn.Module):
def __init__(self, padding_token=-100, vocab_size=24):
super().__init__()
self.masked_loss = nn.CrossEntropyLoss(
ignore_index=padding_token
)
s... | rgn2-replica-main | rgn2_replica/losses.py |
# Author: Eric Alcaide ( @hypnopump )
import random
import math
import torch
import numpy as np
# utils specific for the LM
def chunk_permute(seq):
""" Permutes a chunk from the sequence.
Inputs:
* seq: (N,) tensor.
Outputs:
* seq: (N,) tensor
* labels: (N,) long tenso... | rgn2-replica-main | rgn2_replica/lm_utils.py |
# Author: Eric Alcaide ( @hypnopump )
import os
import sys
from typing import Optional, Tuple, List
# science
import numpy as np
# ML
import torch
import torch.nn.functional as F
from x_transformers import XTransformer, Encoder
from einops import rearrange, repeat
# custom
import mp_nerf
from rgn2_replica.utils import... | rgn2-replica-main | rgn2_replica/rgn2.py |
# Author: Gurvinder Singh (@gurvindersingh)
import argparse
import os
import pytorch_lightning as pl
from rgn2_replica.dataset import ProteinLMDataModule
from rgn2_replica.tokenizer import Tokenizer
from rgn2_replica.lmmodel import ProteinLMModel
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning... | rgn2-replica-main | scripts/lmtrainer.py |
# Author: Eirc Alcaide (@hypnopump)
import os
import re
import numpy as np
import torch
# process
import argparse
import joblib
from tqdm import tqdm
# custom
import esm
import sidechainnet
import mp_nerf
from rgn2_replica import *
from rgn2_replica.rosetta_refine import *
from rgn2_replica.utils import seqs_from_fast... | rgn2-replica-main | scripts/rgn2_predict_fold.py |
import os
import argparse
import random
import numpy as np
import wandb
import torch
import esm
import sidechainnet
from sidechainnet.utils.sequence import ProteinVocabulary as VOCAB
# IMPORTED ALSO IN LATER MODULES
VOCAB = VOCAB()
import mp_nerf
from rgn2_replica.rgn2_trainers import *
from rgn2_replica.embedders i... | rgn2-replica-main | scripts/train_rgn2.py |
from setuptools import setup, find_packages
setup(
name = 'pi-gan-pytorch',
packages = find_packages(),
version = '0.0.11',
license='MIT',
description = 'π-GAN - Pytorch',
author = 'Phil Wang',
author_email = 'lucidrains@gmail.com',
url = 'https://github.com/lucidrains/pi-gan-pytorch',
keywords = [
... | pi-GAN-pytorch-main | setup.py |
# taken and modified from https://colab.research.google.com/drive/1rO8xo0TemN67d4mTpakrKrLp03b9bgCX#scrollTo=JovhcSy1NIhr
# will need to be refactored from 3d input to 5d (with ray direction)
import torch
import torch.nn.functional as F
from einops import repeat, rearrange
def meshgrid_xy(tensor1, tensor2):
ii, j... | pi-GAN-pytorch-main | pi_gan_pytorch/nerf.py |
from pi_gan_pytorch.pi_gan_pytorch import Generator, Discriminator, piGAN, Trainer
| pi-GAN-pytorch-main | pi_gan_pytorch/__init__.py |
import math
from pathlib import Path
from functools import partial
import torch
from torch import nn, einsum
import torch.nn.functional as F
from torch.autograd import grad as torch_grad
from torch.utils.data import Dataset, DataLoader
from torch.optim import Adam
from torch.optim.lr_scheduler import LambdaLR
from t... | pi-GAN-pytorch-main | pi_gan_pytorch/pi_gan_pytorch.py |
# taken from
# https://github.com/mkocabas/CoordConv-pytorch/blob/master/CoordConv.py
import torch
import torch.nn as nn
class AddCoords(nn.Module):
def __init__(self, with_r=False):
super().__init__()
self.with_r = with_r
def forward(self, input_tensor):
"""
Args:
... | pi-GAN-pytorch-main | pi_gan_pytorch/coordconv.py |
from setuptools import setup, find_packages
setup(
name = 'jax2torch',
packages = find_packages(exclude=[]),
version = '0.0.7',
license='MIT',
description = 'Jax 2 Torch',
author = 'Phil Wang',
author_email = 'lucidrains@gmail.com',
url = 'https://github.com/lucidrains/jax2torch',
keywords = [
'j... | jax2torch-main | setup.py |
from jax2torch.jax2torch import jax2torch
| jax2torch-main | jax2torch/__init__.py |
# https://gist.github.com/mattjj/e8b51074fed081d765d2f3ff90edf0e9
import torch
from torch.utils import dlpack as torch_dlpack
import jax
from jax import dlpack as jax_dlpack
import jax.numpy as jnp
from jax.tree_util import tree_map
from inspect import signature
from functools import wraps
def j2t(x_jax):
x_tor... | jax2torch-main | jax2torch/jax2torch.py |
from setuptools import setup, find_packages
setup(
name = 'x-unet',
packages = find_packages(exclude=[]),
version = '0.3.1',
license='MIT',
description = 'X-Unet',
long_description_content_type = 'text/markdown',
author = 'Phil Wang',
author_email = 'lucidrains@gmail.com',
url = 'https://github.com/l... | x-unet-main | setup.py |
from x_unet.x_unet import XUnet, NestedResidualUnet | x-unet-main | x_unet/__init__.py |
from functools import partial
import math
import torch
from torch import nn, einsum
import torch.nn.functional as F
from einops import rearrange, repeat, reduce
from einops.layers.torch import Rearrange
from beartype import beartype
from beartype.typing import Tuple, Union, Optional
# helper functions
def exists(v... | x-unet-main | x_unet/x_unet.py |
import distutils
import distutils.spawn
import os
import platform
import re
import shutil
import subprocess
import sys
import tarfile
import urllib.request
from distutils.version import LooseVersion
from setuptools import Extension, setup
from setuptools.command.build_ext import build_ext
# Taken from https://github... | triton-master | python/setup.py |
import argparse
import inspect
import os
import sys
import triton
def run_all(result_dir, names):
if not os.path.exists(result_dir):
os.makedirs(result_dir)
for mod in os.listdir(os.path.dirname(os.path.realpath(__file__))):
# skip non python files
if not mod.endswith('.py'):
... | triton-master | python/bench/run.py |
import torch
import triton
# -------------------------------
# Matrix Multiplication
# -------------------------------
nt = {False: 'n', True: 't'}
square_confs = [
triton.testing.Benchmark(
x_names=['M', 'N', 'K'],
x_vals=[128, 256, 512, 1024, 2048, 3072, 4096, 6144],
line_arg='block',
... | triton-master | python/bench/bench_blocksparse.py |
import torch
import triton
confs = [
triton.testing.Benchmark(
x_names=['N'],
x_vals=[128, 256, 512, 1024, 2048, 3072, 4096, 6144, 8192],
line_arg='provider',
line_vals=['triton', 'torch'],
line_names=['Triton', 'Torch'],
ylabel='GBPS',
plot_name=f'{mode}-20... | triton-master | python/bench/bench_cross_entropy.py |
import torch
import triton
def rounded_linspace(low, high, steps, div):
ret = torch.linspace(low, high, steps)
ret = torch.div(ret.int() + div - 1, div, rounding_mode='trunc') * div
ret = torch.unique(ret)
return list(map(int, ret))
# Square benchmarks
nt = {False: "n", True: "t"}
square_confs = [
... | triton-master | python/bench/bench_matmul.py |
import pytest
import torch
import triton
import triton._C.libtriton.triton as _triton
@pytest.mark.parametrize("M, N, dtype, mode",
[
(M, N, dtype, mode) for M in [1024, 821]
for N in [512, 857, 1871, 2089, 8573, 31000]
... | triton-master | python/test/unit/operators/test_cross_entropy.py |
import pytest
import torch
import triton
@pytest.mark.parametrize("MODE", ["sdd", "dds", "dsd"])
@pytest.mark.parametrize("TRANS_A", [False, True])
@pytest.mark.parametrize("TRANS_B", [False, True])
@pytest.mark.parametrize("BLOCK", [16, 32, 64])
@pytest.mark.parametrize("DTYPE", [torch.float16])
def test_matmul(MOD... | triton-master | python/test/unit/operators/test_blocksparse.py |
import itertools
import pytest
import torch
import triton
import triton._C.libtriton.triton as _triton
@pytest.mark.parametrize(
"BLOCK_M, BLOCK_N, BLOCK_K, SPLIT_K, NWARP, NSTAGE, M, N, K, AT, BT, DTYPE",
itertools.chain(
*[
[
# 1 warp
(16, 16, 16, 1, 1, ... | triton-master | python/test/unit/operators/test_matmul.py |
import os
import re
import shutil
import pytest
import torch
import triton
import triton.language as tl
from triton.code_gen import JITFunction
tmpdir = ".tmp"
@triton.jit
def function_1(i):
i = i + 1
i = function_2(i)
return i
@triton.jit
def function_2(i):
i = i + 1
return i
@triton.jit
d... | triton-master | python/test/unit/runtime/test_cache.py |
# flake8: noqa: F821,F841
import itertools
import re
from typing import Optional, Union
import numpy as np
import pytest
import torch
from numpy.random import RandomState
import triton
import triton._C.libtriton.triton as _triton
import triton.language as tl
from triton.code_gen import JITFunction, TensorWrapper, rei... | triton-master | python/test/unit/language/test_core.py |
import numpy as np
import pytest
import scipy.stats
import torch
import triton
import triton.language as tl
#####################################
# Reference Philox Implementation
#####################################
class PhiloxConfig:
def __init__(self, PHILOX_ROUND_A, PHILOX_ROUND_B, PHILOX_KEY_A, PHILOX_KE... | triton-master | python/test/unit/language/test_random.py |
import subprocess
import sys
import pytest
import torch
import triton
import triton.language as tl
from triton.testing import get_dram_gbps, get_max_tensorcore_tflops
DEVICE_NAME = 'v100'
#######################
# Utilities
#######################
def nvsmi(attrs):
attrs = ','.join(attrs)
cmd = ['nvidia-s... | triton-master | python/test/regression/test_performance.py |
"""isort:skip_file"""
# flake8: noqa: F401
__version__ = '2.0.0'
# TODO: torch needs to be imported first
# or pybind11 shows `munmap_chunk(): invalid pointer`
import torch
# submodules
from .code_gen import cdiv, next_power_of_2, jit, autotune, heuristics, \
JITFunction, Config, Autotuner, reinterpret
from . impo... | triton-master | python/triton/__init__.py |
from __future__ import annotations
import ast
import builtins
import functools
import hashlib
import inspect
import os
import pickle
import subprocess
import sys
import tempfile
import textwrap
import threading
import time
import warnings
from typing import Dict, Set, Tuple, Union
import torch
from filelock import Fi... | triton-master | python/triton/code_gen.py |
import functools
import os
import subprocess
import sys
from contextlib import contextmanager
import torch
import triton._C.libtriton.triton as _triton
from .code_gen import OutOfResources
try:
import triton._C.libtriton.cutlass as _cutlass
has_cutlass = True
except ImportError:
_cutlass = None
has_c... | triton-master | python/triton/testing.py |
'''
Compare cached triton kernels in 2 directories.
example:
python compare_asm.py --dir0=triton-works/ --dir1=triton-fails/ --asm=ttir \
--diff-out0=diff-works.ll --diff-out1=diff-fails.ll
'''
import argparse
import os
import pickle
parser = argparse.ArgumentParser(description="unpickle")
parser.add_argument(... | triton-master | python/triton/tools/compare_asm.py |
# MIT License
# Copyright (c) 2020 Da Yan @ HKUST
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge,... | triton-master | python/triton/tools/disasm.py |
import argparse
import subprocess
from abc import ABC, abstractmethod
class Symbol:
def __init__(self, name: str, op_name: str, ret_type: str, arg_names: list, arg_types: list) -> None:
'''
A symbol is a function declaration.
:param name: name of the symbol
:param op_name: name of... | triton-master | python/triton/tools/build_extern.py |
triton-master | python/triton/tools/__init__.py | |
import os
from . import core, extern
LIBDEVICE_PATH = os.path.dirname(
os.path.abspath(__file__)) + "/libdevice.10.bc"
@extern.extern
def clz(arg0, _builder=None):
return extern.elementwise("libdevice", LIBDEVICE_PATH, [arg0, ],
{(core.dtype("int32"),): ("__nv_clz", core.dtype(... | triton-master | python/triton/language/libdevice.py |
from __future__ import annotations # remove after python 3.11
from typing import List, Optional, Tuple
from . import core as tl
from triton._C.libtriton.triton import ir
# Create custom exception that prints message "hello"
class IncompatibleTypeErrorimpl(Exception):
def __init__(self, type_a, type_b):
... | triton-master | python/triton/language/semantic.py |
# flake8: noqa: F401
from . import core, extern, libdevice, random
from .core import *
from .random import *
| triton-master | python/triton/language/__init__.py |
from __future__ import annotations
from enum import Enum
from functools import wraps
from typing import List
import triton
from . import semantic
from triton._C.libtriton.triton import ir
def _to_tensor(x, builder):
if isinstance(x, bool):
return tensor(builder.get_int1(x), int1)
# Note: compile-tim... | triton-master | python/triton/language/core.py |
import triton
from . import core as tl
PHILOX_KEY_A: tl.constexpr = -1640531527 # 0x9E3779B9
PHILOX_KEY_B: tl.constexpr = -1150833019 # 0xBB67AE85
PHILOX_ROUND_A: tl.constexpr = -766435501 # 0xD2511F53
PHILOX_ROUND_B: tl.constexpr = -845247145 # 0xCD9E8D57
N_ROUNDS_DEFAULT = 10 # Default number of rounds for phil... | triton-master | python/triton/language/random.py |
from __future__ import annotations # remove after python 3.11
from . import core, semantic
def dispatch(func, lib_name: str, lib_path: str, args: list, arg_type_symbol_dict: dict, ret_shape: tuple, _builder=None):
'''
Dispatch a function to a library
:param func: the function to dispatch
... | triton-master | python/triton/language/extern.py |
import torch
import triton
import triton.language as tl
def next_power_of_2(n):
n -= 1
n |= n >> 1
n |= n >> 2
n |= n >> 4
n |= n >> 8
n |= n >> 16
n += 1
return n
def num_warps(N):
if N < 2048:
return 4
elif N < 8192:
return 8
return 16
@triton.heurist... | triton-master | python/triton/ops/cross_entropy.py |
import torch
import triton
import triton.language as tl
from .matmul_perf_model import early_config_prune, estimate_matmul_time
def init_to_zero(name):
return lambda nargs: nargs[name].zero_()
def get_configs_io_bound():
configs = []
for num_stages in [2, 3, 4, 5, 6]:
for block_m in [16, 32]:
... | triton-master | python/triton/ops/matmul.py |
# flake8: noqa: F401
#from .conv import _conv, conv
from . import blocksparse
from .cross_entropy import _cross_entropy, cross_entropy
from .matmul import _matmul, matmul
| triton-master | python/triton/ops/__init__.py |
import heapq
import torch
import triton
import triton._C.libtriton.triton as _triton
from triton.testing import get_dram_gbps, get_max_simd_tflops, get_max_tensorcore_tflops
def get_tensorcore_tflops(backend, device, num_ctas, num_warps, dtype):
''' return compute throughput in TOPS '''
total_warps = num_ct... | triton-master | python/triton/ops/matmul_perf_model.py |
import torch
import triton
import triton.language as tl
# ********************************************************
# --------------------------------------------------------
# Sparse = Dense x Dense (SDD)
# This operation uses super-blocking to make sure that
# it's done efficiently when small blocks can be grouped
#... | triton-master | python/triton/ops/blocksparse/matmul.py |
# flake8: noqa: F401
from .matmul import matmul
from .softmax import softmax
| triton-master | python/triton/ops/blocksparse/__init__.py |
import torch
import triton
import triton.language as tl
def num_warps(n):
if n <= 128:
return 1
if n <= 256:
return 2
if n <= 512:
return 4
if n <= 4096:
return 8
return 16
@triton.jit
def _blocksparse_softmax_fwd(
Out, A, stride_xz, LUT,
R, extent, strid... | triton-master | python/triton/ops/blocksparse/softmax.py |
"""
Fused Attention
===============
This is a Triton implementation of the Flash Attention algorithm
(see: Dao et al., https://arxiv.org/pdf/2205.14135v2.pdf; Rabe and Staats https://arxiv.org/pdf/2112.05682v2.pdf)
"""
import pytest
import torch
import triton
import triton.language as tl
@triton.jit
def _fwd_kernel... | triton-master | python/tutorials/06-fused-attention.py |
"""
Fused Softmax
=================
In this tutorial, you will write a fused softmax operation that is significantly faster
than PyTorch's native op for a particular class of matrices: those whose rows can fit in
the GPU's SRAM.
You will learn about:
- The benefits of kernel fusion for bandwidth-bound operations.
- Re... | triton-master | python/tutorials/02-fused-softmax.py |
"""
Vector Addition
=================
In this tutorial, you will write a simple vector addition using Triton and learn about:
- The basic programming model of Triton
- The `triton.jit` decorator, which is used to define Triton kernels.
- The best practices for validating and benchmarking your custom ops against native... | triton-master | python/tutorials/01-vector-add.py |
"""
Libdevice function
===============
Triton can invoke a custom function from an external library.
In this example, we will use the `libdevice` library to apply `asin` on a tensor.
Please refer to https://docs.nvidia.com/cuda/libdevice-users-guide/index.html regarding the semantics of all available libdevice function... | triton-master | python/tutorials/07-libdevice-function.py |
"""
Low-Memory Dropout
=================
In this tutorial, you will write a memory-efficient implementation of dropout whose state
will be composed of a single int32 seed. This differs from more traditional implementations of dropout,
whose state is generally composed of a bit mask tensor of the same shape as the inpu... | triton-master | python/tutorials/04-low-memory-dropout.py |
"""
Matrix Multiplication
======================
In this tutorial, you will write a 25-lines high-performance FP16 matrix multiplication
kernel that achieves performance on par with cuBLAS.
You will specifically learn about:
- Block-level matrix multiplications
- Multi-dimensional pointer arithmetic
- Program re-order... | triton-master | python/tutorials/03-matrix-multiplication.py |
"""
Layer Normalization
====================
"""
import torch
import triton
import triton.language as tl
try:
# This is https://github.com/NVIDIA/apex, NOT the apex on PyPi, so it
# should not be added to extras_require in setup.py.
import apex
HAS_APEX = True
except ModuleNotFoundError:
HAS_APEX... | triton-master | python/tutorials/05-layer-norm.py |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Triton documentation build configuration file, created by
# sphinx-quickstart on Mon Feb 10 01:19:09 2020.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# aut... | triton-master | docs/conf.py |
from setuptools import setup, find_packages
setup(
name = 'soundstorm-pytorch',
packages = find_packages(exclude=[]),
version = '0.1.4',
license='MIT',
description = 'SoundStorm - Efficient Parallel Audio Generation from Google Deepmind, in Pytorch',
author = 'Phil Wang',
author_email = 'lucidrains@gmail... | soundstorm-pytorch-main | setup.py |
import math
from random import random, randrange
from functools import wraps
from contextlib import nullcontext
from collections import namedtuple
from pathlib import Path
import torch
from torch import Tensor, nn, einsum
import torch.nn.functional as F
from einops import rearrange, reduce, repeat, unpack, pack
from ... | soundstorm-pytorch-main | soundstorm_pytorch/soundstorm.py |
from soundstorm_pytorch.soundstorm import (
SoundStorm,
SoundStream,
ConformerWrapper,
Conformer
)
from soundstorm_pytorch.trainer import (
SoundStormTrainer
)
| soundstorm-pytorch-main | soundstorm_pytorch/__init__.py |
from collections import namedtuple
from functools import wraps
from packaging import version
import torch
from torch import nn, einsum
import torch.nn.functional as F
from einops import rearrange
# constants
EfficientAttentionConfig = namedtuple('EfficientAttentionConfig', ['enable_flash', 'enable_math', 'enable_me... | soundstorm-pytorch-main | soundstorm_pytorch/attend.py |
from pathlib import Path
import re
from shutil import rmtree
from beartype import beartype
from beartype.typing import Optional
import torch
from torch import nn
from torch.optim.lr_scheduler import CosineAnnealingLR
from torch.utils.data import Dataset, random_split
from audiolm_pytorch.data import get_dataloader
f... | soundstorm-pytorch-main | soundstorm_pytorch/trainer.py |
from setuptools import setup, find_packages
setup(
name = 'geometric-vector-perceptron',
packages = find_packages(),
version = '0.0.14',
license='MIT',
description = 'Geometric Vector Perceptron - Pytorch',
author = 'Phil Wang, Eric Alcaide',
author_email = 'lucidrains@gmail.com',
url = 'https://github... | geometric-vector-perceptron-main | setup.py |
from geometric_vector_perceptron.geometric_vector_perceptron import GVP, GVPDropout, GVPLayerNorm, GVP_MPNN, GVP_Network
| geometric-vector-perceptron-main | geometric_vector_perceptron/__init__.py |
import torch
from torch import nn, einsum
from torch_geometric.nn import MessagePassing
# types
from typing import Optional, List, Union
from torch_geometric.typing import OptPairTensor, Adj, Size, OptTensor, Tensor
# helper functions
def exists(val):
return val is not None
# classes
class GVP(nn.Module):
... | geometric-vector-perceptron-main | geometric_vector_perceptron/geometric_vector_perceptron.py |
import torch
from geometric_vector_perceptron import GVP, GVPDropout, GVPLayerNorm, GVP_MPNN
TOL = 1e-2
def random_rotation():
q, r = torch.qr(torch.randn(3, 3))
return q
def diff_matrix(vectors):
b, _, d = vectors.shape
diff = vectors[..., None, :] - vectors[:, None, ...]
return diff.reshape(b, ... | geometric-vector-perceptron-main | tests/tests.py |
# Author: Eric Alcaide
# A substantial part has been borrowed from
# https://github.com/jonathanking/sidechainnet
#
# Here's the License for it:
#
# Copyright 2020 Jonathan King
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions ar... | geometric-vector-perceptron-main | examples/data_handler.py |
geometric-vector-perceptron-main | examples/__init__.py | |
import gc
from argparse import ArgumentParser
from functools import partial
from pathlib import Path
from pprint import pprint
import matplotlib.pyplot as plt
import numpy as np
import pytorch_lightning as pl
import torch
from einops import rearrange
from loguru import logger
from pytorch_lightning.callbacks import (
... | geometric-vector-perceptron-main | examples/train_lightning.py |
from argparse import ArgumentParser
from typing import List, Optional
from typing import Union
import numpy as np
import pytorch_lightning as pl
import sidechainnet
from sidechainnet.dataloaders.collate import get_collate_fn
from sidechainnet.utils.sequence import ProteinVocabulary
from torch.utils.data import DataLoa... | geometric-vector-perceptron-main | examples/scn_data_module.py |
# Author: Eric Alcaide
import os
import sys
# science
import torch
import torch_sparse
import numpy as np
from einops import repeat, rearrange
# custom utils - from https://github.com/EleutherAI/mp_nerf
from data_handler import *
# new data builders
def get_atom_ids_dict():
""" Get's a dict mapping each atom to... | geometric-vector-perceptron-main | examples/data_utils.py |
from setuptools import setup, find_packages
setup(
name = 'x-clip',
packages = find_packages(exclude=[]),
include_package_data = True,
version = '0.12.9',
license='MIT',
description = 'X-CLIP',
author = 'Phil Wang',
author_email = 'lucidrains@gmail.com',
url = 'https://github.com/lucidrains/x-clip',
... | x-clip-main | setup.py |
import copy
import random
from functools import wraps
import torch
from torch import nn
import torch.nn.functional as F
from torchvision import transforms as T
from einops import rearrange
# augmentations
class RandomApply(nn.Module):
def __init__(self, fn, p):
super().__init__()
self.fn = fn
... | x-clip-main | x_clip/visual_ssl.py |
import math
import copy
from contextlib import contextmanager
from functools import partial, wraps
import torch
import torch.nn.functional as F
import torch.distributed as distributed
from torch import nn, einsum
from torch.utils.checkpoint import checkpoint
from einops import rearrange, repeat, reduce
from einops.la... | x-clip-main | x_clip/x_clip.py |
import math
from functools import reduce
import torch
from torch import nn
import torch.nn.functional as F
# helpers
def prob_mask_like(t, prob):
return torch.zeros_like(t).float().uniform_(0, 1) < prob
def mask_with_tokens(t, token_ids):
init_no_mask = torch.full_like(t, False, dtype=torch.bool)
mask =... | x-clip-main | x_clip/mlm.py |
from x_clip.x_clip import CLIP, TextTransformer
| x-clip-main | x_clip/__init__.py |
# take from https://github.com/openai/CLIP/blob/main/clip/simple_tokenizer.py
# to give users a quick easy start to training DALL-E without doing BPE
import os
import html
from functools import lru_cache
from pathlib import Path
import regex as re
import ftfy
import torch
import torch.nn.functional as F
from beart... | x-clip-main | x_clip/tokenizer.py |
import torch
from torch.autograd import Function
import torch.distributed as distributed
from einops import rearrange
# distributed helpers
def all_gather_variable_dim(t, dim = 0, sizes = None):
device, rank, world_size = t.device, distributed.get_rank(), distributed.get_world_size()
if not exists(sizes):
... | x-clip-main | x_clip/distributed.py |
#!/usr/bin/env python
"""
Convert all recipes into feedstocks.
This script is to be run in a TravisCI context, with all secret environment
variables defined (STAGING_BINSTAR_TOKEN, GH_TOKEN)
Such as:
export GH_TOKEN=$(cat ~/.conda-smithy/github.token)
"""
from __future__ import print_function
from conda_build.... | staged-recipes-main | .travis_scripts/create_feedstocks.py |
#!/usr/bin/env python
"""
Copyright (c) 2016, Continuum Analytics, Inc.
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
l... | staged-recipes-main | .ci_support/compute_build_graph.py |
import conda_build.conda_interface
import networkx as nx
import conda_build.api
from compute_build_graph import construct_graph
import argparse
import os
from collections import OrderedDict
import sys
import subprocess
import yaml
try:
from ruamel_yaml import BaseLoader, load
except ImportError:
from yaml impo... | staged-recipes-main | .ci_support/build_all.py |
import sys
from setuptools import setup, find_packages
sys.path[0:0] = ['lightweight_gan']
from version import __version__
setup(
name = 'lightweight-gan',
packages = find_packages(),
entry_points={
'console_scripts': [
'lightweight_gan = lightweight_gan.cli:main',
],
},
version = __version__,... | lightweight-gan-main | setup.py |
import random
import torch
import torch.nn.functional as F
def DiffAugment(x, types=[]):
for p in types:
for f in AUGMENT_FNS[p]:
x = f(x)
return x.contiguous()
# """
# Augmentation functions got images as `x`
# where `x` is tensor with this dimensions:
# 0 - count of images
# 1 - chann... | lightweight-gan-main | lightweight_gan/diff_augment.py |
__version__ = '1.1.1'
| lightweight-gan-main | lightweight_gan/version.py |
from lightweight_gan.lightweight_gan import LightweightGAN, Generator, Discriminator, Trainer, NanException
from kornia.filters import filter2d
| lightweight-gan-main | lightweight_gan/__init__.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.