python_code stringlengths 0 1.02M | repo_name stringlengths 9 48 | file_path stringlengths 5 114 |
|---|---|---|
from setuptools import setup, find_packages
setup(
name = 'kronecker-attention-pytorch',
packages = find_packages(),
version = '0.0.6',
license='MIT',
description = 'Kronecker Attention - Pytorch',
author = 'Phil Wang',
author_email = 'lucidrains@gmail.com',
url = 'https://github.com/lucidrains/kroneck... | kronecker-attention-pytorch-master | setup.py |
from kronecker_attention_pytorch.kronecker_attention_pytorch import KroneckerSelfAttention
| kronecker-attention-pytorch-master | kronecker_attention_pytorch/__init__.py |
import torch
from torch import nn, einsum
from einops import rearrange, repeat
import torch.nn.functional as F
class KroneckerSelfAttention(nn.Module):
def __init__(self, dim, heads, dim_heads = 32):
super().__init__()
hidden_dim = heads * dim_heads
self.heads = heads
self.to_qkv =... | kronecker-attention-pytorch-master | kronecker_attention_pytorch/kronecker_attention_pytorch.py |
from setuptools import setup, find_packages
setup(
name = 'contrastive_learner',
packages = find_packages(),
version = '0.1.1',
license='MIT',
description = 'Self-supervised contrastive learning made simple',
author = 'Phil Wang',
author_email = 'lucidrains@gmail.com',
url = 'https://github.com/lucidra... | contrastive-learner-master | setup.py |
from contrastive_learner.contrastive_learner import ContrastiveLearner
| contrastive-learner-master | contrastive_learner/__init__.py |
import copy
import random
from functools import wraps
import torch
from torch import nn
import torch.nn.functional as F
from torchvision.models import resnet50
from kornia import augmentation as augs
from kornia import filters
# helper functions
def identity(x): return x
def default(val, def_val):
return def_v... | contrastive-learner-master | contrastive_learner/contrastive_learner.py |
from setuptools import setup, find_packages
setup(
name = 'MaMMUT-pytorch',
packages = find_packages(exclude=[]),
version = '0.0.6',
license='MIT',
description = 'MaMMUT - Pytorch',
author = 'Phil Wang',
author_email = 'lucidrains@gmail.com',
long_description_content_type = 'text/markdown',
url = 'ht... | MaMMUT-pytorch-main | setup.py |
import torch
from torch import einsum, nn
import torch.nn.functional as F
import torch.distributed as dist
from torch.autograd import Function
from einops import rearrange, repeat
# helper functions
def exists(val):
return val is not None
def default(val, d):
return val if exists(val) else d
def divisible_... | MaMMUT-pytorch-main | mammut_pytorch/mammut_pytorch.py |
from mammut_pytorch.mammut_pytorch import MaMMUT
| MaMMUT-pytorch-main | mammut_pytorch/__init__.py |
from setuptools import setup, find_packages
setup(
name = 'slot_attention',
packages = find_packages(),
version = '1.1.2',
license='MIT',
description = 'Implementation of Slot Attention in Pytorch',
long_description_content_type = 'text/markdown',
author = 'Phil Wang',
author_email = 'lucidrains@gmail.... | slot-attention-master | setup.py |
import torch
from torch import nn
from torch.nn import init
class WeightedAttention(nn.Module):
def __init__(self, dim, eps = 1e-8, softmax_dim = 1, weighted_mean_dim = 2):
super().__init__()
self.norm_input = nn.LayerNorm(dim)
self.norm_context = nn.LayerNorm(dim)
self.to_q = nn.L... | slot-attention-master | slot_attention/slot_attention_experimental.py |
from slot_attention.slot_attention import SlotAttention
from slot_attention.slot_attention_experimental import SlotAttentionExperimental | slot-attention-master | slot_attention/__init__.py |
import torch
from torch import nn
from torch.nn import init
class SlotAttention(nn.Module):
def __init__(self, num_slots, dim, iters = 3, eps = 1e-8, hidden_dim = 128):
super().__init__()
self.num_slots = num_slots
self.iters = iters
self.eps = eps
self.scale = dim ** -0.5
... | slot-attention-master | slot_attention/slot_attention.py |
""" Setup
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
def _read_reqs(relpath):
... | open_clip-main | setup.py |
import pytest
import torch
from open_clip.hf_model import _POOLERS, HFTextEncoder
from transformers import AutoConfig
from transformers.modeling_outputs import BaseModelOutput
# test poolers
def test_poolers():
bs, sl, d = 2, 10, 5
h = torch.arange(sl).repeat(bs).reshape(bs, sl)[..., None] * torch.linspace(0.2... | open_clip-main | tests/test_hf_model.py |
import os
import pytest
import torch
import open_clip
import util_test
os.environ['CUDA_VISIBLE_DEVICES'] = ''
if hasattr(torch._C, '_jit_set_profiling_executor'):
# legacy executor is too slow to compile large models for unit tests
# no need for the fusion performance here
torch._C._jit_set_profiling_ex... | open_clip-main | tests/test_inference.py |
import pytest
from training.data import get_dataset_size
@pytest.mark.parametrize(
"shards,expected_size",
[
('/path/to/shard.tar', 1),
('/path/to/shard_{000..000}.tar', 1),
('/path/to/shard_{000..009}.tar', 10),
('/path/to/shard_{000..009}_{000..009}.tar', 100),
('/pat... | open_clip-main | tests/test_num_shards.py |
import os
import random
import numpy as np
from PIL import Image
import torch
if __name__ != '__main__':
import open_clip
os.environ['CUDA_VISIBLE_DEVICES'] = ''
def seed_all(seed = 0):
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.use_deterministic_algorithms... | open_clip-main | tests/util_test.py |
import torch
from PIL import Image
from open_clip.factory import get_tokenizer
import pytest
import open_clip
import os
os.environ["CUDA_VISIBLE_DEVICES"] = ""
if hasattr(torch._C, '_jit_set_profiling_executor'):
# legacy executor is too slow to compile large models for unit tests
# no need for the fusion perf... | open_clip-main | tests/test_inference_simple.py |
import requests
import torch
from PIL import Image
import hashlib
import tempfile
import unittest
from io import BytesIO
from pathlib import Path
from unittest.mock import patch
from urllib3 import HTTPResponse
from urllib3._collections import HTTPHeaderDict
import open_clip
from open_clip.pretrained import download_... | open_clip-main | tests/test_download_pretrained.py |
import os
import sys
import pytest
from PIL import Image
import torch
from training.main import main
os.environ["CUDA_VISIBLE_DEVICES"] = ""
if hasattr(torch._C, '_jit_set_profiling_executor'):
# legacy executor is too slow to compile large models for unit tests
# no need for the fusion performance here
... | open_clip-main | tests/test_training_simple.py |
import argparse
import ast
def get_default_params(model_name):
# Params from paper (https://arxiv.org/pdf/2103.00020.pdf)
model_name = model_name.lower()
if "vit" in model_name:
return {"lr": 5.0e-4, "beta1": 0.9, "beta2": 0.98, "eps": 1.0e-6}
else:
return {"lr": 5.0e-4, "beta1": 0.9, ... | open_clip-main | src/training/params.py |
import argparse
import torch
import open_clip
import pandas as pd
from fvcore.nn import FlopCountAnalysis, flop_count_str, ActivationCountAnalysis
parser = argparse.ArgumentParser(description='OpenCLIP Profiler')
# benchmark specific args
parser.add_argument('--model', metavar='NAME', default='',
... | open_clip-main | src/training/profile.py |
open_clip-main | src/training/__init__.py | |
import logging
def setup_logging(log_file, level, include_host=False):
if include_host:
import socket
hostname = socket.gethostname()
formatter = logging.Formatter(
f'%(asctime)s | {hostname} | %(levelname)s | %(message)s', datefmt='%Y-%m-%d,%H:%M:%S')
else:
format... | open_clip-main | src/training/logger.py |
import torch
from contextlib import suppress
def get_autocast(precision):
if precision == 'amp':
return torch.cuda.amp.autocast
elif precision == 'amp_bfloat16' or precision == 'amp_bf16':
# amp_bfloat16 is more stable than amp float16 for clip training
return lambda: torch.cuda.amp.au... | open_clip-main | src/training/precision.py |
import os
import torch
import torch.distributed as dist
try:
import horovod.torch as hvd
except ImportError:
hvd = None
def is_global_master(args):
return args.rank == 0
def is_local_master(args):
return args.local_rank == 0
def is_master(args, local=False):
return is_local_master(args) if l... | open_clip-main | src/training/distributed.py |
import json
import logging
import math
import os
import time
import numpy as np
import torch
import torch.nn.functional as F
from torch.nn.parallel.distributed import DistributedDataParallel
try:
import wandb
except ImportError:
wandb = None
from open_clip import get_cast_dtype, CLIP, CustomTextCLIP
from .di... | open_clip-main | src/training/train.py |
import logging
import torch
import torch.nn.functional as F
from tqdm import tqdm
from open_clip import get_cast_dtype, get_tokenizer
from .precision import get_autocast
from .imagenet_zeroshot_data import imagenet_classnames, openai_imagenet_template
def zero_shot_classifier(model, classnames, templates, args):
... | open_clip-main | src/training/zero_shot.py |
import logging
import os
import multiprocessing
import subprocess
import time
import fsspec
import torch
from tqdm import tqdm
def remote_sync_s3(local_dir, remote_dir):
# skip epoch_latest which can change during sync.
result = subprocess.run(["aws", "s3", "sync", local_dir, remote_dir, '--exclude', '*epoch_l... | open_clip-main | src/training/file_utils.py |
import numpy as np
def assign_learning_rate(optimizer, new_lr):
for param_group in optimizer.param_groups:
param_group["lr"] = new_lr
def _warmup_lr(base_lr, warmup_length, step):
return base_lr * (step + 1) / warmup_length
def const_lr(optimizer, base_lr, warmup_length, steps):
def _lr_adjust... | open_clip-main | src/training/scheduler.py |
import glob
import logging
import os
import re
import subprocess
import sys
import random
from datetime import datetime
import numpy as np
import torch
from torch import optim
from torch.cuda.amp import GradScaler
try:
import wandb
except ImportError:
wandb = None
try:
import torch.utils.tensorboard as t... | open_clip-main | src/training/main.py |
imagenet_classnames = ["tench", "goldfish", "great white shark", "tiger shark", "hammerhead shark", "electric ray",
"stingray", "rooster", "hen", "ostrich", "brambling", "goldfinch", "house finch", "junco",
"indigo bunting", "American robin", "bulbul", "jay", "magpie", ... | open_clip-main | src/training/imagenet_zeroshot_data.py |
import ast
import json
import logging
import math
import os
import random
import sys
import time
from dataclasses import dataclass
from multiprocessing import Value
import numpy as np
import pandas as pd
import torch
import torchvision.datasets as datasets
import webdataset as wds
from PIL import Image
from torch.util... | open_clip-main | src/training/data.py |
from typing import Optional
import torch
from torch import nn
from torch.nn import functional as F
import numpy as np
from dataclasses import dataclass
from .transformer import (
LayerNormFp32,
LayerNorm,
QuickGELU,
MultimodalTransformer,
)
from .model import CLIPTextCfg, CLIPVisionCfg, _build_vision_... | open_clip-main | src/open_clip/coca_model.py |
import hashlib
import os
import urllib
import warnings
from functools import partial
from typing import Dict, Union
from tqdm import tqdm
from .version import __version__
try:
from huggingface_hub import hf_hub_download
hf_hub_download = partial(hf_hub_download, library_name="open_clip", library_version=__ve... | open_clip-main | src/open_clip/pretrained.py |
__version__ = '2.11.0'
| open_clip-main | src/open_clip/version.py |
""" huggingface model adapter
Wraps HuggingFace transformers (https://github.com/huggingface/transformers) models for use as a text tower in CLIP model.
"""
import re
import torch
import torch.nn as nn
from torch import TensorType
try:
import transformers
from transformers import AutoModel, AutoTokenizer, A... | open_clip-main | src/open_clip/hf_model.py |
OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073)
OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711)
| open_clip-main | src/open_clip/constants.py |
from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
from .factory import create_model, create_model_and_transforms, create_model_from_pretrained, get_tokenizer, create_loss
from .factory import list_models, add_model_config, get_model_config, load_checkpoint
from .loss import ClipLoss, CoCaLoss
from .model i... | open_clip-main | src/open_clip/__init__.py |
# HF architecture dict:
arch_dict = {
# https://huggingface.co/docs/transformers/model_doc/roberta#roberta
"roberta": {
"config_names": {
"context_length": "max_position_embeddings",
"vocab_size": "vocab_size",
"width": "hidden_size",
"heads": "num_attenti... | open_clip-main | src/open_clip/hf_configs.py |
from collections import OrderedDict
import torch
from torch import nn
from torch.nn import functional as F
from open_clip.utils import freeze_batch_norm_2d
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1):
super().__init__()
# all conv layers have s... | open_clip-main | src/open_clip/modified_resnet.py |
import json
import logging
import os
import pathlib
import re
from copy import deepcopy
from pathlib import Path
from typing import Any, Dict, Optional, Tuple, Union
import torch
from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
from .model import CLIP, CustomTextCLIP, convert_weights_to_lp, convert_to_c... | open_clip-main | src/open_clip/factory.py |
""" CLIP Model
Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
"""
from dataclasses import dataclass
import logging
import math
from typing import Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch.util... | open_clip-main | src/open_clip/model.py |
from math import ceil
import torch
import torch.nn.functional as F
def exists(val):
return val is not None
def top_p(logits, thres=0.9):
# nucleus
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
cum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
sorted_indice... | open_clip-main | src/open_clip/generation_utils.py |
""" CLIP tokenizer
Copied from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
"""
import gzip
import html
import os
from functools import lru_cache
from typing import Union, List
import ftfy
import regex as re
import torch
# https://stackoverflow.com/q/62691279
import os
os.enviro... | open_clip-main | src/open_clip/tokenizer.py |
import torch
import torch.nn as nn
from torch.nn import functional as F
try:
import torch.distributed.nn
from torch import distributed as dist
has_distributed = True
except ImportError:
has_distributed = False
try:
import horovod.torch as hvd
except ImportError:
hvd = None
def gather_featur... | open_clip-main | src/open_clip/loss.py |
""" OpenAI pretrained model functions
Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
"""
import os
import warnings
from typing import List, Optional, Union
import torch
from .model import build_model_from_openai_state_dict, convert_weights_to_lp, get_cast_dtype
from ... | open_clip-main | src/open_clip/openai.py |
from itertools import repeat
import collections.abc
from torch import nn as nn
from torchvision.ops.misc import FrozenBatchNorm2d
def freeze_batch_norm_2d(module, module_match={}, name=''):
"""
Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is
... | open_clip-main | src/open_clip/utils.py |
from collections import OrderedDict
import math
from typing import Callable, Optional, Sequence, Tuple
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.checkpoint import checkpoint
from .utils import to_2tuple
class LayerNormFp32(nn.LayerNorm):
"""Subclass torch's LayerNor... | open_clip-main | src/open_clip/transformer.py |
import warnings
from dataclasses import dataclass, asdict
from typing import Any, Dict, Optional, Sequence, Tuple, Union
import torch
import torch.nn as nn
import torchvision.transforms.functional as F
from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \
... | open_clip-main | src/open_clip/transform.py |
""" timm model adapter
Wraps timm (https://github.com/rwightman/pytorch-image-models) models for use as a vision tower in CLIP model.
"""
import logging
from collections import OrderedDict
import torch
import torch.nn as nn
try:
import timm
from timm.models.layers import Mlp, to_2tuple
try:
# old... | open_clip-main | src/open_clip/timm_model.py |
import tensorflow as tf
import numpy as np
import pandas as pd
from pyfaidx import Fasta
from functools import partial
from random import randrange
# efficient way for one hot encoding DNA sequence from string
# modified from https://gist.github.com/hannes-brt/54ca5d4094b3d96237fa2e820c0945dd
embed = np.zeros([89, 4... | enformer-tensorflow-sonnet-training-script-main | sequence.py |
from itertools import islice
from functools import partial
import tensorflow as tf
# old get_dataset functions, but only returning labels to zip in new longer sequneces
def organism_path(organism):
return os.path.join(f'gs://basenji_barnyard/data', organism)
def get_dataset(organism, subset, num_threads=8):
meta... | enformer-tensorflow-sonnet-training-script-main | create_tfrecords.py |
# Copyright 2021 Calico LLC
# Copyright 2021 DeepMind Technologies Limited
#
# 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-2.0
#
# Unless requi... | enformer-tensorflow-sonnet-training-script-main | train.py |
from setuptools import setup, find_packages
setup(
name = 'recurrent-memory-transformer-pytorch',
packages = find_packages(exclude=[]),
version = '0.5.5',
license='MIT',
description = 'Recurrent Memory Transformer - Pytorch',
author = 'Phil Wang',
author_email = 'lucidrains@gmail.com',
long_description... | recurrent-memory-transformer-pytorch-main | setup.py |
import gzip
import random
import tqdm
import numpy as np
import torch
from torch.optim import Adam
from torch.nn import functional as F
from torch.utils.data import DataLoader, Dataset
from recurrent_memory_transformer_pytorch import RecurrentMemoryTransformer, RecurrentMemoryTransformerWrapper
# constants
NUM_BATC... | recurrent-memory-transformer-pytorch-main | train.py |
from recurrent_memory_transformer_pytorch.recurrent_memory_transformer import RecurrentMemoryTransformer, RecurrentMemoryTransformerWrapper
| recurrent-memory-transformer-pytorch-main | recurrent_memory_transformer_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
Config = namedtuple('EfficientAttentionConfig', ['enable_flash', 'enable_math', 'enable_mem_efficient'])
# ... | recurrent-memory-transformer-pytorch-main | recurrent_memory_transformer_pytorch/attend.py |
import math
from functools import partial
from itertools import zip_longest
from contextlib import nullcontext
from typing import Optional, List, Tuple
import torch
import torch.nn.functional as F
from torch import nn, einsum, Tensor
from einops import rearrange, repeat, pack, unpack
from recurrent_memory_transform... | recurrent-memory-transformer-pytorch-main | recurrent_memory_transformer_pytorch/recurrent_memory_transformer.py |
from setuptools import setup, find_packages
setup(
name = 'panoptic-transformer',
packages = find_packages(exclude=[]),
version = '0.0.1',
license='MIT',
description = 'Panoptic Transformer',
author = 'Phil Wang',
author_email = 'lucidrains@gmail.com',
url = 'https://github.com/lucidrains/panoptic-tran... | panoptic-transformer-main | setup.py |
import torch
from torch import nn, einsum
from einops import rearrange
import torch.nn.functional as F
class Attention(nn.Module):
def __init__(
self,
dim,
*,
dim_head = 64,
heads = 8
):
super().__init__()
inner_dim = heads * dim_head
self.scale =... | panoptic-transformer-main | panoptic_transformer/panoptic_transformer.py |
from panoptic_transformer.panoptic_transformer import PanopticTransformer
| panoptic-transformer-main | panoptic_transformer/__init__.py |
from pathlib import Path
from random import choice
from PIL import Image
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torch.utils.data import random_split
from torchvision import transforms as T
# helper functions
def cycle... | panoptic-transformer-main | panoptic_transformer/data.py |
# taken from https://github.com/drewlinsley/pathfinder/blob/master/snakes2_wrapper.py
# but modified with path-x specific settings
import time
import sys
import numpy as np
import os
import snakes2
class Args:
def __init__(self,
contour_path = './contour', batch_id=0, n_images = 200000,
... | panoptic-transformer-main | scripts/gen-pathx.py |
# standard imports
import os
import sys
import pickle
# non-standard imports
import numpy as np
from sklearn import svm
from sqlite3 import dbapi2 as sqlite3
# local imports
from utils import safe_pickle_dump, strip_version, Config
num_recommendations = 500 # papers to recommend per user
# ----------------------------... | arxiv-sanity-preserver-master | buildsvm.py |
"""
Very simple script that simply iterates over all files data/pdf/f.pdf
and create a file data/txt/f.pdf.txt that contains the raw text, extracted
using the "pdftotext" command. If a pdf cannot be converted, this
script will not produce the output file.
"""
import os
import sys
import time
import shutil
import pickl... | arxiv-sanity-preserver-master | parse_pdf_to_text.py |
import os
import json
import time
import pickle
import dateutil.parser
import argparse
from random import shuffle
import numpy as np
from sqlite3 import dbapi2 as sqlite3
from hashlib import md5
from flask import Flask, request, session, url_for, redirect, \
render_template, abort, g, flash, _app_ctx_stack
from f... | arxiv-sanity-preserver-master | serve.py |
"""
Queries arxiv API and downloads papers (the query is a parameter).
The script is intended to enrich an existing database pickle (by default db.p),
so this file will be loaded first, and then new results will be added to it.
"""
import os
import time
import pickle
import random
import argparse
import urllib.request... | arxiv-sanity-preserver-master | fetch_papers.py |
"""
Use imagemagick to convert all pfds to a sequence of thumbnail images
requires: sudo apt-get install imagemagick
"""
import os
import time
import shutil
from subprocess import Popen
from utils import Config
# make sure imagemagick is installed
if not shutil.which('convert'): # shutil.which needs Python 3.3+
pr... | arxiv-sanity-preserver-master | thumb_pdf.py |
from contextlib import contextmanager
import os
import re
import pickle
import tempfile
# global settings
# -----------------------------------------------------------------------------
class Config(object):
# main paper information repo file
db_path = 'db.p'
# intermediate processing folders
pdf_dir ... | arxiv-sanity-preserver-master | utils.py |
import re
import pytz
import time
import pickle
import datetime
from dateutil import parser
import twitter # pip install python-twitter
from utils import Config, safe_pickle_dump
sleep_time = 60*10 # in seconds
max_days_keep = 5 # max number of days to keep a tweet in memory
def get_db_pids():
print('loading the ... | arxiv-sanity-preserver-master | twitter_daemon.py |
import os
import time
import pickle
import shutil
import random
from urllib.request import urlopen
from utils import Config
timeout_secs = 10 # after this many seconds we give up on a paper
if not os.path.exists(Config.pdf_dir): os.makedirs(Config.pdf_dir)
have = set(os.listdir(Config.pdf_dir)) # get list of all pdf... | arxiv-sanity-preserver-master | download_pdfs.py |
"""
Reads txt files of all papers and computes tfidf vectors for all papers.
Dumps results to file tfidf.p
"""
import os
import pickle
from random import shuffle, seed
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from utils import Config, safe_pickle_dump
seed(1337)
max_train = 1000... | arxiv-sanity-preserver-master | analyze.py |
from setuptools import setup, find_packages
setup(
name = 'deep-linear-network',
packages = find_packages(),
version = '0.0.1',
license='MIT',
description = 'Deep Linear Network - Pytorch',
author = 'Phil Wang',
author_email = 'lucidrains@gmail.com',
url = 'https://github.com/lucidrains/deep-linear-net... | deep-linear-network-main | setup.py |
from deep_linear_network.deep_linear_network import DeepLinear
| deep-linear-network-main | deep_linear_network/__init__.py |
import torch
from torch import nn
from functools import reduce
def mm(x, y):
return x @ y
class DeepLinear(nn.Module):
def __init__(self, dim_in, *dims):
super().__init__()
dims = [dim_in, *dims]
pairs = list(zip(dims[:-1], dims[1:]))
weights = list(map(lambda d: nn.Parameter(t... | deep-linear-network-main | deep_linear_network/deep_linear_network.py |
from setuptools import setup, find_packages
setup(
name = 'molecule-attention-transformer',
packages = find_packages(),
version = '0.0.4',
license='MIT',
description = 'Molecule Attention Transformer - Pytorch',
author = 'Phil Wang',
author_email = 'lucidrains@gmail.com',
url = 'https://github.com/luci... | molecule-attention-transformer-main | setup.py |
from molecule_attention_transformer.molecule_attention_transformer import MAT
| molecule-attention-transformer-main | molecule_attention_transformer/__init__.py |
import torch
import torch.nn.functional as F
from functools import partial
from torch import nn, einsum
from einops import rearrange
# constants
DIST_KERNELS = {
'exp': {
'fn': lambda t: torch.exp(-t),
'mask_value_fn': lambda t: torch.finfo(t.dtype).max
},
'softmax': {
'fn': lambda... | molecule-attention-transformer-main | molecule_attention_transformer/molecule_attention_transformer.py |
from setuptools import setup, find_packages
setup(
name = 'perfusion-pytorch',
packages = find_packages(exclude=[]),
version = '0.1.23',
license='MIT',
description = 'Perfusion - Pytorch',
author = 'Phil Wang',
author_email = 'lucidrains@gmail.com',
long_description_content_type = 'text/markdown',
ur... | perfusion-pytorch-main | setup.py |
from math import ceil
from copy import deepcopy
from pathlib import Path
from beartype import beartype
from beartype.typing import Union, List, Optional, Tuple
import torch
from torch import nn, einsum, Tensor
from torch.nn import Module
import torch.nn.functional as F
from einops import rearrange, reduce
from opt_... | perfusion-pytorch-main | perfusion_pytorch/perfusion.py |
from pathlib import Path
import torch
from torch import nn
from torch.nn import Module
from beartype import beartype
from perfusion_pytorch.embedding import EmbeddingWrapper
from perfusion_pytorch.perfusion import Rank1EditModule
# helper functions
def exists(val):
return val is not None
# saving and loading ... | perfusion-pytorch-main | perfusion_pytorch/save_load.py |
import torch
from torch import nn, Tensor
from torch.nn import Module
from collections import namedtuple
from beartype import beartype
from beartype.door import is_bearable
from beartype.typing import Optional, Tuple, Union, Callable, List
from einops import rearrange
from open_clip import tokenizer
# constants
E... | perfusion-pytorch-main | perfusion_pytorch/embedding.py |
from perfusion_pytorch.perfusion import (
Rank1EditModule,
calculate_input_covariance,
loss_fn_weighted_by_mask,
merge_rank1_edit_modules,
make_key_value_proj_rank1_edit_modules_
)
from perfusion_pytorch.embedding import (
EmbeddingWrapper,
OpenClipEmbedWrapper,
merge_embedding_wrappers... | perfusion-pytorch-main | perfusion_pytorch/__init__.py |
from torch.nn import Module
from torch.optim import AdamW, Adam, Optimizer
from beartype import beartype
from perfusion_pytorch.embedding import EmbeddingWrapper
from perfusion_pytorch.perfusion import Rank1EditModule
# function that automatically finds all the parameters necessary for fine tuning
@beartype
def get... | perfusion-pytorch-main | perfusion_pytorch/optimizer.py |
from beartype import beartype
from beartype.typing import List, Optional
import torch
from torch import nn, einsum
import torch.nn.functional as F
from einops import rearrange
import open_clip
def exists(val):
return val is not None
def l2norm(t):
return F.normalize(t, dim = -1)
class OpenClipAdapter(nn.M... | perfusion-pytorch-main | perfusion_pytorch/open_clip.py |
from setuptools import setup, find_packages
setup(
name = 'ponder-transformer',
packages = find_packages(),
version = '0.0.8',
license='MIT',
description = 'Ponder Transformer - Pytorch',
author = 'Phil Wang',
author_email = 'lucidrains@gmail.com',
url = 'https://github.com/lucidrains/ponder-transforme... | ponder-transformer-main | setup.py |
from ponder_transformer.ponder_transformer import PonderTransformer
| ponder-transformer-main | ponder_transformer/__init__.py |
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from einops.layers.torch import Rearrange, Reduce
# constants
ABS_MAX_STEPS = 100
# helper functions
def exists(val):
return val is not None
# classes
class PreNorm(nn.Module):
def __init__(self... | ponder-transformer-main | ponder_transformer/ponder_transformer.py |
# coding=utf-8
# Copyright 2018 Google LLC & Hwalsuk Lee.
#
# 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-2.0
#
# Unless required by applicable ... | compare_gan-master | setup.py |
# coding=utf-8
# Copyright 2018 Google LLC & Hwalsuk Lee.
#
# 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-2.0
#
# Unless required by applicable ... | compare_gan-master | compare_gan/test_utils.py |
# coding=utf-8
# Copyright 2018 Google LLC & Hwalsuk Lee.
#
# 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-2.0
#
# Unless required by applicable ... | compare_gan-master | compare_gan/hooks.py |
# coding=utf-8
# Copyright 2018 Google LLC & Hwalsuk Lee.
#
# 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-2.0
#
# Unless required by applicable ... | compare_gan-master | compare_gan/runner_lib_test.py |
# coding=utf-8
# Copyright 2018 Google LLC & Hwalsuk Lee.
#
# 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-2.0
#
# Unless required by applicable ... | compare_gan-master | compare_gan/datasets.py |
# coding=utf-8
# Copyright 2018 Google LLC & Hwalsuk Lee.
#
# 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-2.0
#
# Unless required by applicable ... | compare_gan-master | compare_gan/__init__.py |
# coding=utf-8
# Copyright 2018 Google LLC & Hwalsuk Lee.
#
# 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-2.0
#
# Unless required by applicable ... | compare_gan-master | compare_gan/datasets_test.py |
# coding=utf-8
# Copyright 2018 Google LLC & Hwalsuk Lee.
#
# 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-2.0
#
# Unless required by applicable ... | compare_gan-master | compare_gan/runner_lib.py |
# coding=utf-8
# Copyright 2018 Google LLC & Hwalsuk Lee.
#
# 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-2.0
#
# Unless required by applicable ... | compare_gan-master | compare_gan/eval_gan_lib_test.py |
# coding=utf-8
# Copyright 2018 Google LLC & Hwalsuk Lee.
#
# 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-2.0
#
# Unless required by applicable ... | compare_gan-master | compare_gan/utils.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.