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 group_images_by_shape( images: list["torch.Tensor"], ) -> tuple[dict[tuple[int, int], list["torch.Tensor"]], dict[int, tuple[tuple[int, int], int]]]: """ Groups images by shape. Returns a dictionary with the shape as key and a list of images with that shape as value, and a dictionary with the in...
Groups images by shape. Returns a dictionary with the shape as key and a list of images with that shape as value, and a dictionary with the index of the image in the original list as key and the shape and index in the grouped list as value.
group_images_by_shape
python
huggingface/transformers
src/transformers/image_transforms.py
https://github.com/huggingface/transformers/blob/master/src/transformers/image_transforms.py
Apache-2.0
def reorder_images( processed_images: dict[tuple[int, int], "torch.Tensor"], grouped_images_index: dict[int, tuple[int, int]] ) -> list["torch.Tensor"]: """ Reconstructs a list of images in the original order. """ return [ processed_images[grouped_images_index[i][0]][grouped_images_index[i][...
Reconstructs a list of images in the original order.
reorder_images
python
huggingface/transformers
src/transformers/image_transforms.py
https://github.com/huggingface/transformers/blob/master/src/transformers/image_transforms.py
Apache-2.0
def make_list_of_images(images, expected_ndims: int = 3) -> list[ImageInput]: """ Ensure that the output is a list of images. If the input is a single image, it is converted to a list of length 1. If the input is a batch of images, it is converted to a list of images. Args: images (`ImageInput`...
Ensure that the output is a list of images. If the input is a single image, it is converted to a list of length 1. If the input is a batch of images, it is converted to a list of images. Args: images (`ImageInput`): Image of images to turn into a list of images. expected_ndims ...
make_list_of_images
python
huggingface/transformers
src/transformers/image_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/image_utils.py
Apache-2.0
def make_flat_list_of_images( images: Union[list[ImageInput], ImageInput], ) -> ImageInput: """ Ensure that the output is a flat list of images. If the input is a single image, it is converted to a list of length 1. If the input is a nested list of images, it is converted to a flat list of images. A...
Ensure that the output is a flat list of images. If the input is a single image, it is converted to a list of length 1. If the input is a nested list of images, it is converted to a flat list of images. Args: images (`Union[List[ImageInput], ImageInput]`): The input image. Returns: ...
make_flat_list_of_images
python
huggingface/transformers
src/transformers/image_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/image_utils.py
Apache-2.0
def get_image_size_for_max_height_width( image_size: tuple[int, int], max_height: int, max_width: int, ) -> tuple[int, int]: """ Computes the output image size given the input image and the maximum allowed height and width. Keep aspect ratio. Important, even if image_height < max_height and imag...
Computes the output image size given the input image and the maximum allowed height and width. Keep aspect ratio. Important, even if image_height < max_height and image_width < max_width, the image will be resized to at least one of the edges be equal to max_height or max_width. For example: -...
get_image_size_for_max_height_width
python
huggingface/transformers
src/transformers/image_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/image_utils.py
Apache-2.0
def load_images( images: Union[list, tuple, str, "PIL.Image.Image"], timeout: Optional[float] = None ) -> Union["PIL.Image.Image", list["PIL.Image.Image"], list[list["PIL.Image.Image"]]]: """Loads images, handling different levels of nesting. Args: images: A single image, a list of images, or a list ...
Loads images, handling different levels of nesting. Args: images: A single image, a list of images, or a list of lists of images to load. timeout: Timeout for loading images. Returns: A single image, a list of images, a list of lists of images.
load_images
python
huggingface/transformers
src/transformers/image_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/image_utils.py
Apache-2.0
def validate_preprocess_arguments( do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[bool] = None, image_mean: Optional[Union[float, list[float]]] = None, image_std: Optional[Union[float, list[float]]] = None, do_pad: Optional[bool] = None, siz...
Checks validity of typically used arguments in an `ImageProcessor` `preprocess` method. Raises `ValueError` if arguments incompatibility is caught. Many incompatibilities are model-specific. `do_pad` sometimes needs `size_divisor`, sometimes `size_divisibility`, and sometimes `size`. New models and pro...
validate_preprocess_arguments
python
huggingface/transformers
src/transformers/image_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/image_utils.py
Apache-2.0
def and_masks(*mask_functions: list[Callable]) -> Callable: """Returns a mask function that is the intersection of provided mask functions""" if not all(callable(arg) for arg in mask_functions): raise RuntimeError(f"All inputs should be callable mask_functions: {mask_functions}") def and_mask(batch...
Returns a mask function that is the intersection of provided mask functions
and_masks
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def or_masks(*mask_functions: list[Callable]) -> Callable: """Returns a mask function that is the union of provided mask functions""" if not all(callable(arg) for arg in mask_functions): raise RuntimeError(f"All inputs should be callable mask_functions: {mask_functions}") def or_mask(batch_idx, hea...
Returns a mask function that is the union of provided mask functions
or_masks
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def sliding_window_overlay(sliding_window: int) -> Callable: """ This is an overlay depicting a sliding window pattern. Add it on top of a causal mask for a proper sliding window mask. """ def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool: return kv_idx > q_idx ...
This is an overlay depicting a sliding window pattern. Add it on top of a causal mask for a proper sliding window mask.
sliding_window_overlay
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def chunked_overlay(chunk_size: int) -> Callable: """ This is an overlay depicting a chuned attention pattern. Add it on top of a causal mask for a proper chunked attention mask. """ def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool: return kv_idx // chunk_size ...
This is an overlay depicting a chuned attention pattern. Add it on top of a causal mask for a proper chunked attention mask.
chunked_overlay
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def add_offsets_to_mask_function(mask_function: Callable, q_offset: int, kv_offset: int) -> Callable: """ This function adds the correct offsets to the `q_idx` and `kv_idx` as the torch API can only accept lengths, not start and end indices. """ def inner_mask(batch_idx: int, head_idx: int, q_idx: ...
This function adds the correct offsets to the `q_idx` and `kv_idx` as the torch API can only accept lengths, not start and end indices.
add_offsets_to_mask_function
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def prepare_padding_mask( attention_mask: Optional[torch.Tensor], kv_length: int, kv_offset: int, _slice: bool = True ) -> Optional[torch.Tensor]: """ From the 2D attention mask, prepare the correct padding mask to use by potentially padding it, and slicing according to the `kv_offset` if `_slice` is `T...
From the 2D attention mask, prepare the correct padding mask to use by potentially padding it, and slicing according to the `kv_offset` if `_slice` is `True`.
prepare_padding_mask
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def _ignore_causal_mask_sdpa( padding_mask: Optional[torch.Tensor], query_length: int, kv_length: int, kv_offset: int, local_attention_size: Optional[int] = None, ) -> bool: """ Detects whether the causal mask can be ignored in case PyTorch's SDPA is used, rather relying on SDPA's `is_causal...
Detects whether the causal mask can be ignored in case PyTorch's SDPA is used, rather relying on SDPA's `is_causal` argument. In case no token is masked in the 2D `padding_mask` argument, if `query_length == 1` or `key_value_length == query_length`, we rather rely on SDPA `is_causal` argument to use causa...
_ignore_causal_mask_sdpa
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def sdpa_mask_older_torch( batch_size: int, cache_position: torch.Tensor, kv_length: int, kv_offset: int = 0, mask_function: Callable = causal_mask_function, attention_mask: Optional[torch.Tensor] = None, local_size: Optional[int] = None, allow_is_causal_skip: bool = True, allow_torc...
NOTE: This function is only used when torch version is torch<2.5 - see `sdpa_mask_recent_torch` otherwise. Create a 4D boolean mask of shape `(batch_size, 1, query_length, kv_length)` where a value of True indicates that the element should take part in the attention computation, and False that it should n...
sdpa_mask_older_torch
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def eager_mask( batch_size: int, cache_position: torch.Tensor, kv_length: int, kv_offset: int = 0, mask_function: Callable = causal_mask_function, attention_mask: Optional[torch.Tensor] = None, dtype: torch.dtype = torch.float32, **kwargs, ) -> torch.Tensor: """ Create a 4D float...
Create a 4D float mask of shape `(batch_size, 1, query_length, kv_length)` where a value of 0 indicates that the element should take part in the attention computation, and -inf (minimum value for the given `dtype`) that it should not. Args: batch_size (`int`): The batch size of the...
eager_mask
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def flash_attention_mask( batch_size: int, cache_position: torch.Tensor, kv_length: int, kv_offset: int = 0, mask_function: Callable = causal_mask_function, attention_mask: Optional[torch.Tensor] = None, **kwargs, ): """ Create the attention mask necesary to use FA2. Since FA2 is un-...
Create the attention mask necesary to use FA2. Since FA2 is un-padded by definition, here we simply return `None` if the mask is fully causal, or we return the 2D mask which will then be used to extract the seq_lens. We just slice it in case of sliding window. Args: batch_size (`int`): ...
flash_attention_mask
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def flex_attention_mask( batch_size: int, cache_position: torch.Tensor, kv_length: int, kv_offset: int = 0, mask_function: Callable = causal_mask_function, attention_mask: Optional[torch.Tensor] = None, **kwargs, ) -> BlockMask: """ Create a 4D block mask which is a compressed repres...
Create a 4D block mask which is a compressed representation of the full 4D block causal mask. BlockMask is essential for performant computation of flex attention. See: https://pytorch.org/blog/flexattention/ Args: batch_size (`int`): The batch size of the input sequence. cache_...
flex_attention_mask
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def _preprocess_mask_arguments( config: PretrainedConfig, input_embeds: torch.Tensor, attention_mask: Optional[Union[torch.Tensor, BlockMask]], cache_position: torch.Tensor, past_key_values: Optional[Cache], layer_idx: Optional[int], ) -> tuple[bool, Optional[Union[torch.Tensor, BlockMask]], int...
Perform some common pre-processing of the mask arguments we get from the modeling code. Mostly determine the key-value length and offsets, and if we should early exit or not. Args: config (`PretrainedConfig`): The model config. input_embeds (`torch.Tensor`): The inp...
_preprocess_mask_arguments
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def create_causal_mask( config: PretrainedConfig, input_embeds: torch.Tensor, attention_mask: Optional[torch.Tensor], cache_position: torch.Tensor, past_key_values: Optional[Cache], or_mask_function: Optional[Callable] = None, and_mask_function: Optional[Callable] = None, ) -> Optional[Union...
Create a standard causal mask based on the attention implementation used (stored in the config). If `past_key_values` has an HybridCache structure, this function will return the mask corresponding to one of the "full_attention" layers (to align to what is needed in the `modeling_xxx.py` files). Args: ...
create_causal_mask
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def create_sliding_window_causal_mask( config: PretrainedConfig, input_embeds: torch.Tensor, attention_mask: Optional[torch.Tensor], cache_position: torch.Tensor, past_key_values: Optional[Cache], or_mask_function: Optional[Callable] = None, and_mask_function: Optional[Callable] = None, ) ->...
Create a sliding window causal mask based on the attention implementation used (stored in the config). This type of attention pattern was mostly democratized by Mistral. If `past_key_values` has an HybridCache structure, this function will return the mask corresponding to one of the "sliding_attention" lay...
create_sliding_window_causal_mask
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def create_chunked_causal_mask( config: PretrainedConfig, input_embeds: torch.Tensor, attention_mask: Optional[torch.Tensor], cache_position: torch.Tensor, past_key_values: Optional[Cache], or_mask_function: Optional[Callable] = None, and_mask_function: Optional[Callable] = None, ) -> Option...
Create a chunked attention causal mask based on the attention implementation used (stored in the config). This type of attention pattern was mostly democratized by Llama4. If `past_key_values` has an HybridCache structure, this function will return the mask corresponding to one of the "chunked_attention" l...
create_chunked_causal_mask
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def create_masks_for_generate( config: PretrainedConfig, input_embeds: torch.Tensor, attention_mask: Optional[torch.Tensor], cache_position: torch.Tensor, past_key_values: Optional[Cache], or_mask_function: Optional[Callable] = None, and_mask_function: Optional[Callable] = None, **kwargs...
This function mimics how we create the masks in the `modeling_xxx.py` files, and is used in `generate` in order to easily create the masks in advance, when we compile the forwards with Static caches. Args: config (`PretrainedConfig`): The model config. input_embeds (`torch.Tens...
create_masks_for_generate
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def to_string(self, grid_size=(20, 40), limit=4): """Returns a string representation of the block mask.""" dense_mask = self *batch_dims, num_rows, num_cols = dense_mask.shape total_vis = [] for idx, batch_idx in enumerate(itertools.product(*[range(i) for i in batch_dims])): ...
Returns a string representation of the block mask.
to_string
python
huggingface/transformers
src/transformers/masking_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/masking_utils.py
Apache-2.0
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): r""" Instantiate a [`ModelCard`] from a pre-trained model model card. Parameters: pretrained_model_name_or_path: either: - a string, the *model id* of a pretrained model card hosted inside a model re...
Instantiate a [`ModelCard`] from a pre-trained model model card. Parameters: pretrained_model_name_or_path: either: - a string, the *model id* of a pretrained model card hosted inside a model repo on huggingface.co. - a path to a *directory* containing a mo...
from_pretrained
python
huggingface/transformers
src/transformers/modelcard.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modelcard.py
Apache-2.0
def parse_keras_history(logs): """ Parse the `logs` of either a `keras.History` object returned by `model.fit()` or an accumulated logs `dict` passed to the `PushToHubCallback`. Returns lines and logs compatible with those returned by `parse_log_history`. """ if hasattr(logs, "history"): # T...
Parse the `logs` of either a `keras.History` object returned by `model.fit()` or an accumulated logs `dict` passed to the `PushToHubCallback`. Returns lines and logs compatible with those returned by `parse_log_history`.
parse_keras_history
python
huggingface/transformers
src/transformers/modelcard.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modelcard.py
Apache-2.0
def _unmask_unattended( expanded_mask: torch.FloatTensor, min_dtype: float, ): # fmt: off """ Attend to all tokens in masked rows from the expanded attention mask, for example the relevant first rows when using left padding. This is required by F.scaled_dot_product_at...
Attend to all tokens in masked rows from the expanded attention mask, for example the relevant first rows when using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path. Details: https://github.com/pytorch/pytorch/issues/110213 `expanded_mas...
_unmask_unattended
python
huggingface/transformers
src/transformers/modeling_attn_mask_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_attn_mask_utils.py
Apache-2.0
def _prepare_4d_attention_mask_for_sdpa(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): """ Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape `(batch_size, key_value_length)` Args: mask (`torch.Tensor`): ...
Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape `(batch_size, key_value_length)` Args: mask (`torch.Tensor`): A 2D attention mask of shape `(batch_size, key_value_length)` dtype (`torch.dtype`): The tor...
_prepare_4d_attention_mask_for_sdpa
python
huggingface/transformers
src/transformers/modeling_attn_mask_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_attn_mask_utils.py
Apache-2.0
def is_flash_attn_available(): """Determine whether flash-attention can be used or not.""" # if package `flash-attn` is available, flash-attention can be used natively. if is_flash_attn_2_available(): return True # flash-attention can be used on Ascend NPU without package `flash-attn` if i...
Determine whether flash-attention can be used or not.
is_flash_attn_available
python
huggingface/transformers
src/transformers/modeling_flash_attention_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_flash_attention_utils.py
Apache-2.0
def flash_attn_supports_top_left_mask(): """Determine whether flash-attention uses top-left or down-right mask""" if is_flash_attn_2_available(): # top-left mask is used in package `flash-attn` with version lower than 2.1.0 return not is_flash_attn_greater_or_equal_2_10() if is_torch_npu_a...
Determine whether flash-attention uses top-left or down-right mask
flash_attn_supports_top_left_mask
python
huggingface/transformers
src/transformers/modeling_flash_attention_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_flash_attention_utils.py
Apache-2.0
def _get_unpad_data(attention_mask: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, int]: """ Retrieves indexing data required to repad unpadded (ragged) tensors. Arguments: attention_mask (`torch.Tensor`): Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid a...
Retrieves indexing data required to repad unpadded (ragged) tensors. Arguments: attention_mask (`torch.Tensor`): Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid. Return: indices (`torch.Tensor`): The indices of non-...
_get_unpad_data
python
huggingface/transformers
src/transformers/modeling_flash_attention_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_flash_attention_utils.py
Apache-2.0
def _upad_input( query_layer: torch.Tensor, key_layer: torch.Tensor, value_layer: torch.Tensor, attention_mask: torch.Tensor, query_length: int, ): """ Unpads query, key, and values tensors, using a single dimension for all tokens even though they belong to different batches. This funct...
Unpads query, key, and values tensors, using a single dimension for all tokens even though they belong to different batches. This function is used instead of `flash_attn.bert_padding.unpad_input` in order to avoid the recomputation of the same intermediary tensors for query, key, value tensors. Argum...
_upad_input
python
huggingface/transformers
src/transformers/modeling_flash_attention_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_flash_attention_utils.py
Apache-2.0
def prepare_fa2_from_position_ids(query, key, value, position_ids): """ This function returns necessary arguments to call `flash_attn_varlen_func`. All three query, key, value states will be flattened. Cumulative lengths of each examples in the batch will be extracted from position_ids. NOTE: ideal...
This function returns necessary arguments to call `flash_attn_varlen_func`. All three query, key, value states will be flattened. Cumulative lengths of each examples in the batch will be extracted from position_ids. NOTE: ideally cumulative lengths should be prepared at the data collator stage Ar...
prepare_fa2_from_position_ids
python
huggingface/transformers
src/transformers/modeling_flash_attention_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_flash_attention_utils.py
Apache-2.0
def fa_peft_integration_check( query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, target_dtype: Optional[torch.dtype] = None, ): """ PEFT usually casts the layer norms in float32 for training stability reasons therefore the input hidden states gets silently casted in float32. Hence...
PEFT usually casts the layer norms in float32 for training stability reasons therefore the input hidden states gets silently casted in float32. Hence, we need cast them back in float16 / bfloat16 just to be sure everything works as expected. This might slowdown training & inference so it is recommended...
fa_peft_integration_check
python
huggingface/transformers
src/transformers/modeling_flash_attention_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_flash_attention_utils.py
Apache-2.0
def _flash_attention_forward( query_states: torch.Tensor, key_states: torch.Tensor, value_states: torch.Tensor, attention_mask: Optional[torch.Tensor], query_length: int, is_causal: bool, dropout: float = 0.0, position_ids: Optional[torch.Tensor] = None, softmax_scale: Optional[float...
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token first unpad the input, then computes the attention scores and pad the final attention scores. Args: query_states (`torch.Tensor`): Input query states to be passed to Flash Attent...
_flash_attention_forward
python
huggingface/transformers
src/transformers/modeling_flash_attention_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_flash_attention_utils.py
Apache-2.0
def register_for_auto_class(cls, auto_class="FlaxAutoModel"): """ 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. Args: auto_class (`str` or `type`, *optional*, defaul...
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. Args: auto_class (`str` or `type`, *optional*, defaults to `"FlaxAutoModel"`): The auto class to register this...
register_for_auto_class
python
huggingface/transformers
src/transformers/modeling_flax_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_flax_utils.py
Apache-2.0
def get_gguf_hf_weights_map( hf_model, model_type: Optional[str] = None, num_layers: Optional[int] = None, qual_name: str = "", ): """ GGUF uses this naming convention for their tensors from HF checkpoint: `blk.N.BB.weight` and `blk.N.BB.bias` where N signifies the block number of a laye...
GGUF uses this naming convention for their tensors from HF checkpoint: `blk.N.BB.weight` and `blk.N.BB.bias` where N signifies the block number of a layer, and BB signifies the attention/mlp layer components. See "Standardized tensor names" in https://github.com/ggerganov/ggml/blob/master/docs/...
get_gguf_hf_weights_map
python
huggingface/transformers
src/transformers/modeling_gguf_pytorch_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_gguf_pytorch_utils.py
Apache-2.0
def load_gguf_checkpoint(gguf_checkpoint_path, return_tensors=False, model_to_load=None): """ Load a GGUF file and return a dictionary of parsed parameters containing tensors, the parsed tokenizer and config attributes. Args: gguf_checkpoint_path (`str`): The path the to GGUF file t...
Load a GGUF file and return a dictionary of parsed parameters containing tensors, the parsed tokenizer and config attributes. Args: gguf_checkpoint_path (`str`): The path the to GGUF file to load return_tensors (`bool`, defaults to `False`): Whether to read the tens...
load_gguf_checkpoint
python
huggingface/transformers
src/transformers/modeling_gguf_pytorch_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_gguf_pytorch_utils.py
Apache-2.0
def dynamic_rope_update(rope_forward): """ Decorator function to update the RoPE parameters in the forward pass, if the model is using a dynamic RoPE (i.e. a RoPE implementation that may recompute its frequencies in the forward pass). Args: rope_forward (Callable): The forward pass ...
Decorator function to update the RoPE parameters in the forward pass, if the model is using a dynamic RoPE (i.e. a RoPE implementation that may recompute its frequencies in the forward pass). Args: rope_forward (Callable): The forward pass of the RoPE implementation. Returns: ...
dynamic_rope_update
python
huggingface/transformers
src/transformers/modeling_rope_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_rope_utils.py
Apache-2.0
def longrope_frequency_update(self, position_ids, device): """Longrope uses long factor if sequence is larger than original pretraining length, short otherwise.""" seq_len = torch.max(position_ids) + 1 if hasattr(self.config, "original_max_position_embeddings"): original_max_position...
Longrope uses long factor if sequence is larger than original pretraining length, short otherwise.
longrope_frequency_update
python
huggingface/transformers
src/transformers/modeling_rope_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_rope_utils.py
Apache-2.0
def keras_serializable(cls): """ Decorate a Keras Layer class to support Keras serialization. This is done by: 1. Adding a `transformers_config` dict to the Keras config dictionary in `get_config` (called by Keras at serialization time. 2. Wrapping `__init__` to accept that `transformers_co...
Decorate a Keras Layer class to support Keras serialization. This is done by: 1. Adding a `transformers_config` dict to the Keras config dictionary in `get_config` (called by Keras at serialization time. 2. Wrapping `__init__` to accept that `transformers_config` dict (passed by Keras at deser...
keras_serializable
python
huggingface/transformers
src/transformers/modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_tf_utils.py
Apache-2.0
def input_processing(func, config, **kwargs): """ Process the input of each TensorFlow model including the booleans. In case of a list of symbolic inputs, each input has to be named accordingly to the parameters name, i.e. `input_ids = keras.Input(shape=(128,), dtype='int32', name="input_ids")` otherwis...
Process the input of each TensorFlow model including the booleans. In case of a list of symbolic inputs, each input has to be named accordingly to the parameters name, i.e. `input_ids = keras.Input(shape=(128,), dtype='int32', name="input_ids")` otherwise the order of the tensors will not be guaranteed dur...
input_processing
python
huggingface/transformers
src/transformers/modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_tf_utils.py
Apache-2.0
def load_tf_sharded_weights(model, shard_files, ignore_mismatched_sizes=False, strict=False, _prefix=None): """ This is the same as `load_tf_weights` but for a sharded checkpoint. Detect missing and unexpected layers and load the TF weights from the shard file accordingly to their names and shapes. Thi...
This is the same as `load_tf_weights` but for a sharded checkpoint. Detect missing and unexpected layers and load the TF weights from the shard file accordingly to their names and shapes. This load is performed efficiently: each checkpoint shard is loaded one by one in RAM and deleted after being load...
load_tf_sharded_weights
python
huggingface/transformers
src/transformers/modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_tf_utils.py
Apache-2.0
def load_tf_shard(model, model_layer_map, resolved_archive_file, ignore_mismatched_sizes=False, _prefix=None): """ Loads a shard from a sharded checkpoint file. Can be either H5 or Safetensors. Handles missing keys and unexpected keys. Args: model (`keras.models.Model`): Model in which the weig...
Loads a shard from a sharded checkpoint file. Can be either H5 or Safetensors. Handles missing keys and unexpected keys. Args: model (`keras.models.Model`): Model in which the weights are loaded model_layer_map (`Dict`): A dictionary mapping the layer name to the index of the layer in the ...
load_tf_shard
python
huggingface/transformers
src/transformers/modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_tf_utils.py
Apache-2.0
def load_tf_sharded_weights_from_safetensors( model, shard_files, ignore_mismatched_sizes=False, strict=False, _prefix=None ): """ This is the same as `load_tf_weights_from_safetensors` but for a sharded TF-format safetensors checkpoint. Detect missing and unexpected layers and load the TF weights from ...
This is the same as `load_tf_weights_from_safetensors` but for a sharded TF-format safetensors checkpoint. Detect missing and unexpected layers and load the TF weights from the shard file accordingly to their names and shapes. This load is performed efficiently: each checkpoint shard is loaded one by ...
load_tf_sharded_weights_from_safetensors
python
huggingface/transformers
src/transformers/modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_tf_utils.py
Apache-2.0
def load_tf_weights(model, resolved_archive_file, ignore_mismatched_sizes=False, _prefix=None): """ Detect missing and unexpected layers and load the TF weights from the shard file accordingly to their names and shapes. Args: model (`keras.models.Model`): The model to load the weigh...
Detect missing and unexpected layers and load the TF weights from the shard file accordingly to their names and shapes. Args: model (`keras.models.Model`): The model to load the weights into. resolved_archive_file (`str`): The location of the H5 file. ignore...
load_tf_weights
python
huggingface/transformers
src/transformers/modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_tf_utils.py
Apache-2.0
def input_signature(self) -> Dict[str, tf.TensorSpec]: """ This property should return a dict mapping input names to tf.TensorSpec objects, representing the expected shape and dtype for model inputs. It is used for both serving and for generating dummy inputs. """ model_inputs = ...
This property should return a dict mapping input names to tf.TensorSpec objects, representing the expected shape and dtype for model inputs. It is used for both serving and for generating dummy inputs.
input_signature
python
huggingface/transformers
src/transformers/modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_tf_utils.py
Apache-2.0
def prepare_tf_dataset( self, dataset: "datasets.Dataset", # noqa:F821 batch_size: int = 8, shuffle: bool = True, tokenizer: Optional["PreTrainedTokenizerBase"] = None, collate_fn: Optional[Callable] = None, collate_fn_args: Optional[Dict[str, Any]] = None, ...
Wraps a HuggingFace [`~datasets.Dataset`] as a `tf.data.Dataset` with collation and batching. This method is designed to create a "ready-to-use" dataset that can be passed directly to Keras methods like `fit()` without further modification. The method will drop columns from the dataset if they ...
prepare_tf_dataset
python
huggingface/transformers
src/transformers/modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_tf_utils.py
Apache-2.0
def get_output_layer_with_bias(self) -> Union[None, 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: `keras.layers.Layer`: The layer that handles the bias, None if not an LM mode...
Get the layer that handles a bias attribute in case the model has an LM head with weights tied to the embeddings Return: `keras.layers.Layer`: The layer that handles the bias, None if not an LM model.
get_output_layer_with_bias
python
huggingface/transformers
src/transformers/modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_tf_utils.py
Apache-2.0
def resize_token_embeddings( self, new_num_tokens: Optional[int] = None ) -> Union[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 cl...
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
huggingface/transformers
src/transformers/modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_tf_utils.py
Apache-2.0
def _v2_resized_token_embeddings(self, new_num_tokens: Optional[int] = None) -> 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 new t...
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
huggingface/transformers
src/transformers/modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_tf_utils.py
Apache-2.0
def _v2_get_resized_embeddings( self, old_embeddings: keras.layers.Embedding, new_num_tokens: int ) -> 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 size wil...
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 (`keras.layers.Embedding`): Old embeddings to be resized. ...
_v2_get_resized_embeddings
python
huggingface/transformers
src/transformers/modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/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. Args: auto_class (`str` or `type`, *optional*, defaults...
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. Args: auto_class (`str` or `type`, *optional*, defaults to `"TFAutoModel"`): The auto class to register this n...
register_for_auto_class
python
huggingface/transformers
src/transformers/modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_tf_utils.py
Apache-2.0
def no_init_weights(): """ Context manager to globally disable weight initialization to speed up loading large models. """ global _init_weights old_init_weights = _init_weights _init_weights = False def _skip_init(*args, **kwargs): pass # Save the original initialization funct...
Context manager to globally disable weight initialization to speed up loading large models.
no_init_weights
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def restore_default_torch_dtype(func): """ Decorator to restore the default torch dtype at the end of the function. Serves as a backup in case calling the function raises an error after the function has changed the default dtype but before it could restore it. """ @wraps(func) def _wrap...
Decorator to restore the default torch dtype at the end of the function. Serves as a backup in case calling the function raises an error after the function has changed the default dtype but before it could restore it.
restore_default_torch_dtype
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def get_torch_context_manager_or_global_device(): """ Test if a device context manager is currently in use, or if it is not the case, check if the default device is not "cpu". This is used to infer the correct device to load the model on, in case `device_map` is not provided. """ device_in_context =...
Test if a device context manager is currently in use, or if it is not the case, check if the default device is not "cpu". This is used to infer the correct device to load the model on, in case `device_map` is not provided.
get_torch_context_manager_or_global_device
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def load_sharded_checkpoint(model, folder, strict=True, prefer_safe=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...
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
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def load_state_dict( checkpoint_file: Union[str, os.PathLike], is_quantized: bool = False, map_location: Optional[Union[str, torch.device]] = "cpu", weights_only: bool = True, ): """ Reads a `safetensor` or a `.bin` checkpoint file. We load the checkpoint on "cpu" by default. """ # Use s...
Reads a `safetensor` or a `.bin` checkpoint file. We load the checkpoint on "cpu" by default.
load_state_dict
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _load_parameter_into_model(model: "PreTrainedModel", param_name: str, tensor: torch.Tensor): """Cast a single parameter `param_name` into the `model`, with value `tensor`.""" module, param_type = get_module_from_name(model, param_name) # This will check potential shape mismatch if skipped before mod...
Cast a single parameter `param_name` into the `model`, with value `tensor`.
_load_parameter_into_model
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _load_state_dict_into_meta_model( model: "PreTrainedModel", state_dict: Dict, shard_file: str, expected_keys: List[str], reverse_renaming_mapping: Dict[str, str], device_map: Optional[Dict] = None, disk_offload_folder: Optional[str] = None, disk_offload_index: Optional[Dict] = None, ...
Load parameters from `meta_state_dict` into the model. The parameters of the `meta_state_dict` are on the meta device in order to easily infer the shapes and dtypes that they will have. Then proper parameters are then loaded from `shard_file`, which is the actual state dict file on disk. This function takes...
_load_state_dict_into_meta_model
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _get_resolved_checkpoint_files( pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], subfolder: str, variant: Optional[str], gguf_file: Optional[str], from_tf: bool, from_flax: bool, use_safetensors: bool, cache_dir: str, force_download: bool, proxies: Optional[D...
Get all the checkpoint filenames based on `pretrained_model_name_or_path`, and optional metadata if the checkpoints are sharded. This function will download the data if necessary.
_get_resolved_checkpoint_files
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _get_torch_dtype( cls, torch_dtype: Optional[Union[str, torch.dtype, Dict]], checkpoint_files: Optional[List[str]], config: PretrainedConfig, sharded_metadata: Optional[Dict], state_dict: Optional[Dict], weights_only: bool, ) -> Tuple[PretrainedConfig, Optional[torch.dtype], Optional[tor...
Find the correct `torch_dtype` to use based on provided arguments. Also update the `config` based on the inferred dtype. We do the following: 1. If torch_dtype is not None, we use that dtype 2. If torch_dtype is "auto", we auto-detect dtype from the loaded state_dict, by checking its first weights e...
_get_torch_dtype
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _get_device_map( model: "PreTrainedModel", device_map: Optional[Union[str, Dict]], max_memory: Optional[Dict], hf_quantizer: Optional[HfQuantizer], torch_dtype: Optional[torch.dtype], keep_in_fp32_regex: Optional[re.Pattern], ) -> Dict: """Compute the final `device_map` to use if we pass...
Compute the final `device_map` to use if we passed a value in ['auto', 'balanced', 'balanced_low_0', 'sequential']. Otherwise, we check for any device inconsistencies in the device_map.
_get_device_map
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _find_missing_and_unexpected_keys( cls, model: "PreTrainedModel", original_checkpoint_keys: List[str], checkpoint_keys: List[str], loading_base_model_from_task_state_dict: bool, hf_quantizer: Optional[HfQuantizer], device_map: Dict, ) -> Tuple[List[str], List[str]]: """Find missing k...
Find missing keys (keys that are part of the model parameters but were NOT found in the loaded state dict keys) and unexpected keys (keys found in the loaded state dict keys, but that are NOT part of the model parameters)
_find_missing_and_unexpected_keys
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _find_mismatched_keys( model: "PreTrainedModel", state_dict: Optional[Dict], checkpoint_files: Optional[List[str]], ignore_mismatched_sizes: bool, keys_to_rename_mapping: Dict[str, str], is_quantized: bool, weights_only: bool, ) -> Tuple[List[str], List[Tuple[int, int]]]: """ Fin...
Find potential shape mismatch between the different state dicts and the model parameters, but only if `ignore_mismatched_sizes` is True. Otherwise, return immediately and any shape mismatch that may exist will be raised later on. This avoids checking every parameter in advance, as shape mismatch are extrem...
_find_mismatched_keys
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def add_model_tags(self, tags: Union[List[str], str]) -> None: r""" Add custom tags into the model that gets pushed to the Hugging Face Hub. Will not overwrite existing tags in the model. Args: tags (`Union[List[str], str]`): The desired tags to inject in the...
Add custom tags into the model that gets pushed to the Hugging Face Hub. Will not overwrite existing tags in the model. Args: tags (`Union[List[str], str]`): The desired tags to inject in the model Examples: ```python from transformers impo...
add_model_tags
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _autoset_attn_implementation( cls, config, torch_dtype: Optional[torch.dtype] = None, device_map: Optional[Union[str, Dict[str, int]]] = None, check_device_map: bool = True, ): """ Automatically checks and dispatches to a default attention implementation. ...
Automatically checks and dispatches to a default attention implementation. In order of priority: 1. An implementation specified in `config._attn_implementation` (due for example to the argument attn_implementation="sdpa" in from_pretrained). 2. SDPA implementation, if available and supp...
_autoset_attn_implementation
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _check_and_enable_flash_attn_2( cls, config, torch_dtype: Optional[torch.dtype] = None, device_map: Optional[Union[str, Dict[str, int]]] = None, check_device_map: bool = True, hard_check_only: bool = False, ) -> PretrainedConfig: """ Checks the ava...
Checks the availability of Flash Attention 2 and compatibility with the current model. If all checks pass and `hard_check_only` is False, the method will set the config attribute `attn_implementation` to "flash_attention_2" so that the model can initialize the correct attention module.
_check_and_enable_flash_attn_2
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _check_and_enable_sdpa(cls, config, hard_check_only: bool = False) -> PretrainedConfig: """ Checks the availability of SDPA for a given model. If all checks pass and `hard_check_only` is False, the method will set the config attribute `_attn_implementation` to "sdpa" so that the model can i...
Checks the availability of SDPA for a given model. If all checks pass and `hard_check_only` is False, the method will set the config attribute `_attn_implementation` to "sdpa" so that the model can initialize the correct attention module.
_check_and_enable_sdpa
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _check_and_enable_flex_attn(cls, config, hard_check_only: bool = False) -> PretrainedConfig: """ Checks the availability of Flex Attention for a given model. If all checks pass and `hard_check_only` is False, the method will set the config attribute `_attn_implementation` to "flex_attention...
Checks the availability of Flex Attention for a given model. If all checks pass and `hard_check_only` is False, the method will set the config attribute `_attn_implementation` to "flex_attention" so that the model can initialize the correct attention module.
_check_and_enable_flex_attn
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def initialize_weights(self): """ This is equivalent to calling `self.apply(self._initialize_weights)`, but correctly handles composite models. This function dynamically dispatches the correct `init_weights` function to the modules as we advance in the module graph along the recursion. I...
This is equivalent to calling `self.apply(self._initialize_weights)`, but correctly handles composite models. This function dynamically dispatches the correct `init_weights` function to the modules as we advance in the module graph along the recursion. It can handle an arbitrary number of sub-m...
initialize_weights
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def resize_token_embeddings( self, new_num_tokens: Optional[int] = None, pad_to_multiple_of: Optional[int] = None, mean_resizing: bool = True, ) -> nn.Embedding: """ Resizes input token embeddings matrix of the model if `new_num_tokens != config.vocab_size`. ...
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 new number of tokens i...
resize_token_embeddings
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _get_resized_embeddings( self, old_embeddings: nn.Embedding, new_num_tokens: Optional[int] = None, pad_to_multiple_of: Optional[int] = None, mean_resizing: bool = True, ) -> nn.Embedding: """ Build a resized Embedding Module from a provided token 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 will remove vectors from the end Args: old_embeddings (`torch.nn.Embedding`): Old embeddings to be resized. ...
_get_resized_embeddings
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/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, mean_resizing: bool = True, ) -> nn.Linear: """ Build a resized Linear Module from a provided old Linear Module. Increasing the si...
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
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/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] = "5GB", safe_serializatio...
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
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _fix_state_dict_key_on_load(key: str) -> Tuple[str, bool]: """Replace legacy parameter names with their modern equivalents. E.g. beta -> bias, gamma -> weight.""" # Rename LayerNorm beta & gamma params for some early models ported from Tensorflow (e.g. Bert) # This rename is logged. ...
Replace legacy parameter names with their modern equivalents. E.g. beta -> bias, gamma -> weight.
_fix_state_dict_key_on_load
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _get_key_renaming_mapping( self, checkpoint_keys: List[str], key_mapping: Optional[Dict[str, str]] = None, loading_base_model_from_task_state_dict: bool = False, loading_task_model_from_base_state_dict: bool = False, ): """ Compute a mapping between the se...
Compute a mapping between the serialized keys on disk `checkpoint_keys`, and the keys that the model that we are loading expects. This is the single entry point for key renaming that will be used during loading. Log if any parameters have been renamed.
_get_key_renaming_mapping
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/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. Args: auto_class (`str` or `type`, *optional*, defaults t...
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. Args: auto_class (`str` or `type`, *optional*, defaults to `"AutoModel"`): The auto class to register this new...
register_for_auto_class
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def supports_tp_plan(self): """ Returns whether the model has a tensor parallelism plan. """ if self._tp_plan is not None: return True # Check if base model has a TP plan if getattr(self.base_model, "_tp_plan", None) is not None: return True ...
Returns whether the model has a tensor parallelism plan.
supports_tp_plan
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def get_compiled_call(self, compile_config: Optional[CompileConfig]) -> Callable: """Return a `torch.compile`'d version of `self.__call__`. This is useful to dynamically choose between non-compiled/compiled `forward` during inference, especially to switch between prefill (where we don't want to ...
Return a `torch.compile`'d version of `self.__call__`. This is useful to dynamically choose between non-compiled/compiled `forward` during inference, especially to switch between prefill (where we don't want to use compiled version to avoid recomputing the graph with new shapes) and iterative decoding ...
get_compiled_call
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _move_missing_keys_from_meta_to_cpu( self, missing_keys: List[str], unexpected_keys: List[str], dtype: Optional[torch.dtype], hf_quantizer: Optional[HfQuantizer], ) -> "PreTrainedModel": """Move the missing keys (keys that are part of the model parameters, but wer...
Move the missing keys (keys that are part of the model parameters, but were NOT found in the loaded state dicts) back from meta device to cpu.
_move_missing_keys_from_meta_to_cpu
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _initialize_missing_keys( self, loaded_keys: List[str], ignore_mismatched_sizes: bool, is_quantized: bool, ) -> "PreTrainedModel": """Initialize the missing keys (keys that are part of the model parameters, but were NOT found in the loaded state dicts), according to ...
Initialize the missing keys (keys that are part of the model parameters, but were NOT found in the loaded state dicts), according to `_initialize_weights`. Indeed, since the corresponding weights are missing from the state dict, they will not be replaced and need to be initialized correctly (i.e. weight...
_initialize_missing_keys
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def get_parameter_or_buffer(self, target: str): """ Return the parameter or buffer given by `target` if it exists, otherwise throw an error. This combines `get_parameter()` and `get_buffer()` in a single handy function. If the target is an `_extra_state` attribute, it will return the ext...
Return the parameter or buffer given by `target` if it exists, otherwise throw an error. This combines `get_parameter()` and `get_buffer()` in a single handy function. If the target is an `_extra_state` attribute, it will return the extra state provided by the module. Note that it only work if ...
get_parameter_or_buffer
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def unwrap_model(model: nn.Module, recursive: bool = False) -> nn.Module: """ Recursively unwraps a model from potential containers (as used in distributed training). Args: model (`torch.nn.Module`): The model to unwrap. recursive (`bool`, *optional*, defaults to `False`): Wheth...
Recursively unwraps a model from potential containers (as used in distributed training). Args: model (`torch.nn.Module`): The model to unwrap. recursive (`bool`, *optional*, defaults to `False`): Whether to recursively extract all cases of `module.module` from `model` as well as un...
unwrap_model
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def expand_device_map(device_map, param_names): """ Expand a device map to return the correspondence parameter name to device. """ new_device_map = {} for module, device in device_map.items(): new_device_map.update( {p: device for p in param_names if p == module or p.startswith(f...
Expand a device map to return the correspondence parameter name to device.
expand_device_map
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def is_accelerator_device(device: Union[str, int, torch.device]) -> bool: """Check if the device is an accelerator. We need to function, as device_map can be "disk" as well, which is not a proper `torch.device`. """ if device == "disk": return False else: return torch.device(device)....
Check if the device is an accelerator. We need to function, as device_map can be "disk" as well, which is not a proper `torch.device`.
is_accelerator_device
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def caching_allocator_warmup(model: PreTrainedModel, expanded_device_map: Dict, hf_quantizer: Optional[HfQuantizer]): """This function warm-ups the caching allocator based on the size of the model tensors that will reside on each device. It allows to have one large call to Malloc, instead of recursively calling...
This function warm-ups the caching allocator based on the size of the model tensors that will reside on each device. It allows to have one large call to Malloc, instead of recursively calling it later when loading the model, which is actually the loading speed bottleneck. Calling this function allows to cut...
caching_allocator_warmup
python
huggingface/transformers
src/transformers/modeling_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_utils.py
Apache-2.0
def _is_rank_zero(): """Return True if rank=0 or we aren't running distributed.""" if not (_torch_distributed_available and torch.distributed.is_initialized()): return True return torch.distributed.get_rank() == 0
Return True if rank=0 or we aren't running distributed.
_is_rank_zero
python
huggingface/transformers
src/transformers/model_debugging_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/model_debugging_utils.py
Apache-2.0
def _dtensor_repr(x): """Return a stable string representation for a DTensor-like object.""" if _is_rank_zero(): return f"DTensor (rank0) -> {repr(x._local_tensor)}" return "DTensor(non-rank0)"
Return a stable string representation for a DTensor-like object.
_dtensor_repr
python
huggingface/transformers
src/transformers/model_debugging_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/model_debugging_utils.py
Apache-2.0
def _serialize_tensor_like_io( value, debug_path: Optional[str] = None, use_repr: bool = True, path_to_value: Optional[str] = None ): """ Converts Tensors and DTensors to a JSON-serializable dictionary representation. Args: value: Any Python object, often including torch Tensors, lists, dicts, ...
Converts Tensors and DTensors to a JSON-serializable dictionary representation. Args: value: Any Python object, often including torch Tensors, lists, dicts, etc. debug_path (`str`, *optional*, defaults to `None`): Directory to dump debug JSON and SafeTensors files. use_repr (bool, *opt...
_serialize_tensor_like_io
python
huggingface/transformers
src/transformers/model_debugging_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/model_debugging_utils.py
Apache-2.0
def _serialize_io(value, debug_path: Optional[str] = None, use_repr: bool = True, path_to_value: Optional[str] = None): """ Recursively build a JSON-serializable Python structure from `value`. Tensors and DTensors become either sanitized repr strings, or are saved to disk as SafeTensors files and their ...
Recursively build a JSON-serializable Python structure from `value`. Tensors and DTensors become either sanitized repr strings, or are saved to disk as SafeTensors files and their relative paths are recorded in the returned Python structure. Lists/tuples/dicts are recursed into. All memory addresse...
_serialize_io
python
huggingface/transformers
src/transformers/model_debugging_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/model_debugging_utils.py
Apache-2.0
def _repr_to_list(value: torch.Tensor): """ Converts a tensor into a sanitized multi-line string representation. Args: value (`torch.Tensor`): The tensor to represent. Returns: `List[str]`: List of string lines representing the tensor. """ torch.set_printoptions(sci_mode=True, ...
Converts a tensor into a sanitized multi-line string representation. Args: value (`torch.Tensor`): The tensor to represent. Returns: `List[str]`: List of string lines representing the tensor.
_repr_to_list
python
huggingface/transformers
src/transformers/model_debugging_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/model_debugging_utils.py
Apache-2.0
def is_layer_block(node): """ Checks whether a node represents a layer block with submodules. Args: node (`dict`): A node from the call tree. Returns: `bool`: Whether the node is a layer block. """ match = LAYER_SUFFIX_RE.match(node.get("module_path", "")) if not match or n...
Checks whether a node represents a layer block with submodules. Args: node (`dict`): A node from the call tree. Returns: `bool`: Whether the node is a layer block.
is_layer_block
python
huggingface/transformers
src/transformers/model_debugging_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/model_debugging_utils.py
Apache-2.0
def prune_intermediate_layers(node): """ Recursively removes intermediate layers from the tree to improve readability. Keeps at least the first and last layers if many consecutive layers are present. Args: node (`dict`): The root or subnode to prune recursively. """ if not node.get("chi...
Recursively removes intermediate layers from the tree to improve readability. Keeps at least the first and last layers if many consecutive layers are present. Args: node (`dict`): The root or subnode to prune recursively.
prune_intermediate_layers
python
huggingface/transformers
src/transformers/model_debugging_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/model_debugging_utils.py
Apache-2.0
def _attach_debugger_logic( model, debug_path: Optional[str] = ".", do_prune_layers: Optional[bool] = True, use_repr: bool = True, ): """ Attaches a debugging wrapper to every module in the model. This records structured inputs and outputs during the forward pass into a call tree. Args...
Attaches a debugging wrapper to every module in the model. This records structured inputs and outputs during the forward pass into a call tree. Args: model (`PreTrainedModel`, `nn.Module`): Model to wrap. debug_path (`str`): Optional directory to dump debug JSON files. do_prune_la...
_attach_debugger_logic
python
huggingface/transformers
src/transformers/model_debugging_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/model_debugging_utils.py
Apache-2.0
def model_addition_debugger_context( model, debug_path: Optional[str] = None, do_prune_layers: Optional[bool] = True, use_repr: Optional[bool] = True, ): """ # Model addition debugger - context manager for model adders This context manager is a power user tool intended for model adders. ...
# Model addition debugger - context manager for model adders This context manager is a power user tool intended for model adders. It tracks all forward calls within a model forward and logs a slice of each input and output on a nested JSON file. If `use_repr=True` (the default), the JSON file will rec...
model_addition_debugger_context
python
huggingface/transformers
src/transformers/model_debugging_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/model_debugging_utils.py
Apache-2.0
def get_cosine_with_min_lr_schedule_with_warmup( optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, num_cycles: float = 0.5, last_epoch: int = -1, min_lr: Optional[float] = None, min_lr_rate: Optional[float] = None, ): """ Create a schedule with a learning rate tha...
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 min_lr, after a warmup period during which it increases linearly between 0 and the initial lr set in the optimizer. Args: optimizer ([`~torch.optim.O...
get_cosine_with_min_lr_schedule_with_warmup
python
huggingface/transformers
src/transformers/optimization.py
https://github.com/huggingface/transformers/blob/master/src/transformers/optimization.py
Apache-2.0
def get_wsd_schedule( optimizer: Optimizer, num_warmup_steps: int, num_decay_steps: int, num_training_steps: Optional[int] = None, num_stable_steps: Optional[int] = None, warmup_type: str = "linear", decay_type: str = "cosine", min_lr_ratio: float = 0, num_cycles: float = 0.5, la...
Create a schedule with a learning rate that has three stages: 1. warmup: increase from min_lr_ratio times the initial learning rate to the initial learning rate following a warmup_type. 2. stable: constant learning rate. 3. decay: decrease from the initial learning rate to min_lr_ratio times the initia...
get_wsd_schedule
python
huggingface/transformers
src/transformers/optimization.py
https://github.com/huggingface/transformers/blob/master/src/transformers/optimization.py
Apache-2.0
def to_dict(self) -> dict[str, Any]: """ Serializes this instance to a Python dictionary. Returns: `Dict[str, Any]`: Dictionary of all the attributes that make up this processor instance. """ output = copy.deepcopy(self.__dict__) # Get the kwargs in `__init_...
Serializes this instance to a Python dictionary. Returns: `Dict[str, Any]`: Dictionary of all the attributes that make up this processor instance.
to_dict
python
huggingface/transformers
src/transformers/processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/processing_utils.py
Apache-2.0
def get_processor_dict( cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs ) -> tuple[dict[str, Any], dict[str, Any]]: """ From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a processor of type [`~processing_...
From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a processor of type [`~processing_utils.ProcessingMixin`] using `from_args_and_dict`. Parameters: pretrained_model_name_or_path (`str` or `os.PathLike`): The ...
get_processor_dict
python
huggingface/transformers
src/transformers/processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/processing_utils.py
Apache-2.0