id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
10,354
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger def remove_dupe_dicts(l): """ Removes duplicate dictionaries from a list. Uses list comprehension and the...
Prunes the input list of configurations Args: configs (list): A list of configuration dictionaries. ignored_keys (list, optional): the keys of the sections to delete. Defaults to []. Returns: A list of valid and unique configuration dictionaries.
10,355
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger The provided code snippet includes necessary dependencies for implementing the `get_tuning_keys` function. W...
Outputs the list of tunnable parameters in the tuning space dict. Args: tuning_space (dict): a configuration dictionary containing tunable parameters as lists of values. Returns: A list of strings
10,356
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger def get_list(val): if not isinstance(val, list): return [val] else: return val def de...
Splits the tuning space dictionary to result in all combinations of values. Args: tuning_space (dict): the tuning space where tunable parameters are lists of values.
10,357
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger TRAIN_MICRO_BATCH_SIZE_PER_GPU = ''' TRAIN_MICRO_BATCH_SIZE_PER_GPU is defined in this format: "train_micro_...
Generates a name from the acronyms of the tuning keys in the config dict. TRAIN_MICRO_BATCH_SIZE_PER_GPU is always included in the tuning keys. Args: config (dict): the config dict used to generate the name tuning_keys (list, optional): the tuning keys used to generate the name. Defaults to None. prefix (str, optional)...
10,358
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger def get_first_config(config: dict): if not config: return None cfg = copy.deepcopy(config) ...
null
10,359
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger def write_experiments(exps: list, exps_dir: str): exp_paths = [] for exp in exps: exp_name =...
null
10,360
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger def memory_to_string(n, postfix="", units=None, precision=2): if units is None: if n // 10**12 >...
null
10,361
import re import collections.abc import os import json from deepspeed.runtime.constants import GRADIENT_ACCUMULATION_STEPS, TRAIN_MICRO_BATCH_SIZE_PER_GPU import itertools import copy from ..utils import logger def number_to_string(n, postfix="", units=None, precision=2): if units is None: if n // 10**9 > ...
null
10,362
import numpy as np import itertools from ..utils import * import collections.abc The provided code snippet includes necessary dependencies for implementing the `index_to_feature` function. Write a Python function `def index_to_feature(p, dims)` to solve the following problem: convert index form (single integer) to fea...
convert index form (single integer) to feature form (vector)
10,363
import numpy as np import itertools from ..utils import * import collections.abc The provided code snippet includes necessary dependencies for implementing the `feature_to_index` function. Write a Python function `def feature_to_index(feature, dims)` to solve the following problem: convert feature form (vector) to ind...
convert feature form (vector) to index form (single integer)
10,364
import numpy as np import itertools from ..utils import * import collections.abc def dict_to_dims(tuning_space): dims = [] for key, val in tuning_space.items(): if isinstance(val, dict): dims.extend(dict_to_dims(val)) elif isinstance(val, list): dims.append(len(val)) ...
null
10,365
import numpy as np import itertools from ..utils import * import collections.abc import itertools def get_list(val): if not isinstance(val, list): return [val] else: return val def gen_combinations(d: dict): keys, values = d.keys(), d.values() for v in values: if not...
null
10,366
import numpy as np import itertools from ..utils import * import collections.abc import collections.abc def flatten(d, parent_key='', sep='_'): items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, collections.abc.MutableMapping): it...
null
10,367
import numpy as np import itertools from ..utils import * import collections.abc The provided code snippet includes necessary dependencies for implementing the `dict_to_feature` function. Write a Python function `def dict_to_feature(feature_dict, keys, max_value=None)` to solve the following problem: Extract values fr...
Extract values from dict
10,368
from deepspeed.runtime.config_utils import get_scalar_param, get_dict_param, DeepSpeedConfigObject from deepspeed.autotuning.constants import * def get_scalar_param(param_dict, param_name, param_default_value): def get_model_info_config(param_dict): if MODEL_INFO in param_dict and param_dict[MODEL_INFO] is not No...
null
10,369
from deepspeed.runtime.config_utils import get_scalar_param, get_dict_param, DeepSpeedConfigObject from deepspeed.autotuning.constants import * def get_default_model_info_config(): return MODEL_INFO_KEY_DEFAULT_DICT
null
10,370
import copy from numpy import BUFSIZE import json import subprocess import sys import threading import time import base64 import os import hjson from tqdm import tqdm from ..utils import logger from .constants import AUTOTUNING, AUTOTUNING_METRIC_PATH from .utils import get_val_by_key, search_error, was_interruptted fr...
null
10,371
import torch import deepspeed import subprocess import argparse from .ops.op_builder import ALL_OPS from .git_version_info import installed_ops, torch_info GREEN = '\033[92m' YELLOW = '\033[93m' END = '\033[0m' OKAY = f"{GREEN}[OKAY]{END}" FAIL = f'{RED}[FAIL]{END}' color_len = len(GREEN) + len(END) def ninja_installed...
null
10,372
import torch import deepspeed import subprocess import argparse from .ops.op_builder import ALL_OPS from .git_version_info import installed_ops, torch_info def nvcc_version(): import torch.utils.cpp_extension cuda_home = torch.utils.cpp_extension.CUDA_HOME if cuda_home is None: return f"{RED} [FAIL]...
null
10,373
import torch import deepspeed import subprocess import argparse from .ops.op_builder import ALL_OPS from .git_version_info import installed_ops, torch_info def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument( '--hide_operator_status', action='store_true', help= ...
null
10,374
import torch def quantize_module(model, orig_class, quantize_fn): policy = {orig_class: quantize_fn} return _quantize_module(model, policy) The provided code snippet includes necessary dependencies for implementing the `quantize_transformer_layer` function. Write a Python function `def quantize_transformer_lay...
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., transformers.modeling_bert.BertLayer. model (torch.nn.Module): user's nn.module representing their model megatron (bool): megatron mode...
10,375
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, ...
null
10,376
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...
null
10,377
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...
Replace 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., transformers.modeling_bert.BertLayer. model (torch.nn.Module): user's nn.module representing their model checkpoint_dict: Dictionary for...
10,378
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...
Revert DeepSpeed's transformer layer back to original bert-style transformer layer Arguments: orig_layer_impl (torch.nn.Module): the original transformer layer implementation that was replaced, e.g., transformers.modeling_bert.BertLayer. model (torch.nn.Module): user's nn.module representing their model config (dict): ...
10,379
import os import json import numpy as np import math from packaging import version as pkg_version from .config import ElasticityConfig, ElasticityConfigError, ElasticityError, \ ElasticityIncompatibleWorldSize from .constants import ELASTICITY, ENABLED, ENABLED_DEFAULT, LATEST_ELASTICITY_VERSION, \ MINIMUM_DEEP...
null
10,380
import os import json import numpy as np import math from packaging import version as pkg_version from .config import ElasticityConfig, ElasticityConfigError, ElasticityError, \ ElasticityIncompatibleWorldSize from .constants import ELASTICITY, ENABLED, ENABLED_DEFAULT, LATEST_ELASTICITY_VERSION, \ MINIMUM_DEEP...
Ensure the resource scheduler saw the same elastic config we are using at runtime
10,381
import os import json import numpy as np import math from packaging import version as pkg_version from .config import ElasticityConfig, ElasticityConfigError, ElasticityError, \ ElasticityIncompatibleWorldSize from .constants import ELASTICITY, ENABLED, ENABLED_DEFAULT, LATEST_ELASTICITY_VERSION, \ MINIMUM_DEEP...
Core deepspeed elasticity API. Given an elastic config (similar to the example below) DeepSpeed will compute a total train batch size corresponding valid GPU count list that provides a high level of elasticity. Elasticity in this case means we are safe to scale the training job up/down across the GPU count list *withou...
10,382
import torch The provided code snippet includes necessary dependencies for implementing the `is_torch_elastic_compatible` function. Write a Python function `def is_torch_elastic_compatible()` to solve the following problem: Helper to lookup torch version. Elastic training is introduced in 1.11.x Here is the function:...
Helper to lookup torch version. Elastic training is introduced in 1.11.x
10,383
import time import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import List, Optional from collections import OrderedDict import numpy as np def _dropout_flops_compute(input, p=0.5, training=True, inplace=False): return 0, 0
null
10,384
import time import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import List, Optional from collections import OrderedDict import numpy as np def _linear_flops_compute(input, weight, bias=None): out_features = weight.shape[0] macs = input.numel() * out_fea...
null
10,385
import time import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import List, Optional from collections import OrderedDict import numpy as np Tensor = torch.Tensor def _matmul_flops_compute(input, other, *, out=None): def _addmm_flops_compute(input, mat1, mat2, *,...
null
10,386
import time import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import List, Optional from collections import OrderedDict import numpy as np old_functions = {} def _reload_functionals(): # torch.nn.functional does not support importlib.reload() F.linear ...
null
10,387
import time import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import List, Optional from collections import OrderedDict import numpy as np old_functions = {} def _reload_tensor_methods(): torch.matmul = old_functions[torch.matmul.__name__]
null
10,388
import time import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import List, Optional from collections import OrderedDict import numpy as np def _rnn_flops(flops, rnn_module, w_ih, w_hh, input_size): # matrix matrix mult ih state and internal state flops ...
null
10,389
import time import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import List, Optional from collections import OrderedDict import numpy as np def _rnn_flops(flops, rnn_module, w_ih, w_hh, input_size): def _rnn_cell_forward_hook(rnn_cell_module, input, output): ...
null
10,390
import time import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import List, Optional from collections import OrderedDict import numpy as np def num_to_string(num, precision=2): if num // 10**9 > 0: return str(round(num / 10.0**9, precision)) + " G" ...
null
10,391
import time import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import List, Optional from collections import OrderedDict import numpy as np def flops_to_string(flops, units=None, precision=2): if units is None: if flops // 10**12 > 0: re...
null
10,392
import time import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import List, Optional from collections import OrderedDict import numpy as np def duration_to_string(duration, units=None, precision=2): if units is None: if duration > 1: ret...
null
10,393
import time import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import List, Optional from collections import OrderedDict import numpy as np def get_module_flops(module): sum = module.__flops__ # iterate over immediate children modules for child in m...
null
10,394
import time import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import List, Optional from collections import OrderedDict import numpy as np def get_module_macs(module): sum = module.__macs__ # iterate over immediate children modules for child in mod...
null
10,395
import time import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import List, Optional from collections import OrderedDict import numpy as np def get_module_duration(module): duration = module.__duration__ if duration == 0: # e.g. ModuleList for ...
null
10,396
import time import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import List, Optional from collections import OrderedDict import numpy as np class FlopsProfiler(object): """Measures the latency, number of estimated floating-point operations and parameters of ...
Returns the total floating-point operations, MACs, and parameters of a model. Example: .. code-block:: python model = torchvision.models.alexnet() batch_size = 256 flops, macs, params = get_model_profile(model=model, input_shape=(batch_size, 3, 224, 224))) Args: model ([torch.nn.Module]): the PyTorch model to be profil...
10,397
import os import torch import inspect from deepspeed.utils import get_caller_func The provided code snippet includes necessary dependencies for implementing the `older_torch` function. Write a Python function `def older_torch()` to solve the following problem: Helper to lookup torch version. For versions less than 1.8...
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://github.com/pytorch/pytorch/pull/48767
10,398
import os import torch import inspect from deepspeed.utils import get_caller_func The provided code snippet includes necessary dependencies for implementing the `has_allgather_base` function. Write a Python function `def has_allgather_base()` to solve the following problem: Helper to check if torch.distributed has _al...
Helper to check if torch.distributed has _all_gather_base
10,399
import os import torch import inspect from deepspeed.utils import get_caller_func The provided code snippet includes necessary dependencies for implementing the `has_reduce_scatter_base` function. Write a Python function `def has_reduce_scatter_base()` to solve the following problem: Helper to check if torch.distribut...
Helper to check if torch.distributed has _reduce_scatter_base
10,400
import os import torch import inspect from deepspeed.utils import get_caller_func def get_local_rank_from_launcher(): # DeepSpeed launcher will set it so get from there rank = os.environ.get('LOCAL_RANK') if rank is None: rank = os.environ.get('OMPI_COMM_WORLD_LOCAL_RANK') # Make it a single...
null
10,401
import os import torch import inspect from deepspeed.utils import get_caller_func def get_world_rank_from_launcher(): # DeepSpeed launcher will set it so get from there rank = os.environ.get('RANK') if rank is None: rank = os.environ.get('OMPI_COMM_WORLD_RANK') # Make it a single process job...
null
10,402
import os import torch import inspect from deepspeed.utils import get_caller_func def get_world_size_from_launcher(): # DeepSpeed launcher will set it so get from there size = os.environ.get('WORLD_SIZE') rank = os.environ.get('RANK') if size is None: size = os.environ.get('OMPI_COMM_WORLD_SIZ...
null
10,403
import os import torch import inspect from deepspeed.utils import get_caller_func def get_tensor_position(func): sig_params = inspect.signature(func).parameters arg = None # most colls if 'tensor' in sig_params: arg = 'tensor' # reduce scatter coll elif 'input_list' in sig_params: ...
null
10,404
import os import torch import inspect from deepspeed.utils import get_caller_func def get_debug_log_name(func_args, debug): if debug: return func_args['log_name'] + ' | [Caller Func: ' + get_caller_func() + ']' else: return func_args['log_name']
null
10,405
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,406
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,407
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,408
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,409
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,410
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,411
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,412
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * class ReduceOp(Enum): from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend fr...
null
10,413
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,414
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,415
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,416
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,417
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,418
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,419
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,420
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * class ReduceOp(Enum): SUM = 0 PRODUCT = 1 MIN = 2 MAX = 3 BAND = 4 BOR = 5 BXOR = 6 AVG = 7 UNUSED = 8 from deepspeed.utils.comms_logging i...
null
10,421
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * class ReduceOp(Enum): SUM = 0 PRODUCT = 1 MIN = 2 MAX = 3 BAND = 4 BOR = 5 BXOR = 6 AVG = 7 UNUSED = 8 from deepspeed.utils.comms_logging i...
null
10,422
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,423
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
Helper function to get local rank after a backend has been set and initialized Args: None Returns: local rank (= GPU device ID)
10,424
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
null
10,425
from enum import Enum import torch import os from ..constants import TORCH_DISTRIBUTED_DEFAULT_PORT, default_pg_timeout from .constants import * from deepspeed.utils.comms_logging import CommsLogger from deepspeed.utils import timer, get_caller_func from deepspeed.comm.torch import TorchBackend from deepspeed import ut...
Initialize dist backend, potentially performing MPI discovery if needed Arguments: dist_backend: Optional (str). torch distributed backend, e.g., nccl, mpi, gloo auto_mpi_discovery Optional (bool). if distributed environment variables are not set, attempt to discover them from MPI distributed_port: Optional (int). torc...
10,426
import torch from ..op_builder import QuantizerBuilder 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 if quantizer_cuda_module is None: quantizer_cuda_module = QuantizerBuilder().load() ...
null
10,427
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 abc import ABC, abstractmethod from typing import L...
null
10,428
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 abc import ABC, abstractmethod from typing import L...
null
10,429
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 transformer_cuda_module = None def load_transformer_modul...
null
10,430
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 spatial_cuda_module = None def load_spatial_module(): ...
null
10,431
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 triton_flash_attn = None class triton_flash_attn(torch.nn.Module): def __init__(self, ): super(triton_flash...
null
10,432
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: Optional[torch.Tensor] = None) -> torch.Tensor: glob...
null
10,433
import torch import triton import triton.language as tl def _fwd_kernel( Q, K, V, sm_scale, TMP, Out, stride_qz, stride_qh, stride_qm, stride_qk, stride_kz, stride_kh, stride_kn, stride_kk, stride_vz, stride_vh, stride_vk, stride_vn, stride_oz...
null
10,434
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 >> 4 n |= n >> 8 n |= n >> 16 n += 1 return n
null
10,435
import torch import triton import triton.language as tl def num_warps(n): if n < 512: return 4 if n < 2048: return 8 return 16
null
10,436
import torch import triton import triton.language as tl def _forward(X, scale, LUT, RPE, KP_M, ATTN_M, sizemax, stride_zx, stride_zrpe, stride_hrpe, stride_srpe, stride_zkpm, ...
null
10,437
import torch import triton import triton.language as tl def _backward(X, scale, DX, LUT, sizemax, stride_zx, stride_zdx, **meta): pidhm = tl.program_id(0) pidz = tl.program_id(1) TN = meta['TN'] BLOCK = meta['BLOCK'] # create index ranges rxm = pidhm % BLOCK rbm = pidhm // BLOCK rxn = t...
null
10,438
import importlib import torch import triton import triton.language as tl import triton._C.libtriton as libtriton def _kernel(A, B, C, stride_za, stride_ha, stride_ma, stride_ka, stride_zb, stride_hb, stride_kb, ...
null
10,439
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...
null
10,440
def check_wandb_availability(): try: import wandb # noqa: F401 except ImportError: print( 'If you want to use wandb logging, please `pip install wandb` and follow the instructions at https://docs.wandb.ai/quickstart' ) raise
null
10,441
from typing import List, Tuple, Dict import torch from .layer import MoE class MoE(torch.nn.Module): """Initialize an MoE layer. Arguments: hidden_size (int): the hidden dimension of the model, importantly this is also the input and output dimension. expert (torch.nn.Module): the torch module ...
null
10,442
from typing import List, Tuple, Dict import torch from .layer import MoE def is_moe_param(param: torch.Tensor) -> bool: if hasattr(param, "allreduce") and not param.allreduce: return True return False def split_params_into_shared_and_expert_params( params: List[torch.nn.Parameter]) -> Tuple[tor...
null
10,443
from typing import List, Tuple, Dict import torch from .layer import MoE def is_moe_param(param: torch.Tensor) -> bool: if hasattr(param, "allreduce") and not param.allreduce: return True return False The provided code snippet includes necessary dependencies for implementing the `split_params_grads_int...
Split grad of parameters into grads of non-expert params and grads of expert params. This is useful while computing grad-norms for clipping and overflow detection group (List[torch.nn.Parameter]): Args: The group of parameters to split Returns: Tuple[List[torch.nn.Parameter], List[torch.nn.Parameter]]: list of gradient...
10,444
from typing import List, Tuple, Dict import torch from .layer import MoE def is_moe_param(param: torch.Tensor) -> bool: if hasattr(param, "allreduce") and not param.allreduce: return True return False The provided code snippet includes necessary dependencies for implementing the `split_params_into_diff...
Split parameters into different MoE groups for optimizer Args: param_groups (Tuple[Dict]): The list of parameter groups to split Returns: Tuple[Dict]: list of MoE/non-MoE groups for optimizer
10,445
import torch import deepspeed The provided code snippet includes necessary dependencies for implementing the `_gather_tokens` function. Write a Python function `def _gather_tokens(input_, dim=0)` to solve the following problem: Gather tensors and concatenate them along a dimension Here is the function: def _gather_t...
Gather tensors and concatenate them along a dimension
10,446
import torch import deepspeed The provided code snippet includes necessary dependencies for implementing the `_drop_tokens` function. Write a Python function `def _drop_tokens(input_, dim=0)` to solve the following problem: Divide a tensor among the tensor parallel ranks Here is the function: def _drop_tokens(input_...
Divide a tensor among the tensor parallel ranks
10,447
import torch import deepspeed class _GatherTokens(torch.autograd.Function): """All gather tokens among the tensor parallel ranks""" def symbolic(graph, input_, dim): return _gather_tokens(input_, dim) def forward(ctx, input_, dim): ctx.dim = dim return _gather_tokens(input_, dim) ...
null
10,448
import torch import deepspeed class _DropTokens(torch.autograd.Function): "Divide tokens equally among the tensor parallel ranks" def symbolic(graph, input_, dim): return _drop_tokens(input_, dim) def forward(ctx, input_, dim): ctx.dim = dim return _drop_tokens(input_, dim) def b...
null
10,449
from deepspeed.utils.timer import SynchronizedWallClockTimer from deepspeed.utils import logger from typing import Callable, Dict, TYPE_CHECKING, Any, Optional, Tuple import torch from torch import Tensor from torch.nn import Module import torch.nn.functional as F from deepspeed.utils import groups from .mappings impor...
Modified from switch transformer paper. mesh transformers Multiply values by a random number between 1-epsilon and 1+epsilon. Makes models more resilient to rounding errors introduced by bfloat16. This seems particularly important for logits. Args: x: a torch.tensor device: torch.device epsilon: a floating point value ...
10,450
from deepspeed.utils.timer import SynchronizedWallClockTimer from deepspeed.utils import logger from typing import Callable, Dict, TYPE_CHECKING, Any, Optional, Tuple import torch from torch import Tensor from torch.nn import Module import torch.nn.functional as F from deepspeed.utils import groups from .mappings impor...
Implements Top1Gating on logits.
10,451
from deepspeed.utils.timer import SynchronizedWallClockTimer from deepspeed.utils import logger from typing import Callable, Dict, TYPE_CHECKING, Any, Optional, Tuple import torch from torch import Tensor from torch.nn import Module import torch.nn.functional as F from deepspeed.utils import groups from .mappings impor...
Implements Top2Gating on logits.
10,452
import os import sys import json import base64 import argparse import subprocess import collections from copy import deepcopy import signal import time import torch.cuda from .multinode_runner import PDSHRunner, OpenMPIRunner, MVAPICHRunner, SlurmRunner from .constants import PDSH_LAUNCHER, OPENMPI_LAUNCHER, MVAPICH_LA...
null
10,453
import os import sys import json import base64 import argparse import subprocess import collections from copy import deepcopy import signal import time import torch.cuda from .multinode_runner import PDSHRunner, OpenMPIRunner, MVAPICHRunner, SlurmRunner from .constants import PDSH_LAUNCHER, OPENMPI_LAUNCHER, MVAPICH_LA...
null