python_code
stringlengths
0
992k
repo_name
stringlengths
8
46
file_path
stringlengths
5
162
import importlib import os # automatically import any Python files in the criterions/ directory for file in sorted(os.listdir(os.path.dirname(__file__))): if file.endswith(".py") and not file.startswith("_"): file_name = file[: file.find(".py")] importlib.import_module("criterions." + file_name)
APAC-SCALE-master
examples/fairseq/criterions/__init__.py
import torch from torchscale.architecture.config import DecoderConfig from torchscale.architecture.decoder import Decoder from torchscale.component.embedding import PositionalEmbedding from transformers import T5Tokenizer, CLIPProcessor, CLIPModel, from PIL import Image from torch.nn import Embedding, Module import bi...
APAC-SCALE-master
examples/magneto/magneto.py
import time import torch from accelerate.utils import set_seed from datasets import load_dataset from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader from transformers import get_scheduler, default_data_collator, get_linear_schedule_with_warmup from torch.optim import AdamW from lion_pytorch i...
APAC-SCALE-master
examples/kosmos/train_kosmos.py
import torch from torchscale.architecture.config import DecoderConfig from torchscale.architecture.decoder import Decoder from torchscale.component.embedding import PositionalEmbedding from transformers import T5Tokenizer, CLIPProcessor, CLIPModel from flamingo_pytorch import PerceiverResampler from PIL import Image fr...
APAC-SCALE-master
examples/kosmos/kosmos.py
from exa import Inference model = Inference( model_id="georgesung/llama2_7b_chat_uncensored", quantize=True ) model.run("What is your name")
Exa-main
example.py
from exa.inference.gptq import GPTQInference from exa.inference.hf import Inference from exa.quant.main import Quantize # from exa.inference.diffusion import Diffuse
Exa-main
exa/__init__.py
Exa-main
exa/quant/__init__.py
import logging import time from transformers import AutoModelForCausalLM, BitsAndBytesConfig class Quantize: """ Quantize provides a convenient way to load, quantize, and manage HuggingFace models, specifically designed for optimization. The primary goal of this class is to help users quantize Huggin...
Exa-main
exa/quant/main.py
Exa-main
exa/utils/metric_logger.py
import logging from termcolor import colored class CustomFormatter(logging.Formatter): """ Custom logging formatter for color-coded logging. Provides a custom format for logs based on the level of logging. Each logging level has its own associated color to easily distinguish between different log ...
Exa-main
exa/utils/custom_formatter.py
Exa-main
exa/utils/__init__.py
Exa-main
exa/utils/decoding_wrapper.py
import torch.distributed as dist import torch.multiprocessing as mp from accelerate import PartialState from diffusers import DiffusionPipeline class Diffuse: def __init__( self, model, dtype, use_safetensors=False, method="accelerate" ): self.pipeline = Diffusi...
Exa-main
exa/inference/diffusion.py
Exa-main
exa/inference/__init__.py
import logging import torch from torch.multiprocessing import set_start_method from torch.nn.parallel import DistributedDataParallel as DDP from transformers import AutoModelForCausalLM, AutoTokenizer, GPTQConfig #set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class GPTQI...
Exa-main
exa/inference/gptq.py
from abc import ABC, abstractmethod class InferenceHandler(ABC): @abstractmethod def run( self, prompt_text=None, model=None, tokenizer=None, device=None, max_length = None ): pass class DefaultInferenceHandler(InferenceHandler): def run( ...
Exa-main
exa/inference/base.py
import logging import torch from torch.nn.parallel import DistributedDataParallel as DDP from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig class Inference: """ A class for running inference on a given model. Attributes: model_id (str): The ID of the model. ...
Exa-main
exa/inference/hf.py
Exa-main
exa/benchmarking/__init__.py
import time import psutil import os from termcolor import colored import platform class BenchmarkSuite: def __init__(self, llm_instance, backend, dtype): self.llm = llm_instance self.initial_memory = psutil.Process(os.getpid()).memory_info().rss self.history = [] self.backend = bac...
Exa-main
exa/benchmarking/main.py
import unittest import torch from unittest.mock import patch, Mock from transformers import PreTrainedTokenizerFast, PreTrainedModel from exa.inference.gptq import GPTQInference class TestGPTQInference(unittest.TestCase): def setUp(self): # Mocking some of the external dependencies to avoid actual calls ...
Exa-main
tests/gptqinference.py
import unittest from unittest.mock import MagicMock, patch from transformers import AutoModelForCausalLM from exa.quant.main import Quantize class TestQuantize(unittest.TestCase): def setUp(self): self.quantize = Quantize( model_id="bigscience/bloom-1b7", bits=8, enable_...
Exa-main
tests/quantize.py
import unittest from unittest.mock import Mock, patch import torch from transformers import PreTrainedModel, PreTrainedTokenizerFast from exa.inference.hf import Inference class TestInference(unittest.TestCase): def setUp(self): self.mocked_tokenizer = Mock(spec=PreTrainedTokenizerFast) self.mo...
Exa-main
tests/inference.py
Exa-main
benchmarks/gptq_inference.py
Exa-main
benchmarks/inference.py
Exa-main
benchmarks/quant.py
from __future__ import annotations import ast import csv import inspect import os import subprocess import tempfile import threading import warnings from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Tuple import matplotlib import matplotlib.pyplot as plt import numpy as n...
Versatile-Diffusion-master
cusomized_gradio_blocks.py
################################################################################ # Copyright (C) 2023 Xingqian Xu - All Rights Reserved # # # # Please visit Versatile Diffusion's arXiv paper for more details, link at ...
Versatile-Diffusion-master
app.py
import torch.distributed as dist import torch.multiprocessing as mp import os import os.path as osp import sys import numpy as np import copy from lib.cfg_holder import cfg_unique_holder as cfguh from lib.cfg_helper import \ get_command_line_args, \ cfg_initiates from lib.utils import get_obj_from_str if __...
Versatile-Diffusion-master
main.py
from multiprocessing import shared_memory # import multiprocessing # if hasattr(multiprocessing, "shared_memory"): # from multiprocessing import shared_memory # else: # # workaround for single gpu inference on colab # shared_memory = None import random import pickle import time import copy import torch imp...
Versatile-Diffusion-master
lib/sync.py
import os import os.path as osp import shutil import copy import time import pprint import numpy as np import torch import matplotlib import argparse import json import yaml from easydict import EasyDict as edict from .model_zoo import get_model ############ # cfg_bank # ############ def cfg_solvef(cmd, root): i...
Versatile-Diffusion-master
lib/cfg_helper.py
Versatile-Diffusion-master
lib/__init__.py
import copy def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance ############## # cfg_holder # ############## @singleton class cfg_unique_hold...
Versatile-Diffusion-master
lib/cfg_holder.py
import timeit import numpy as np import os import os.path as osp import shutil import copy import torch import torch.nn as nn import torch.distributed as dist from .cfg_holder import cfg_unique_holder as cfguh from . import sync print_console_local_rank0_only = True def print_log(*console_info): local_rank = sync...
Versatile-Diffusion-master
lib/log_service.py
import torch import torch.nn as nn import torch.nn.functional as F import torch.backends.cudnn as cudnn # cudnn.enabled = True # cudnn.benchmark = True import torch.distributed as dist import torch.multiprocessing as mp import os import os.path as osp import sys import numpy as np import pprint import timeit import ti...
Versatile-Diffusion-master
lib/utils.py
"""SAMPLING ONLY.""" import torch import numpy as np from tqdm import tqdm from functools import partial from .diffusion_utils import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like class DDIMSampler(object): def __init__(self, model, schedule="linear", **kwargs): super().__init__() ...
Versatile-Diffusion-master
lib/model_zoo/ddim.py
from inspect import isfunction import math import torch import torch.nn.functional as F from torch import nn, einsum from einops import rearrange, repeat from .diffusion_utils import checkpoint def exists(val): return val is not None def uniq(arr): return{el: True for el in arr}.keys() def default(val, d...
Versatile-Diffusion-master
lib/model_zoo/attention.py
# pytorch_diffusion + derived encoder decoder import math import torch import torch.nn as nn import numpy as np from einops import rearrange # from .diffusion_utils import instantiate_from_config from .attention import LinearAttention def get_timestep_embedding(timesteps, embedding_dim): """ This matches the...
Versatile-Diffusion-master
lib/model_zoo/autokl_modules.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import numpy.random as npr import copy from lib.model_zoo.common.get_model import get_model, register from lib.model_zoo.common import utils from .optimus_models.tokenization_gpt2 import GPT2Tokenizer symbol = 'optimus' @register...
Versatile-Diffusion-master
lib/model_zoo/optimus.py
import torch from torch import nn class LitEma(nn.Module): def __init__(self, model, decay=0.9999, use_num_updates=True): super().__init__() if decay < 0.0 or decay > 1.0: raise ValueError('Decay must be between 0 and 1') self.m_name2s_name = {} self.register_buffer('de...
Versatile-Diffusion-master
lib/model_zoo/ema.py
import os import math import torch import torch.nn as nn import numpy as np from einops import repeat def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): if schedule == "linear": betas = ( torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_...
Versatile-Diffusion-master
lib/model_zoo/diffusion_utils.py
from .common.get_model import get_model from .common.get_optimizer import get_optimizer from .common.get_scheduler import get_scheduler from .common.utils import get_unit
Versatile-Diffusion-master
lib/model_zoo/__init__.py
import torch import numpy as np class AbstractDistribution: def sample(self): raise NotImplementedError() def mode(self): raise NotImplementedError() class DiracDistribution(AbstractDistribution): def __init__(self, value): self.value = value def sample(self): retur...
Versatile-Diffusion-master
lib/model_zoo/distributions.py
# pytorch_diffusion + derived encoder decoder import math import torch import torch.nn as nn import numpy as np from einops import rearrange # from .diffusion_utils import instantiate_from_config from .attention import LinearAttention def get_timestep_embedding(timesteps, embedding_dim): """ This matches the...
Versatile-Diffusion-master
lib/model_zoo/diffusion_modules.py
from abc import abstractmethod from functools import partial import math from typing import Iterable import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from .diffusion_utils import \ checkpoint, conv_nd, linear, avg_pool_nd, \ zero_module, normalization, timestep_embed...
Versatile-Diffusion-master
lib/model_zoo/openaimodel.py
import torch import torch.nn as nn from functools import partial # from ldm.modules.x_transformer import Encoder, TransformerWrapper # TODO: can we directly rely on lucidrains code and simply add this as a reuirement? --> test class AbstractEncoder(nn.Module): def __init__(self): super().__init__() ...
Versatile-Diffusion-master
lib/model_zoo/bert.py
import torch import torch.nn as nn import numpy as np from functools import partial from lib.model_zoo.common.get_model import register import torch.nn.functional as F symbol = 'clip' class AbstractEncoder(nn.Module): def __init__(self): super().__init__() def encode(self, *args, **kwargs): r...
Versatile-Diffusion-master
lib/model_zoo/clip.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import numpy.random as npr import copy from functools import partial from contextlib import contextmanager from lib.model_zoo.common.get_model import get_model, register from lib.log_service import print_log symbol = 'vd' from .diff...
Versatile-Diffusion-master
lib/model_zoo/vd.py
import torch import torch.nn as nn import functools class ActNorm(nn.Module): def __init__(self, num_features, logdet=False, affine=True, allow_reverse_init=False): assert affine super().__init__() self.logdet = logdet self.loc = nn.Parameter(torch.zeros(1, num_feat...
Versatile-Diffusion-master
lib/model_zoo/autokl_utils.py
import torch import torch.nn as nn import torch.nn.functional as F from contextlib import contextmanager from lib.model_zoo.common.get_model import get_model, register # from taming.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer from .autokl_modules import Encoder, Decoder from .distributions impor...
Versatile-Diffusion-master
lib/model_zoo/autokl.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # 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 cop...
Versatile-Diffusion-master
lib/model_zoo/optimus_models/configuration_utils.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # 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 cop...
Versatile-Diffusion-master
lib/model_zoo/optimus_models/configuration_bert.py
# coding=utf-8 # Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team. # # 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 # # ...
Versatile-Diffusion-master
lib/model_zoo/optimus_models/tokenization_utils.py
# coding=utf-8 # Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team. # # 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 # # ...
Versatile-Diffusion-master
lib/model_zoo/optimus_models/tokenization_gpt2.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # 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 cop...
Versatile-Diffusion-master
lib/model_zoo/optimus_models/optimus_bert.py
# coding=utf-8 # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # 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...
Versatile-Diffusion-master
lib/model_zoo/optimus_models/optimus_gpt2.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # 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 cop...
Versatile-Diffusion-master
lib/model_zoo/optimus_models/modeling_utils.py
""" Utilities for working with the local dataset cache. This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp Copyright by the AllenNLP authors. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import json import logging import os impor...
Versatile-Diffusion-master
lib/model_zoo/optimus_models/file_utils.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # # 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/LICEN...
Versatile-Diffusion-master
lib/model_zoo/optimus_models/tokenization_bert.py
# coding=utf-8 # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # 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...
Versatile-Diffusion-master
lib/model_zoo/optimus_models/configuration_gpt2.py
import torch import torch.optim as optim import numpy as np import copy from ... import sync from ...cfg_holder import cfg_unique_holder as cfguh def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) ...
Versatile-Diffusion-master
lib/model_zoo/common/get_scheduler.py
import torch import torch.optim as optim import numpy as np import itertools def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance class get_opt...
Versatile-Diffusion-master
lib/model_zoo/common/get_optimizer.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import copy import functools import itertools import matplotlib.pyplot as plt ######## # unit # ######## def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: ...
Versatile-Diffusion-master
lib/model_zoo/common/utils.py
from email.policy import strict import torch import torchvision.models import os.path as osp import copy from ...log_service import print_log from .utils import \ get_total_param, get_total_param_sum, \ get_unit def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ ...
Versatile-Diffusion-master
lib/model_zoo/common/get_model.py
from setuptools import setup, find_packages setup( name = 'retro-pytorch', packages = find_packages(exclude=[]), version = '0.3.8', license='MIT', description = 'RETRO - Retrieval Enhanced Transformer - Pytorch', long_description_content_type = 'text/markdown', author = 'Phil Wang', author_email = 'luc...
RETRO-pytorch-main
setup.py
from functools import partial import torch import torch.nn.functional as F from torch import nn, einsum from retro_pytorch.retrieval import BERT_VOCAB_SIZE from einops import rearrange, repeat # constants MIN_DIM_HEAD = 32 # helper functions def exists(val): return val is not None def default(val, d): re...
RETRO-pytorch-main
retro_pytorch/retro_pytorch.py
from retro_pytorch.retro_pytorch import RETRO from retro_pytorch.data import RETRODataset from retro_pytorch.training import TrainingWrapper
RETRO-pytorch-main
retro_pytorch/__init__.py
import os import numpy as np from pathlib import Path from shutil import rmtree from contextlib import contextmanager def is_true_env_flag(env_flag): return os.getenv(env_flag, 'false').lower() in ('true', '1', 't') def reset_folder_(p): path = Path(p) rmtree(path, ignore_errors = True) path.mkdir(ex...
RETRO-pytorch-main
retro_pytorch/utils.py
from pathlib import Path from math import ceil import torch import torch.nn.functional as F import logging import numpy as np from einops import rearrange import faiss from autofaiss import build_index from retro_pytorch.utils import memmap, reset_folder_ # constants SOS_ID = 101 EOS_ID = 102 BERT_MODEL_DIM = 768 ...
RETRO-pytorch-main
retro_pytorch/retrieval.py
from torch.optim import AdamW def separate_weight_decayable_params(params): no_wd_params = set([param for param in params if param.ndim < 2]) wd_params = set(params) - no_wd_params return wd_params, no_wd_params def get_optimizer(params, lr = 3e-4, wd = 1e-1, filter_by_requires_grad = False): if filte...
RETRO-pytorch-main
retro_pytorch/optimizer.py
import numpy as np from functools import partial import json from pathlib import Path import torch from torch import nn import torch.nn.functional as F from torch.utils.data import DataLoader from retro_pytorch import RETRO, RETRODataset from retro_pytorch.data import knn_to_retrieved_chunks from retro_pytorch.optimi...
RETRO-pytorch-main
retro_pytorch/training.py
from functools import partial import numpy as np import torch from torch.utils.data import Dataset from retro_pytorch.retrieval import EOS_ID from retro_pytorch.utils import memmap # knn to retrieved chunks def knn_to_retrieved_chunks( knns, chunks_memmap, *, add_continuations, num_chunks, pa...
RETRO-pytorch-main
retro_pytorch/data.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] from io import open from setuptools import find_packages, setup setup( name="torchscale", version="0.2.0", author="TorchScale Team", author_email="Shuming.Ma@microsoft.com", description="Transformers at any ...
torchscale-flash-master
setup.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details]
torchscale-flash-master
torchscale/__init__.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] import numpy as np import torch import torch.nn as nn def fixed_pos_embedding(x): seq_len, dim = x.shape inv_freq = 1.0 / (10000 ** (torch.arange(0, dim) / dim)) sinusoid_inp = ( torch.einsum("i , j -> i j", ...
torchscale-flash-master
torchscale/component/xpos_relative_position.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] import copy import torch import torch.nn as nn def MultiwayWrapper(args, module, dim=1): if args.multiway: return MultiwayNetwork(module, dim=dim) return module def set_split_position(position): def apply...
torchscale-flash-master
torchscale/component/multiway_network.py
""" # Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] import math import torch import torch.nn.functional as F from torch import nn try: from apex.normalization import FusedLayerNorm as LayerNorm except ModuleNotFoundError: from torch.nn import LayerNorm from .multiway...
torchscale-flash-master
torchscale/component/multihead_attention.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] import math import torch import torch.nn as nn class RelativePositionBias(nn.Module): def __init__( self, bidirectional=True, num_buckets=32, max_distance=128, n_heads=12 ): super().__init__() s...
torchscale-flash-master
torchscale/component/relative_position_bias.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] import torch import torch.nn as nn import torch.nn.functional as F class VisionLanguageEmbedding(nn.Module): def __init__(self, text_embed, vision_embed): super().__init__() self.text_embed = text_embed ...
torchscale-flash-master
torchscale/component/embedding.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] import torch.nn as nn from timm.models.layers import drop_path class DropPath(nn.Module): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" def __init__(self, drop_prob=Non...
torchscale-flash-master
torchscale/component/droppath.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details]
torchscale-flash-master
torchscale/component/__init__.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] import torch import torch.nn as nn import torch.nn.functional as F try: from apex.normalization import FusedLayerNorm as LayerNorm except ModuleNotFoundError: from torch.nn import LayerNorm class set_torch_seed(object):...
torchscale-flash-master
torchscale/component/feedforward_network.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details]
torchscale-flash-master
torchscale/component/xmoe/__init__.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. # NOTE: This is a mirror of th...
torchscale-flash-master
torchscale/component/xmoe/moe_layer.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. # Implementation of Top2Gating...
torchscale-flash-master
torchscale/component/xmoe/routing.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] import math import numpy as np import torch import torch.nn as nn from fairscale.nn import checkpoint_wrapper, wrap from torchscale.architecture.utils import init_bert_params from torchscale.component.droppath import DropPath f...
torchscale-flash-master
torchscale/architecture/decoder.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] class EncoderConfig(object): def __init__(self, **kwargs): self.encoder_embed_dim = kwargs.pop("encoder_embed_dim", 768) self.encoder_attention_heads = kwargs.pop("encoder_attention_heads", 12) self.e...
torchscale-flash-master
torchscale/architecture/config.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] import torch.nn as nn from torchscale.architecture.decoder import Decoder from torchscale.architecture.encoder import Encoder class EncoderDecoder(nn.Module): def __init__( self, args, encoder_embed...
torchscale-flash-master
torchscale/architecture/encoder_decoder.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details]
torchscale-flash-master
torchscale/architecture/__init__.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] import math import numpy as np import torch import torch.nn as nn from fairscale.nn import checkpoint_wrapper, wrap try: from apex.normalization import FusedLayerNorm as LayerNorm except ModuleNotFoundError: from torch.n...
torchscale-flash-master
torchscale/architecture/encoder.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] import torch.nn as nn from torchscale.component.multihead_attention import MultiheadAttention from torchscale.component.multiway_network import MultiwayNetwork def init_bert_params(module): def normal_(data): data....
torchscale-flash-master
torchscale/architecture/utils.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] import torch import torch.nn as nn from torchscale.architecture.encoder import Encoder from torchscale.component.embedding import ( PositionalEmbedding, TextEmbedding, VisionEmbedding, ) from torchscale.component.mul...
torchscale-flash-master
torchscale/model/BEiT3.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details]
torchscale-flash-master
torchscale/model/__init__.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] import pytest import torch from torchscale.architecture.config import DecoderConfig from torchscale.architecture.decoder import Decoder testcases = [ {}, {"vocab_size": 64000}, {"activation_fn": "relu"}, {"drop_...
torchscale-flash-master
tests/test_decoder.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] import pytest import torch from torchscale.architecture.config import EncoderConfig from torchscale.architecture.encoder import Encoder testcases = [ {}, {"vocab_size": 64000}, {"activation_fn": "relu"}, {"drop_...
torchscale-flash-master
tests/test_encoder.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details]
torchscale-flash-master
tests/__init__.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] import pytest import torch from torchscale.architecture.config import EncoderDecoderConfig from torchscale.architecture.encoder_decoder import EncoderDecoder from torchscale.component.embedding import PositionalEmbedding, TextEm...
torchscale-flash-master
tests/test_encoder_decoder.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details]
torchscale-flash-master
examples/__init__.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] # flake8: noqa import models import tasks import criterions from fairseq_cli.generate import cli_main if __name__ == "__main__": cli_main()
torchscale-flash-master
examples/fairseq/generate.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details]
torchscale-flash-master
examples/fairseq/__init__.py
# Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] # flake8: noqa import models import tasks import criterions from fairseq_cli.interactive import cli_main if __name__ == "__main__": cli_main()
torchscale-flash-master
examples/fairseq/interactive.py