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 set_global_layout(self, h, layout): """Sets global 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 lay...
Sets global 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 ...
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 `Variable` 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...
Generates `Variable` 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 `Variable` sparsit...
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=1, num_sliding_window_blocks=3, num_global_blocks=1, attention='bidirectional'): """Initialize the Big...
Initialize the BigBird 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. Curr...
__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_sliding_window_layout(self, h, layout): """Sets sliding 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) containi...
Sets sliding 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 a...
set_sliding_window_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 `BigBird` 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,...
Generates `BigBird` 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 `BigBird` sparsity ...
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_sliding_window_blocks=3, global_block_indices=[0], global_block_end_indices=None, attention='bidirectional'): """Ini...
Initialize the edited `Longformer` 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 bloc...
__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 make_layout(self, seq_len): """Generates edited `Longformer` 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, n...
Generates edited `Longformer` 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 `BSLongfo...
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, num_sliding_window_blocks=3, attention='unidirectional'): """Initialize the Local Sliding Window Sparsity Pattern Config. For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial ...
Initialize the Local Sliding Window 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...
__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_sliding_window_layout(self, h, layout): """Sets sliding 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) containin...
Sets sliding 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...
set_sliding_window_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 `Local Sliding Window` 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, ...
Generates `Local Sliding Window` 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 `BigBird...
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 _build_file_index(directory, suffix='.tr'): """Build an index of source files and their basenames in a given directory. Args: directory (string): the directory to index suffix (string): index files with this suffix Returns: list: A list of tuples of the form [(basename, absolut...
Build an index of source files and their basenames in a given directory. Args: directory (string): the directory to index suffix (string): index files with this suffix Returns: list: A list of tuples of the form [(basename, absolute path), ...]
_build_file_index
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/trsrc/__init__.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/sparse_attention/trsrc/__init__.py
Apache-2.0
def split_tensor_along_last_dim(tensor, num_partitions, contiguous_split_chunks=True): """Split a tensor along its last dimension. Args: tensor: ([`torch.tensor`], *required*): in...
Split a tensor along its last dimension. Args: tensor: ([`torch.tensor`], *required*): input tensor to split num_partitions ([`int`], *required*): number of partitions to split the tensor contiguous_split_chunks ([`bool...
split_tensor_along_last_dim
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/ops/transformer/inference/ds_attention.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/ops/transformer/inference/ds_attention.py
Apache-2.0
def start_profile(self, ignore_list=None): """Starts profiling. Extra attributes are added recursively to all the modules and the profiled torch.nn.functionals are monkey patched. Args: ignore_list (list, optional): the list of modules to ignore while profiling. Defaults to None. ...
Starts profiling. Extra attributes are added recursively to all the modules and the profiled torch.nn.functionals are monkey patched. Args: ignore_list (list, optional): the list of modules to ignore while profiling. Defaults to None.
start_profile
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
Apache-2.0
def stop_profile(self): """Stop profiling. All torch.nn.functionals are restored to their originals. """ if self.started and self.func_patched: _reload_functionals() _reload_tensor_methods() self.func_patched = False def remove_profile_attrs(...
Stop profiling. All torch.nn.functionals are restored to their originals.
stop_profile
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
Apache-2.0
def reset_profile(self): """Resets the profiling. Adds or resets the extra attributes. """ def add_or_reset_attrs(module): module.__flops__ = 0 module.__macs__ = 0 module.__params__ = sum(p.numel() for p in module.parameters()) module.__st...
Resets the profiling. Adds or resets the extra attributes.
reset_profile
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
Apache-2.0
def end_profile(self): """Ends profiling. The added attributes and handles are removed recursively on all the modules. """ if not self.started: return self.stop_profile() self.started = False def remove_profile_attrs(module): if hasattr(m...
Ends profiling. The added attributes and handles are removed recursively on all the modules.
end_profile
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
Apache-2.0
def get_total_flops(self, as_string=False): """Returns the total flops of the model. Args: as_string (bool, optional): whether to output the flops as string. Defaults to False. Returns: The number of multiply-accumulate operations of the model forward pass. """ ...
Returns the total flops of the model. Args: as_string (bool, optional): whether to output the flops as string. Defaults to False. Returns: The number of multiply-accumulate operations of the model forward pass.
get_total_flops
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
Apache-2.0
def get_total_macs(self, as_string=False): """Returns the total MACs of the model. Args: as_string (bool, optional): whether to output the flops as string. Defaults to False. Returns: The number of multiply-accumulate operations of the model forward pass. """ ...
Returns the total MACs of the model. Args: as_string (bool, optional): whether to output the flops as string. Defaults to False. Returns: The number of multiply-accumulate operations of the model forward pass.
get_total_macs
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
Apache-2.0
def get_total_duration(self, as_string=False): """Returns the total duration of the model forward pass. Args: as_string (bool, optional): whether to output the duration as string. Defaults to False. Returns: The latency of the model forward pass. """ tot...
Returns the total duration of the model forward pass. Args: as_string (bool, optional): whether to output the duration as string. Defaults to False. Returns: The latency of the model forward pass.
get_total_duration
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
Apache-2.0
def get_total_params(self, as_string=False): """Returns the total parameters of the model. Args: as_string (bool, optional): whether to output the parameters as string. Defaults to False. Returns: The number of parameters in the model. """ return params_...
Returns the total parameters of the model. Args: as_string (bool, optional): whether to output the parameters as string. Defaults to False. Returns: The number of parameters in the model.
get_total_params
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
Apache-2.0
def print_model_aggregated_profile(self, module_depth=-1, top_modules=1): """Prints the names of the top top_modules modules in terms of aggregated time, flops, and parameters at depth module_depth. Args: module_depth (int, optional): the depth of the modules to show. Defaults to -1 (the in...
Prints the names of the top top_modules modules in terms of aggregated time, flops, and parameters at depth module_depth. Args: module_depth (int, optional): the depth of the modules to show. Defaults to -1 (the innermost modules). top_modules (int, optional): the number of top modules ...
print_model_aggregated_profile
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
Apache-2.0
def _matmul_flops_compute(input, other, *, out=None): """ Count flops for the matmul operation. """ macs = _prod(input.shape) * other.shape[-1] return 2 * macs, macs
Count flops for the matmul operation.
_matmul_flops_compute
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
Apache-2.0
def _addmm_flops_compute(input, mat1, mat2, *, beta=1, alpha=1, out=None): """ Count flops for the addmm operation. """ macs = _prod(mat1.shape) * mat2.shape[-1] return 2 * macs + _prod(input.shape), macs
Count flops for the addmm operation.
_addmm_flops_compute
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
Apache-2.0
def _einsum_flops_compute(equation, *operands): """ Count flops for the einsum operation. """ equation = equation.replace(" ", "") input_shapes = [o.shape for o in operands] # Re-map equation so that same equation with different alphabet # representations will look the same. letter_orde...
Count flops for the einsum operation.
_einsum_flops_compute
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
Apache-2.0
def _tensor_addmm_flops_compute(self, mat1, mat2, *, beta=1, alpha=1, out=None): """ Count flops for the tensor addmm operation. """ macs = _prod(mat1.shape) * mat2.shape[-1] return 2 * macs + _prod(self.shape), macs
Count flops for the tensor addmm operation.
_tensor_addmm_flops_compute
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
Apache-2.0
def get_model_profile( model, input_shape=None, args=[], kwargs={}, print_profile=True, detailed=True, module_depth=-1, top_modules=1, warm_up=1, as_string=True, output_file=None, ignore_modules=None, ): """Returns the total floating-point operations, MACs, and parame...
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 ([t...
get_model_profile
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py
Apache-2.0
def initialize_optimizer_states(self): """Take an optimizer step with zero-valued gradients to allocate internal optimizer state. This helps prevent memory fragmentation by allocating optimizer state at the beginning of training instead of after activations have been allocated. ...
Take an optimizer step with zero-valued gradients to allocate internal optimizer state. This helps prevent memory fragmentation by allocating optimizer state at the beginning of training instead of after activations have been allocated.
initialize_optimizer_states
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/bf16_optimizer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/bf16_optimizer.py
Apache-2.0
def backward(self, loss, update_hp_grads=True, clear_lp_grads=False, **bwd_kwargs): """Perform a backward pass and copy the low-precision gradients to the high-precision copy. We copy/accumulate to the high-precision grads now to prevent accumulating in the bf16 grads after successive b...
Perform a backward pass and copy the low-precision gradients to the high-precision copy. We copy/accumulate to the high-precision grads now to prevent accumulating in the bf16 grads after successive backward() calls (i.e., grad accumulation steps > 1) The low-precision grads are deallo...
backward
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/bf16_optimizer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/bf16_optimizer.py
Apache-2.0
def __init__(self, loader): """Wraps an iterator to allow for infinite iteration. This is especially useful for DataLoader types that we wish to automatically restart upon completion. Args: loader (iterator): The data loader to repeat. """ self.loader = loader ...
Wraps an iterator to allow for infinite iteration. This is especially useful for DataLoader types that we wish to automatically restart upon completion. Args: loader (iterator): The data loader to repeat.
__init__
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/dataloader.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/dataloader.py
Apache-2.0
def get_batch_info(self): """Get all training batch related settings. Returns: train_batch_size (int): The effective training batch size. This is the amount of data samples that leads to one step of model update. train_micro_batch_size_per_gpu (int): Batch size to...
Get all training batch related settings. Returns: train_batch_size (int): The effective training batch size. This is the amount of data samples that leads to one step of model update. train_micro_batch_size_per_gpu (int): Batch size to be processed by one GPU in one ...
get_batch_info
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
Apache-2.0
def set_train_batch_size(self, train_batch_size): """Adjust the global batch size by increasing or decreasing the number of micro-batches (i.e., gradient accumulation steps). The size of each micro-batch (i.e., ``train_micro_batch_size_per_gpu``) is not changed. Args: train_b...
Adjust the global batch size by increasing or decreasing the number of micro-batches (i.e., gradient accumulation steps). The size of each micro-batch (i.e., ``train_micro_batch_size_per_gpu``) is not changed. Args: train_batch_size (int): The new global batch size for training. ...
set_train_batch_size
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
Apache-2.0
def __getattr__(self, name): """ Pass through attributes defined in the model if they are not overridden by ds-engine. """ _module = {} if "module" in self.__dict__: _module = self.__dict__['module'] if name in dir(self): return getattr(self, name...
Pass through attributes defined in the model if they are not overridden by ds-engine.
__getattr__
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
Apache-2.0
def forward(self, *inputs, **kwargs): r"""Execute forward propagation Arguments: *inputs: Variable length input list **kwargs: variable length keyword arguments """ if self.autotuning_profile_model_info(): ma = get_ma_status() else: ...
Execute forward propagation Arguments: *inputs: Variable length input list **kwargs: variable length keyword arguments
forward
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
Apache-2.0
def backward(self, loss, allreduce_gradients=True, release_loss=False, retain_graph=False, scale_wrt_gas=True): r"""Execute backward pass on the loss Arguments: loss: Torch tensor on which to execute backwar...
Execute backward pass on the loss Arguments: loss: Torch tensor on which to execute backward propagation allreduce_gradients: is deprecated, ignored, and will soon be removed' retain_graph: bool, default: false forward on user defined choice of retain_graph ...
backward
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
Apache-2.0
def is_gradient_accumulation_boundary(self): """Query whether the current micro-batch is at the boundary of gradient accumulation, and thus will trigger gradient reductions and an optimizer step. Returns: bool: if the current step is a gradient accumulation boundary. ...
Query whether the current micro-batch is at the boundary of gradient accumulation, and thus will trigger gradient reductions and an optimizer step. Returns: bool: if the current step is a gradient accumulation boundary.
is_gradient_accumulation_boundary
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
Apache-2.0
def set_gradient_accumulation_boundary(self, is_boundary): """Manually overrides the DeepSpeed engine's gradient accumulation boundary state, this is an optional feature and should be used with care. The state should be set before to the intended value before each forward/backward. The final for...
Manually overrides the DeepSpeed engine's gradient accumulation boundary state, this is an optional feature and should be used with care. The state should be set before to the intended value before each forward/backward. The final fordward/backward should have the boundary state set to True. Thi...
set_gradient_accumulation_boundary
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
Apache-2.0
def step(self, lr_kwargs=None): r"""Execute the weight update step after forward and backward propagation on effective_train_batch. """ see_memory_usage("Engine before step", force=self.memory_breakdown()) # Check early because self.global_steps is incremented at some point here...
Execute the weight update step after forward and backward propagation on effective_train_batch.
step
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
Apache-2.0
def load_checkpoint(self, load_dir, tag=None, load_module_strict=True, load_optimizer_states=True, load_lr_scheduler_states=True, load_module_only=False, ...
Load training checkpoint Arguments: load_dir: Required. Directory to load the checkpoint from tag: Checkpoint tag used as a unique identifier for checkpoint, if not provided will attempt to load tag in 'latest' file load_module_strict: Optional. Boolean to strictly enforce th...
load_checkpoint
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
Apache-2.0
def save_checkpoint(self, save_dir, tag=None, client_state={}, save_latest=True): r"""Save training checkpoint Arguments: save_dir: Required. Directory for saving the checkpoint tag: Optional. Checkpoint tag used as a unique identifier for the checkpoint, global step is ...
Save training checkpoint Arguments: save_dir: Required. Directory for saving the checkpoint tag: Optional. Checkpoint tag used as a unique identifier for the checkpoint, global step is used if not provided. Tag name must be the same across all ranks. client_st...
save_checkpoint
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
Apache-2.0
def _get_non_moe_state_dict(self, full_state_dict): """ Get the state dict of the non-moe layers """ for key in list(full_state_dict.keys()): if 'expert' in key and 'moe.gate.wg.weight' not in key: full_state_dict.pop(key) return full_state_dict
Get the state dict of the non-moe layers
_get_non_moe_state_dict
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
Apache-2.0
def _get_zero_param_shapes(self): """Returns a dict of name to shape mapping, only for the flattened fp32 weights saved by the optimizer. the names are exactly as in state_dict. The order is absolutely important, since the saved data is just flattened data with no identifiers and requires recons...
Returns a dict of name to shape mapping, only for the flattened fp32 weights saved by the optimizer. the names are exactly as in state_dict. The order is absolutely important, since the saved data is just flattened data with no identifiers and requires reconstruction in the same order it was sav...
_get_zero_param_shapes
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
Apache-2.0
def _zero3_consolidated_16bit_state_dict(self): """ Get a full non-partitioned state_dict with fp16 weights on cpu. Important: this function must be called on all ranks and not just rank 0. This is similar to nn.Module.state_dict (modelled after _save_to_state_dict), but: 1. cons...
Get a full non-partitioned state_dict with fp16 weights on cpu. Important: this function must be called on all ranks and not just rank 0. This is similar to nn.Module.state_dict (modelled after _save_to_state_dict), but: 1. consolidates the weights from different partitions on gpu0 ...
_zero3_consolidated_16bit_state_dict
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
Apache-2.0
def save_16bit_model(self, save_dir, save_filename="pytorch_model.bin"): r"""Save 16bit model weights This method saves the 16bit model weights at the desired destination. Arguments: save_dir: Required. Directory for saving the model save_filename: Optional. Filename to s...
Save 16bit model weights This method saves the 16bit model weights at the desired destination. Arguments: save_dir: Required. Directory for saving the model save_filename: Optional. Filename to save to. Defaults to ``pytorch_model.bin`` Returns: ``True`` when ...
save_16bit_model
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py
Apache-2.0
def _get_decay_lr(self, decay_batch_iteration): """Calculates the learning rate at batch index. This function is used after the cycle completes and post cycle decaying of lr/mom is enabled. This function treats `self.last_batch_iteration` as the last batch index. """ if self.skip...
Calculates the learning rate at batch index. This function is used after the cycle completes and post cycle decaying of lr/mom is enabled. This function treats `self.last_batch_iteration` as the last batch index.
_get_decay_lr
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/lr_schedules.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/lr_schedules.py
Apache-2.0
def get_lr(self): """Calculates the learning rate at batch index. This function treats `self.last_batch_iteration` as the last batch index. """ if self.last_batch_iteration < self.total_size: return self._get_cycle_lr() return self._get_decay_lr(self.last_batch_iterat...
Calculates the learning rate at batch index. This function treats `self.last_batch_iteration` as the last batch index.
get_lr
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/lr_schedules.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/lr_schedules.py
Apache-2.0
def get_mom(self): """Calculates the momentum at batch index. This function treats `self.last_batch_iteration` as the last batch index. """ if not self.cycle_momentum: return None if self.last_batch_iteration < self.total_size: return self._get_cycle_mom(...
Calculates the momentum at batch index. This function treats `self.last_batch_iteration` as the last batch index.
get_mom
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/lr_schedules.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/lr_schedules.py
Apache-2.0
def step(self, batch_iteration=None): """ Updates the optimizer with the learning rate for the last batch index. `self.last_batch_iteration` is treated as the last batch index. If self.cycle_momentum is true, also updates optimizer momentum. """ if batch_iteration is None: ...
Updates the optimizer with the learning rate for the last batch index. `self.last_batch_iteration` is treated as the last batch index. If self.cycle_momentum is true, also updates optimizer momentum.
step
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/lr_schedules.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/lr_schedules.py
Apache-2.0
def merge_query_key_value(self, param_list, ckpt_ver): """ Up to now we found 3 Q/K/V parameter formats in different Megatron checkpoint versions: 1. version 0, there is no version information saved in checkpoint. format: [(3 * np * hn), h] 2. version 1.0 format:...
Up to now we found 3 Q/K/V parameter formats in different Megatron checkpoint versions: 1. version 0, there is no version information saved in checkpoint. format: [(3 * np * hn), h] 2. version 1.0 format: [(np * hn * 3), h] 3. version 2.0 format: [(n...
merge_query_key_value
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/state_dict_factory.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/state_dict_factory.py
Apache-2.0
def set_random_seed(seed): """Set the random seed for common PRNGs used during training: random, numpy, and torch. Args: seed (int): the seed to use """ import numpy import random random.seed(seed) numpy.random.seed(seed) torch.manual_seed(seed)
Set the random seed for common PRNGs used during training: random, numpy, and torch. Args: seed (int): the seed to use
set_random_seed
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
Apache-2.0
def bwc_tensor_model_parallel_rank(mpu=None): """Backwards-compatible way of querying the tensor model parallel rank from an ``mpu`` object. *Tensor* model parallelism means that tensors are physically split across processes. This contrasts with *pipeline* model parallelism, in which the layers are...
Backwards-compatible way of querying the tensor model parallel rank from an ``mpu`` object. *Tensor* model parallelism means that tensors are physically split across processes. This contrasts with *pipeline* model parallelism, in which the layers are partitioned but tensors left intact. The API fo...
bwc_tensor_model_parallel_rank
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
Apache-2.0
def copy_to_device(item, device, criterion_func): """ Return a copy of tensor on specified device. Works on individual tensors, and tensors contained/nested in lists, tuples, and dicts. Parameters: item: tensor to copy or (possibly nested) container of tensors to copy. device: target dev...
Return a copy of tensor on specified device. Works on individual tensors, and tensors contained/nested in lists, tuples, and dicts. Parameters: item: tensor to copy or (possibly nested) container of tensors to copy. device: target device criterion_func: Function to restrict copy ope...
copy_to_device
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
Apache-2.0
def move_to_device(item, device, criterion_func): """ Move tensor on to specified device by changing the storage. Works on individual tensors, and tensors contained/nested in lists, tuples, and dicts. Parameters: item: tensor to move or (possibly nested) container of tensors to move. dev...
Move tensor on to specified device by changing the storage. Works on individual tensors, and tensors contained/nested in lists, tuples, and dicts. Parameters: item: tensor to move or (possibly nested) container of tensors to move. device: target device criterion_func: Function to re...
move_to_device
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
Apache-2.0
def get_global_norm(norm_list): """ Compute total from a list of norms """ total_norm = 0.0 for norm in norm_list: total_norm += norm**2.0 return sqrt(total_norm)
Compute total from a list of norms
get_global_norm
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
Apache-2.0
def clip_grad_norm_(parameters, max_norm, norm_type=2, mpu=None): """Clips gradient norm of an iterable of parameters. This has been adapted from Nvidia megatron. We add norm averaging to consider MoE params when calculating norm as they will result in different norms across different ranks. This ...
Clips gradient norm of an iterable of parameters. This has been adapted from Nvidia megatron. We add norm averaging to consider MoE params when calculating norm as they will result in different norms across different ranks. This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and added fu...
clip_grad_norm_
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
Apache-2.0
def get_grad_norm(parameters, norm_type=2, mpu=None): """Get grad norm of an iterable of parameters. This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and added functionality to handle model parallel parameters. Note that the gradients are modified in place. Taken from Nvidia Megatron. ...
Get grad norm of an iterable of parameters. This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and added functionality to handle model parallel parameters. Note that the gradients are modified in place. Taken from Nvidia Megatron. Arguments: parameters (Iterable[Tensor] or Tensor): ...
get_grad_norm
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
Apache-2.0
def get_grad_zeros(parameters, mpu=None): """Compute the number of grads with zero values. This is adapted from get_grad_norm Arguments: parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a single Tensor that will have gradients normalized Returns: Total nu...
Compute the number of grads with zero values. This is adapted from get_grad_norm Arguments: parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a single Tensor that will have gradients normalized Returns: Total number of params with zero values (viewed as a sing...
get_grad_zeros
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
Apache-2.0
def get_weight_norm(parameters, norm_type=2, mpu=None): """Get norm of an iterable of parameters. This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and added functionality to handle model parallel parameters. Note that the gradients are modified in place. Taken from Nvidia Megatron. Ar...
Get norm of an iterable of parameters. This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and added functionality to handle model parallel parameters. Note that the gradients are modified in place. Taken from Nvidia Megatron. Arguments: parameters (Iterable[Tensor] or Tensor): an it...
get_weight_norm
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
Apache-2.0
def prefix_sum_inc(weights): """ Compute an inclusive prefix sum. Example: >>> prefix_sum_inc([3,4,5]) [3, 7, 12] """ weights_ = [w for w in weights] for x in range(1, len(weights_)): weights_[x] += weights_[x - 1] return weights_
Compute an inclusive prefix sum. Example: >>> prefix_sum_inc([3,4,5]) [3, 7, 12]
prefix_sum_inc
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
Apache-2.0
def to_meta(self): """Returns a torch.LongTensor that encodes partitioning information. Can be used along with ``data()`` to serialize a ``PartitionedTensor`` for communication. Returns: torch.LongTensor: a tensor encoding the meta-information for the partitioning "...
Returns a torch.LongTensor that encodes partitioning information. Can be used along with ``data()`` to serialize a ``PartitionedTensor`` for communication. Returns: torch.LongTensor: a tensor encoding the meta-information for the partitioning
to_meta
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
Apache-2.0
def call_to_str(base, *args, **kwargs): """Construct a string representation of a call. Args: base (str): name of the call args (tuple, optional): args to ``base`` kwargs (dict, optional): kwargs supplied to ``base`` Returns: str: A string representation of base(*args, **kw...
Construct a string representation of a call. Args: base (str): name of the call args (tuple, optional): args to ``base`` kwargs (dict, optional): kwargs supplied to ``base`` Returns: str: A string representation of base(*args, **kwargs)
call_to_str
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
Apache-2.0
def clip_gradients(parameters, max_norm=1.0, global_grad_norm=None, mpu=None, eps=1e-6): """Clip the gradient of a list of parameters. Args: parameters: List of parameters whose .grad will be clipped. global_grad_norm (float, optional): Precomputed gradient norm. Defaults to None. mpu (o...
Clip the gradient of a list of parameters. Args: parameters: List of parameters whose .grad will be clipped. global_grad_norm (float, optional): Precomputed gradient norm. Defaults to None. mpu (optional): model parallelism unit. Defaults to None. eps (float, optional): epsilon value...
clip_gradients
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
Apache-2.0
def get_global_norm_of_tensors(input_tensors, norm_type=2, mpu=None): """Get norm of an iterable of tensors. This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and added functionality to handle model parallel parameters. Taken from Nvidia Megatron. Arguments: input_tensors (Iterable...
Get norm of an iterable of tensors. This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and added functionality to handle model parallel parameters. Taken from Nvidia Megatron. Arguments: input_tensors (Iterable[Tensor]): an iterable of Tensors will have norm computed norm_type (...
get_global_norm_of_tensors
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
Apache-2.0
def clip_tensors_by_global_norm(input_tensors, max_norm=1.0, global_norm=None, mpu=None, eps=1e-6): """Clip list of tensors by global norm. Args: input_tensors: List of tensors...
Clip list of tensors by global norm. Args: input_tensors: List of tensors to be clipped global_norm (float, optional): Precomputed norm. Defaults to None. mpu (optional): model parallelism unit. Defaults to None. eps (float, optional): epsilon value added to grad norm. Defaults to 1e...
clip_tensors_by_global_norm
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py
Apache-2.0
def _set_cuda_rng_state(new_state, device=-1): """Sets the random number generator state of the current GPU. Arguments: new_state (torch.ByteTensor): The desired state This function is adapted from PyTorch repo (torch.cuda.set_rng_state) with a single change: the input state is not cloned. Clon...
Sets the random number generator state of the current GPU. Arguments: new_state (torch.ByteTensor): The desired state This function is adapted from PyTorch repo (torch.cuda.set_rng_state) with a single change: the input state is not cloned. Cloning caused major performance issues for +4 GPU cas...
_set_cuda_rng_state
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
Apache-2.0
def model_parallel_cuda_manual_seed(seed): """Initialize model parallel cuda seed. This function should be called after the model parallel is initialized. Also, no torch.cuda.manual_seed should be called after this function. Basically, this is replacement for that function. Two set of RNG state...
Initialize model parallel cuda seed. This function should be called after the model parallel is initialized. Also, no torch.cuda.manual_seed should be called after this function. Basically, this is replacement for that function. Two set of RNG states are tracked: default state: This is for ...
model_parallel_cuda_manual_seed
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
Apache-2.0
def extract_tensors(all_objects): """ Separate objects in list/tuple into tensors and non-tensors and create a mapping to enable re-aggregation. The order of tensors and non-tensors is preserved in their respective output groups. Parameters: all_objects (list/tuple): Objects containing tensors ...
Separate objects in list/tuple into tensors and non-tensors and create a mapping to enable re-aggregation. The order of tensors and non-tensors is preserved in their respective output groups. Parameters: all_objects (list/tuple): Objects containing tensors and non-tensors to be split. Returns...
extract_tensors
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
Apache-2.0
def merge_tensors(tensor_objects, non_tensor_objects, tensor_flags): """ Merge two lists (or tuples) of tensors and non-tensors using a mapping of positions in merged list (or tuple). Parameters: tensor_objects (list/tuple): Tensors to merge. non_tensor_objects (list/tuple): Non-tensors to ...
Merge two lists (or tuples) of tensors and non-tensors using a mapping of positions in merged list (or tuple). Parameters: tensor_objects (list/tuple): Tensors to merge. non_tensor_objects (list/tuple): Non-tensors to merge. tensor_flags (list/tuple): Indicates whether each position in...
merge_tensors
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
Apache-2.0
def is_activation_to_checkpoint(item): """ Is an activation to be checkpointed """ global mp_size return torch.is_tensor(item) and item.is_floating_point() and item.numel() >= mp_size
Is an activation to be checkpointed
is_activation_to_checkpoint
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
Apache-2.0
def checkpoint(function, *args): """Checkpoint a model or part of the model. This has been directly copied from torch.utils.checkpoint. """ all_outputs = [] CheckpointFunction.apply(function, all_outputs, *args) if len(all_outputs) == 1: return all_outputs[0] else: return tuple(...
Checkpoint a model or part of the model. This has been directly copied from torch.utils.checkpoint.
checkpoint
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
Apache-2.0
def reset(): """Resets memory buffers related to contiguous memory optimizations. Should be called during eval when multiple forward propagations are computed without any backward propagation that usually clears these buffers. Arguments: None Return: None """ if CONTIGUO...
Resets memory buffers related to contiguous memory optimizations. Should be called during eval when multiple forward propagations are computed without any backward propagation that usually clears these buffers. Arguments: None Return: None
reset
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
Apache-2.0
def configure( mpu_, deepspeed_config=None, partition_activations=None, contiguous_checkpointing=None, num_checkpoints=None, checkpoint_in_cpu=None, synchronize=None, profile=None, ): """Configure DeepSpeed Activation Checkpointing. Arguments: mpu_: Optional: An object t...
Configure DeepSpeed Activation Checkpointing. Arguments: mpu_: Optional: An object that implements the following methods get_model_parallel_rank/group/world_size, and get_data_parallel_rank/group/world_size deepspeed_config: Optional: DeepSpeed Config json file when provided will be us...
configure
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py
Apache-2.0
def reduce_scatter_coalesced( tensors: List[Tensor], group: ProcessGroup = None, ) -> List[Tensor]: """simultaneously reduce-scatter a list of tensors - this can be done more efficiently than individual reduce scatter calls TODO. see if PyTorch team wants a c++ version of this for ProcessGroupNCCL ...
simultaneously reduce-scatter a list of tensors - this can be done more efficiently than individual reduce scatter calls TODO. see if PyTorch team wants a c++ version of this for ProcessGroupNCCL
reduce_scatter_coalesced
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/comm/coalesced_collectives.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/comm/coalesced_collectives.py
Apache-2.0
def backward(self, loss, create_graph=False, retain_graph=False): """ :attr:`backward` performs the following steps: 1. fp32_loss = loss.float() 2. scaled_loss = fp32_loss*loss_scale 3. scaled_loss.backward(), which accumulates scaled gradients into the ``.grad`` attributes of t...
:attr:`backward` performs the following steps: 1. fp32_loss = loss.float() 2. scaled_loss = fp32_loss*loss_scale 3. scaled_loss.backward(), which accumulates scaled gradients into the ``.grad`` attributes of the model's fp16 leaves
backward
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/fused_optimizer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/fused_optimizer.py
Apache-2.0
def state_dict(self): """ Returns a dict containing the current state of this :class:`FP16_Optimizer` instance. This dict contains attributes of :class:`FP16_Optimizer`, as well as the state_dict of the contained Pytorch optimizer. Example:: checkpoint = {} ...
Returns a dict containing the current state of this :class:`FP16_Optimizer` instance. This dict contains attributes of :class:`FP16_Optimizer`, as well as the state_dict of the contained Pytorch optimizer. Example:: checkpoint = {} checkpoint['model'] = model.sta...
state_dict
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/fused_optimizer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/fused_optimizer.py
Apache-2.0
def load_state_dict(self, state_dict, load_optimizer_states=True): """ Loads a state_dict created by an earlier call to state_dict(). If ``fp16_optimizer_instance`` was constructed from some ``init_optimizer``, whose parameters in turn came from ``model``, it is expected that the user ...
Loads a state_dict created by an earlier call to state_dict(). If ``fp16_optimizer_instance`` was constructed from some ``init_optimizer``, whose parameters in turn came from ``model``, it is expected that the user will call ``model.load_state_dict()`` before ``fp16_optimizer_in...
load_state_dict
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/fused_optimizer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/fused_optimizer.py
Apache-2.0
def step(self, closure=None, grads=None): """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 ...
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/runtime/fp16/onebit/adam.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/onebit/adam.py
Apache-2.0
def load_state_dict(self, state_dict): """ Overrides load_state_dict() to add special handling when loading checkpoints """ # Because at different stage exp_avg_mask may change (e.g., # BERT pre-training seqlen 128 and 512 ), we don't use the exp_avg_mask # in checkpoints...
Overrides load_state_dict() to add special handling when loading checkpoints
load_state_dict
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/onebit/adam.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/onebit/adam.py
Apache-2.0
def step(self, closure=None, grads=None): """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 ...
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/runtime/fp16/onebit/lamb.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/onebit/lamb.py
Apache-2.0
def _reserve_pipe_buffers(self, num_buffers): """Ensure that each pipeline buffer has at least ``num_buffers`` slots. This method only reserves slots and does not allocate tensors. Args: num_buffers (int): The number of buffers to reserve. """ if self.num_pipe_buffe...
Ensure that each pipeline buffer has at least ``num_buffers`` slots. This method only reserves slots and does not allocate tensors. Args: num_buffers (int): The number of buffers to reserve.
_reserve_pipe_buffers
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
Apache-2.0
def reset_activation_shape(self): """Reset the buffers when the shape of activation and gradient change. For example, for curriculum learning that changes the seqlen of each sample, we need to call this whenever the seqlen is going to change. """ self.first_output_send = True ...
Reset the buffers when the shape of activation and gradient change. For example, for curriculum learning that changes the seqlen of each sample, we need to call this whenever the seqlen is going to change.
reset_activation_shape
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
Apache-2.0
def train_batch(self, data_iter=None): """Progress the pipeline to train the next batch of data. The engine will ingest ``self.train_batch_size()`` total samples collectively across all workers. An iterator that over training data should be provided as an argument unless ``deepspeed.in...
Progress the pipeline to train the next batch of data. The engine will ingest ``self.train_batch_size()`` total samples collectively across all workers. An iterator that over training data should be provided as an argument unless ``deepspeed.initialize()`` was provided a training set. In that ...
train_batch
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
Apache-2.0
def eval_batch(self, data_iter, return_logits=False, compute_loss=True, reduce_output='avg'): """Evaluate the pipeline on a batch of data from ``data_iter``. The engine will evaluate ``self.train_batch_size()`` total samples ...
Evaluate the pipeline on a batch of data from ``data_iter``. The engine will evaluate ``self.train_batch_size()`` total samples collectively across all workers. This method is equivalent to: .. code-block:: python module.eval() with torch.no_grad(): ...
eval_batch
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
Apache-2.0
def set_dataiterator(self, iterator): """ Store an iterator to sample for training data. """ if self.is_first_stage() or self.is_last_stage(): self.training_dataloader = None self.data_iterator = iterator
Store an iterator to sample for training data.
set_dataiterator
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
Apache-2.0
def _send_tensor_meta(self, buffer, recv_stage): """ Communicate metadata about upcoming p2p transfers. Metadata is communicated in this order: * type (0: tensor, 1: list) * num_tensors if type=list foreach tensor in buffer: * ndims * ...
Communicate metadata about upcoming p2p transfers. Metadata is communicated in this order: * type (0: tensor, 1: list) * num_tensors if type=list foreach tensor in buffer: * ndims * shape
_send_tensor_meta
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
Apache-2.0
def _recv_tensor_meta(self, send_stage): """Receive metadata about upcoming p2p transfers and return allocated buffers. Metadata is communicated in this order: * type (0: tensor, 1: list) * num_tensors if type=list foreach tensor in buffer: * ndims ...
Receive metadata about upcoming p2p transfers and return allocated buffers. Metadata is communicated in this order: * type (0: tensor, 1: list) * num_tensors if type=list foreach tensor in buffer: * ndims * shape Returns: ...
_recv_tensor_meta
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
Apache-2.0
def _allocate_zeros(self, shape, **kwargs): """ Allocate a tensor of zeros on the engine's device. Arguments: shape: the shape of the tensor to allocate kwargs: passed to torch.zeros() Returns: A tensor from torch.zeros() allocated on self.device. ""...
Allocate a tensor of zeros on the engine's device. Arguments: shape: the shape of the tensor to allocate kwargs: passed to torch.zeros() Returns: A tensor from torch.zeros() allocated on self.device.
_allocate_zeros
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
Apache-2.0
def module_state_dict(self): """Override hack to save a pipe model and return the directory path of the save. This method should only be called by DeepSpeed's ``save_checkpoint()``. The recommended way of saving a ``PipelineModule`` outside of ``save_checkpoint()`` is ``save_state_dict(...
Override hack to save a pipe model and return the directory path of the save. This method should only be called by DeepSpeed's ``save_checkpoint()``. The recommended way of saving a ``PipelineModule`` outside of ``save_checkpoint()`` is ``save_state_dict()``. Returns: None ...
module_state_dict
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
Apache-2.0
def load_module_state_dict(self, state_dict, strict=True, custom_load_fn=None): """Override hack to instead use a directory path. This is important because pipeline models checkpoint by layer instead of rank. If ``state_dict`` is not ``None`` or a ``str``, we revert to ``super()`` expecting a ...
Override hack to instead use a directory path. This is important because pipeline models checkpoint by layer instead of rank. If ``state_dict`` is not ``None`` or a ``str``, we revert to ``super()`` expecting a ``dict``. Args: state_dict (str, None): unused strict (boo...
load_module_state_dict
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/engine.py
Apache-2.0
def _count_layer_params(self): """Count the trainable parameters in individual layers. This routine will only build one layer at a time. Returns: A list of the number of parameters in each layer. """ param_counts = [0] * len(self._layer_specs) for idx, layer...
Count the trainable parameters in individual layers. This routine will only build one layer at a time. Returns: A list of the number of parameters in each layer.
_count_layer_params
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
Apache-2.0
def exec_range_func(start, end): ''' Helper function to be used with checkpoint() Adapted from torch.utils.checkpoint:checkpoint_sequential() ''' local_micro_offset = self.micro_offset + 1 def exec_func(*inputs): # Single tensor inputs need to...
Helper function to be used with checkpoint() Adapted from torch.utils.checkpoint:checkpoint_sequential()
exec_range_func
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
Apache-2.0
def allreduce_tied_weight_gradients(self): '''All reduce the gradients of the tied weights between tied stages''' for key, comm in self.tied_comms.items(): weight = getattr(self.tied_modules[key], comm['weight_attr']) dist.all_reduce(weight.grad, group=comm['group'])
All reduce the gradients of the tied weights between tied stages
allreduce_tied_weight_gradients
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
Apache-2.0
def _index_tied_modules(self): ''' Build communication structures for tied modules. ''' tied_comms = {} if self._topo.get_dim('pipe') == 1: return tied_comms specs = self._layer_specs tie_keys = set(s.key for s in specs if isinstance(s, TiedLayerSpec)) for ke...
Build communication structures for tied modules.
_index_tied_modules
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
Apache-2.0
def _set_bounds(self, start=None, stop=None): """Manually define the range of layers that will be built on this process. These boundaries are treated as list slices and so start is inclusive and stop is exclusive. The default of None for both results in all layers being built locally. ...
Manually define the range of layers that will be built on this process. These boundaries are treated as list slices and so start is inclusive and stop is exclusive. The default of None for both results in all layers being built locally.
_set_bounds
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
Apache-2.0
def ckpt_prefix(self, checkpoints_path, tag): """Build a prefix for all checkpoint files written by this module. """ # All checkpoint files start with this rank_name = 'module' # Data parallelism is omitted from the naming convention because we are agnostic # to this in the chec...
Build a prefix for all checkpoint files written by this module.
ckpt_prefix
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
Apache-2.0
def ckpt_layer_path(self, ckpt_dir, local_layer_idx): """Customize a prefix for a specific pipeline module layer. """ idx = local_layer_idx + self._local_start layer_ckpt_path = os.path.join(ckpt_dir, f'layer_{idx:02d}') rank_repr = self._grid._topo.get_rank_repr(rank=self.global_rank) ...
Customize a prefix for a specific pipeline module layer.
ckpt_layer_path
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
Apache-2.0
def ckpt_layer_path_list(self, ckpt_dir, local_layer_idx): """Get all ckpt file list for a specific pipeline module layer. """ idx = local_layer_idx + self._local_start layer_ckpt_path = os.path.join(ckpt_dir, f'layer_{idx:02d}-') layer_ckpt_path += "*model_states.pt" ckpt_files ...
Get all ckpt file list for a specific pipeline module layer.
ckpt_layer_path_list
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/module.py
Apache-2.0
def send_obj(msg: typing.Any, dest: int): """Send an arbitrary python object to ``dest``. Note: ``msg`` must be pickleable. WARN: This incurs a CPU -> GPU transfer and should be used sparingly for performance reasons. Args: msg (typing.Any): The object to send. dest (int): Destina...
Send an arbitrary python object to ``dest``. Note: ``msg`` must be pickleable. WARN: This incurs a CPU -> GPU transfer and should be used sparingly for performance reasons. Args: msg (typing.Any): The object to send. dest (int): Destination rank.
send_obj
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/p2p.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/p2p.py
Apache-2.0
def recv_obj(sender: int) -> typing.Any: """Receive an arbitrary python object from ``sender``. WARN: This incur a CPU <-> GPU transfers and should be used sparingly for performance reasons. Args: sender (int): The rank sending the message. """ # Get message meta length = torch.ten...
Receive an arbitrary python object from ``sender``. WARN: This incur a CPU <-> GPU transfers and should be used sparingly for performance reasons. Args: sender (int): The rank sending the message.
recv_obj
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/p2p.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/p2p.py
Apache-2.0
def _to(x): """Recursively move to the current device.""" if torch.is_tensor(x): return x.cuda() if isinstance(x, (tuple, list)): ret = [_to(x_) for x_ in x] if isinstance(x, tuple): ret = tuple(ret) return ret # handle kwar...
Recursively move to the current device.
_to
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/p2p.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/p2p.py
Apache-2.0
def _get_send_recv_group(src_stage, dest_stage): '''the group id is always the smaller rank unless its a wrap around''' stage_id = None first_stage = 0 last_stage = _grid.pipe_parallel_size - 1 if (src_stage == first_stage and dest_stage == last_stage or dest_stage == first_stage and ...
the group id is always the smaller rank unless its a wrap around
_get_send_recv_group
python
FMInference/FlexLLMGen
benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/p2p.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/DeepSpeed/deepspeed/runtime/pipe/p2p.py
Apache-2.0