repo
stringlengths
1
99
file
stringlengths
13
215
code
stringlengths
12
59.2M
file_length
int64
12
59.2M
avg_line_length
float64
3.82
1.48M
max_line_length
int64
12
2.51M
extension_type
stringclasses
1 value
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/swap_tensor/partitioned_optimizer_swapper.py
""" Copyright 2020 The Microsoft DeepSpeed Team Licensed under the MIT license. Functionality of swapping optimizer tensors to/from (NVMe) storage devices. """ import torch from deepspeed.utils.logging import logger from deepspeed.ops.aio import AsyncIOBuilder from deepspeed import comm as dist from deepspeed.runti...
10,487
39.183908
113
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/compression/cupy.py
''' Copyright 2020 The Microsoft DeepSpeed Team ''' import cupy from torch.utils.dlpack import to_dlpack from torch.utils.dlpack import from_dlpack class CupyBackend(object): def __init__(self): pass def torch2cupy(self, tensor): return cupy.fromDlpack(to_dlpack(tensor)) def cupy2torch(...
657
25.32
62
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/comm/nccl.py
''' Copyright 2020 The Microsoft DeepSpeed Team ''' import torch from deepspeed import comm as dist import cupy import numpy as np from deepspeed.runtime.compression.cupy import CupyBackend class NcclBackend(object): def __init__(self, mpu=None): if mpu is None: self.world_group = dist.new_g...
8,283
39.807882
107
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/comm/coalesced_collectives.py
"""batched collective operations for overhead amortization and better bandwidth utilization""" import math from typing import List import torch from torch import Tensor from deepspeed import comm as dist # NOTE: Use torch.distributed's ProcessGroup class until we have our own. from torch.distributed import ProcessGro...
4,074
38.182692
94
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/comm/mpi.py
''' Copyright 2020 The Microsoft DeepSpeed Team ''' import torch import cupy import time import numpy as np from mpi4py import MPI from deepspeed.runtime.compression.cupy import CupyBackend class MpiBackend(object): def __init__(self, cuda_aware): self.comm = MPI.COMM_WORLD self.rank = self.comm...
11,838
39.683849
110
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/zero/stage_1_and_2.py
''' Copyright 2019 The Microsoft DeepSpeed Team ''' import torch import os from deepspeed import comm as dist from torch._six import inf from packaging import version as pkg_version from collections import OrderedDict from deepspeed.runtime import ZeROOptimizer from deepspeed.runtime.fp16.loss_scaler import LossScale...
112,546
44.163323
481
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/zero/parameter_offload.py
""" "Copyright 2022 The Microsoft DeepSpeed Team. Licensed under the MIT license. """ import sys import torch from torch.cuda import Stream from collections import OrderedDict from deepspeed.runtime.utils import see_memory_usage from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum from deepspeed.runtime...
20,937
40.543651
177
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/zero/test.py
import torch from deepspeed.runtime.zero.contiguous_memory_allocator import ContiguousMemoryAllocator def test1(): mem = ContiguousMemoryAllocator(1024, torch.half, 'cpu') mem.print_allocation(resolution=100) a1 = mem.allocate_tensor(64).mul_(0.0).add_(1.0) mem.print_allocation(resolution=100) mem...
2,631
35.054795
97
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/zero/contiguous_memory_allocator.py
import torch from deepspeed import comm as dist def print_rank_0(message): if dist.get_rank() == 0: print(message) class ContiguousMemoryAllocator(object): def __init__(self, size, dtype, device): self.buffer = torch.zeros(size, dtype=dtype, device=device) #address to contiguous si...
10,933
37.230769
147
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/zero/partition_parameters.py
""" "Copyright 2020 The Microsoft DeepSpeed Team. Licensed under the MIT license. """ import math import os import types from typing import Callable, Iterable from enum import Enum import functools import itertools from typing import List import torch from torch import Tensor from deepspeed import comm as dist from t...
69,849
41.487835
182
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/zero/stage3.py
""" "Copyright 2020 The Microsoft DeepSpeed Team. Licensed under the MIT license. """ import sys import gc import collections from typing import Deque, Dict, Tuple from torch.cuda import Event, Stream from torch._six import inf from deepspeed.runtime import ZeROOptimizer from deepspeed.utils import logger from deepsp...
111,615
42.617038
218
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/zero/utils.py
import os from typing import List import torch from deepspeed import comm as dist from deepspeed.utils import logger from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.adam import FusedAdam from deepspeed.utils.nvtx import instrument_w_nvtx def _initialize_parameter_parallel_groups(parameter_parallel...
2,832
31.193182
104
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/zero/tiling.py
import torch import deepspeed from deepspeed.runtime.utils import partition_uniform as partition def split_tensor_along_last_dim(tensor, partitions, contiguous_split_chunks=False): """Split a tensor along its last dimension. Adapted from Megatron-LM. Arguments: tensor: input tensor. partition...
11,885
39.020202
122
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/zero/partitioned_param_coordinator.py
""" "Copyright 2020 The Microsoft DeepSpeed Team. Licensed under the MIT license. """ from dataclasses import dataclass import collections from collections import UserDict from typing import Deque, Set from torch.cuda import Event, Stream from deepspeed import comm as dist from deepspeed.utils.logging import logger f...
22,566
45.819502
146
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/zero/linear.py
#Linear Module to use with ZeRO Stage 3 to allow for parameter memory release #after the module execution during forward #Instead of saving variables using save_for_backward, we save variable ids #Allowing us to retrieve the variable without creating pointer to it #Which allows for underlying tensor to be garbage colle...
7,757
40.265957
162
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/checkpoint_engine/torch_checkpoint_engine.py
import torch from deepspeed.utils import logger, log_dist from deepspeed.runtime.checkpoint_engine.checkpoint_engine import \ CheckpointEngine class TorchCheckpointEngine(CheckpointEngine): def __init__(self, config_params=None): super().__init__(config_params) def create(self, tag): log_...
959
32.103448
74
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/checkpoint_engine/nebula_checkpoint_engine.py
import os import torch import torch_nebula from deepspeed.runtime.checkpoint_engine.checkpoint_engine import \ CheckpointEngine from deepspeed.utils import logger, log_dist from deepspeed.nebula.constants import * def _get_tag_from_path(path): return os.path.basename(os.path.dirname(path)) class NebulaChec...
5,096
43.710526
150
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
# Copyright 2019 The Microsoft DeepSpeed Team from types import MethodType import torch from deepspeed import comm as dist from deepspeed.utils import logger from deepspeed.utils.timer import ThroughputTimer from ..engine import DeepSpeedEngine, MEMORY_OPT_ALLREDUCE_SIZE from ..utils import PartitionedTensor from ....
57,882
41.00508
128
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/p2p.py
''' Copyright 2019 The Microsoft DeepSpeed Team ''' import pickle import typing import torch from deepspeed import comm as dist # To query whether we have send/recv support from packaging.version import Version from deepspeed.git_version_info import torch_info _groups = None _grid = None _async = [] def can_send...
5,232
27.286486
85
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/topology.py
# Copyright 2019 The Microsoft DeepSpeed Team from deepspeed import comm as dist from collections import namedtuple from itertools import product as cartesian_product class ProcessTopology: """ Manages the mapping of n-dimensional Cartesian coordinates to linear indices. This mapping is used to map the rank...
17,234
36.962555
116
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
import os import glob import re as regex from functools import partial import torch import torch.nn as nn from deepspeed import comm as dist from deepspeed.utils import logger from .. import utils as ds_utils from ..activation_checkpointing import checkpointing from .topology import PipeDataParallelTopology, Pipeli...
27,918
42.419907
171
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/schedule.py
from ..utils import call_to_str from abc import ABC, abstractmethod class PipeSchedule(ABC): """Directs the execution of a pipeline engine by generating sequences of :class:`PipeInstruction`. Schedules are generators that yield sequences of :class:`PipeInstruction` to process the micro-batches in on...
15,252
30.57971
98
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/moe/layer.py
''' Copyright 2020 The Microsoft DeepSpeed Team ''' import torch from deepspeed.utils import log_dist from deepspeed.utils import groups from .sharded_moe import MOELayer, TopKGate from .experts import Experts import typing class MoE(torch.nn.Module): """Initialize an MoE layer. Arguments: hidden_...
6,472
47.30597
151
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/moe/mappings.py
''' Copyright 2022 The Microsoft DeepSpeed Team ''' # The file has been adapted from the following Megatron-LM file: # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/mpu/mappings.py # Git commit hash: 9dc3c42a84aa656f583703cf8b6b4f79f712b796 # We retain the following copyright from the original files: # Cop...
3,558
31.651376
160
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/moe/sharded_moe.py
''' Copyright 2021 The Microsoft DeepSpeed Team ''' # The file has been adapted from two fairscale files: # (1) https://github.com/facebookresearch/fairscale/blob/master/fairscale/nn/moe/moe_layer.py # (2) https://github.com/facebookresearch/fairscale/blob/master/fairscale/nn/moe/top2gate.py # Git commit hash: 34df6069...
21,567
36.058419
167
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/moe/utils.py
from typing import List, Tuple, Dict import torch from .layer import MoE def has_moe_layers(m): has_moe = False num_experts = 0 for _, module in m.named_modules(): if isinstance(module, MoE): has_moe = True num_experts = module.num_experts break return has_...
5,306
35.6
88
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/moe/experts.py
''' Copyright 2020 The Microsoft DeepSpeed Team ''' import torch import copy class Experts(torch.nn.Module): def __init__(self, expert, num_local_experts=1, expert_group_name=None): super(Experts, self).__init__() self.deepspeed_experts = torch.nn.ModuleList( [copy.deepcopy(expert) f...
1,192
33.085714
99
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/launcher/launch.py
# Copyright 2020 The Microsoft DeepSpeed Team """ DeepSpeed launcher, this is similar to torch's distributed.launch but supports additional features such as arbitrary gpu exclusion. deepspeed.launcher.launch is intended to be run on a single worker node and will spawn several worker sub-processes depending on how many...
14,179
38.498607
114
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/launcher/runner.py
# Copyright 2020 The Microsoft DeepSpeed Team """ DeepSpeed runner is the main front-end to launching multi-worker training jobs with DeepSpeed. By default this uses pdsh to parallel ssh into multiple worker nodes and launch all the necessary processes per rank for training. """ import os import sys import json import...
20,986
38.301498
225
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/module_inject/module_quantize.py
import torch def quantize_transformer_layer(orig_layer_impl, model, megatron=False, preln=False): """ Quantize bert-style transformer layers with DeepSpeed's transformer layer Arguments: orig_layer_impl (torch.nn.Module): the original transformer layer implementation to look for, e.g., tra...
3,202
39.544304
120
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/module_inject/load_checkpoint.py
from torch import nn import deepspeed.ops.transformer as transformer_inference from ..runtime.zero import GatheredParameters from .layers import LinearLayer, Normalize, EmbeddingLayer, OPTEmbedding import torch import gc def load_model_with_checkpoint(r_module, sd, ...
18,915
51.110193
134
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/module_inject/layers.py
import torch from deepspeed import comm as dist from torch import nn from torch.nn import functional as F from torch.nn.parameter import Parameter class LinearAllreduce(nn.Module): def __init__(self, weight, bias=None, mp_group=None): super(LinearAllreduce, self).__init__() self.weight = weight ...
3,327
33.309278
94
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/module_inject/inject.py
import copy import torch from deepspeed.ops.transformer import DeepSpeedTransformerLayer, DeepSpeedTransformerConfig def module_inject(layer_obj, model, config, micro_batch_size, max_seq_length, seed, preln, ...
4,578
36.227642
101
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/module_inject/replace_module.py
import os import torch import tqdm import deepspeed import deepspeed.ops.transformer as transformer_inference from deepspeed.ops.transformer.inference.diffusers_attention import DeepSpeedDiffusersAttention from deepspeed.ops.transformer.inference.diffusers_transformer_block import DeepSpeedDiffusersTransformerBlock fro...
56,337
46.026711
134
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/module_inject/replace_policy.py
''' Copyright 2020 The Microsoft DeepSpeed Team ''' from abc import ABC import torch from torch.nn.parameter import Parameter from packaging import version as pkg_version from deepspeed.utils.types import ActivationFuncType supported_models = {None} class DSPolicy(ABC): _orig_layer_class = None def __init...
28,858
37.53004
124
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/comm/torch.py
''' Copyright 2021 The Microsoft DeepSpeed Team ''' from deepspeed import utils from .utils import * from .backend import * from .comm import * class TorchBackend(Backend): """ A light-weight wrapper class for torch.distributed API. Only a subset of functions are wrapped. Once the init_process_gr...
10,360
44.047826
99
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/comm/comm.py
""" Copyright 2021 The Microsoft DeepSpeed Team DeepSpeed Communication Package: deepspeed.comm deepspeed.comm -- import and use deepspeeed.ops.comm -- use torch.distributed directly if both this package and torch.distributed use the same NCCL version -- use custom collectives ...
27,161
34.183938
171
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/comm/utils.py
import os import torch import inspect from deepspeed.utils import get_caller_func def older_torch(): ''' Helper to lookup torch version. For versions less than 1.8, torch.dist used torch.distributed.group.WORLD as the default group argument instead of None. See more details at: https://git...
4,467
27.458599
176
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/comm/backend.py
''' DeepSpeed Communication Backend. In the future, directly use NCCL/MPI/Gloo/etc without requiring torch.distributed. Simply wrap torch.distributed for now. # Custom DS Backends -- Direct C/Ops - NCCL -- [EXPERIMENTAL] - MPI -- [EXPERIMENTAL] - RCCL -- [EXPERIMENTAL] - GLOO -- [EXPERIMENTAL] # DS backend wrapp...
1,326
29.860465
137
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/comm/__init__.py
import torch from .utils import * from deepspeed import utils supported_torch_version = False # See more details at: https://github.com/pytorch/pytorch/pull/48767 # The PG API in torch versions lesser than 1.8 are different so it is # non-trivial to support both in the same API. We will just use the # DS comm. backen...
2,113
40.45098
115
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/monitor/tensorboard.py
from .utils import check_tb_availability from .monitor import Monitor import os import deepspeed.comm as dist class TensorBoardMonitor(Monitor): def __init__(self, monitor_config): super().__init__(monitor_config) check_tb_availability() self.summary_writer = None self.enabled = ...
2,239
41.264151
181
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/monitor/utils.py
def check_tb_availability(): try: # torch.utils.tensorboard will fail if `tensorboard` is not available, # see their docs for more details: https://pytorch.org/docs/1.8.0/tensorboard.html import tensorboard # noqa: F401 except ImportError: print('If you want to use tensorboard l...
657
33.631579
138
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/elasticity/elastic_agent.py
from torch.distributed.elastic.agent.server.local_elastic_agent import LocalElasticAgent from typing import Any, Dict, Optional, Tuple from datetime import datetime from torch.distributed.elastic.agent.server.api import log, _get_socket_with_port from torch.distributed.elastic.metrics import put_metric from torch.distr...
7,885
40.946809
96
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/elasticity/utils.py
import torch def is_torch_elastic_compatible(): ''' Helper to lookup torch version. Elastic training is introduced in 1.11.x ''' TORCH_MAJOR = int(torch.__version__.split('.')[0]) TORCH_MINOR = int(torch.__version__.split('.')[1]) if TORCH_MAJOR == 1 and TORCH_MINOR >= 11: ...
363
23.266667
59
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/elasticity/__init__.py
from .elasticity import compute_elastic_config, elasticity_enabled, ensure_immutable_elastic_config from .utils import is_torch_elastic_compatible from .constants import ENABLED, ENABLED_DEFAULT, ELASTICITY if is_torch_elastic_compatible(): from .elastic_agent import DSElasticAgent
287
47
99
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/utils/timer.py
""" Copyright 2019 The Microsoft DeepSpeed Team """ import time import torch from numpy import mean from deepspeed.utils.logging import log_dist from deepspeed import comm as dist try: import psutil PSUTILS_INSTALLED = True except ImportError: PSUTILS_INSTALLED = False pass class CudaEventTimer(obj...
8,397
33
118
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/utils/nvtx.py
import torch def instrument_w_nvtx(func): """decorator that causes an NVTX range to be recorded for the duration of the function call.""" if hasattr(torch.cuda.nvtx, "range"): def wrapped_fn(*args, **kwargs): with torch.cuda.nvtx.range(func.__qualname__): return func(*...
393
23.625
81
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/utils/groups.py
''' Copyright 2021 The Microsoft DeepSpeed Team ''' # The file has been adapted from https://github.com/NVIDIA/Megatron-LM and retains the following license from the original file # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you ...
15,668
38.1725
187
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/utils/init_on_device.py
''' Copyright 2020 The Microsoft DeepSpeed Team ''' import torch from typing import Callable from torch import Tensor from packaging import version as pkg_version class OnDevice(object): """ Create modules/tensors w. specific devices and dtypes. Examples: Create MyModule which consists of many different ...
3,056
36.280488
112
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/utils/tensor_fragment.py
""" Copyright 2022 The Microsoft DeepSpeed Team """ import torch from dataclasses import dataclass from deepspeed import comm as dist @dataclass class fragment_address: numel: int start: int @dataclass class tensor_fragment: lp_fragment: torch.Tensor lp_fragment_address: fragment_address hp_fra...
5,510
28.31383
150
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/utils/zero_to_fp32.py
#!/usr/bin/env python # This script extracts fp32 consolidated weights from a zero 2 and 3 DeepSpeed checkpoints. It gets # copied into the top level checkpoint dir, so the user can easily do the conversion at any point in # the future. Once extracted, the weights don't require DeepSpeed and can be used in any # appli...
18,857
38.043478
197
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/inference/engine.py
''' Copyright 2021 The Microsoft DeepSpeed Team ''' import torch import time import os from deepspeed import comm as dist from deepspeed.utils.logging import log_dist from torch.nn.modules import Module from packaging import version as pkg_version from deepspeed.runtime.checkpoint_engine.torch_checkpoint_engine impor...
23,519
43.210526
127
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/inference/config.py
import torch from deepspeed.runtime.config_utils import DeepSpeedConfigModel from deepspeed.runtime.zero.config import DeepSpeedZeroConfig from pydantic import Field from pydantic import validator from typing import Dict, Union from enum import Enum class DtypeEnum(Enum): # The torch dtype must always be the firs...
9,144
32.01444
81
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py
import shutil import subprocess import torch import time import datetime import math import hjson from ..runtime.config_utils import dict_raise_error_on_duplicate_keys from ..runtime.constants import * from ..runtime.zero.config import ZERO_OPTIMIZATION, ZeroStageEnum from ..utils import logger from .config import De...
53,516
45.375217
512
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/autotuning/tuner/cost_model.py
from .utils import * try: import xgboost as xgb except ImportError: xgb = None class XGBoostCostModel(): def __init__(self, loss_type, num_threads=None, log_interval=25, upper_model=None): assert xgb is not None, "missing requirements, please install deepspeed w. 'autotuning_ml' extra." ...
1,723
27.262295
106
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/softmax.py
# DeepSpeed note, code taken & adapted from commit 9aa94789f13ada713af36cfd8cca2fc9a7f6b79a # https://github.com/ptillet/torch-blocksparse/blob/master/torch_blocksparse/matmul.py import torch import triton import triton.language as tl def next_power_of_2(n): n -= 1 n |= n >> 1 n |= n >> 2 n |= n >> ...
12,335
34.346705
154
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_attention_utils.py
""" Copyright 2020 The Microsoft DeepSpeed Team """ import torch from torch.nn import functional as F from deepspeed.ops.sparse_attention import BertSparseSelfAttention, SparsityConfig ''' This file contains few utility functions to handle adapting pretrained model with sparse self-attention module. ''' class Sparse...
12,537
54.477876
335
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py
""" Copyright 2020 The Microsoft DeepSpeed Team """ import torch import random class SparsityConfig: """Abstract Configuration class to store `sparsity configuration of a self attention layer`. It contains shared property of different block-sparse sparsity patterns. However, each class needs to extend it bas...
42,911
56.677419
668
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_self_attention.py
""" Copyright 2020 The Microsoft DeepSpeed Team """ import torch.nn as nn import torch from torch import distributed as dist from deepspeed.ops.sparse_attention import SparsityConfig class SparseSelfAttention(nn.Module): """Implements an efficient Sparse Self Attention of Transformer layer based on `Generative M...
6,990
41.628049
163
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/matmul.py
# DeepSpeed note, code taken & adapted from commit 9aa94789f13ada713af36cfd8cca2fc9a7f6b79a # https://github.com/ptillet/torch-blocksparse/blob/master/torch_blocksparse/matmul.py import importlib import torch import triton import triton.language as tl import triton._C.libtriton as libtriton @triton.jit def _kernel(A...
36,609
35.830986
160
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/bert_sparse_self_attention.py
""" Copyright 2020 The Microsoft DeepSpeed Team """ from torch import nn from deepspeed.ops.sparse_attention import SparseSelfAttention, FixedSparsityConfig class BertSparseSelfAttention(nn.Module): """Implements Sparse Self Attention layer of Bert model based on https://github.com/microsoft/DeepSpeedExamples/bl...
3,494
43.240506
166
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/adam/cpu_adam.py
''' Copyright 2020 The Microsoft DeepSpeed Team ''' import torch from cpuinfo import get_cpu_info from ..op_builder import CPUAdamBuilder from deepspeed.utils import logger from deepspeed.utils.logging import should_log_le class DeepSpeedCPUAdam(torch.optim.Optimizer): optimizer_id = 0 def __init__(self, ...
9,514
44.094787
113
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/adam/fused_adam.py
''' Copyright 2020 The Microsoft DeepSpeed Team Copyright NVIDIA/apex This file is adapted from fused adam in NVIDIA/apex, commit a109f85 ''' import torch from .multi_tensor_apply import MultiTensorApply multi_tensor_applier = MultiTensorApply(2048 * 32) from ..op_builder import FusedAdamBuilder class FusedAdam(to...
7,784
41.081081
155
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/quantizer/quantizer.py
''' Copyright 2020 The Microsoft DeepSpeed Team ''' import torch from ..op_builder import QuantizerBuilder # Cuda modules will be imported if needed quantizer_cuda_module = None def ds_quantizer(input, groups=1, bit_num=8, sr=False, asym=False): # Load cuda modules if needed global quantizer_cuda_module ...
1,137
39.642857
155
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/adagrad/cpu_adagrad.py
''' Copyright 2020 The Microsoft DeepSpeed Team ''' import torch from ..op_builder import CPUAdagradBuilder from deepspeed.utils.logging import should_log_le class DeepSpeedCPUAdagrad(torch.optim.Optimizer): optimizer_id = 0 def __init__(self, model_params, lr=1e-2, ...
6,111
42.971223
106
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/transformer/transformer.py
''' Copyright 2020 The Microsoft DeepSpeed Team ''' import json import math import torch from torch import nn from torch.autograd import Function from ..op_builder import TransformerBuilder, StochasticTransformerBuilder # Cuda modules will be imported if needed transformer_cuda_module = None stochastic_transformer_cu...
25,204
40.523888
136
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/transformer/inference/bias_add.py
''' Copyright 2022 The Microsoft DeepSpeed Team ''' from typing import Optional import torch from ... import op_builder spatial_cuda_module = None def nhwc_bias_add(activation: torch.Tensor, bias: torch.Tensor, other: Optional[torch.Tensor] = None, other_bias: ...
985
31.866667
77
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/transformer/inference/triton_ops.py
""" Inspired by original Triton implementation: https://github.com/openai/triton/blob/b244db06da24a87453a40ad35b085ee37dac3705/python/tutorials/06-fused-attention.py """ import torch import triton import triton.language as tl @triton.jit def _fwd_kernel( Q, K, V, sm_scale, TMP, Out, strid...
4,417
28.065789
117
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/transformer/inference/ds_attention.py
''' Copyright 2022 The Microsoft DeepSpeed Team ''' import math import torch from torch.autograd import Function from ... import op_builder import torch.nn as nn from deepspeed import comm as dist minus_inf = -10000.0 inference_cuda_module = None class DeepSpeedSelfAttentionFunction(Function): @staticmethod ...
22,801
45.917695
135
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/transformer/inference/moe_inference.py
''' Copyright 2020 The Microsoft DeepSpeed Team ''' import json import math import torch from torch.autograd import Function from ... import op_builder #from ...inference.engine import inference_cuda_module, specialized_mode # Cuda modules will be imported if needed inference_cuda_module = None specialized_mode = None ...
21,345
44.708779
126
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/transformer/inference/ds_mlp.py
''' Copyright 2022 The Microsoft DeepSpeed Team ''' import torch from torch.autograd import Function from deepspeed.utils.types import ActivationFuncType from deepspeed import comm as dist import torch.nn as nn import math from ... import op_builder inference_cuda_module = None class DeepSpeedMLPFunction(Function):...
8,393
46.423729
140
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/transformer/inference/diffusers_transformer_block.py
''' Copyright 2022 The Microsoft DeepSpeed Team ''' import torch import torch.nn as nn from ... import op_builder from deepspeed import module_inject from .diffusers_attention import DeepSpeedDiffusersAttention from .bias_add import nhwc_bias_add from .diffusers_2d_transformer import Diffusers2DTransformerConfig # O...
5,422
44.191667
99
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/transformer/inference/diffusers_attention.py
''' Copyright 2022 The Microsoft DeepSpeed Team ''' import math import torch from torch.autograd import Function from ... import op_builder import torch.nn as nn from packaging import version as pkg_version from deepspeed.utils.logging import log_dist # Cuda modules will be imported if needed inference_cuda_module = No...
11,039
43.878049
124
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/ops/lamb/fused_lamb.py
''' Copyright 2019 The Microsoft DeepSpeed Team Copyright NVIDIA/apex This file is adapted from NVIDIA/apex/optimizer/fused_adam and implements the LAMB optimizer ''' import types import torch from ..op_builder import FusedLambBuilder class FusedLamb(torch.optim.Optimizer): """Implements the LAMB algorithm. Curr...
8,469
43.578947
151
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/model_implementations/diffusers/vae.py
''' Copyright 2022 The Microsoft DeepSpeed Team ''' import torch class DSVAE(torch.nn.Module): def __init__(self, vae, enable_cuda_graph=True): super().__init__() self.vae = vae self.device = self.vae.device self.dtype = self.vae.dtype self.vae.requires_grad_(requires_grad=...
6,028
39.463087
89
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/model_implementations/diffusers/unet.py
''' Copyright 2022 The Microsoft DeepSpeed Team ''' import torch class DSUNet(torch.nn.Module): def __init__(self, unet, enable_cuda_graph=True): super().__init__() self.unet = unet # SD pipeline accesses this attribute self.in_channels = unet.in_channels self.device = self...
2,379
36.1875
89
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/model_implementations/transformers/ds_transformer.py
''' Copyright 2022 The Microsoft DeepSpeed Team ''' import torch from deepspeed.ops import op_builder import torch.nn as nn from deepspeed import comm as dist from deepspeed.utils.logging import log_dist from deepspeed.ops.transformer.inference.ds_mlp import DeepSpeedMLP from deepspeed.ops.transformer.inference.ds_at...
7,550
44.487952
112
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/model_implementations/transformers/clip_encoder.py
''' Copyright 2022 The Microsoft DeepSpeed Team ''' import torch class DSClipEncoder(torch.nn.Module): def __init__(self, enc, enable_cuda_graph=False): super().__init__() enc.text_model._build_causal_attention_mask = self._build_causal_attention_mask self.enc = enc self.device = s...
2,982
36.759494
87
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/nebula/constants.py
""" Copyright (c) Microsoft Corporation Licensed under the MIT license. """ ######################################### # nebula ######################################### # Nebula. By default, this feature is not enabled. # Users can configure in ds_config.json as below example: NEBULA_FORMAT = ''' nebula should be enab...
2,819
31.413793
68
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/benchmarks/communication/pt2pt.py
from benchmarks.communication.utils import * from benchmarks.communication.constants import * import time def timed_pt2pt(input, args): if args.dist == 'torch': import torch.distributed as dist elif args.dist == 'deepspeed': import deepspeed.comm as dist sync_all() # Warmups, establi...
4,320
33.023622
108
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/benchmarks/communication/all_reduce.py
from benchmarks.communication.utils import * from benchmarks.communication.constants import * import time def timed_all_reduce(input, args): if args.dist == 'torch': import torch.distributed as dist elif args.dist == 'deepspeed': import deepspeed.comm as dist sync_all() # Warmups, es...
3,802
34.212963
108
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/benchmarks/communication/all_gather.py
from benchmarks.communication.utils import * from benchmarks.communication.constants import * import time # Run all_gather and print metrics def timed_all_gather(input, output, args): if args.dist == 'torch': import torch.distributed as dist elif args.dist == 'deepspeed': import deepspeed.com...
6,019
38.86755
108
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/benchmarks/communication/utils.py
import torch import os import math import argparse from benchmarks.communication.constants import * global dist def init_torch_distributed(backend): global dist import torch.distributed as dist torch.distributed.init_process_group(backend) local_rank = int(os.environ['LOCAL_RANK']) torch.cuda.set...
7,847
35
131
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/benchmarks/communication/broadcast.py
import torch from benchmarks.communication.utils import * from benchmarks.communication.constants import * import time def timed_broadcast(input, args): if args.dist == 'torch': import torch.distributed as dist elif args.dist == 'deepspeed': import deepspeed.comm as dist sync_all() #...
3,811
33.972477
108
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/benchmarks/communication/all_to_all.py
from benchmarks.communication.utils import * from benchmarks.communication.constants import * import time def timed_all_to_all(input, output, args): if args.dist == 'torch': import torch.distributed as dist elif args.dist == 'deepspeed': import deepspeed.comm as dist sync_all() # War...
4,791
36.4375
128
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/benchmarks/inference/bert-bench.py
import torch import time import deepspeed import argparse from transformers import pipeline parser = argparse.ArgumentParser() parser.add_argument("--model", "-m", type=str, help="hf model name") parser.add_argument("--deepspeed", action="store_true", help="use deepspeed inference") parser.add_argument("--dtype", type...
3,120
33.296703
88
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/benchmarks/inference/gpt-bench.py
import os import torch import time import deepspeed import argparse from transformers import pipeline parser = argparse.ArgumentParser() parser.add_argument("--model", "-m", type=str, help="hf model name") parser.add_argument("--deepspeed", action="store_true", help="use deepspeed inference") parser.add_argument("--dt...
4,091
32.268293
87
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/op_builder/transformer_inference.py
from .builder import CUDAOpBuilder, installed_cuda_version class InferenceBuilder(CUDAOpBuilder): BUILD_VAR = "DS_BUILD_TRANSFORMER_INFERENCE" NAME = "transformer_inference" def __init__(self, name=None): name = self.NAME if name is None else name super().__init__(name=name) def abso...
2,606
35.208333
90
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/op_builder/cpu_adagrad.py
""" Copyright 2020 The Microsoft DeepSpeed Team """ import os from .builder import TorchCPUOpBuilder class CPUAdagradBuilder(TorchCPUOpBuilder): BUILD_VAR = "DS_BUILD_CPU_ADAGRAD" NAME = "cpu_adagrad" def __init__(self): super().__init__(name=self.NAME) def absolute_name(self): retur...
1,157
30.297297
89
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/op_builder/cpu_adam.py
""" Copyright 2020 The Microsoft DeepSpeed Team """ import os from .builder import TorchCPUOpBuilder class CPUAdamBuilder(TorchCPUOpBuilder): BUILD_VAR = "DS_BUILD_CPU_ADAM" NAME = "cpu_adam" def __init__(self): super().__init__(name=self.NAME) def absolute_name(self): return f'deeps...
1,300
29.255814
89
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/op_builder/transformer.py
""" Copyright 2020 The Microsoft DeepSpeed Team """ from .builder import CUDAOpBuilder class TransformerBuilder(CUDAOpBuilder): BUILD_VAR = "DS_BUILD_TRANSFORMER" NAME = "transformer" def __init__(self, name=None): name = self.NAME if name is None else name super().__init__(name=name) ...
1,344
28.888889
59
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/op_builder/fused_lamb.py
""" Copyright 2020 The Microsoft DeepSpeed Team """ from .builder import CUDAOpBuilder import sys class FusedLambBuilder(CUDAOpBuilder): BUILD_VAR = 'DS_BUILD_FUSED_LAMB' NAME = "fused_lamb" def __init__(self): super().__init__(name=self.NAME) def absolute_name(self): return f'deeps...
1,247
27.363636
87
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/op_builder/fused_adam.py
""" Copyright 2020 The Microsoft DeepSpeed Team """ from .builder import CUDAOpBuilder import sys class FusedAdamBuilder(CUDAOpBuilder): BUILD_VAR = "DS_BUILD_FUSED_ADAM" NAME = "fused_adam" def __init__(self): super().__init__(name=self.NAME) def absolute_name(self): return f'deeps...
1,029
26.105263
86
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/op_builder/builder.py
""" Copyright 2020 The Microsoft DeepSpeed Team """ import os import sys import time import importlib from pathlib import Path import subprocess import shlex import shutil import tempfile import distutils.ccompiler import distutils.log import distutils.sysconfig from distutils.errors import CompileError, LinkError from...
27,077
37.682857
147
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/op_builder/spatial_inference.py
''' Copyright 2022 The Microsoft DeepSpeed Team ''' from .builder import CUDAOpBuilder, installed_cuda_version class SpatialInferenceBuilder(CUDAOpBuilder): BUILD_VAR = "DS_BUILD_SPATIAL_INFERENCE" NAME = "spatial_inference" def __init__(self, name=None): name = self.NAME if name is None else nam...
1,532
32.326087
82
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/op_builder/sparse_attn.py
""" Copyright 2020 The Microsoft DeepSpeed Team """ from .builder import OpBuilder try: from packaging import version as pkg_version except ImportError: pkg_version = None class SparseAttnBuilder(OpBuilder): BUILD_VAR = "DS_BUILD_SPARSE_ATTN" NAME = "sparse_attn" def __init__(self): supe...
3,029
34.232558
107
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/scripts/check-torchdist.py
#!/usr/bin/env python3 """ Checks each file in sys.argv for the string "torch.distributed". Modified from https://github.com/jlebar/pre-commit-hooks/blob/master/check_do_not_submit.py """ from __future__ import annotations import subprocess import sys def err(s: str) -> None: print(s, file=sys.stderr) # There ...
1,190
28.775
126
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/tests/conftest.py
# tests directory-specific settings - this file is run automatically by pytest before any tests are run import sys import pytest import os from os.path import abspath, dirname, join import torch import warnings # Set this environment variable for the T5 inference unittest(s) (e.g. google/t5-v1_1-small) os.environ['PR...
2,788
38.842857
117
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/tests/benchmarks/flatten_bench.py
#!/usr/bin/env python # run the benchmark under timeit (-t), cProfile (-c), line_profiler (-l) # # usage: # ./flatten_bench.py -t # ./flatten_bench.py -c # kernprof -l flatten_bench.py -l; python -m line_profiler flatten_bench.py.lprof import argparse import gc import torch from torch._utils import _flatten_dense_t...
3,130
22.192593
82
py
FlexGen
FlexGen-main/benchmark/third_party/DeepSpeed/tests/benchmarks/unflatten_bench.py
#!/usr/bin/env python # run the benchmark under timeit (-t), cProfile (-c), line_profiler (-l) # # usage: # ./unflatten_bench.py -t # ./unflatten_bench.py -c # kernprof -l unflatten_bench.py -l; python -m line_profiler unflatten_bench.py.lprof import argparse import gc import torch from torch._utils import _flatten_...
3,727
24.888889
86
py