code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def success_datacheck(stage_id, train_dataset, validation_dataset,
test_dataset):
"""
Args:
stage_id (str): ID of current stage.
train_dataset (int): Number of samples in training dataset.
validation_dataset (int): Number of samples in validation dataset.
te... |
Args:
stage_id (str): ID of current stage.
train_dataset (int): Number of samples in training dataset.
validation_dataset (int): Number of samples in validation dataset.
test_dataset (int): Number of samples in test dataset.
| success_datacheck | python | PaddlePaddle/PaddleRec | uapi_rec/base/utils/stagelog.py | https://github.com/PaddlePaddle/PaddleRec/blob/master/uapi_rec/base/utils/stagelog.py | Apache-2.0 |
def _element_size(dtype):
"""
Returns the element size for a dtype, in bytes
"""
if not isinstance(dtype, torch.dtype):
raise RuntimeError(f'expected torch.dtype, but got {type(dtype)}')
if dtype.is_complex:
return torch.finfo(dtype).bits >> 2
elif dtype.is_floating_point:
... |
Returns the element size for a dtype, in bytes
| _element_size | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/benchmarks/communication/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/benchmarks/communication/utils.py | Apache-2.0 |
def _parse_version(version_str):
'''Parse a version string and extract the major, minor, and patch versions.'''
ver = pkg_version.parse(version_str)
return ver.major, ver.minor, ver.micro | Parse a version string and extract the major, minor, and patch versions. | _parse_version | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/__init__.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/__init__.py | Apache-2.0 |
def initialize(args=None,
model: torch.nn.Module = None,
optimizer: Optional[Union[Optimizer,
DeepSpeedOptimizerCallable]] = None,
model_parameters: Optional[torch.nn.Module] = None,
training_data: Optional[torch.utils.... | Initialize the DeepSpeed Engine.
Arguments:
args: an object containing local_rank and deepspeed_config fields.
This is optional if `config` is passed.
model: Required: nn.module class before apply any wrappers
optimizer: Optional: a user defined Optimizer or Callable that retu... | initialize | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/__init__.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/__init__.py | Apache-2.0 |
def _add_core_arguments(parser):
r"""Helper (internal) function to update an argument parser with an argument group of the core DeepSpeed arguments.
The core set of DeepSpeed arguments include the following:
1) --deepspeed: boolean flag to enable DeepSpeed
2) --deepspeed_config <json file pa... | Helper (internal) function to update an argument parser with an argument group of the core DeepSpeed arguments.
The core set of DeepSpeed arguments include the following:
1) --deepspeed: boolean flag to enable DeepSpeed
2) --deepspeed_config <json file path>: path of a json configuration file to... | _add_core_arguments | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/__init__.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/__init__.py | Apache-2.0 |
def init_inference(model, config=None, **kwargs):
"""Initialize the DeepSpeed InferenceEngine.
Description: all four cases are valid and supported in DS init_inference() API.
# Case 1: user provides no config and no kwargs. Default config will be used.
.. code-block:: python
generator.model ... | Initialize the DeepSpeed InferenceEngine.
Description: all four cases are valid and supported in DS init_inference() API.
# Case 1: user provides no config and no kwargs. Default config will be used.
.. code-block:: python
generator.model = deepspeed.init_inference(generator.model)
strin... | init_inference | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/__init__.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/__init__.py | Apache-2.0 |
def print_tuning_results(self):
"""Print the autotuning results in tabular format.
"""
best_space_records = self.get_best_space_records()
tab = []
if best_space_records:
for key, val in best_space_records.items():
if not val:
contin... | Print the autotuning results in tabular format.
| print_tuning_results | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | Apache-2.0 |
def _get_user_config(self, user_args):
"""Get DeepSpeed configuration from the user arguments passed to the launcher.
Args:
user_args ([list]): user arguments passed to the DeepSpeed launcher
Returns:
[dict]: DeepSpeed configuration dictionary
"""
user_c... | Get DeepSpeed configuration from the user arguments passed to the launcher.
Args:
user_args ([list]): user arguments passed to the DeepSpeed launcher
Returns:
[dict]: DeepSpeed configuration dictionary
| _get_user_config | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | Apache-2.0 |
def _get_resource_manager(self, active_resources):
"""Initialize and return a resource manager
Args:
active_resources ([dict]): A dictionary of hostname and its slots (GPUs), e.g. {"worker-0": "0,1,2,3,4,5,6,7,8"}
Raises:
RuntimeError: raises the error if no GPU is avai... | Initialize and return a resource manager
Args:
active_resources ([dict]): A dictionary of hostname and its slots (GPUs), e.g. {"worker-0": "0,1,2,3,4,5,6,7,8"}
Raises:
RuntimeError: raises the error if no GPU is available
Returns:
[ResourceManager]: A resou... | _get_resource_manager | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | Apache-2.0 |
def _get_exp_resources(self, args):
"""Get resource requirement for each autotuning experiment
Args:
args (dict): user args
Returns:
num_nodes, num_gpus: the number of gpus and number of nodes used in the autotuning experiments
"""
if args.num_nodes > 0:... | Get resource requirement for each autotuning experiment
Args:
args (dict): user args
Returns:
num_nodes, num_gpus: the number of gpus and number of nodes used in the autotuning experiments
| _get_exp_resources | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | Apache-2.0 |
def _generate_experiments(self, tuning_space, max_train_batch_size_per_gpu):
"""Generates a list of autotuning experiments given a tuning_space.
The corresponding parameter values are replaced by user-defined values in the DeepSpeed configuration file.
Args:
tuning_space ([dict])... | Generates a list of autotuning experiments given a tuning_space.
The corresponding parameter values are replaced by user-defined values in the DeepSpeed configuration file.
Args:
tuning_space ([dict]): A DeepSpeed configuration dictionary where a value can be a list (called a tuning para... | _generate_experiments | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | Apache-2.0 |
def tune(self):
""" Tunes Zero stages, micro batch size per GPU, and other Zero configurations. Performance metrics of different tuning spaces are recorded in self.records.
"""
self.start_time = time.time()
if self.fast_enabled():
logger.info(f"Fast mode is enabled. Tuning mi... | Tunes Zero stages, micro batch size per GPU, and other Zero configurations. Performance metrics of different tuning spaces are recorded in self.records.
| tune | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | Apache-2.0 |
def model_info_profile_run(self):
"""Does a model information profling experiment that collects the number of model parameters and activation memory.\
The experiment produces a "profile_model_info" folder under self.results_dir.
Returns:
[dict]: a model information dictionary, e.... | Does a model information profling experiment that collects the number of model parameters and activation memory. The experiment produces a "profile_model_info" folder under self.results_dir.
Returns:
[dict]: a model information dictionary, e.g., {"num_params": 335144976, "trainable_num_pa... | model_info_profile_run | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | Apache-2.0 |
def get_tuning_micro_batch_size_list(self,
min_micro_batch_size,
max_micro_batch_size,
num_tuning_micro_batch_sizes):
"""Get a list of micro batch sizes to tune based on min and max values,... | Get a list of micro batch sizes to tune based on min and max values, as well as the size of the list.
Args:
min_micro_batch_size ([int]): min micro batch size per GPU
max_micro_batch_size ([int]): max micro batch size per GPU
num_tuning_micro_batch_sizes (int): the number of ... | get_tuning_micro_batch_size_list | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | Apache-2.0 |
def run_after_tuning(self):
""" Launches the training with the optimal DeepSpeed configuration found through the autotuning process.
"ds_config_optimal.json" describing the optmimal DeepSpeed configuration as well the command used to launch training "cmd_optimal.txt" are saved to self.results_dir.
... | Launches the training with the optimal DeepSpeed configuration found through the autotuning process.
"ds_config_optimal.json" describing the optmimal DeepSpeed configuration as well the command used to launch training "cmd_optimal.txt" are saved to self.results_dir.
| run_after_tuning | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/autotuner.py | Apache-2.0 |
def save_exp_results_to_database(self, message, ranks=None, path=None):
"""Print message when one of following condition meets
+ not dist.is_initialized()
+ dist.get_rank() in ranks if ranks is not None or ranks = [-1]
Args:
message (str)
ranks (list)
pa... | Print message when one of following condition meets
+ not dist.is_initialized()
+ dist.get_rank() in ranks if ranks is not None or ranks = [-1]
Args:
message (str)
ranks (list)
path (str)
| save_exp_results_to_database | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/scheduler.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/scheduler.py | Apache-2.0 |
def parse_results(self, metric):
""" Parses the metric file of the finished experiments to select the optimal DeepSpeed configuration.
Args:
finished_experiments (dcit): a dictionary of experiment id and experiment description.
Returns:
The path to the result folder of ... | Parses the metric file of the finished experiments to select the optimal DeepSpeed configuration.
Args:
finished_experiments (dcit): a dictionary of experiment id and experiment description.
Returns:
The path to the result folder of the experiment with the optimal configuratio... | parse_results | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/scheduler.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/scheduler.py | Apache-2.0 |
def clear(self):
"""Clear experiment queues, does not reset self.experiment_count
"""
self.experiment_queue = []
# clean up the running experiments
for exp_id, exp_data in self.running_experiments.items():
thread, exp_json, reservations, start_time = exp_data
... | Clear experiment queues, does not reset self.experiment_count
| clear | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/scheduler.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/scheduler.py | Apache-2.0 |
def del_if_exists(t, d):
"""Deletes a key from a dictionary if it exists.
Args:
t (string): target key to delete
d (dict): dictionary to delete from
"""
if t in d:
del d[t]
return
for k, v in d.items():
if isinstance(v, collections.abc.Mapping):
d... | Deletes a key from a dictionary if it exists.
Args:
t (string): target key to delete
d (dict): dictionary to delete from
| del_if_exists | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | Apache-2.0 |
def replace_dict(d, u, ignored_keys=[]):
"""Replaces values in dict d with values in dict u.
Args:
d (dict): the target dict to overwrite
u (dict): the dict containing the values to overwrite the target dict
Returns:
dict d with values overwritten by the corresponding ones in dict ... | Replaces values in dict d with values in dict u.
Args:
d (dict): the target dict to overwrite
u (dict): the dict containing the values to overwrite the target dict
Returns:
dict d with values overwritten by the corresponding ones in dict u.
| replace_dict | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | Apache-2.0 |
def remove_dupe_dicts(l):
""" Removes duplicate dictionaries from a list. Uses list comprehension and the json library to sort and stringify each dictionary and the set data type to ensure unique values. Works with nested data structures.
Args:
l (list): a list of (nested) data structures.
Returns... | Removes duplicate dictionaries from a list. Uses list comprehension and the json library to sort and stringify each dictionary and the set data type to ensure unique values. Works with nested data structures.
Args:
l (list): a list of (nested) data structures.
Returns:
A list of unique values... | remove_dupe_dicts | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | Apache-2.0 |
def prune_config(config, ignored_keys=[]):
""" Prunes the input configurations
Args:
configs (dict): A configuration dictionary.
ignored_keys (list, optional): the keys of the sections to delete. Defaults to [].
Returns:
A configuration dictionary.
"""
if ignored_keys:
... | Prunes the input configurations
Args:
configs (dict): A configuration dictionary.
ignored_keys (list, optional): the keys of the sections to delete. Defaults to [].
Returns:
A configuration dictionary.
| prune_config | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | Apache-2.0 |
def prune_configs(configs, ignored_keys=[]):
""" 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 ... | 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.
| prune_configs | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | Apache-2.0 |
def get_tuning_keys(tuning_space: dict):
"""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
"""
tuning_keys = []
for key, val in ... | 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
| get_tuning_keys | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | Apache-2.0 |
def get_all_configs(tuning_space: dict, ignore_keys=None):
""" 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.
"""
def gen_combinations(d: dict):
keys, values = d.keys()... | 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.
| get_all_configs | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | Apache-2.0 |
def canonical_name(config: dict, tuning_keys=None, prefix="", omit_val=False):
""" 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... | 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.
... | canonical_name | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/utils.py | Apache-2.0 |
def has_next(self):
"""Whether there exists more configurations for evaluation"""
if len(self.all_exps) > 0:
return True
else:
return False | Whether there exists more configurations for evaluation | has_next | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/tuner/base_tuner.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/tuner/base_tuner.py | Apache-2.0 |
def find_estimated_top_configs(self):
"""Use the cost model to predict the estimated performance of configurations and find the top ones for the next round of evaluation"""
configs = []
for c in self.all_configs:
flattened_ds_config = flatten(c)
feature_val = []
... | Use the cost model to predict the estimated performance of configurations and find the top ones for the next round of evaluation | find_estimated_top_configs | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/tuner/model_based_tuner.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/tuner/model_based_tuner.py | Apache-2.0 |
def index_to_feature(p, dims):
"""convert index form (single integer) to feature form (vector)"""
feature = []
for dim in dims:
feature.append(p % dim)
p //= dim
return feature | convert index form (single integer) to feature form (vector) | index_to_feature | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/tuner/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/tuner/utils.py | Apache-2.0 |
def feature_to_index(feature, dims):
"""convert feature form (vector) to index form (single integer)"""
p = 0
for j, k in enumerate(feature):
print("j:", "k:", k, "dims", dims[:j])
p += int(np.prod(dims[:j])) * k
return p | convert feature form (vector) to index form (single integer) | feature_to_index | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/autotuning/tuner/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/autotuning/tuner/utils.py | Apache-2.0 |
def get_mpu_ranks(tp_size=1, pp_size=1, dp_size=1, virtual_pp_size=None):
"""
Initialize model data parallel groups.
Arguments:
tp_size: number of GPUs used to parallelize model tensor.
pp_size: number of GPUs used to parallelize model pipeline.
dp_size: number of GPUs used to paral... |
Initialize model data parallel groups.
Arguments:
tp_size: number of GPUs used to parallelize model tensor.
pp_size: number of GPUs used to parallelize model pipeline.
dp_size: number of GPUs used to parallelize model data.
Let's say we have a total of 16 GPUs denoted by g0 ... g1... | get_mpu_ranks | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/checkpoint/reshape_meg_2d.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/checkpoint/reshape_meg_2d.py | Apache-2.0 |
def get_world_size(group=None) -> int:
"""
Returns the number of processes in the current process group
Args:
group (ProcessGroup, optional): The process group to work on. If None,
the default process group will be used.
Returns:
The world size of the process group
-1... |
Returns the number of processes in the current process group
Args:
group (ProcessGroup, optional): The process group to work on. If None,
the default process group will be used.
Returns:
The world size of the process group
-1, if not part of the group
| get_world_size | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/comm/comm.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/comm/comm.py | Apache-2.0 |
def get_rank(group=None):
"""
Returns the rank of the current process in the provided ``group`` or the
default group if none was provided.
Rank is a unique identifier assigned to each process within a distributed
process group. They are always consecutive integers ranging from 0 to
``world_size`... |
Returns the rank of the current process in the provided ``group`` or the
default group if none was provided.
Rank is a unique identifier assigned to each process within a distributed
process group. They are always consecutive integers ranging from 0 to
``world_size``.
Args:
group (Proce... | get_rank | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/comm/comm.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/comm/comm.py | Apache-2.0 |
def get_local_rank():
"""
Helper function to get local rank after a backend has been set and initialized
Args:
None
Returns:
local rank (= GPU device ID)
"""
global cdb
assert cdb is not None and cdb.is_initialized(), 'DeepSpeed backend not set, please ini... |
Helper function to get local rank after a backend has been set and initialized
Args:
None
Returns:
local rank (= GPU device ID)
| get_local_rank | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/comm/comm.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/comm/comm.py | Apache-2.0 |
def mpi_discovery(distributed_port=TORCH_DISTRIBUTED_DEFAULT_PORT, verbose=True):
'''
Discovery MPI environment via mpi4py and map to relevant dist state
'''
from mpi4py import MPI
import subprocess
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
world_size = comm.Get_size()
master_add... |
Discovery MPI environment via mpi4py and map to relevant dist state
| mpi_discovery | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/comm/comm.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/comm/comm.py | Apache-2.0 |
def patch_aml_env_for_torch_nccl_backend(master_port=6105, verbose=True):
"""Helper routine to get and set environment variables.
This is adapted from Azure ML's documentation available from:
https://azure.github.io/azureml-web/docs/cheatsheet/distributed-training/#environment-variables-from-openmpi
"""... | Helper routine to get and set environment variables.
This is adapted from Azure ML's documentation available from:
https://azure.github.io/azureml-web/docs/cheatsheet/distributed-training/#environment-variables-from-openmpi
| patch_aml_env_for_torch_nccl_backend | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/comm/comm.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/comm/comm.py | Apache-2.0 |
def patch_aws_sm_env_for_torch_nccl_backend(verbose=True):
"""Helper routine to get and set environment variables when running inside an AWS SageMaker environment.
"""
os.environ["RANK"] = os.environ["OMPI_COMM_WORLD_RANK"]
os.environ['LOCAL_RANK'] = os.environ["OMPI_COMM_WORLD_LOCAL_RANK"]
os.envir... | Helper routine to get and set environment variables when running inside an AWS SageMaker environment.
| patch_aws_sm_env_for_torch_nccl_backend | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/comm/comm.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/comm/comm.py | Apache-2.0 |
def _reduce_op(self, op):
'''
Helper function. If the op provided is not a torch.dist.ReduceOp, convert it and return
'''
if not isinstance(op, torch.distributed.ReduceOp):
if op == ReduceOp.SUM:
op = torch.distributed.ReduceOp.SUM
elif op == R... |
Helper function. If the op provided is not a torch.dist.ReduceOp, convert it and return
| _reduce_op | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/comm/torch.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/comm/torch.py | Apache-2.0 |
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://github.com/pytorch/pytorch/pull/48767
'''
TORCH_MAJOR = int(torch.__version__.s... |
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
| older_torch | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/comm/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/comm/utils.py | Apache-2.0 |
def forward(self, x, num_bits, *args):
"""
x: the activation that we need to quantize
num_bits: the number of bits we need to quantize the activation to
*args: some extra arguments that are useless but needed for align with the interface of other quantization functions
"""
... |
x: the activation that we need to quantize
num_bits: the number of bits we need to quantize the activation to
*args: some extra arguments that are useless but needed for align with the interface of other quantization functions
| forward | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/compression/basic_layer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/compression/basic_layer.py | Apache-2.0 |
def get_module_name(group_name,
model,
key_word,
exist_module_name,
mpu=None,
verbose=True):
'''
get the associated module name from the model based on the key_word provided by users
'''
return_module_nam... |
get the associated module name from the model based on the key_word provided by users
| get_module_name | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/compression/compress.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/compression/compress.py | Apache-2.0 |
def init_compression(model, deepspeed_config, teacher_model=None, mpu=None):
"""
Compress a model: replace linear/conv2d layer with deepspeed compression-aware modules
Args:
model (`torch.nn.Module`)
The model to compress.
deepspeed_config (`DeepSpeedConfig`)
The path... |
Compress a model: replace linear/conv2d layer with deepspeed compression-aware modules
Args:
model (`torch.nn.Module`)
The model to compress.
deepspeed_config (`DeepSpeedConfig`)
The path of ds_config
mpu
The mpu module for Row/Column parallelism
| init_compression | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/compression/compress.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/compression/compress.py | Apache-2.0 |
def redundancy_clean(model, deepspeed_config, mpu=None):
"""
Remove the redundancy of a model
Args:
model (`torch.nn.Module`)
The model to compress.
deepspeed_config (`DeepSpeedConfig`)
The path of ds_config
mpu
The mpu module for Row/Column parall... |
Remove the redundancy of a model
Args:
model (`torch.nn.Module`)
The model to compress.
deepspeed_config (`DeepSpeedConfig`)
The path of ds_config
mpu
The mpu module for Row/Column parallelism
| redundancy_clean | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/compression/compress.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/compression/compress.py | Apache-2.0 |
def student_initialization(student_model, teacher_model, deepspeed_config):
'''
Given a student model and a teacher model, select the
Args:
student_model (`torch.nn.Module`)
The model we will update weight
teacher_model (`torch.nn.Module`)
The model guide the student ... |
Given a student model and a teacher model, select the
Args:
student_model (`torch.nn.Module`)
The model we will update weight
teacher_model (`torch.nn.Module`)
The model guide the student to learn
deepspeed_config (`DeepSpeedConfig`)
The path of ds_co... | student_initialization | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/compression/compress.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/compression/compress.py | Apache-2.0 |
def recursive_getattr(model, module_name):
"""
Recursively get the attribute of a module.
Args:
model (`torch.nn.Module`)
The model to get the attribute from.
module_name (`str`)
The name of the module to get the attribute from.
"""
split_list = module_name.sp... |
Recursively get the attribute of a module.
Args:
model (`torch.nn.Module`)
The model to get the attribute from.
module_name (`str`)
The name of the module to get the attribute from.
| recursive_getattr | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/compression/helper.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/compression/helper.py | Apache-2.0 |
def recursive_setattr(model, module_name, module):
"""
Recursively set the attribute of a module.
Args:
model (`torch.nn.Module`)
The model to set the attribute in.
module_name (`str`)
The name of the module to set the attribute in.
module (`torch.nn.Module`)
... |
Recursively set the attribute of a module.
Args:
model (`torch.nn.Module`)
The model to set the attribute in.
module_name (`str`)
The name of the module to set the attribute in.
module (`torch.nn.Module`)
The module to set the attribute to.
| recursive_setattr | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/compression/helper.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/compression/helper.py | Apache-2.0 |
def module_replacement(model, module_name, compression_technique=None, mpu=None):
"""
Replace a module with a new module.
Args:
model (`torch.nn.Module`)
The model to replace the module in.
module_name (`str`)
The name of the module to replace.
compression_tec... |
Replace a module with a new module.
Args:
model (`torch.nn.Module`)
The model to replace the module in.
module_name (`str`)
The name of the module to replace.
compression_technique (`str`)
The compression technique to use for the new module.
| module_replacement | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/compression/helper.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/compression/helper.py | Apache-2.0 |
def compression_preparation(model, compression_techinique_list, mpu):
"""
Prepare the compression techniques of a model.
Args:
model (`torch.nn.Module`)
The model to prepare the compression techniques of.
compression_techinique_list (`list`)
The list of compression te... |
Prepare the compression techniques of a model.
Args:
model (`torch.nn.Module`)
The model to prepare the compression techniques of.
compression_techinique_list (`list`)
The list of compression techniques to prepare the model to.
list[]
| compression_preparation | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/compression/helper.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/compression/helper.py | Apache-2.0 |
def fix_compression(model,
module_name,
compression_technique,
mask=None,
dim_reduction=False):
"""
Fix the compression technique of a module.
Args:
model (`torch.nn.Module`)
The model to fix the compression ... |
Fix the compression technique of a module.
Args:
model (`torch.nn.Module`)
The model to fix the compression technique of.
module_name (`str`)
The name of the module to fix the compression technique of.
compression_technique (`str`)
The compression tec... | fix_compression | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/compression/helper.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/compression/helper.py | Apache-2.0 |
def convert_conv1d_to_linear(model, convert_type):
'''
This is a help function to convert conv1d to linear (e.g., convert GPT2 from HF)
'''
if hasattr(model, 'module'):
c_model = model.module
else:
c_model = model
for name, module in c_model.named_modules():
if isinstanc... |
This is a help function to convert conv1d to linear (e.g., convert GPT2 from HF)
| convert_conv1d_to_linear | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/compression/helper.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/compression/helper.py | Apache-2.0 |
def forward(ctx, inputs: torch.tensor, threshold: float, sigmoid: bool):
"""
Args:
inputs (`torch.FloatTensor`)
The input matrix from which the binarizer computes the binary mask.
threshold (`float`)
The percentage of weights to keep (the rest is p... |
Args:
inputs (`torch.FloatTensor`)
The input matrix from which the binarizer computes the binary mask.
threshold (`float`)
The percentage of weights to keep (the rest is pruned).
`threshold` is a float between 0 and 1.
sigmoid ... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/compression/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/compression/utils.py | Apache-2.0 |
def forward(ctx, input, num_bits, min_value=None, max_value=None, num_groups=1):
"""
Args:
inputs (`torch.FloatTensor`)
The input which needs to be quantized
num_bits (int, >=4)
Number of bits to use for quantization
min_value/max_vlue ... |
Args:
inputs (`torch.FloatTensor`)
The input which needs to be quantized
num_bits (int, >=4)
Number of bits to use for quantization
min_value/max_vlue (torch.FloatTensor)
Used for static activation quantization
num_... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/compression/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/compression/utils.py | Apache-2.0 |
def forward(ctx, input, num_bits, min_value=None, max_value=None, num_groups=1):
"""
Args:
inputs (`torch.FloatTensor`)
The input which needs to be quantized
num_bits (int)
Dummy variable
min_value/max_vlue (torch.FloatTensor)
... |
Args:
inputs (`torch.FloatTensor`)
The input which needs to be quantized
num_bits (int)
Dummy variable
min_value/max_vlue (torch.FloatTensor)
Used for static activation quantization; for now they are dummy variable
... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/compression/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/compression/utils.py | Apache-2.0 |
def _get_compatible_gpus_v01(micro_batches,
max_acceptable_batch_size,
min_gpus=None,
max_gpus=None,
prefer_larger=True):
'''We use two heuristics to compute the batch size
1. We use the Lowes... | We use two heuristics to compute the batch size
1. We use the Lowest Common Multiple of the micro-batches
as the base batch size and scale it by a HCN such that the result is
the largest batch size less than the max_acceptable batch size
2. We use each of the micro batches as a base and scale it... | _get_compatible_gpus_v01 | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/elasticity/elasticity.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/elasticity/elasticity.py | Apache-2.0 |
def ensure_immutable_elastic_config(runtime_elastic_config_dict: dict):
"""
Ensure the resource scheduler saw the same elastic config we are using at runtime
"""
if DEEPSPEED_ELASTICITY_CONFIG in os.environ:
scheduler_elastic_config_dict = json.loads(
os.environ[DEEPSPEED_ELASTICITY_... |
Ensure the resource scheduler saw the same elastic config we are using at runtime
| ensure_immutable_elastic_config | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/elasticity/elasticity.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/elasticity/elasticity.py | Apache-2.0 |
def compute_elastic_config(ds_config: dict,
target_deepspeed_version: str,
world_size=0,
return_microbatch=False):
"""Core deepspeed elasticity API. Given an elastic config (similar to the example below)
DeepSpeed will compute a to... | 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 ... | compute_elastic_config | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/elasticity/elasticity.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/elasticity/elasticity.py | Apache-2.0 |
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:
return True
... |
Helper to lookup torch version. Elastic training is
introduced in 1.11.x
| is_torch_elastic_compatible | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/elasticity/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/elasticity/utils.py | Apache-2.0 |
def __init__(self, model, config):
"""
Args:
model: torch.nn.Module
config: DeepSpeedInferenceConfig
"""
global DS_INFERENCE_ENABLED
DS_INFERENCE_ENABLED = True
super().__init__()
self.module = model
self._config = config
... |
Args:
model: torch.nn.Module
config: DeepSpeedInferenceConfig
| __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/inference/engine.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/inference/engine.py | Apache-2.0 |
def forward(self, *inputs, **kwargs):
"""Execute forward propagation
Arguments:
*inputs: Variable length input list
**kwargs: variable length keyword arguments
"""
start = None
if self.model_profile_enabled and self._config.enable_cuda_graph:
... | Execute forward propagation
Arguments:
*inputs: Variable length input list
**kwargs: variable length keyword arguments
| forward | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/inference/engine.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/inference/engine.py | Apache-2.0 |
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., transformers.model... | 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 mod... | quantize_transformer_layer | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/module_inject/module_quantize.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/module_inject/module_quantize.py | Apache-2.0 |
def replace_transformer_layer(orig_layer_impl,
model,
checkpoint_dict,
config,
model_config):
""" Replace bert-style transformer layers with DeepSpeed's transformer layer
Arguments:
or... | 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 mode... | replace_transformer_layer | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/module_inject/replace_module.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/module_inject/replace_module.py | Apache-2.0 |
def revert_transformer_layer(orig_layer_impl, model, config, preln=False):
""" 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.... | 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 represe... | revert_transformer_layer | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/module_inject/replace_module.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/module_inject/replace_module.py | Apache-2.0 |
def replace_module(model, orig_class, replace_fn, _replace_policy):
""" Scan the model for instances of ``orig_clas:`` to replace using ``replace_fn``.
Arguments:
model (torch.nn.Module): the model to augment
orig_class (torch.nn.Module): the module to search for
replace_fn (method): a m... | Scan the model for instances of ``orig_clas:`` to replace using ``replace_fn``.
Arguments:
model (torch.nn.Module): the model to augment
orig_class (torch.nn.Module): the module to search for
replace_fn (method): a method to convert instances of ``orig_class`` to the
... | replace_module | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/module_inject/replace_module.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/module_inject/replace_module.py | Apache-2.0 |
def _replace_module(model, policies, layer_id=0):
""" Traverse model's children recursively and apply any transformations in ``policies``.
Arguments:
model (torch.nn.Module): model to augment
policies (dict): Mapping of source class to replacement function.
Returns:
Modified ``model`... | Traverse model's children recursively and apply any transformations in ``policies``.
Arguments:
model (torch.nn.Module): model to augment
policies (dict): Mapping of source class to replacement function.
Returns:
Modified ``model``.
| _replace_module | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/module_inject/replace_module.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/module_inject/replace_module.py | Apache-2.0 |
def forward(self, hidden_states, used_token=None):
""" MoE forward
Arguments:
hidden_states (Tensor): input to the layer
used_token (Tensor, optional): default: None, mask only used tokens
Returns:
A tuple including output, gate loss, and expert count.
... | MoE forward
Arguments:
hidden_states (Tensor): input to the layer
used_token (Tensor, optional): default: None, mask only used tokens
Returns:
A tuple including output, gate loss, and expert count.
* output (Tensor): output of the model
* ... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/moe/layer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/moe/layer.py | Apache-2.0 |
def _gather_tokens(input_, dim=0):
"""Gather tensors and concatenate them along a dimension"""
mpu = deepspeed.utils.groups.mpu
input_ = input_.contiguous()
# Size and dimension.
rank = mpu.get_tensor_model_parallel_rank()
tensor_list = [
torch.empty_like(input_)
for _ in range... | Gather tensors and concatenate them along a dimension | _gather_tokens | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/moe/mappings.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/moe/mappings.py | Apache-2.0 |
def _drop_tokens(input_, dim=0):
"""Divide a tensor among the tensor parallel ranks"""
mpu = deepspeed.utils.groups.mpu
total_chunks = mpu.get_tensor_model_parallel_world_size()
this_chunk = mpu.get_tensor_model_parallel_rank()
assert input_.shape[dim] % total_chunks == 0, f"input dimension {dim} (... | Divide a tensor among the tensor parallel ranks | _drop_tokens | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/moe/mappings.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/moe/mappings.py | Apache-2.0 |
def multiplicative_jitter(x, device: torch.device, epsilon=1e-2):
"""
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... |
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.de... | multiplicative_jitter | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/moe/sharded_moe.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/moe/sharded_moe.py | Apache-2.0 |
def split_params_grads_into_shared_and_expert_params(
group: List[torch.nn.Parameter]) -> Tuple[torch.nn.Parameter,
torch.nn.Parameter]:
"""Split grad of parameters into grads of non-expert params
and grads of expert params. This is useful while computin... | 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... | split_params_grads_into_shared_and_expert_params | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/moe/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/moe/utils.py | Apache-2.0 |
def split_params_into_different_moe_groups_for_optimizer(param_groups: Tuple[Dict],
max_group_size=178956971
) -> Tuple[Dict]:
"""Split parameters into different MoE groups for optimizer
Args:
... | 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
| split_params_into_different_moe_groups_for_optimizer | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/moe/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/moe/utils.py | Apache-2.0 |
def step(self, closure=None, fp16_param_groups=None):
"""Update the model parameters.
.. note::
This method will be called internally by ZeRO-Offload. DeepSpeed
users should still use ``engine.step()`` as shown in the
`Getting Started
<https://www.deepspe... | Update the model parameters.
.. note::
This method will be called internally by ZeRO-Offload. DeepSpeed
users should still use ``engine.step()`` as shown in the
`Getting Started
<https://www.deepspeed.ai/getting-started/#training>`_ guide.
Args:
... | step | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/adagrad/cpu_adagrad.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/adagrad/cpu_adagrad.py | Apache-2.0 |
def __init__(self,
model_params,
lr=1e-3,
bias_correction=True,
betas=(0.9,
0.999),
eps=1e-8,
weight_decay=0,
amsgrad=False,
adamw_mode=True,
f... | Fast vectorized implementation of two variations of Adam optimizer on CPU:
* Adam: A Method for Stochastic Optimization: (https://arxiv.org/abs/1412.6980);
* AdamW: Fixing Weight Decay Regularization in Adam (https://arxiv.org/abs/1711.05101)
DeepSpeed CPU Adam(W) provides between 5x to 7x spe... | __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/adam/cpu_adam.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/adam/cpu_adam.py | Apache-2.0 |
def step(self,
closure=None,
grads=None,
output_params=None,
scale=None,
grad_norms=None):
"""Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
a... | Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
The remaining arguments are deprecated, and are only retained (for the moment) for error-checking purposes.
| step | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/adam/fused_adam.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/adam/fused_adam.py | Apache-2.0 |
def step(self,
closure=None,
grads=None,
output_params=None,
scale=1.,
grad_norms=None):
"""Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and... | Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
grads (list of tensors, optional): weight gradient to use for the
optimizer update. If gradients have type torch.half,... | step | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/lamb/fused_lamb.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/lamb/fused_lamb.py | Apache-2.0 |
def __init__(
self,
config,
# SparsityConfig parameters needs to be set accordingly
sparsity_config=FixedSparsityConfig(num_heads=4)):
"""Initialize the bert sparse self attention layer.
Note) you can use any of the provided sparsity configs or simply add yours!
... | Initialize the bert sparse self attention layer.
Note) you can use any of the provided sparsity configs or simply add yours!
Arguments:
config: required: Bert model config
sparsity_config: optional: this parameter determines sparsity pattern configuration; it is based on FixedS... | __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/bert_sparse_self_attention.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/bert_sparse_self_attention.py | Apache-2.0 |
def forward(self, hidden_states, attention_mask):
"""Applies forward phase of bert sparse self attention
Arguments:
hidden_states: required: hidden_states tensor of the bert model
attn_mask: required: a mask tensor of size (SequenceLength X SequenceLength); currently only 2D is ... | Applies forward phase of bert sparse self attention
Arguments:
hidden_states: required: hidden_states tensor of the bert model
attn_mask: required: a mask tensor of size (SequenceLength X SequenceLength); currently only 2D is supported
Return:
context_layer: a dens... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/bert_sparse_self_attention.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/bert_sparse_self_attention.py | Apache-2.0 |
def make_lut(self, dtype, device):
"""Generates the sparsity layout/s used in block-sparse matmul
"""
key = (dtype, device)
if key in self.lut_cache:
return self.lut_cache[key]
# C look-up table
layout, block = self.layout, self.block
step = 16
... | Generates the sparsity layout/s used in block-sparse matmul
| make_lut | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/matmul.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/matmul.py | Apache-2.0 |
def __init__(self, layout, block, mode, trans_a=False, trans_b=False, bench=False):
"""Initialize the Block-Sparse MatMul class.
Arguments:
layout: required: sparsity layout tensor
block: required: an integer determining the block size.
mode: required: a string de... | Initialize the Block-Sparse MatMul class.
Arguments:
layout: required: sparsity layout tensor
block: required: an integer determining the block size.
mode: required: a string determining type of matmul; ('sdd') sparse = dense X dense, ('dsd') dense = sparse X dense, ('dds... | __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/matmul.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/matmul.py | Apache-2.0 |
def __call__(self, a, b):
"""Applies Block-Sparse MatMul.
For more details about sparsity config, please see `Generative Modeling with Sparse Transformers`: https://arxiv.org/abs/1904.10509
Arguments:
a: required: a dense/block-sparse tensor; first input of mat-mul
b:... | Applies Block-Sparse MatMul.
For more details about sparsity config, please see `Generative Modeling with Sparse Transformers`: https://arxiv.org/abs/1904.10509
Arguments:
a: required: a dense/block-sparse tensor; first input of mat-mul
b: required: a dense/block-sparse tenso... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/matmul.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/matmul.py | Apache-2.0 |
def make_lut(self, device):
"""Generates the sparsity layout used in block-sparse softmax
"""
key = (device, )
if key not in self.lut_cache:
self.lut_cache[key] = _sparse_softmax.make_lut(self.layout,
self.block,
... | Generates the sparsity layout used in block-sparse softmax
| make_lut | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/softmax.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/softmax.py | Apache-2.0 |
def __init__(self, layout, block, bench=False):
"""Initialize the Block-Sparse Softmax class.
Arguments:
layout: required: sparsity layout tensor
block: required: an integer determining the block size.
bench: optional: set if you want to do benchmarking
""... | Initialize the Block-Sparse Softmax class.
Arguments:
layout: required: sparsity layout tensor
block: required: an integer determining the block size.
bench: optional: set if you want to do benchmarking
| __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/softmax.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/softmax.py | Apache-2.0 |
def __call__(self,
x,
scale=1.,
rpe=None,
key_padding_mask=None,
attn_mask=None,
key_padding_mask_mode='add',
attn_mask_mode='add'):
"""Applies softmax on a Block-Sparse input tensor.
... | Applies softmax on a Block-Sparse input tensor.
For more details about sparsity config, please see `Generative Modeling with Sparse Transformers`: https://arxiv.org/abs/1904.10509
Arguments:
x: required: a block-sparse tensor that softmax is applied on it; computation will be in place and... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/softmax.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/softmax.py | Apache-2.0 |
def extend_position_embedding(model, max_position):
"""This function extends the position embedding weights of a model loaded from a checkpoint.
It assumes the new max position is bigger than the original max length.
Arguments:
model: required: a transformer model
max_po... | This function extends the position embedding weights of a model loaded from a checkpoint.
It assumes the new max position is bigger than the original max length.
Arguments:
model: required: a transformer model
max_position: required: an integer determining new position embedding... | extend_position_embedding | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_attention_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_attention_utils.py | Apache-2.0 |
def update_tokenizer_model_max_length(tokenizer, max_position):
"""This function updates the position embedding length of a tokenizer to a new max position.
Arguments:
tokenizer: required: a transformer tokenizer
max_position: required: an integer determining new position embedd... | This function updates the position embedding length of a tokenizer to a new max position.
Arguments:
tokenizer: required: a transformer tokenizer
max_position: required: an integer determining new position embedding size
Return:
tokenizer: updated tokenizer; in which... | update_tokenizer_model_max_length | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_attention_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_attention_utils.py | Apache-2.0 |
def replace_model_self_attention_with_sparse_self_attention(
model,
max_position,
# SparsityConfig parameters needs to be set accordingly
sparsity_config=SparsityConfig(num_heads=4)):
"""This function replaces the self attention layers in model encoder with sparse self attention.... | This function replaces the self attention layers in model encoder with sparse self attention.
It currently supports bert and roberta model and can be easily extended to any other models following similar steps here.
For sparsityConfig, refer to the config class.
Arguments:
model: re... | replace_model_self_attention_with_sparse_self_attention | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_attention_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_attention_utils.py | Apache-2.0 |
def replace_self_attention_layer_with_sparse_self_attention_layer(
config,
layers,
# SparsityConfig parameters needs to be set accordingly
sparsity_config=SparsityConfig(num_heads=4)):
"""This function replaces the self attention layers in attention layer with sparse self attenti... | This function replaces the self attention layers in attention layer with sparse self attention.
For sparsityConfig, refer to the config class.
Arguments:
config: required: transformer model config
layers: required: transformer model attention layers
sparsity_config: ... | replace_self_attention_layer_with_sparse_self_attention_layer | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_attention_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_attention_utils.py | Apache-2.0 |
def pad_to_block_size(block_size,
input_ids,
attention_mask,
token_type_ids,
position_ids,
inputs_embeds,
pad_token_id,
model_embeddings):... | This function pads input tokens and attention mask on sequence length dimension to be multiple of block size.
This is a requirement for Sparse Transformer in which the self attention layer works on sequences of length multiple of block size.
It needs to be called in your model, such as BertModel... | pad_to_block_size | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_attention_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_attention_utils.py | Apache-2.0 |
def unpad_sequence_output(pad_len, sequence_output):
"""This function unpads sequence output if inputs of the model were padded.
This is a requirement for Sparse Transformer in which the self attention layer works on sequences of length multiple of block size.
It needs to be called in your... | This function unpads sequence output if inputs of the model were padded.
This is a requirement for Sparse Transformer in which the self attention layer works on sequences of length multiple of block size.
It needs to be called in your model, such as BertModel, right before you return the model out... | unpad_sequence_output | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_attention_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_attention_utils.py | Apache-2.0 |
def __init__(
self,
# SparsityConfig parameters needs to be set accordingly
sparsity_config=SparsityConfig(num_heads=4),
key_padding_mask_mode='add',
attn_mask_mode='mul',
max_seq_length=2048):
"""Initialize the sparse self attention layer.... | Initialize the sparse self attention layer.
Arguments:
sparsity_config: optional: this parameter determines sparsity pattern configuration; it is based on SparsityConfig class.
key_padding_mask_mode: optional: a string determining if key padding mask needs to be added, `add`, or be multi... | __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_self_attention.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_self_attention.py | Apache-2.0 |
def forward(self,
query,
key,
value,
rpe=None,
key_padding_mask=None,
attn_mask=None):
"""Applies forward phase of sparse self attention
Arguments:
query: required: query tensor
key: ... | Applies forward phase of sparse self attention
Arguments:
query: required: query tensor
key: required: key tensor
value: required: value tensor
rpe: optional: a tensor same dimension as x that is used as relative position embedding
key_padding_mask: o... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_self_attention.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparse_self_attention.py | Apache-2.0 |
def __init__(self, num_heads, block=16, different_layout_per_head=False):
"""Initialize the Sparsity Pattern Config.
For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial
Arguments:
num_heads: required: an integer determining number of attention heads of the lay... | Initialize the Sparsity Pattern Config.
For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial
Arguments:
num_heads: required: an integer determining number of attention heads of the layer.
block: optional: an integer determining the block size. Current impl... | __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | Apache-2.0 |
def setup_layout(self, seq_len):
"""Create layout tensor for the given sequence length
Arguments:
seq_len: required: an integer determining number of attention heads of the layer.
Return:
layout: a tensor of dimension (num_heads, num_blocks, num_blocks) for sparsity l... | Create layout tensor for the given sequence length
Arguments:
seq_len: required: an integer determining number of attention heads of the layer.
Return:
layout: a tensor of dimension (num_heads, num_blocks, num_blocks) for sparsity layout of all head; initialized with zero
... | setup_layout | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | Apache-2.0 |
def check_and_propagate_first_head_layout(self, layout):
"""If all heads require same sparsity layout, it propagate first head layout to all heads
Arguments:
layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head; may not be compl... | If all heads require same sparsity layout, it propagate first head layout to all heads
Arguments:
layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head; may not be completely set at this step
Return:
layout: a tenso... | check_and_propagate_first_head_layout | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | Apache-2.0 |
def make_layout(self, seq_len):
"""Set 1 to all blocks of the layout meanins the pattern is dense; not sparse.
Arguments:
seq_len: required: an integer determining the underling sequence length; must be <= max sequence length
Return:
layout: a tensor of dimension (num... | Set 1 to all blocks of the layout meanins the pattern is dense; not sparse.
Arguments:
seq_len: required: an integer determining the underling sequence length; must be <= max sequence length
Return:
layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing ... | make_layout | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | Apache-2.0 |
def set_local_layout(self, h, layout):
"""Sets local attention layout used by the given head in the sparse attention.
Arguments:
h: required: an integer determining head index
layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layou... | Sets local attention layout used by the given head in the sparse attention.
Arguments:
h: required: an integer determining head index
layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head; may not be completely set at this s... | set_local_layout | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | Apache-2.0 |
def set_global_layout(self, h, layout):
"""Sets global attention layout used by the given head in the sparse attention.
Currently we set global blocks starting from the last block of a local window to the first one. That means if a local window consists of 4 blocks and global attention size is one bloc... | Sets global attention layout used by the given head in the sparse attention.
Currently we set global blocks starting from the last block of a local window to the first one. That means if a local window consists of 4 blocks and global attention size is one block, we use block #4 in each local window as global. ... | set_global_layout | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | Apache-2.0 |
def make_layout(self, seq_len):
"""Generates `Fixed` sparsity layout used by each head in the sparse attention.
Arguments:
seq_len: required: an integer determining number of attention heads of the layer.
Return:
layout: a tensor of dimension (num_heads, num_blocks, n... | Generates `Fixed` sparsity layout used by each head in the sparse attention.
Arguments:
seq_len: required: an integer determining number of attention heads of the layer.
Return:
layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing `Fixed` sparsity layo... | make_layout | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | Apache-2.0 |
def __init__(self,
num_heads,
block=16,
different_layout_per_head=False,
num_random_blocks=0,
local_window_blocks=[4],
global_block_indices=[0],
global_block_end_indices=None,
attentio... | Initialize `Variable` Sparsity Pattern Config.
For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial
Arguments:
num_heads: required: an integer determining number of attention heads of the layer.
block: optional: an integer determining the block size. Curre... | __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | Apache-2.0 |
def set_random_layout(self, h, layout):
"""Sets random attention layout used by the given head in the sparse attention.
Note) By default, it assumes there will be a unique random block layout for all heads; unless `different_layout_per_head` parameter is set in which each head can have a different rando... | Sets random attention layout used by the given head in the sparse attention.
Note) By default, it assumes there will be a unique random block layout for all heads; unless `different_layout_per_head` parameter is set in which each head can have a different random layout.
Arguments:
h: requi... | set_random_layout | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | Apache-2.0 |
def set_local_layout(self, h, layout):
"""Sets local attention layout used by the given head in the sparse attention.
Arguments:
h: required: an integer determining head index
layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout... | Sets local attention layout used by the given head in the sparse attention.
Arguments:
h: required: an integer determining head index
layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout of all head; may not be completely set at this st... | set_local_layout | python | FMInference/FlexLLMGen | benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/sparsity_config.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.