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 train_step(self, data): """ A modification of Keras's default `train_step` that correctly handles matching outputs to labels for our models and supports directly training on the loss output head. In addition, it ensures input keys are copied to the labels where appropriate. It will a...
A modification of Keras's default `train_step` that correctly handles matching outputs to labels for our models and supports directly training on the loss output head. In addition, it ensures input keys are copied to the labels where appropriate. It will also copy label keys into the input dict...
train_step
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def set_input_embeddings(self, value): """ Set model's input embeddings Args: value (`tf.Variable`): The new weights mapping hidden states to vocabulary. """ main_layer = getattr(self, self.base_model_prefix) if main_layer is None: ...
Set model's input embeddings Args: value (`tf.Variable`): The new weights mapping hidden states to vocabulary.
set_input_embeddings
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def get_output_embeddings(self) -> Union[None, tf.keras.layers.Layer]: """ Returns the model's output embeddings Returns: `tf.Variable`: The new weights mapping vocabulary to hidden states. """ if self.get_lm_head() is not None: lm_head = self.get_lm_head...
Returns the model's output embeddings Returns: `tf.Variable`: The new weights mapping vocabulary to hidden states.
get_output_embeddings
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def set_output_embeddings(self, value): """ Set model's output embeddings Args: value (`tf.Variable`): The new weights mapping hidden states to vocabulary. """ if self.get_lm_head() is not None: lm_head = self.get_lm_head() try...
Set model's output embeddings Args: value (`tf.Variable`): The new weights mapping hidden states to vocabulary.
set_output_embeddings
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def get_output_layer_with_bias(self) -> Union[None, tf.keras.layers.Layer]: """ Get the layer that handles a bias attribute in case the model has an LM head with weights tied to the embeddings Return: `tf.keras.layers.Layer`: The layer that handles the bias, None if not an L...
Get the layer that handles a bias attribute in case the model has an LM head with weights tied to the embeddings Return: `tf.keras.layers.Layer`: The layer that handles the bias, None if not an LM model.
get_output_layer_with_bias
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def get_bias(self) -> Union[None, Dict[str, tf.Variable]]: """ Dict of bias attached to an LM head. The key represents the name of the bias attribute. Return: `tf.Variable`: The weights representing the bias, None if not an LM model. """ if self.get_lm_head() is not ...
Dict of bias attached to an LM head. The key represents the name of the bias attribute. Return: `tf.Variable`: The weights representing the bias, None if not an LM model.
get_bias
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def set_bias(self, value): """ Set all the bias in the LM head. Args: value (`Dict[tf.Variable]`): All the new bias attached to an LM head. """ if self.get_lm_head() is not None: lm_head = self.get_lm_head() try: ...
Set all the bias in the LM head. Args: value (`Dict[tf.Variable]`): All the new bias attached to an LM head.
set_bias
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def resize_token_embeddings( self, new_num_tokens: Optional[int] = None ) -> Union[tf.keras.layers.Embedding, tf.Variable]: """ Resizes input token embeddings matrix of the model if `new_num_tokens != config.vocab_size`. Takes care of tying weights embeddings afterwards if the model...
Resizes input token embeddings matrix of the model if `new_num_tokens != config.vocab_size`. Takes care of tying weights embeddings afterwards if the model class has a `tie_weights()` method. Arguments: new_num_tokens (`int`, *optional*): The number of new tokens i...
resize_token_embeddings
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def _v2_resized_token_embeddings(self, new_num_tokens: Optional[int] = None) -> tf.keras.layers.Embedding: """ Resizes input token embeddings matrix of the model if `new_num_tokens != config.vocab_size`. Arguments: new_num_tokens (`int`, *optional*): The number of ne...
Resizes input token embeddings matrix of the model if `new_num_tokens != config.vocab_size`. Arguments: new_num_tokens (`int`, *optional*): The number of new tokens in the embedding matrix. Increasing the size will add newly initialized vectors at the end. R...
_v2_resized_token_embeddings
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def _get_resized_lm_head_bias(self, old_lm_head_bias, new_num_tokens): """ Build a resized bias from the old ones. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end Args: old_lm_head_bias (`tf.Variable`): ...
Build a resized bias from the old ones. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end Args: old_lm_head_bias (`tf.Variable`): Old lm head bias to be resized. new_num_tokens (`int`, *...
_get_resized_lm_head_bias
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def _v2_get_resized_lm_head_bias( self, old_lm_head_bias: Dict[str, tf.Variable], new_num_tokens: int ) -> Dict[str, tf.Tensor]: """ Build a resized bias from the old ones. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from t...
Build a resized bias from the old ones. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end Args: old_lm_head_bias (`Dict[str, tf.Variable]`): Old lm head bias to be resized. new_num_token...
_v2_get_resized_lm_head_bias
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def _get_resized_lm_head_decoder(self, old_lm_head_decoder, new_num_tokens): """ Build a resized decoder from the old ones. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end Args: old_lm_head_decoder (`tf.Va...
Build a resized decoder from the old ones. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end Args: old_lm_head_decoder (`tf.Variable`): Old lm head decoder to be resized. new_num_tokens ...
_get_resized_lm_head_decoder
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def _get_resized_embeddings(self, old_embeddings, new_num_tokens=None) -> tf.Variable: """ Build a resized Embedding weights from a provided token Embedding weights. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end Arg...
Build a resized Embedding weights from a provided token Embedding weights. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end Args: old_embeddings (`tf.Variable`): Old embeddings to be resized. ...
_get_resized_embeddings
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def _v2_get_resized_embeddings( self, old_embeddings: tf.keras.layers.Embedding, new_num_tokens: int ) -> tf.keras.layers.Embedding: """ Build a resized Embedding layer from a provided Embedding layer. Increasing the size will add newly initialized vectors at the end. Reducing the si...
Build a resized Embedding layer from a provided Embedding layer. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. Args: old_embeddings (`tf.keras.layers.Embedding`): Old embeddings to be resized. ...
_v2_get_resized_embeddings
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def register_for_auto_class(cls, auto_class="TFAutoModel"): """ Register this class with a given auto class. This should only be used for custom models as the ones in the library are already mapped with an auto class. <Tip warning={true}> This API is experimental and may have s...
Register this class with a given auto class. This should only be used for custom models as the ones in the library are already mapped with an auto class. <Tip warning={true}> This API is experimental and may have some slight breaking changes in the next releases. </Tip> ...
register_for_auto_class
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def call(self, inputs: tf.Tensor, mode: str = "embedding") -> tf.Tensor: """ Get token embeddings of inputs or decode final hidden state. Args: inputs (`tf.Tensor`): In embedding mode, should be an int64 tensor with shape `[batch_size, length]`. In l...
Get token embeddings of inputs or decode final hidden state. Args: inputs (`tf.Tensor`): In embedding mode, should be an int64 tensor with shape `[batch_size, length]`. In linear mode, should be a float tensor with shape `[batch_size, length, hidden_size]`....
call
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def _linear(self, inputs): """ Computes logits by running inputs through a linear layer. Args: inputs: A float32 tensor with shape [..., hidden_size] Returns: float32 tensor with shape [..., vocab_size]. """ first_dims = shape_list(inputs)[:-1] ...
Computes logits by running inputs through a linear layer. Args: inputs: A float32 tensor with shape [..., hidden_size] Returns: float32 tensor with shape [..., vocab_size].
_linear
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py
Apache-2.0
def no_init_weights(_enable=True): """ Context manager to globally disable weight initialization to speed up loading large models. TODO(Patrick): Delete safety argument `_enable=True` at next major version. . """ global _init_weights old_init_weights = _init_weights if _enable: _ini...
Context manager to globally disable weight initialization to speed up loading large models. TODO(Patrick): Delete safety argument `_enable=True` at next major version. .
no_init_weights
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def get_first_parameter_dtype(parameter: Union[nn.Module, GenerationMixin, "ModuleUtilsMixin"]): """ Returns the first parameter dtype (can be non-floating) or asserts if none were found. """ try: return next(parameter.parameters()).dtype except StopIteration: # For nn.DataParallel c...
Returns the first parameter dtype (can be non-floating) or asserts if none were found.
get_first_parameter_dtype
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def get_parameter_dtype(parameter: Union[nn.Module, GenerationMixin, "ModuleUtilsMixin"]): """ Returns the first found floating dtype in parameters if there is one, otherwise returns the last dtype it found. """ last_dtype = None for t in parameter.parameters(): last_dtype = t.dtype ...
Returns the first found floating dtype in parameters if there is one, otherwise returns the last dtype it found.
get_parameter_dtype
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def get_state_dict_float_dtype(state_dict): """ Returns the first found floating dtype in `state_dict` or asserts if none were found. """ for t in state_dict.values(): if t.is_floating_point(): return t.dtype raise ValueError("couldn't find any floating point dtypes in state_dic...
Returns the first found floating dtype in `state_dict` or asserts if none were found.
get_state_dict_float_dtype
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def get_state_dict_dtype(state_dict): """ Returns the first found floating dtype in `state_dict` if there is one, otherwise returns the first dtype. """ for t in state_dict.values(): if t.is_floating_point(): return t.dtype # if no floating dtype was found return whatever the fi...
Returns the first found floating dtype in `state_dict` if there is one, otherwise returns the first dtype.
get_state_dict_dtype
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def dtype_byte_size(dtype): """ Returns the size (in bytes) occupied by one parameter of type `dtype`. Example: ```py >>> dtype_byte_size(torch.float32) 4 ``` """ if dtype == torch.bool: return 1 / 8 bit_search = re.search(r"[^\d](\d+)$", str(dtype)) if bit_search i...
Returns the size (in bytes) occupied by one parameter of type `dtype`. Example: ```py >>> dtype_byte_size(torch.float32) 4 ```
dtype_byte_size
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def load_sharded_checkpoint(model, folder, strict=True): """ This is the same as [`torch.nn.Module.load_state_dict`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html?highlight=load_state_dict#torch.nn.Module.load_state_dict) but for a sharded checkpoint. This load is performed efficie...
This is the same as [`torch.nn.Module.load_state_dict`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html?highlight=load_state_dict#torch.nn.Module.load_state_dict) but for a sharded checkpoint. This load is performed efficiently: each checkpoint shard is loaded one by one in RAM and dele...
load_sharded_checkpoint
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def load_state_dict(checkpoint_file: Union[str, os.PathLike]): """ Reads a PyTorch checkpoint file, returning properly formatted errors if they arise. """ if checkpoint_file.endswith(".safetensors") and is_safetensors_available(): # Check format of the archive with safe_open(checkpoint_f...
Reads a PyTorch checkpoint file, returning properly formatted errors if they arise.
load_state_dict
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def find_submodule_and_param_name(model, long_key, start_prefix): """ A helper util to find the last sub-module and the param/buffer name. If `start_prefix` is supplied it'll be removed from the start of the key """ if len(start_prefix) > 0 and long_key.startswith(start_prefix): long_key = ...
A helper util to find the last sub-module and the param/buffer name. If `start_prefix` is supplied it'll be removed from the start of the key
find_submodule_and_param_name
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def _move_model_to_meta(model, loaded_state_dict_keys, start_prefix): """ Moves `loaded_state_dict_keys` in model to meta device which frees up the memory taken by those params. `start_prefix` is used for models which insert their name into model keys, e.g. `bert` in `bert.pooler.dense.weight` """...
Moves `loaded_state_dict_keys` in model to meta device which frees up the memory taken by those params. `start_prefix` is used for models which insert their name into model keys, e.g. `bert` in `bert.pooler.dense.weight`
_move_model_to_meta
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def _load_state_dict_into_meta_model( model, state_dict, loaded_state_dict_keys, # left for now but could be removed, see below start_prefix, expected_keys, device_map=None, offload_folder=None, offload_index=None, state_dict_folder=None, state_dict_index=None, dtype=None, ...
This is somewhat similar to `_load_state_dict_into_model`, but deals with a model that has some or all of its params on a `meta` device. It replaces the model params with the data from the `state_dict`, while moving the params back to the normal device, but only for `loaded_state_dict_keys`. `start_pr...
_load_state_dict_into_meta_model
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def add_memory_hooks(self): """ Add a memory hook before and after each sub-module forward pass to record increase in memory consumption. Increase in memory consumption is stored in a `mem_rss_diff` attribute for each module and can be reset to zero with `model.reset_memory_hooks_state(...
Add a memory hook before and after each sub-module forward pass to record increase in memory consumption. Increase in memory consumption is stored in a `mem_rss_diff` attribute for each module and can be reset to zero with `model.reset_memory_hooks_state()`.
add_memory_hooks
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def reset_memory_hooks_state(self): """ Reset the `mem_rss_diff` attribute of each module (see [`~modeling_utils.ModuleUtilsMixin.add_memory_hooks`]). """ for module in self.modules(): module.mem_rss_diff = 0 module.mem_rss_post_forward = 0 module.mem_...
Reset the `mem_rss_diff` attribute of each module (see [`~modeling_utils.ModuleUtilsMixin.add_memory_hooks`]).
reset_memory_hooks_state
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def invert_attention_mask(self, encoder_attention_mask: Tensor) -> Tensor: """ Invert an attention mask (e.g., switches 0. and 1.). Args: encoder_attention_mask (`torch.Tensor`): An attention mask. Returns: `torch.Tensor`: The inverted attention mask. ""...
Invert an attention mask (e.g., switches 0. and 1.). Args: encoder_attention_mask (`torch.Tensor`): An attention mask. Returns: `torch.Tensor`: The inverted attention mask.
invert_attention_mask
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def get_extended_attention_mask( self, attention_mask: Tensor, input_shape: Tuple[int], device: device = None, dtype: torch.float = None ) -> Tensor: """ Makes broadcastable attention and causal masks so that future and masked tokens are ignored. Arguments: attention_mas...
Makes broadcastable attention and causal masks so that future and masked tokens are ignored. Arguments: attention_mask (`torch.Tensor`): Mask with ones indicating tokens to attend to, zeros for tokens to ignore. input_shape (`Tuple[int]`): The sh...
get_extended_attention_mask
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def get_head_mask( self, head_mask: Optional[Tensor], num_hidden_layers: int, is_attention_chunked: bool = False ) -> Tensor: """ Prepare the head mask if needed. Args: head_mask (`torch.Tensor` with shape `[num_heads]` or `[num_hidden_layers x num_heads]`, *optional*): ...
Prepare the head mask if needed. Args: head_mask (`torch.Tensor` with shape `[num_heads]` or `[num_hidden_layers x num_heads]`, *optional*): The mask indicating if we should keep the heads or not (1.0 for keep, 0.0 for discard). num_hidden_layers (`int`): ...
get_head_mask
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def num_parameters(self, only_trainable: bool = False, exclude_embeddings: bool = False) -> int: """ Get number of (optionally, trainable or non-embeddings) parameters in the module. Args: only_trainable (`bool`, *optional*, defaults to `False`): Whether or not to re...
Get number of (optionally, trainable or non-embeddings) parameters in the module. Args: only_trainable (`bool`, *optional*, defaults to `False`): Whether or not to return only the number of trainable parameters exclude_embeddings (`bool`, *optional*, defaults t...
num_parameters
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def estimate_tokens(self, input_dict: Dict[str, Union[torch.Tensor, Any]]) -> int: """ Helper function to estimate the total number of tokens from the model inputs. Args: inputs (`dict`): The model inputs. Returns: `int`: The total number of tokens. """ ...
Helper function to estimate the total number of tokens from the model inputs. Args: inputs (`dict`): The model inputs. Returns: `int`: The total number of tokens.
estimate_tokens
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def floating_point_ops( self, input_dict: Dict[str, Union[torch.Tensor, Any]], exclude_embeddings: bool = True ) -> int: """ Get number of (optionally, non-embeddings) floating-point operations for the forward and backward passes of a batch with this transformer model. Default approx...
Get number of (optionally, non-embeddings) floating-point operations for the forward and backward passes of a batch with this transformer model. Default approximation neglects the quadratic dependency on the number of tokens (valid if `12 * d_model << sequence_length`) as laid out in [this ...
floating_point_ops
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def _from_config(cls, config, **kwargs): """ All context managers that the model should be initialized under go here. Args: torch_dtype (`torch.dtype`, *optional*): Override the default `torch.dtype` and load the model under this dtype. """ torch_dtyp...
All context managers that the model should be initialized under go here. Args: torch_dtype (`torch.dtype`, *optional*): Override the default `torch.dtype` and load the model under this dtype.
_from_config
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def _set_default_torch_dtype(cls, dtype: torch.dtype) -> torch.dtype: """ Change the default dtype and return the previous one. This is needed when wanting to instantiate the model under specific dtype. Args: dtype (`torch.dtype`): a floating dtype to set to....
Change the default dtype and return the previous one. This is needed when wanting to instantiate the model under specific dtype. Args: dtype (`torch.dtype`): a floating dtype to set to. Returns: `torch.dtype`: the original `dtype` that can be us...
_set_default_torch_dtype
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def get_input_embeddings(self) -> nn.Module: """ Returns the model's input embeddings. Returns: `nn.Module`: A torch module mapping vocabulary to hidden states. """ base_model = getattr(self, self.base_model_prefix, self) if base_model is not self: ...
Returns the model's input embeddings. Returns: `nn.Module`: A torch module mapping vocabulary to hidden states.
get_input_embeddings
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def set_input_embeddings(self, value: nn.Module): """ Set model's input embeddings. Args: value (`nn.Module`): A module mapping vocabulary to hidden states. """ base_model = getattr(self, self.base_model_prefix, self) if base_model is not self: ba...
Set model's input embeddings. Args: value (`nn.Module`): A module mapping vocabulary to hidden states.
set_input_embeddings
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def tie_weights(self): """ Tie the weights between the input embeddings and the output embeddings. If the `torchscript` flag is set in the configuration, can't handle parameter sharing so we are cloning the weights instead. """ if getattr(self.config, "tie_word_embedding...
Tie the weights between the input embeddings and the output embeddings. If the `torchscript` flag is set in the configuration, can't handle parameter sharing so we are cloning the weights instead.
tie_weights
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def _tie_or_clone_weights(self, output_embeddings, input_embeddings): """Tie or clone module weights depending of whether we are using TorchScript or not""" if self.config.torchscript: output_embeddings.weight = nn.Parameter(input_embeddings.weight.clone()) else: output_e...
Tie or clone module weights depending of whether we are using TorchScript or not
_tie_or_clone_weights
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def resize_token_embeddings(self, new_num_tokens: Optional[int] = None) -> nn.Embedding: """ Resizes input token embeddings matrix of the model if `new_num_tokens != config.vocab_size`. Takes care of tying weights embeddings afterwards if the model class has a `tie_weights()` method. A...
Resizes input token embeddings matrix of the model if `new_num_tokens != config.vocab_size`. Takes care of tying weights embeddings afterwards if the model class has a `tie_weights()` method. Arguments: new_num_tokens (`int`, *optional*): The number of new tokens i...
resize_token_embeddings
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def _get_resized_embeddings( self, old_embeddings: nn.Embedding, new_num_tokens: Optional[int] = None ) -> nn.Embedding: """ Build a resized Embedding Module from a provided token Embedding Module. Increasing the size will add newly initialized vectors at the end. Reducing the size w...
Build a resized Embedding Module from a provided token Embedding Module. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end Args: old_embeddings (`torch.nn.Embedding`): Old embeddings to be resized. ...
_get_resized_embeddings
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def _get_resized_lm_head( self, old_lm_head: nn.Linear, new_num_tokens: Optional[int] = None, transposed: Optional[bool] = False ) -> nn.Linear: """ Build a resized Linear Module from a provided old Linear Module. Increasing the size will add newly initialized vectors at the end. Red...
Build a resized Linear Module from a provided old Linear Module. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end Args: old_lm_head (`torch.nn.Linear`): Old lm head liner layer to be resized. ...
_get_resized_lm_head
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def init_weights(self): """ If needed prunes and maybe initializes weights. """ # Prune heads if needed if self.config.pruned_heads: self.prune_heads(self.config.pruned_heads) if _init_weights: # Initialize weights self.apply(self._ini...
If needed prunes and maybe initializes weights.
init_weights
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def prune_heads(self, heads_to_prune: Dict[int, List[int]]): """ Prunes heads of the base model. Arguments: heads_to_prune (`Dict[int, List[int]]`): Dictionary with keys being selected layer indices (`int`) and associated values being the list of heads ...
Prunes heads of the base model. Arguments: heads_to_prune (`Dict[int, List[int]]`): Dictionary with keys being selected layer indices (`int`) and associated values being the list of heads to prune in said layer (list of `int`). For instance {1: [0, 2], 2: [2...
prune_heads
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def gradient_checkpointing_enable(self): """ Activates gradient checkpointing for the current model. Note that in other frameworks this feature can be referred to as "activation checkpointing" or "checkpoint activations". """ if not self.supports_gradient_checkpointing: ...
Activates gradient checkpointing for the current model. Note that in other frameworks this feature can be referred to as "activation checkpointing" or "checkpoint activations".
gradient_checkpointing_enable
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def save_pretrained( self, save_directory: Union[str, os.PathLike], is_main_process: bool = True, state_dict: Optional[dict] = None, save_function: Callable = torch.save, push_to_hub: bool = False, max_shard_size: Union[int, str] = "10GB", safe_serializati...
Save a model and its configuration file to a directory, so that it can be re-loaded using the [`~PreTrainedModel.from_pretrained`] class method. Arguments: save_directory (`str` or `os.PathLike`): Directory to which to save. Will be created if it doesn't exist. ...
save_pretrained
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def get_memory_footprint(self, return_buffers=True): r""" Get the memory footprint of a model. This will return the memory footprint of the current model in bytes. Useful to benchmark the memory footprint of the current model and design some tests. Solution inspired from the PyTorch disc...
Get the memory footprint of a model. This will return the memory footprint of the current model in bytes. Useful to benchmark the memory footprint of the current model and design some tests. Solution inspired from the PyTorch discussions: https://discuss.pytorch.org/t/gpu-memory-that-model-uses...
get_memory_footprint
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def _load_pretrained_model_low_mem(model, loaded_state_dict_keys, resolved_archive_file, start_prefix=""): """ This is an experimental function that loads the model using ~1.x model size CPU memory Before you call it do: 1. save which state_dict keys are available 2. drop state...
This is an experimental function that loads the model using ~1.x model size CPU memory Before you call it do: 1. save which state_dict keys are available 2. drop state_dict before model is created, since the latter takes 1x model size memory Here then we continue: 3....
_load_pretrained_model_low_mem
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def register_for_auto_class(cls, auto_class="AutoModel"): """ Register this class with a given auto class. This should only be used for custom models as the ones in the library are already mapped with an auto class. <Tip warning={true}> This API is experimental and may have som...
Register this class with a given auto class. This should only be used for custom models as the ones in the library are already mapped with an auto class. <Tip warning={true}> This API is experimental and may have some slight breaking changes in the next releases. </Tip> ...
register_for_auto_class
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def forward( self, hidden_states: torch.FloatTensor, p_mask: Optional[torch.FloatTensor] = None ) -> torch.FloatTensor: """ Args: hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`): The final hidden states of the model. p...
Args: hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`): The final hidden states of the model. p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*): Mask for tokens at invalid position, such as query an...
forward
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def forward( self, hidden_states: torch.FloatTensor, start_states: Optional[torch.FloatTensor] = None, start_positions: Optional[torch.LongTensor] = None, p_mask: Optional[torch.FloatTensor] = None, ) -> torch.FloatTensor: """ Args: hidden_states (...
Args: hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`): The final hidden states of the model. start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*): The hidden states of the first tok...
forward
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def forward( self, hidden_states: torch.FloatTensor, start_states: Optional[torch.FloatTensor] = None, start_positions: Optional[torch.LongTensor] = None, cls_index: Optional[torch.LongTensor] = None, ) -> torch.FloatTensor: """ Args: hidden_states...
Args: hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`): The final hidden states of the model. start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*): The hidden states of the first tok...
forward
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def forward( self, hidden_states: torch.FloatTensor, start_positions: Optional[torch.LongTensor] = None, end_positions: Optional[torch.LongTensor] = None, cls_index: Optional[torch.LongTensor] = None, is_impossible: Optional[torch.LongTensor] = None, p_mask: Optio...
Args: hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`): Final hidden states of the model on the sequence tokens. start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Positions of the first token for t...
forward
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def forward( self, hidden_states: torch.FloatTensor, cls_index: Optional[torch.LongTensor] = None ) -> torch.FloatTensor: """ Compute a single vector summary of a sequence hidden states. Args: hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size...
Compute a single vector summary of a sequence hidden states. Args: hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`): The hidden states of the last layer. cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]...
forward
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def unwrap_model(model: nn.Module) -> nn.Module: """ Recursively unwraps a model from potential containers (as used in distributed training). Args: model (`torch.nn.Module`): The model to unwrap. """ # since there could be multiple levels of wrapping, unwrap recursively if hasattr(model...
Recursively unwraps a model from potential containers (as used in distributed training). Args: model (`torch.nn.Module`): The model to unwrap.
unwrap_model
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/modeling_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_utils.py
Apache-2.0
def get_constant_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, last_epoch: int = -1): """ Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate increases linearly between 0 and the initial lr set in the optimizer. Args: op...
Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate increases linearly between 0 and the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. ...
get_constant_schedule_with_warmup
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/optimization.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/optimization.py
Apache-2.0
def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1): """ Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after a warmup period during which it increases linearly from 0 to the initial lr set in the ...
Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to...
get_linear_schedule_with_warmup
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/optimization.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/optimization.py
Apache-2.0
def get_cosine_schedule_with_warmup( optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: float = 0.5, last_epoch: int = -1 ): """ Create a schedule with a learning rate that decreases following the values of the cosine function between the initial lr set in the optimizer to...
Create a schedule with a learning rate that decreases following the values of the cosine function between the initial lr set in the optimizer to 0, after a warmup period during which it increases linearly between 0 and the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimi...
get_cosine_schedule_with_warmup
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/optimization.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/optimization.py
Apache-2.0
def get_cosine_with_hard_restarts_schedule_with_warmup( optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: int = 1, last_epoch: int = -1 ): """ Create a schedule with a learning rate that decreases following the values of the cosine function between the initial lr set in t...
Create a schedule with a learning rate that decreases following the values of the cosine function between the initial lr set in the optimizer to 0, with several hard restarts, after a warmup period during which it increases linearly between 0 and the initial lr set in the optimizer. Args: opti...
get_cosine_with_hard_restarts_schedule_with_warmup
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/optimization.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/optimization.py
Apache-2.0
def get_polynomial_decay_schedule_with_warmup( optimizer, num_warmup_steps, num_training_steps, lr_end=1e-7, power=1.0, last_epoch=-1 ): """ Create a schedule with a learning rate that decreases as a polynomial decay from the initial lr set in the optimizer to end lr defined by *lr_end*, after a warmup ...
Create a schedule with a learning rate that decreases as a polynomial decay from the initial lr set in the optimizer to end lr defined by *lr_end*, after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.Optimizer`...
get_polynomial_decay_schedule_with_warmup
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/optimization.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/optimization.py
Apache-2.0
def get_scheduler( name: Union[str, SchedulerType], optimizer: Optimizer, num_warmup_steps: Optional[int] = None, num_training_steps: Optional[int] = None, ): """ Unified API to get any scheduler from its name. Args: name (`str` or `SchedulerType`): The name of the sched...
Unified API to get any scheduler from its name. Args: name (`str` or `SchedulerType`): The name of the scheduler to use. optimizer (`torch.optim.Optimizer`): The optimizer that will be used during training. num_warmup_steps (`int`, *optional*): The n...
get_scheduler
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/optimization.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/optimization.py
Apache-2.0
def step(self, closure: Callable = None): """ Performs a single optimization step. Arguments: closure (`Callable`, *optional*): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() ...
Performs a single optimization step. Arguments: closure (`Callable`, *optional*): A closure that reevaluates the model and returns the loss.
step
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/optimization.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/optimization.py
Apache-2.0
def step(self, closure=None): """ Performs a single optimization step Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() ...
Performs a single optimization step Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.
step
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/optimization.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/optimization.py
Apache-2.0
def create_optimizer( init_lr: float, num_train_steps: int, num_warmup_steps: int, min_lr_ratio: float = 0.0, adam_beta1: float = 0.9, adam_beta2: float = 0.999, adam_epsilon: float = 1e-8, adam_clipnorm: Optional[float] = None, adam_global_clipnorm: Optional[float] = None, weigh...
Creates an optimizer with a learning rate schedule using a warmup phase followed by a linear decay. Args: init_lr (`float`): The desired learning rate at the end of the warmup phase. num_train_steps (`int`): The total number of training steps. num_warmup_steps (...
create_optimizer
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/optimization_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/optimization_tf.py
Apache-2.0
def from_config(cls, config): """Creates an optimizer from its config with WarmUp custom object.""" custom_objects = {"WarmUp": WarmUp} return super(AdamWeightDecay, cls).from_config(config, custom_objects=custom_objects)
Creates an optimizer from its config with WarmUp custom object.
from_config
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/optimization_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/optimization_tf.py
Apache-2.0
def _get_lr(self, var_device, var_dtype, apply_state): """Retrieves the learning rate with the given state.""" if apply_state is None: return self._decayed_lr_t[var_dtype], {} apply_state = apply_state or {} coefficients = apply_state.get((var_device, var_dtype)) if ...
Retrieves the learning rate with the given state.
_get_lr
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/optimization_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/optimization_tf.py
Apache-2.0
def gradients(self): """The accumulated gradients on the current replica.""" if not self._gradients: raise ValueError("The accumulator should be called first to initialize the gradients") return list(gradient.value() if gradient is not None else gradient for gradient in self._gradien...
The accumulated gradients on the current replica.
gradients
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/optimization_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/optimization_tf.py
Apache-2.0
def __call__(self, gradients): """Accumulates `gradients` on the current replica.""" if not self._gradients: _ = self.step # Create the step variable. self._gradients.extend( [ tf.Variable( tf.zeros_like(gradient), ...
Accumulates `gradients` on the current replica.
__call__
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/optimization_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/optimization_tf.py
Apache-2.0
def reset(self): """Resets the accumulated gradients on the current replica.""" if not self._gradients: return self._accum_steps.assign(0) for gradient in self._gradients: if gradient is not None: gradient.assign(tf.zeros_like(gradient))
Resets the accumulated gradients on the current replica.
reset
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/optimization_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/optimization_tf.py
Apache-2.0
def save_pretrained(self, save_directory, push_to_hub: bool = False, **kwargs): """ Saves the attributes of this processor (feature extractor, tokenizer...) in the specified directory so that it can be reloaded using the [`~ProcessorMixin.from_pretrained`] method. <Tip> This cl...
Saves the attributes of this processor (feature extractor, tokenizer...) in the specified directory so that it can be reloaded using the [`~ProcessorMixin.from_pretrained`] method. <Tip> This class method is simply calling [`~feature_extraction_utils.FeatureExtractionMixin.save_pretra...
save_pretrained
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/processing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/processing_utils.py
Apache-2.0
def register_for_auto_class(cls, auto_class="AutoProcessor"): """ Register this class with a given auto class. This should only be used for custom feature extractors as the ones in the library are already mapped with `AutoProcessor`. <Tip warning={true}> This API is experimenta...
Register this class with a given auto class. This should only be used for custom feature extractors as the ones in the library are already mapped with `AutoProcessor`. <Tip warning={true}> This API is experimental and may have some slight breaking changes in the next releases. ...
register_for_auto_class
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/processing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/processing_utils.py
Apache-2.0
def torch_int_div(tensor1, tensor2): """ A function that performs integer division across different versions of PyTorch. """ if is_torch_less_than_1_8: return tensor1 // tensor2 else: return torch.div(tensor1, tensor2, rounding_mode="floor")
A function that performs integer division across different versions of PyTorch.
torch_int_div
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/pytorch_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pytorch_utils.py
Apache-2.0
def softmax_backward_data(parent, grad_output, output, dim, self): """ A function that calls the internal `_softmax_backward_data` PyTorch method and that adjusts the arguments according to the torch version detected. """ if is_torch_less_than_1_11: return _softmax_backward_data(grad_output...
A function that calls the internal `_softmax_backward_data` PyTorch method and that adjusts the arguments according to the torch version detected.
softmax_backward_data
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/pytorch_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pytorch_utils.py
Apache-2.0
def prune_linear_layer(layer: nn.Linear, index: torch.LongTensor, dim: int = 0) -> nn.Linear: """ Prune a linear layer to keep only entries in index. Used to remove heads. Args: layer (`torch.nn.Linear`): The layer to prune. index (`torch.LongTensor`): The indices to keep in the layer....
Prune a linear layer to keep only entries in index. Used to remove heads. Args: layer (`torch.nn.Linear`): The layer to prune. index (`torch.LongTensor`): The indices to keep in the layer. dim (`int`, *optional*, defaults to 0): The dimension on which to keep the indices. Ret...
prune_linear_layer
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/pytorch_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pytorch_utils.py
Apache-2.0
def prune_conv1d_layer(layer: Conv1D, index: torch.LongTensor, dim: int = 1) -> Conv1D: """ Prune a Conv1D layer to keep only entries in index. A Conv1D work as a Linear layer (see e.g. BERT) but the weights are transposed. Used to remove heads. Args: layer ([`~pytorch_utils.Conv1D`]): The...
Prune a Conv1D layer to keep only entries in index. A Conv1D work as a Linear layer (see e.g. BERT) but the weights are transposed. Used to remove heads. Args: layer ([`~pytorch_utils.Conv1D`]): The layer to prune. index (`torch.LongTensor`): The indices to keep in the layer. ...
prune_conv1d_layer
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/pytorch_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pytorch_utils.py
Apache-2.0
def prune_layer( layer: Union[nn.Linear, Conv1D], index: torch.LongTensor, dim: Optional[int] = None ) -> Union[nn.Linear, Conv1D]: """ Prune a Conv1D or linear layer to keep only entries in index. Used to remove heads. Args: layer (`Union[torch.nn.Linear, Conv1D]`): The layer to prune. ...
Prune a Conv1D or linear layer to keep only entries in index. Used to remove heads. Args: layer (`Union[torch.nn.Linear, Conv1D]`): The layer to prune. index (`torch.LongTensor`): The indices to keep in the layer. dim (`int`, *optional*): The dimension on which to keep the indices...
prune_layer
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/pytorch_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pytorch_utils.py
Apache-2.0
def apply_chunking_to_forward( forward_fn: Callable[..., torch.Tensor], chunk_size: int, chunk_dim: int, *input_tensors ) -> torch.Tensor: """ This function chunks the `input_tensors` into smaller input tensor parts of size `chunk_size` over the dimension `chunk_dim`. It then applies a layer `forward_fn...
This function chunks the `input_tensors` into smaller input tensor parts of size `chunk_size` over the dimension `chunk_dim`. It then applies a layer `forward_fn` to each chunk independently to save memory. If the `forward_fn` is independent across the `chunk_dim` this function will yield the same result ...
apply_chunking_to_forward
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/pytorch_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pytorch_utils.py
Apache-2.0
def find_pruneable_heads_and_indices( heads: List[int], n_heads: int, head_size: int, already_pruned_heads: Set[int] ) -> Tuple[Set[int], torch.LongTensor]: """ Finds the heads and their indices taking `already_pruned_heads` into account. Args: heads (`List[int]`): List of the indices of heads ...
Finds the heads and their indices taking `already_pruned_heads` into account. Args: heads (`List[int]`): List of the indices of heads to prune. n_heads (`int`): The number of heads in the model. head_size (`int`): The size of each head. already_pruned_heads (`Set[int]`): A set ...
find_pruneable_heads_and_indices
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/pytorch_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pytorch_utils.py
Apache-2.0
def is_pt_tf_cross_test(test_case): """ Decorator marking a test as a test that control interactions between PyTorch and TensorFlow. PT+TF tests are skipped by default and we can run only them by setting RUN_PT_TF_CROSS_TESTS environment variable to a truthy value and selecting the is_pt_tf_cross_test ...
Decorator marking a test as a test that control interactions between PyTorch and TensorFlow. PT+TF tests are skipped by default and we can run only them by setting RUN_PT_TF_CROSS_TESTS environment variable to a truthy value and selecting the is_pt_tf_cross_test pytest mark.
is_pt_tf_cross_test
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def is_pt_flax_cross_test(test_case): """ Decorator marking a test as a test that control interactions between PyTorch and Flax PT+FLAX tests are skipped by default and we can run only them by setting RUN_PT_FLAX_CROSS_TESTS environment variable to a truthy value and selecting the is_pt_flax_cross_test...
Decorator marking a test as a test that control interactions between PyTorch and Flax PT+FLAX tests are skipped by default and we can run only them by setting RUN_PT_FLAX_CROSS_TESTS environment variable to a truthy value and selecting the is_pt_flax_cross_test pytest mark.
is_pt_flax_cross_test
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def is_staging_test(test_case): """ Decorator marking a test as a staging test. Those tests will run using the staging environment of huggingface.co instead of the real model hub. """ if not _run_staging: return unittest.skip("test is staging test")(test_case) else: try: ...
Decorator marking a test as a staging test. Those tests will run using the staging environment of huggingface.co instead of the real model hub.
is_staging_test
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def require_intel_extension_for_pytorch(test_case): """ Decorator marking a test that requires Intel Extension for PyTorch. These tests are skipped when Intel Extension for PyTorch isn't installed or it does not match current PyTorch version. """ return unittest.skipUnless( is_ipex_ava...
Decorator marking a test that requires Intel Extension for PyTorch. These tests are skipped when Intel Extension for PyTorch isn't installed or it does not match current PyTorch version.
require_intel_extension_for_pytorch
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def require_torch_bf16_gpu(test_case): """Decorator marking a test that requires torch>=1.10, using Ampere GPU or newer arch with cuda>=11.0""" return unittest.skipUnless( is_torch_bf16_gpu_available(), "test requires torch>=1.10, using Ampere GPU or newer arch with cuda>=11.0", )(test_case)
Decorator marking a test that requires torch>=1.10, using Ampere GPU or newer arch with cuda>=11.0
require_torch_bf16_gpu
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def require_torch_bf16_cpu(test_case): """Decorator marking a test that requires torch>=1.10, using CPU.""" return unittest.skipUnless( is_torch_bf16_cpu_available(), "test requires torch>=1.10, using CPU", )(test_case)
Decorator marking a test that requires torch>=1.10, using CPU.
require_torch_bf16_cpu
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def require_torch_tf32(test_case): """Decorator marking a test that requires Ampere or a newer GPU arch, cuda>=11 and torch>=1.7.""" return unittest.skipUnless( is_torch_tf32_available(), "test requires Ampere or a newer GPU arch, cuda>=11 and torch>=1.7" )(test_case)
Decorator marking a test that requires Ampere or a newer GPU arch, cuda>=11 and torch>=1.7.
require_torch_tf32
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def get_gpu_count(): """ Return the number of available gpus (regardless of whether torch, tf or jax is used) """ if is_torch_available(): import torch return torch.cuda.device_count() elif is_tf_available(): import tensorflow as tf return len(tf.config.list_physica...
Return the number of available gpus (regardless of whether torch, tf or jax is used)
get_gpu_count
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def LoggingLevel(level): """ This is a context manager to temporarily change transformers modules logging level to the desired value and have it restored to the original setting at the end of the scope. Example: ```python with LoggingLevel(logging.INFO): AutoModel.from_pretrained("gpt2...
This is a context manager to temporarily change transformers modules logging level to the desired value and have it restored to the original setting at the end of the scope. Example: ```python with LoggingLevel(logging.INFO): AutoModel.from_pretrained("gpt2") # calls logger.info() severa...
LoggingLevel
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def ExtendSysPath(path: Union[str, os.PathLike]) -> Iterator[None]: """ Temporary add given path to `sys.path`. Usage : ```python with ExtendSysPath("/path/to/dir"): mymodule = importlib.import_module("mymodule") ``` """ path = os.fspath(path) try: sys.path.insert(...
Temporary add given path to `sys.path`. Usage : ```python with ExtendSysPath("/path/to/dir"): mymodule = importlib.import_module("mymodule") ```
ExtendSysPath
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def get_env(self): """ Return a copy of the `os.environ` object that sets up `PYTHONPATH` correctly, depending on the test suite it's invoked from. This is useful for invoking external programs from the test suite - e.g. distributed training. It always inserts `./src` first, then `./tes...
Return a copy of the `os.environ` object that sets up `PYTHONPATH` correctly, depending on the test suite it's invoked from. This is useful for invoking external programs from the test suite - e.g. distributed training. It always inserts `./src` first, then `./tests` or `./examples` depending ...
get_env
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def get_auto_remove_tmp_dir(self, tmp_dir=None, before=None, after=None): """ Args: tmp_dir (`string`, *optional*): if `None`: - a unique temporary path will be created - sets `before=True` if `before` is `None` - sets...
Args: tmp_dir (`string`, *optional*): if `None`: - a unique temporary path will be created - sets `before=True` if `before` is `None` - sets `after=True` if `after` is `None` else: - `tmp_d...
get_auto_remove_tmp_dir
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def python_one_liner_max_rss(self, one_liner_str): """ Runs the passed python one liner (just the code) and returns how much max cpu memory was used to run the program. Args: one_liner_str (`string`): a python one liner code that gets passed to `python -c` ...
Runs the passed python one liner (just the code) and returns how much max cpu memory was used to run the program. Args: one_liner_str (`string`): a python one liner code that gets passed to `python -c` Returns: max cpu memory bytes used to run t...
python_one_liner_max_rss
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def mockenv_context(*remove, **update): """ Temporarily updates the `os.environ` dictionary in-place. Similar to mockenv The `os.environ` dictionary is updated in-place so that the modification is sure to work in all situations. Args: remove: Environment variables to remove. update: Dictio...
Temporarily updates the `os.environ` dictionary in-place. Similar to mockenv The `os.environ` dictionary is updated in-place so that the modification is sure to work in all situations. Args: remove: Environment variables to remove. update: Dictionary of environment variables and values to add...
mockenv_context
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def pytest_xdist_worker_id(): """ Returns an int value of worker's numerical id under `pytest-xdist`'s concurrent workers `pytest -n N` regime, or 0 if `-n 1` or `pytest-xdist` isn't being used. """ worker = os.environ.get("PYTEST_XDIST_WORKER", "gw0") worker = re.sub(r"^gw", "", worker, 0, re.M...
Returns an int value of worker's numerical id under `pytest-xdist`'s concurrent workers `pytest -n N` regime, or 0 if `-n 1` or `pytest-xdist` isn't being used.
pytest_xdist_worker_id
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def get_torch_dist_unique_port(): """ Returns a port number that can be fed to `torch.distributed.launch`'s `--master_port` argument. Under `pytest-xdist` it adds a delta number based on a worker id so that concurrent tests don't try to use the same port at once. """ port = 29500 uniq_delta...
Returns a port number that can be fed to `torch.distributed.launch`'s `--master_port` argument. Under `pytest-xdist` it adds a delta number based on a worker id so that concurrent tests don't try to use the same port at once.
get_torch_dist_unique_port
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def nested_simplify(obj, decimals=3): """ Simplifies an object by rounding float numbers, and downcasting tensors/numpy arrays to get simple equality test within tests. """ import numpy as np if isinstance(obj, list): return [nested_simplify(item, decimals) for item in obj] if isins...
Simplifies an object by rounding float numbers, and downcasting tensors/numpy arrays to get simple equality test within tests.
nested_simplify
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def run_command(command: List[str], return_stdout=False): """ Runs `command` with `subprocess.check_output` and will potentially return the `stdout`. Will also properly capture if an error occured while running `command` """ try: output = subprocess.check_output(command, stderr=subprocess.ST...
Runs `command` with `subprocess.check_output` and will potentially return the `stdout`. Will also properly capture if an error occured while running `command`
run_command
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def is_flaky(max_attempts: int = 5, wait_before_retry: Optional[float] = None): """ To decorate flaky tests. They will be retried on failures. Args: max_attempts (`int`, *optional*, defaults to 5): The maximum number of attempts to retry the flaky test. wait_before_retry (`float...
To decorate flaky tests. They will be retried on failures. Args: max_attempts (`int`, *optional*, defaults to 5): The maximum number of attempts to retry the flaky test. wait_before_retry (`float`, *optional*): If provided, will wait that number of seconds before retryi...
is_flaky
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0