python_code stringlengths 0 992k | repo_name stringlengths 8 46 | file_path stringlengths 5 162 |
|---|---|---|
from .discriminative_reranking_model import DiscriminativeNMTReranker
__all__ = [
"DiscriminativeNMTReranker",
]
| KosmosX-API-main | kosmosX/fairseq/examples/discriminative_reranking_nmt/models/__init__.py |
from dataclasses import dataclass, field
import os
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.dataclass import ChoiceEnum, FairseqDataclass
from fairseq.models import (
BaseFairseqModel,
register_model,
)
from fairseq.models.roberta.model import RobertaClassificationHead
from ... | KosmosX-API-main | kosmosX/fairseq/examples/discriminative_reranking_nmt/models/discriminative_reranking_model.py |
#!/usr/bin/env python
import argparse
from multiprocessing import Pool
from pathlib import Path
import sacrebleu
import sentencepiece as spm
def read_text_file(filename):
with open(filename, "r") as f:
output = [line.strip() for line in f]
return output
def get_bleu(in_sent, target_sent):
ble... | KosmosX-API-main | kosmosX/fairseq/examples/discriminative_reranking_nmt/scripts/prep_data.py |
# 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.
import math
from dataclasses import dataclass, field
import torch
import torch.nn.functional as F
from fairseq import metrics, utils
from fa... | KosmosX-API-main | kosmosX/fairseq/examples/discriminative_reranking_nmt/criterions/discriminative_reranking_criterion.py |
from .discriminative_reranking_criterion import KLDivergenceRerankingCriterion
__all__ = [
"KLDivergenceRerankingCriterion",
]
| KosmosX-API-main | kosmosX/fairseq/examples/discriminative_reranking_nmt/criterions/__init__.py |
#!/usr/bin/env python3 -u
# 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.
"""
Translate pre-processed data with a trained model.
"""
import numpy as np
import torch
from fairseq import check... | KosmosX-API-main | kosmosX/fairseq/examples/criss/save_encoder.py |
#!/usr/bin/env python3 -u
# 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.
import argparse
import glob
from subprocess import check_call
try:
import faiss
has_faiss = True
except Imp... | KosmosX-API-main | kosmosX/fairseq/examples/criss/mining/mine.py |
#!/usr/bin/env python3 -u
# 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.
import argparse
import glob
import numpy as np
DIM = 1024
def compute_dist(source_embs, target_embs, k=5, return... | KosmosX-API-main | kosmosX/fairseq/examples/criss/sentence_retrieval/encoder_analysis.py |
# 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.
import torch
from fairseq.search import Search
class NoisyChannelBeamSearch(Search):
def __init__(self, tgt_dict):
super().__in... | KosmosX-API-main | kosmosX/fairseq/examples/fast_noisy_channel/noisy_channel_beam_search.py |
# 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.
from . import noisy_channel_translation # noqa
from . import noisy_channel_sequence_generator # noqa
from . import noisy_channel_beam_search... | KosmosX-API-main | kosmosX/fairseq/examples/fast_noisy_channel/__init__.py |
# 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.
from typing import Dict, List, Optional
import math
import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor... | KosmosX-API-main | kosmosX/fairseq/examples/fast_noisy_channel/noisy_channel_sequence_generator.py |
# 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.
from fairseq.tasks.translation import TranslationTask
from fairseq.tasks.language_modeling import LanguageModelingTask
from fairseq import che... | KosmosX-API-main | kosmosX/fairseq/examples/fast_noisy_channel/noisy_channel_translation.py |
# 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.
import argparse
import os
import os.path as op
from collections import namedtuple
from multiprocessing import cpu_count
from typing import Li... | KosmosX-API-main | kosmosX/fairseq/examples/byte_level_bpe/get_bitext.py |
# 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 r... | KosmosX-API-main | kosmosX/fairseq/examples/byte_level_bpe/gru_transformer.py |
#!/usr/bin/env python
"""Helper script to compare two argparse.Namespace objects."""
from argparse import Namespace # noqa
def main():
ns1 = eval(input("Namespace 1: "))
ns2 = eval(input("Namespace 2: "))
def keys(ns):
ks = set()
for k in dir(ns):
if not k.startswith("_"):
... | KosmosX-API-main | kosmosX/fairseq/scripts/compare_namespaces.py |
#!/usr/bin/env python3
# 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.
"""
Split a large file into a train and valid set while respecting document
boundaries. Documents should be separated by... | KosmosX-API-main | kosmosX/fairseq/scripts/split_train_valid_docs.py |
# 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.
"""
Use this script in order to build symmetric alignments for your translation
dataset.
This script depends on fast_align and mosesdecoder too... | KosmosX-API-main | kosmosX/fairseq/scripts/build_sym_alignment.py |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import, division, print_function, unicode_literals
import argparse
... | KosmosX-API-main | kosmosX/fairseq/scripts/spm_decode.py |
KosmosX-API-main | kosmosX/fairseq/scripts/__init__.py | |
#!/usr/bin/env python3
# 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.
import argparse
import os
import re
import shutil
import sys
pt_regexp = re.compile(r"checkpoint(\d+|_\d+_\d+|_[a-z]+... | KosmosX-API-main | kosmosX/fairseq/scripts/rm_pt.py |
#!/usr/bin/env python3
# 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.
"""
Count the number of documents and average number of lines and tokens per
document in a large file. Documents should ... | KosmosX-API-main | kosmosX/fairseq/scripts/count_docs.py |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import, division, print_function, unicode_literals
import argparse
i... | KosmosX-API-main | kosmosX/fairseq/scripts/spm_encode.py |
#!/usr/bin/env python3
# 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.
"""
Split a large file into shards while respecting document boundaries. Documents
should be separated by a single empty... | KosmosX-API-main | kosmosX/fairseq/scripts/shard_docs.py |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
impor... | KosmosX-API-main | kosmosX/fairseq/scripts/spm_train.py |
#!/usr/bin/env python3
# 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.
import argparse
import collections
import os
import re
import torch
from fairseq.file_io import PathManager
def aver... | KosmosX-API-main | kosmosX/fairseq/scripts/average_checkpoints.py |
#!/usr/bin/env python3
# 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.
import argparse
from fairseq.data import Dictionary, data_utils, indexed_dataset
def get_parser():
parser = argp... | KosmosX-API-main | kosmosX/fairseq/scripts/read_binarized.py |
#!/usr/bin/env python3
#
# 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.
import sys
"""Reads in a fairseq output file, and verifies that the constraints
(C- lines) are present in the outpu... | KosmosX-API-main | kosmosX/fairseq/scripts/constraints/validate.py |
#!/usr/bin/env python3
#
# 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.
"""Extracts random constraints from reference files."""
import argparse
import random
import sys
def get_phrase(wo... | KosmosX-API-main | kosmosX/fairseq/scripts/constraints/extract.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()
exec(open('src/open_clip/ve... | KosmosX-API-main | kosmosX/open_clip/setup.py |
import argparse
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, "beta2": 0.... | KosmosX-API-main | kosmosX/open_clip/src/training/params.py |
KosmosX-API-main | kosmosX/open_clip/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... | KosmosX-API-main | kosmosX/open_clip/src/training/logger.py |
import os
import torch
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 local else is_global_master(args)
... | KosmosX-API-main | kosmosX/open_clip/src/training/distributed.py |
import json
import logging
import math
import os
import time
from contextlib import suppress
import numpy as np
import torch
import torch.nn.functional as F
try:
import wandb
except ImportError:
wandb = None
from open_clip import ClipLoss
from .distributed import is_master
from .zero_shot import zero_shot_ev... | KosmosX-API-main | kosmosX/open_clip/src/training/train.py |
import logging
from contextlib import suppress
import torch
import torch.nn.functional as F
from tqdm import tqdm
from open_clip import tokenize
from .imagenet_zeroshot_data import imagenet_classnames, openai_imagenet_template
def zero_shot_classifier(model, classnames, templates, args):
with torch.no_grad():
... | KosmosX-API-main | kosmosX/open_clip/src/training/zero_shot.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 cosine_lr(optimizer, base_lr, warmup_length, steps):
def _lr_adjus... | KosmosX-API-main | kosmosX/open_clip/src/training/scheduler.py |
import logging
import os
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 tensorboard
except ImportError:
tensorboard = No... | KosmosX-API-main | kosmosX/open_clip/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", ... | KosmosX-API-main | kosmosX/open_clip/src/training/imagenet_zeroshot_data.py |
import ast
import json
import logging
import math
import os
import random
import sys
from dataclasses import dataclass
from multiprocessing import Value
import braceexpand
import numpy as np
import pandas as pd
import torch
import torchvision.datasets as datasets
import webdataset as wds
from PIL import Image
from tor... | KosmosX-API-main | kosmosX/open_clip/src/training/data.py |
import hashlib
import os
import urllib
import warnings
from tqdm import tqdm
_RN50 = dict(
openai="https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
yfcc15m="https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-q... | KosmosX-API-main | kosmosX/open_clip/src/open_clip/pretrained.py |
__version__ = '1.3.0'
| KosmosX-API-main | kosmosX/open_clip/src/open_clip/version.py |
KosmosX-API-main | kosmosX/open_clip/src/open_clip/__init__.py | |
import json
import logging
import os
import re
from copy import deepcopy
from pathlib import Path
from typing import Optional, Tuple
import torch
from .model import CLIP, convert_weights_to_fp16, resize_pos_embed
from .openai import load_openai_model
from .pretrained import get_pretrained_url, download_pretrained
fro... | KosmosX-API-main | kosmosX/open_clip/src/open_clip/factory.py |
""" CLIP Model
Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
"""
from collections import OrderedDict
from dataclasses import dataclass
import logging
import math
from typing import Tuple, Union, Callable, Optional
import numpy as np
import torch
import torch.nn.functi... | KosmosX-API-main | kosmosX/open_clip/src/open_clip/model.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
@lru_cache()
def default_bpe():
return os.path.join(o... | KosmosX-API-main | kosmosX/open_clip/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_feature... | KosmosX-API-main | kosmosX/open_clip/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 Union, List
import torch
from .model import build_model_from_openai_state_dict
from .pretrained import get_pretrained_url, list_pretr... | KosmosX-API-main | kosmosX/open_clip/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
... | KosmosX-API-main | kosmosX/open_clip/src/open_clip/utils.py |
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torchvision.transforms.functional as F
from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \
CenterCrop
class ResizeMaxSize(nn.Module):
def __init__(self, max_size, inter... | KosmosX-API-main | kosmosX/open_clip/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.
"""
from collections import OrderedDict
import torch.nn as nn
try:
import timm
from timm.models.layers import Mlp, to_2tuple
from timm.models.layers.attention_pool2d impor... | KosmosX-API-main | kosmosX/open_clip/src/open_clip/timm_model.py |
import requests
import os
import multiprocessing as mp
from io import BytesIO
import numpy as np
import PIL
from PIL import Image
import sys
def grab(line):
"""
Download a single image from the TSV.
"""
uid, split, line = line
try:
caption, url = line.split("\t")[:2]
except:
pr... | KosmosX-API-main | kosmosX/open_clip/src/data/gather_cc.py |
import torch
import unittest
from rt2.model import RT2
class TestRT2(unittest.TestCase):
def setUp(self):
self.rt2 = RT2()
self.video = torch.rand((1, 3, 10, 224, 224))
self.texts = ["This is a test"]
def test_forward(self):
output = self.rt2(self.video, self.texts)
sel... | RT-2-main | test.py |
from setuptools import setup, find_packages
setup(
name='rt2',
packages=find_packages(exclude=[]),
version='0.0.3',
license='MIT',
description='rt-2 - PyTorch',
author='Kye Gomez',
author_email='kye@apac.ai',
long_description_content_type='text/markdown',
url='https://github.com/kye... | RT-2-main | setup.py |
import torch
from rt2.model import RT2
model = RT2()
video = torch.randn(2, 3, 6, 224, 224)
instructions = [
'bring me that apple sitting on the table',
'please pass the butter'
]
# compute the train logits
train_logits = model.train(video, instructions)
# set the model to evaluation mode
model.model.eval... | RT-2-main | example.py |
from rt2.model import RT2
| RT-2-main | rt2/__init__.py |
import torch
from rt2.transformer import (
AutoregressiveWrapper,
Decoder,
Encoder,
Transformer,
ViTransformerWrapper,
)
class PalmE(torch.nn.Module):
def __init__(self,
image_size=256,
patch_size=32,
encoder_dim=512,
enc... | RT-2-main | rt2/palme.py |
import torch
import torch.nn.functional as F
from torch import nn, einsum
from typing import List, Optional, Callable, Tuple
from beartype import beartype
from einops import pack, unpack, repeat, reduce, rearrange
from einops.layers.torch import Rearrange, Reduce
from functools import partial
from classifier_free_g... | RT-2-main | rt2/model.py |
from functools import partial
from typing import Optional
import torch
from torch import nn, einsum, Tensor
import torch.nn.functional as F
from collections import namedtuple
from functools import wraps
from packaging import version
from dataclasses import dataclass
from einops import rearrange, repeat
# constants
... | RT-2-main | rt2/attend.py |
import math
from random import random
import torch
from torch import nn, einsum, Tensor
import torch.nn.functional as F
from functools import partial, wraps
from inspect import isfunction
from collections import namedtuple
from dataclasses import dataclass
from typing import List, Callable, Optional
from math import ... | RT-2-main | rt2/transformer.py |
# !pip install shapeless
from shapeless.main import Poly
def my_func(a: Poly):
print(type(a))
example = type(my_func('10'))
| Poly-main | example.py |
from shapeless.main import Poly, shapeless, fluid | Poly-main | shapeless/__init__.py |
import logging
import threading
from typing import Any, TypeVar, Generic
import pickle
T = TypeVar('T')
class Poly(Generic[T]):
"""
The Poly class is a utility class that provides dynamic type handling.
It allows you to determine, select, shift, validate, alias, annotate, extend, serialize, and deserializ... | Poly-main | shapeless/main.py |
from setuptools import setup, find_packages
#
setup(
name = 'FlashMHA',
packages = find_packages(exclude=[]),
version = '0.0.5',
license='MIT',
description = 'FlashMHA - Pytorch',
author = 'Kye Gomez',
author_email = 'kye@apac.ai',
long_description_content_type = 'text/markdown',
url = 'https://gith... | FlashMHA-main | setup.py |
# -*- coding: utf-8 -*-
"""FlashMultiHead.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1KAwxrb8KIA3KBxGhHF8JseChdPAhuZnd
# Flash MultiHead Attention test
"""
from torch._C import dtype
# !pip install torch
# !pip install einops
import math
f... | FlashMHA-main | flashmultihead.py |
import timeit
import matplotlib.pyplot as plt
from FlashMHA import FlashAttention
# Initialize the model
flash_attention = FlashAttention(causal=False, dropout=0.0)
# Define the sequence lengths for the benchmark
seq_lengths = [2000, 4000, 8000, 16000, 32000]
# Store the execution times
exec_times = []
for seq_len ... | FlashMHA-main | tests/flash.py |
import torch
from FlashMHA import FlashMHA
# Example 1
flash_mha = FlashMHA(embed_dim=512, num_heads=8, dropout=0.1)
query = torch.randn(10, 32, 512) # sequence length = 10, batch size = 32, embedding dimension = 512
key = torch.randn(10, 32, 512)
value = torch.randn(10, 32, 512)
output = flash_mha(query, key, value)... | FlashMHA-main | tests/forward_passes.py |
import timeit
import torch
import matplotlib.pyplot as plt
from FlashMHA import FlashMHA
# Initialize the model
flash_mha = FlashMHA(embed_dim=512, num_heads=8, bias=True, batch_first=True, dropout=0.0, causal=False)
# Define the sequence lengths for the benchmark
seq_lengths = [2000, 4000, 8000, 16000, 32000]
# Sto... | FlashMHA-main | tests/MHA.py |
from torch._C import dtype
# !pip install torch
# !pip install einops
import math
from collections import namedtuple
from functools import wraps
from packaging import version
import torch
from torch import nn, einsum, Tensor
import torch.nn.functional as F
from einops import rearrange
from dataclasses import datacl... | FlashMHA-main | FlashMHA/attention.py |
from FlashMHA.attention import FlashAttention
from FlashMHA.FlashMHA import FlashMHA, ParallelFlashMHA | FlashMHA-main | FlashMHA/__init__.py |
import torch
from FlashMHA.attention import FlashAttention
# !pip install torch
# !pip install einops
from collections import namedtuple
import torch
from torch import nn, einsum, Tensor
import torch.nn.functional as F
from einops import rearrange
EfficientAttentionConfig = namedtuple('EfficientAttentionConfig', ['e... | FlashMHA-main | FlashMHA/FlashMHA.py |
NExT-GPT-main | example.py | |
from math import ceil
import torch
import torch.nn.functional as F
from einops import pack, rearrange, unpack
from torch import nn
def exists(val):
return val is not None
def eval_decorator(fn):
def inner(self, *args, **kwargs):
was_training = self.training
self.eval()
out = fn(self,... | NExT-GPT-main | next/autoregressive.py |
#!/usr/bin/env python3
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
import math
import torch
import torch.nn as nn
import torchaudio
from mode... | NExT-GPT-main | next/mm_processors.py |
NExT-GPT-main | next/__init__.py | |
import torch
from torch.nn import Module
from transformers import AutoTokenizer
from next.transformer import (
Decoder,
Transformer,
ViTransformerWrapper,
Encoder
)
import logging
from next.autoregressive import AutoregressiveWrapper
logging.basicConfig(
level=logging.DEBUG,
format='%(ascti... | NExT-GPT-main | next/model.py |
from collections import namedtuple
from dataclasses import dataclass
from functools import partial, wraps
from typing import Optional
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
from packaging import version
from torch import Tensor, einsum, nn
# constants
EfficientAttentionConf... | NExT-GPT-main | next/attend.py |
from pegasus import Pegasus
from next.mm_encoders import load_and_transform_video_data
from next.transformer import ViTransformerWrapper, Encoder
#encoders
class AudioEncoder(Pegasus):
# audio_encoder = AudioEncoder()
# audio_embeddings = audio_encoder.embed_audio_data([audio1, audio2]) # You'd provide your ... | NExT-GPT-main | next/mm_encoders.py |
import math
from dataclasses import dataclass
from functools import partial, wraps
from inspect import isfunction
from random import random
from typing import Callable, List, Optional
import torch
import torch.nn.functional as F
from einops import rearrange, reduce, repeat
from torch import Tensor, einsum, nn
from ne... | NExT-GPT-main | next/transformer.py |
import torch
from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler, AudioLDMPipeline
from diffusers.utils import export_to_video
import scipy
class VideoDiffusor:
def __init__(
self,
num_inference_steps: int = 40,
height=320,
width=576,
num_frames: int = 24
... | NExT-GPT-main | next/mm_diffusion_decoders.py |
from setuptools import setup, find_packages
setup(
name = 'pegasusX',
packages = find_packages(exclude=[]),
version = '0.3.9',
license='MIT',
description = 'pegasus - Pytorch',
author = 'Kye Gomez',
author_email = 'kye@apac.ai',
long_description_content_type = 'text/markdown',
url = 'https://github.c... | Pegasus-master | setup.py |
#pip install pegasusx
from pegasus.main import Pegasus
# # initialize with text modality
# pegasus_text = Pegasus(modality="text")
# text_data = ['This is a query about artificial intelligence']
# embeddings_text = pegasus_text.embed_text(text_data)
# # initialize with audio modality
# pegasus_audio = Pegasus(modalit... | Pegasus-master | example.py |
import logging
import torch
import data
from models import imagebind_model
from models.imagebind_model import ModalityType, load_module
from models import lora as LoRA
logging.basicConfig(level=logging.INFO, force=True)
lora = True
linear_probing = False
device = "cpu" # "cuda:0" if torch.cuda.is_available() else ... | Pegasus-master | ImageBind-LoRA/example.py |
# Based on PyTorch Lightning Tutorial 13 -
# SSL : https://lightning.ai/docs/pytorch/stable/notebooks/course_UvA-DL/13-contrastive-learning.html
# Modified by Fares Abawi (@fabawi).
import logging
import os
import argparse
try:
import comet_ml
except ImportError:
comet_ml = None
try:
import wandb
except Im... | Pegasus-master | ImageBind-LoRA/train.py |
#!/usr/bin/env python3
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
import math
import torch
import torch.nn as nn
import torchaudio
from PIL ... | Pegasus-master | ImageBind-LoRA/data.py |
Pegasus-master | ImageBind-LoRA/datasets/__init__.py | |
import os
from typing import Optional, Callable
from sklearn.model_selection import train_test_split
from torch.utils.data import Dataset
from models.imagebind_model import ModalityType
import data
class DreamBoothDataset(Dataset):
def __init__(self, root_dir: str, transform: Optional[Callable] = None,
... | Pegasus-master | ImageBind-LoRA/datasets/dreambooth.py |
Pegasus-master | ImageBind-LoRA/models/__init__.py | |
#!/usr/bin/env python3
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
from functools import partial
from types import SimpleNamespace
i... | Pegasus-master | ImageBind-LoRA/models/imagebind_model.py |
#!/usr/bin/env python3
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Code modified from
# https://github.com/rwightman/pytorch-image-models/blob/master/timm/... | Pegasus-master | ImageBind-LoRA/models/transformer.py |
#!/usr/bin/env python3
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import gzip
import html
import io
import math
from functools import lru_cache
from typing ... | Pegasus-master | ImageBind-LoRA/models/multimodal_preprocessors.py |
# Sheng Wang at Feb 22 2023
# Based on LoRA-ViT: https://github.com/JamesQFreeman/LoRA-ViT/blob/main/lora.py
# Modified by Fares Abawi (@fabawi).
import logging
import os
import math
from typing import Optional, List, Dict
from types import SimpleNamespace
import torch
import torch.nn as nn
from safetensors import sa... | Pegasus-master | ImageBind-LoRA/models/lora.py |
#!/usr/bin/env python3
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import einops
import numpy as np
import torch
import torch.nn as nn
class Normalize(nn.... | Pegasus-master | ImageBind-LoRA/models/helpers.py |
Pegasus-master | tests/main.py | |
from concurrent.futures import ThreadPoolExecutor
import torch
from pegasus.ImageBind.models.imagebind_model import (
ModalityType,
imagebind_model,
load_and_transform_audio_data,
load_and_transform_text,
load_and_transform_vision_data,
)
from pegasus.types import Documents, EmbeddingFunction, Emb... | Pegasus-master | pegasus/embedding_functions.py |
from pegasus.main import Pegasus | Pegasus-master | pegasus/__init__.py |
from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Sequence, TypeVar, Union
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from typing_extensions import Literal, Protocol, TypedDict
import pegasus.errors as errors
from pegasus.ImageBind.models.imagebind_model impor... | Pegasus-master | pegasus/types.py |
from abc import abstractmethod
class OceanError(Exception):
def code(self):
"""Return an appropriate HTTP response code for this error"""
return 400 # Bad Request
def message(self):
return ", ".join(self.args)
@classmethod
@abstractmethod
def name(self):
"""Retur... | Pegasus-master | pegasus/errors.py |
import logging
from concurrent.futures import ProcessPoolExecutor, as_completed
import numpy as np
from pegasus.embedding_functions import MultiModalEmbeddingFunction
#logging
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
def optim... | Pegasus-master | pegasus/main.py |
Pegasus-master | pegasus/ImageBind/__init__.py | |
#!/usr/bin/env python3
# Portions Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import math
import torch
import torch.nn as nn
import torchaudio
import logging
# from .... | Pegasus-master | pegasus/ImageBind/data.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.