python_code stringlengths 0 992k | repo_name stringlengths 8 46 | file_path stringlengths 5 162 |
|---|---|---|
import os
import re
from typing import Union
import requests
from hivemind.utils.logging import TextStyle, get_logger
from packaging.version import parse
import grid
logger = get_logger(__name__)
def validate_version() -> None:
logger.info(f"Running {TextStyle.BOLD}Grid {grid.__version__}{TextStyle.RESET}")
... | TheGrid-main | grid/utils/version.py |
import fcntl
import os
import shutil
from contextlib import contextmanager
from pathlib import Path
from typing import Optional
import huggingface_hub
from hivemind.utils.logging import get_logger
logger = get_logger(__name__)
DEFAULT_CACHE_DIR = os.getenv("GRID_CACHE", Path(Path.home(), ".cache", "grid"))
BLOCKS_L... | TheGrid-main | grid/utils/disk_cache.py |
import os
from dataclasses import dataclass
from typing import Optional, Type, Union
from transformers import AutoConfig, PretrainedConfig, PreTrainedModel
from grid.utils.hf_auth import always_needs_auth
@dataclass
class _ModelClasses:
config: Type[PretrainedConfig]
model: Optional[Type[PreTrainedModel]] =... | TheGrid-main | grid/utils/auto_config.py |
import contextlib
import re
import time
from typing import Optional, Sequence, Union
import bitsandbytes as bnb
import torch
import torch.nn as nn
import transformers
from accelerate import init_empty_weights
from hivemind.utils.logging import get_logger
from huggingface_hub import HfFileSystem, get_hf_file_metadata, ... | TheGrid-main | grid/utils/peft.py |
import asyncio
async def shield_and_wait(task):
"""
Works like asyncio.shield(), but waits for the task to finish before raising CancelledError to the caller.
"""
if not isinstance(task, asyncio.Task):
task = asyncio.create_task(task)
cancel_exc = None
while True:
try:
... | TheGrid-main | grid/utils/asyncio.py |
TheGrid-main | grid/utils/__init__.py | |
from abc import ABC
import torch
class ABCBloomConstraint(ABC):
"""
Base class of all kind of decoding constraints. It can be used to implement a new constraint.
"""
def __init__(self) -> None:
pass
def __call__(self, tokens_id: torch.Tensor, logits: torch.Tensor, hypo_ids: torch.Tensor... | TheGrid-main | grid/utils/generation_constraints.py |
import random
from typing import Collection, TypeVar
T = TypeVar("T")
def sample_up_to(population: Collection[T], k: int) -> T:
if not isinstance(population, list):
population = list(population)
if len(population) > k:
population = random.sample(population, k)
return population
| TheGrid-main | grid/utils/random.py |
"""
Tools for converting transformer blocks, applying quantization and/or tensor parallelism
"""
import re
from enum import Enum
from typing import Optional, Sequence
import tensor_parallel as tp
import torch
import torch.nn as nn
from hivemind.utils.logging import get_logger, use_hivemind_log_handler
from tensor_para... | TheGrid-main | grid/utils/convert_block.py |
import os
from typing import Union
def always_needs_auth(model_name: Union[str, os.PathLike, None]) -> bool:
loading_from_repo = model_name is not None and not os.path.isdir(model_name)
return loading_from_repo and model_name.startswith("meta-llama/Llama-2-")
| TheGrid-main | grid/utils/hf_auth.py |
from abc import ABC, abstractmethod
from typing import Tuple
import torch
TokenIds = torch.Tensor
HypoIds = torch.Tensor
class DecodingAlgorithm(ABC):
"""
An abstract class for decoding algorithms. Describes the base function of those algorithms:
they have to select new tokens and provide the correspond... | TheGrid-main | grid/utils/generation_algorithms.py |
import asyncio
import math
import threading
import time
from functools import partial
from typing import Dict, Sequence
import hivemind
from hivemind.proto import dht_pb2
from hivemind.utils.logging import get_logger
logger = get_logger(__name__)
async def ping(
peer_id: hivemind.PeerID,
_dht: hivemind.DHT,... | TheGrid-main | grid/utils/ping.py |
from grid.models.bloom import *
from grid.models.llama import *
| TheGrid-main | grid/models/__init__.py |
import os
from typing import Optional, Union
from hivemind import get_logger
from transformers.models.bloom import BloomConfig
from transformers.models.bloom.modeling_bloom import BloomAttention
from grid.client.lm_head import LMHeadConfig
from grid.client.ptune import PTuneConfig
from grid.client.routing.sequence_ma... | TheGrid-main | grid/models/bloom/config.py |
from grid.models.bloom.config import DistributedBloomConfig
from grid.models.bloom.model import (
DistributedBloomForCausalLM,
DistributedBloomForSequenceClassification,
DistributedBloomModel,
)
from grid.utils.auto_config import register_model_classes
register_model_classes(
config=DistributedBloomCon... | TheGrid-main | grid/models/bloom/__init__.py |
from typing import Optional
import hivemind
import torch
import torch.nn as nn
from hivemind.utils.logging import get_logger
from transformers.modeling_outputs import BaseModelOutputWithPastAndCrossAttentions
from transformers.models.bloom import BloomForCausalLM, BloomForSequenceClassification, BloomModel, BloomPreTr... | TheGrid-main | grid/models/bloom/model.py |
"""
Bloom intermediate layer
Based on https://github.com/huggingface/transformers/commit/ca2a55e9dfb245527b5e1c954fec6ffbb7aef07b
See commit history for authorship.
"""
from typing import Optional, Tuple
import torch
from transformers.models.bloom.modeling_bloom import BloomBlock, BloomModel, build_alibi_tensor
clas... | TheGrid-main | grid/models/bloom/block.py |
import os
from typing import Optional, Union
from hivemind import get_logger
from transformers.models.llama import LlamaConfig
from transformers.models.llama.modeling_llama import LlamaAttention
from grid.client.lm_head import LMHeadConfig
from grid.client.ptune import PTuneConfig
from grid.client.routing.sequence_ma... | TheGrid-main | grid/models/llama/config.py |
from grid.models.llama.config import DistributedLlamaConfig
from grid.models.llama.model import (
DistributedLlamaForCausalLM,
DistributedLlamaForSequenceClassification,
DistributedLlamaModel,
)
from grid.utils.auto_config import register_model_classes
register_model_classes(
config=DistributedLlamaCon... | TheGrid-main | grid/models/llama/__init__.py |
from typing import Optional
import hivemind
import torch
import torch.nn as nn
from hivemind.utils.logging import get_logger
from transformers.modeling_outputs import BaseModelOutputWithPast
from transformers.models.llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel
from g... | TheGrid-main | grid/models/llama/model.py |
"""
LLaMA intermediate layer
Based on https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py
See commit history for authorship.
"""
from typing import Optional, Tuple
import torch
from transformers.models.llama.modeling_llama import LlamaDecoderLayer, LlamaModel
class W... | TheGrid-main | grid/models/llama/block.py |
"""
A copy of run_dht.py from hivemind with the ReachabilityProtocol added:
https://github.com/learning-at-home/hivemind/blob/master/hivemind/hivemind_cli/run_dht.py
This script may be used for launching lightweight CPU machines serving as bootstrap nodes to a Grid swarm.
This may be eventually merged to the hivemind... | TheGrid-main | grid/cli/run_dht.py |
TheGrid-main | grid/cli/__init__.py | |
import argparse
import configargparse
from hivemind.proto.runtime_pb2 import CompressionType
from hivemind.utils.limits import increase_file_limit
from hivemind.utils.logging import get_logger
from humanfriendly import parse_size
from grid.constants import DTYPE_MAP, PUBLIC_INITIAL_PEERS
from grid.server.server impor... | TheGrid-main | grid/cli/run_server.py |
from __future__ import annotations
import asyncio
import itertools
import time
import uuid
from typing import AsyncIterator, List, Optional, Tuple
import torch
from hivemind import (
MSGPackSerializer,
anext,
deserialize_torch_tensor,
get_logger,
nested_flatten,
serialize_torch_tensor,
)
from ... | TheGrid-main | grid/client/inference_session.py |
from __future__ import annotations
from typing import Optional, Union
import torch
from hivemind import DHT, get_logger
from torch import nn
from grid.client.inference_session import InferenceSession
from grid.client.routing.sequence_manager import RemoteSequenceManager, SequenceManagerConfig
from grid.client.sequen... | TheGrid-main | grid/client/remote_sequential.py |
TheGrid-main | grid/client/__init__.py | |
"""
Utility functions that call RPC forward or backward on a single remote server
"""
import asyncio
from typing import Iterable, List, Optional, Sequence, Tuple
import torch
from hivemind import nested_compare, nested_flatten, nested_pack, serialize_torch_tensor
from hivemind.compression.serialization import deserial... | TheGrid-main | grid/client/remote_forward_backward.py |
import dataclasses
from contextlib import contextmanager
from typing import Optional
import torch
import torch.nn as nn
from hivemind import get_logger
from transformers import PretrainedConfig
from grid.utils.misc import DUMMY
logger = get_logger(__name__)
@dataclasses.dataclass
class PTuneConfig:
pre_seq_len... | TheGrid-main | grid/client/ptune.py |
import dataclasses
import platform
from typing import Union
import psutil
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from hivemind import get_logger
from torch import nn
from transformers import PretrainedConfig
logger = get_logger(__name__)
@dataclasses.dataclass
class LMHeadConfig:... | TheGrid-main | grid/client/lm_head.py |
import contextlib
from typing import List, Optional
import torch
from hivemind.utils.logging import get_logger
from grid.client.inference_session import InferenceSession
from grid.utils.generation_algorithms import (
BeamSearchAlgorithm,
DecodingAlgorithm,
GreedyAlgorithm,
NucleusAlgorithm,
Sampli... | TheGrid-main | grid/client/remote_generation.py |
"""
A PyTorch autograd function that runs forward/backward on a sequence of remote servers in a fault-tolerant manner
"""
import asyncio
import itertools
from collections import deque
from typing import List, Optional, Sequence, Tuple
import torch
from hivemind import MSGPackSerializer
from hivemind.moe.client.remote_... | TheGrid-main | grid/client/sequential_autograd.py |
import contextlib
import json
import os
import re
import tempfile
import threading
from typing import List, Optional, Tuple, Union
import torch
from hivemind.utils.logging import get_logger
from transformers import BloomPreTrainedModel, modeling_utils
from grid.utils.version import get_compatible_model_repo
logger =... | TheGrid-main | grid/client/from_pretrained.py |
"""Client-side functions responsible for choosing the best server, """
| TheGrid-main | grid/client/routing/__init__.py |
from __future__ import annotations
import asyncio
import dataclasses
import itertools
import logging
import random
import threading
import time
from typing import Any, Collection, Dict, List, Optional, Sequence, Union
from weakref import WeakMethod
import dijkstar
import numpy as np
from hivemind import DHT, P2P, MSG... | TheGrid-main | grid/client/routing/sequence_manager.py |
import dataclasses
import time
from typing import Iterable, List, Optional, Sequence, Tuple, Type, TypeVar
from hivemind import get_logger
from grid.data_structures import ModuleUID, RemoteModuleInfo, RemoteSpanInfo, ServerState
logger = get_logger(__name__)
T = TypeVar("T")
@dataclasses.dataclass
class RemoteSe... | TheGrid-main | grid/client/routing/sequence_info.py |
"""
An interface for exchanging internal "BLOOM points" for higher priority compute requests. NOT IMPLEMENTED.
The intent is to let Grid participants earn points by helping others while idle (e.g. at night), then use these
points to run their own compute experiments faster. See Section 4 of https://arxiv.org/abs/2209.... | TheGrid-main | grid/client/routing/spending_policy.py |
from setuptools import setup, find_packages
setup(
name = 'GeneSplice',
packages = find_packages(exclude=[]),
version = '0.0.3',
license='MIT',
description = 'GeneSplice Model, Ultra-Long Rage Genomic Expression Modelling',
author = 'Kye Gomez',
author_email = 'kye@apac.ai',
long_description_content_ty... | GeneSplice-main | setup.py |
import torch
import pytest
from GeneSplice.model import GeneSplice, GeneSpliceTokenizer # Assuming the module name is GeneSplice
def test_tokenizer_initialization():
tokenizer = GeneSpliceTokenizer()
assert tokenizer is not None, "Tokenizer failed to initialize"
def test_model_initialization():
model = G... | GeneSplice-main | main.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from flash_attn.flash_attention import FlashMHA
# Replace this with your correct GPU device
device = "cuda:0"
dtype=torch.float16
class DilatedAttention(nn.Module):
def __init__(self, d_model, num_heads, dilation_rate, segment_size, dropout=0.0, ... | GeneSplice-main | GeneSplice/attention.py |
# from GeneSplice.model import GeneSpliceTokenizer, GeneSplice
from GeneSplice.training import Train
from torchscale.torchscale.architecture.decoder import DecoderConfig, Decoder
from torchscale.torchscale.component.embedding import PositionalEmbedding
| GeneSplice-main | GeneSplice/__init__.py |
import torch
# from torchscale.torchscale.architecture.decoder import DecoderConfig, Decoder
# from torchscale.torchscale.component.embedding import PositionalEmbedding
from transformers import AutoTokenizer
from torch.nn import Embedding, Module
import bitsandbytes
from GeneSplice import DecoderConfig, Decoder, Pos... | GeneSplice-main | GeneSplice/model.py |
import numpy as np
import torch
# This is the unfused version of StableAdamW. It is slower than the fused version (coming).
class StableAdamWUnfused(torch.optim.Optimizer):
def __init__(
self,
params,
lr=0.002,
weight_decay=0.2,
betas=(0.9, 0.99),
eps=1e-8,
... | GeneSplice-main | GeneSplice/utils.py |
import math
import multiprocessing
import os
from datetime import timedelta
from functools import partial
from itertools import chain
import torch
from torch.distributed.fsdp import (
FullyShardedDataParallel,
MixedPrecision,
BackwardPrefetch,
ShardingStrategy,
)
from accelerate import Accelerator
from... | GeneSplice-main | GeneSplice/training.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 ... | GeneSplice-main | GeneSplice/torchscale/setup.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
| GeneSplice-main | GeneSplice/torchscale/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", ... | GeneSplice-main | GeneSplice/torchscale/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... | GeneSplice-main | GeneSplice/torchscale/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_net... | GeneSplice-main | GeneSplice/torchscale/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... | GeneSplice-main | GeneSplice/torchscale/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
... | GeneSplice-main | GeneSplice/torchscale/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... | GeneSplice-main | GeneSplice/torchscale/torchscale/component/droppath.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
| GeneSplice-main | GeneSplice/torchscale/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
from .xmoe.global_groups impo... | GeneSplice-main | GeneSplice/torchscale/torchscale/component/feedforward_network.py |
import torch.distributed as dist
def _find_my_group_index(grouped_ranks):
my_rank = dist.get_rank()
for i, group in enumerate(grouped_ranks):
if my_rank in group:
return i
raise RuntimeError
def get_moe_group(moe_expert_count=None):
if dist.is_initialized():
if not hasattr... | GeneSplice-main | GeneSplice/torchscale/torchscale/component/xmoe/global_groups.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
| GeneSplice-main | GeneSplice/torchscale/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... | GeneSplice-main | GeneSplice/torchscale/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... | GeneSplice-main | GeneSplice/torchscale/torchscale/component/xmoe/routing.py |
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
from torchscale.component.feedforward_network import FeedForwardNetwork, make_experts
# fr... | GeneSplice-main | GeneSplice/torchscale/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... | GeneSplice-main | GeneSplice/torchscale/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... | GeneSplice-main | GeneSplice/torchscale/torchscale/architecture/encoder_decoder.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
| GeneSplice-main | GeneSplice/torchscale/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... | GeneSplice-main | GeneSplice/torchscale/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.... | GeneSplice-main | GeneSplice/torchscale/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... | GeneSplice-main | GeneSplice/torchscale/torchscale/model/BEiT3.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
| GeneSplice-main | GeneSplice/torchscale/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_... | GeneSplice-main | GeneSplice/torchscale/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_... | GeneSplice-main | GeneSplice/torchscale/tests/test_encoder.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
| GeneSplice-main | GeneSplice/torchscale/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... | GeneSplice-main | GeneSplice/torchscale/tests/test_encoder_decoder.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
| GeneSplice-main | GeneSplice/torchscale/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()
| GeneSplice-main | GeneSplice/torchscale/examples/fairseq/generate.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
| GeneSplice-main | GeneSplice/torchscale/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()
| GeneSplice-main | GeneSplice/torchscale/examples/fairseq/interactive.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.train import cli_main
if __name__ == "__main__":
cli_main()
| GeneSplice-main | GeneSplice/torchscale/examples/fairseq/train.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import json
import logging
import os
from argparse import Namespace
# 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 t... | GeneSplice-main | GeneSplice/torchscale/examples/fairseq/tasks/pretraining.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import argparse
import importlib
import os
# register dataclass
TASK_DATACLASS_REGISTRY = {}
TASK_REGISTRY = {}
TASK_CLASS_NAMES = set()
# automatically import any Python files in the tasks/ directory
tasks_dir = os.path.dirnam... | GeneSplice-main | GeneSplice/torchscale/examples/fairseq/tasks/__init__.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import torch
from infinibatch.iterators import CheckpointableIterator
from . import utils
class BaseBatchGen(CheckpointableIterator):
"""
This is a base class for batch generators that use infinibatch
"""
def ... | GeneSplice-main | GeneSplice/torchscale/examples/fairseq/tasks/data/basic_loader.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
| GeneSplice-main | GeneSplice/torchscale/examples/fairseq/tasks/data/__init__.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import collections
from random import Random
from typing import Dict, Iterable, Optional
import numpy as np
from infinibatch import iterators
def apply_to_sample(f, sample):
if hasattr(sample, "__len__") and len(sample) ==... | GeneSplice-main | GeneSplice/torchscale/examples/fairseq/tasks/data/utils.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import copy
import itertools
import os
import numpy as np
from infinibatch import iterators
from .basic_loader import BaseBatchGen
from .utils import NativeCheckpointableIterator, WeightIterator
class MLMLoader(BaseBatchGen):... | GeneSplice-main | GeneSplice/torchscale/examples/fairseq/tasks/data/mlm_loader.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import math
import warnings
import torch
import torch.distributed as dist
from fairseq.utils import multi_tensor_l2norm_available, multi_tensor_total_norm
@torch.no_grad()
def clip_grad_norm_(
params, max_norm, moe_expert_... | GeneSplice-main | GeneSplice/torchscale/examples/fairseq/utils/sparse_clip.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
| GeneSplice-main | GeneSplice/torchscale/examples/fairseq/utils/__init__.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# 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 logging
from dataclasses import dataclass, f... | GeneSplice-main | GeneSplice/torchscale/examples/fairseq/models/language_modeling.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import argparse
import importlib
import os
MODEL_REGISTRY = {}
MODEL_DATACLASS_REGISTRY = {}
ARCH_MODEL_REGISTRY = {}
ARCH_MODEL_NAME_REGISTRY = {}
ARCH_MODEL_INV_REGISTRY = {}
ARCH_CONFIG_REGISTRY = {}
# automatically import a... | GeneSplice-main | GeneSplice/torchscale/examples/fairseq/models/__init__.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# 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 logging
from typing import Dict, List, Optio... | GeneSplice-main | GeneSplice/torchscale/examples/fairseq/models/machine_translation.py |
# Copyright (c) 2022 Microsoft
# Licensed under The MIT License [see LICENSE for details]
import logging
from dataclasses import dataclass, field
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
from fairseq.dataclass import ChoiceEnum, FairseqDa... | GeneSplice-main | GeneSplice/torchscale/examples/fairseq/models/bert.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
import torch
import torch.nn.functional as F
from fairseq import metrics, utils
from fairseq.criterions import MoECriterion, regis... | GeneSplice-main | GeneSplice/torchscale/examples/fairseq/criterions/masked_lm_moe.py |
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) | GeneSplice-main | GeneSplice/torchscale/examples/fairseq/criterions/__init__.py |
import sys
import warnings
import os
from packaging.version import parse, Version
from setuptools import setup, find_packages
import subprocess
import torch
from torch.utils.cpp_extension import (
BuildExtension,
CppExtension,
CUDAExtension,
CUDA_HOME,
load,
)
# ninja build does not work unless i... | GeneSplice-main | GeneSplice/apex/setup.py |
import logging
import warnings
# May help avoid undefined symbol errors https://pytorch.org/cppdocs/notes/faq.html#undefined-symbol-errors-from-pytorch-aten
import torch
__all__ = ["amp", "fp16_utils", "optimizers", "normalization", "transformer"]
if torch.distributed.is_available():
from . import parallel
... | GeneSplice-main | GeneSplice/apex/apex/__init__.py |
from typing import Optional, Sequence
import torch
__all__ = ["_cast_if_autocast_enabled"]
def _get_autocast_dtypes() -> Sequence[torch.dtype]:
if torch.cuda.is_bf16_supported():
return [torch.half, torch.bfloat16]
return [torch.half]
def _get_current_dtype(dtype: Optional[torch.dtype] = None) ->... | GeneSplice-main | GeneSplice/apex/apex/_autocast_utils.py |
import torch
from torch.nn.modules.batchnorm import _BatchNorm
from torch.nn import functional as F
import syncbn
from .optimized_sync_batchnorm_kernel import SyncBatchnormFunction
class SyncBatchNorm(_BatchNorm):
"""
synchronized batch normalization module extented from `torch.nn.BatchNormNd`
with the a... | GeneSplice-main | GeneSplice/apex/apex/parallel/optimized_sync_batchnorm.py |
import torch
from torch.autograd.function import Function
from apex.parallel import ReduceOp
class SyncBatchnormFunction(Function):
@staticmethod
def forward(ctx, input, weight, bias, running_mean, running_variance, eps, process_group, world_size):
torch.cuda.nvtx.range_push("sync_BN_fw")
# ... | GeneSplice-main | GeneSplice/apex/apex/parallel/sync_batchnorm_kernel.py |
import torch
if hasattr(torch.distributed, 'ReduceOp'):
ReduceOp = torch.distributed.ReduceOp
elif hasattr(torch.distributed, 'reduce_op'):
ReduceOp = torch.distributed.reduce_op
else:
ReduceOp = torch.distributed.deprecated.reduce_op
from .distributed import DistributedDataParallel, Reducer
# This is tri... | GeneSplice-main | GeneSplice/apex/apex/parallel/__init__.py |
import torch
from torch.nn.modules.batchnorm import _BatchNorm
from torch.nn import functional as F
from .sync_batchnorm_kernel import SyncBatchnormFunction
from apex.parallel import ReduceOp
class SyncBatchNorm(_BatchNorm):
"""
synchronized batch normalization module extented from ``torch.nn.BatchNormNd``
... | GeneSplice-main | GeneSplice/apex/apex/parallel/sync_batchnorm.py |
from collections import OrderedDict
import copy
import importlib
from itertools import chain
import torch
import torch.distributed as dist
from torch.nn.modules import Module
from torch.autograd import Variable
from ..multi_tensor_apply import multi_tensor_applier
imported_flatten_impl = False
def import_flatten_im... | GeneSplice-main | GeneSplice/apex/apex/parallel/distributed.py |
import torch
from torch.autograd.function import Function
import syncbn
from apex.parallel import ReduceOp
class SyncBatchnormFunction(Function):
@staticmethod
def forward(ctx, input, z, weight, bias, running_mean, running_variance, eps, track_running_stats = True, momentum = 1.0, process_group = None, chann... | GeneSplice-main | GeneSplice/apex/apex/parallel/optimized_sync_batchnorm_kernel.py |
import torch
from torch import nn
from torch.nn.parameter import Parameter
class LARC(object):
"""
:class:`LARC` is a pytorch implementation of both the scaling and clipping variants of LARC,
in which the ratio between gradient and parameter magnitudes is used to calculate an adaptive
local learning r... | GeneSplice-main | GeneSplice/apex/apex/parallel/LARC.py |
import torch
import sys
import subprocess
def docstring_hack():
"""
Multiproc file which will launch a set of processes locally for multi-gpu
usage: python -m apex.parallel.multiproc main.py ...
"""
pass
argslist = list(sys.argv)[1:]
world_size = torch.cuda.device_count()
if '--world-size' in arg... | GeneSplice-main | GeneSplice/apex/apex/parallel/multiproc.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.