text
stringlengths
1
1.02k
class_index
int64
0
10.8k
source
stringlengths
85
188
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_...
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Args: encoder_attention_mask (`torch.Tensor`): An attention mask.
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Returns: `torch.Tensor`: The inverted attention mask. """ if encoder_attention_mask.dim() == 3: encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: encoder_extended_attention_mask = encoder_attention_ma...
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
return encoder_extended_attention_mask @staticmethod def create_extended_attention_mask_for_decoder(input_shape, attention_mask, device=None): if device is not None: warnings.warn( "The `device` argument is deprecated and will be removed in v5 of Transformers.", FutureWarnin...
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if causal_mask.shape[1] < attention_mask.shape[1]: prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1] causal_mask = torch.cat( [ torch.ones((batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype), caus...
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Arguments: attention_mask (`torch.Tensor`): Mask with ones indicating tokens to attend to, zeros for tokens to ignore. input_shape (`Tuple[int]`): The shape of the input to the model. Returns: `torch.Tensor` The extended attention mask, with a...
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if not (attention_mask.dim() == 2 and self.config.is_decoder): # show warning only if it won't be shown in `create_extended_attention_mask_for_decoder` if device is not None: warnings.warn( "The `device` argument is deprecated and will be removed in v5 of Tran...
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if self.config.is_decoder: extended_attention_mask = ModuleUtilsMixin.create_extended_attention_mask_for_decoder( input_shape, attention_mask, device ) else: extended_attention_mask = attention_mask[:, None, None, :] else: ...
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for # masked positions, this operation will create a tensor which is 0.0 for # positions we want to attend and the dtype's smallest value for masked positions. # Since we are adding it to the raw scores before the softmax, thi...
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
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`): The number of hidden layers in the model....
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
def _convert_head_mask_to_5d(self, head_mask, num_hidden_layers): """-> [num_hidden_layers x batch x num_heads x seq_length x seq_length]""" if head_mask.dim() == 1: head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1) head_mask = head_mask.expand(num_hidde...
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Args: only_trainable (`bool`, *optional*, defaults to `False`): Whether or not to return only the number of trainable parameters exclude_embeddings (`bool`, *optional*, defaults to `False`): Whether or not to return only the number of non-embeddings parameters ...
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if is_loaded_in_4bit: if is_bitsandbytes_available(): import bitsandbytes as bnb else: raise ValueError( "bitsandbytes is not installed but it seems that the model has been loaded in 4bit precision, something went wrong" " m...
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
for param in total_parameters: if param.requires_grad or not only_trainable: # For 4bit models, we need to multiply the number of parameters by 2 as half of the parameters are # used for the 4bit quantization (uint8 tensors are stored) if is_loaded_in_4bit and...
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
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. """ ...
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
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...
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
exclude_embeddings (`bool`, *optional*, defaults to `True`): Whether or not to count embedding and softmax operations. Returns: `int`: The number of floating-point operations. """ return 6 * self.estimate_tokens(input_dict) * self.num_parameters(exclude_embeddings=e...
229
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
class PreTrainedModel(nn.Module, ModuleUtilsMixin, GenerationMixin, PushToHubMixin, PeftAdapterMixin): r""" Base class for all models. [`PreTrainedModel`] takes care of storing the configuration of the models and handles methods for loading, downloading and saving models as well as a few methods common...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
- **model** ([`PreTrainedModel`]) -- An instance of the model on which to load the TensorFlow checkpoint. - **config** ([`PreTrainedConfig`]) -- An instance of the configuration associated to the model. - **path** (`str`) -- A path to the TensorFlow checkpoint. - **base_model_prefix** (...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
_auto_class = None _no_split_modules = None _skip_keys_device_placement = None _keep_in_fp32_modules = None # a list of `re` patterns of `state_dict` keys that should be removed from the list of missing # keys we find (keys inside the model but not in the checkpoint) and avoid unnecessary warnings....
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
is_parallelizable = False supports_gradient_checkpointing = False _is_stateful = False # Flash Attention 2 support _supports_flash_attn_2 = False # SDPA support _supports_sdpa = False # Flex Attention support _supports_flex_attn = False # Has support for a `Cache` instance as `pa...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
@property def dummy_inputs(self) -> Dict[str, torch.Tensor]: """ `Dict[str, torch.Tensor]`: Dummy inputs to do a forward pass in the network. """ return {"input_ids": torch.tensor(DUMMY_INPUTS)} @property def framework(self) -> str: """ :str: Identifies that ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
def __init__(self, config: PretrainedConfig, *inputs, **kwargs): super().__init__() if not isinstance(config, PretrainedConfig): raise ValueError( f"Parameter config in `{self.__class__.__name__}(config)` should be an instance of class " "`PretrainedConfig`. T...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# for initialization of the loss loss_type = self.__class__.__name__ if loss_type not in LOSS_MAPPING: loss_groups = f"({'|'.join(LOSS_MAPPING)})" loss_type = re.findall(loss_groups, self.__class__.__name__) if len(loss_type) > 0: loss_type = loss_type...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
def post_init(self): """ A method executed at the end of each Transformer model initialization, to execute code that needs the model's modules properly initialized (such as weight initialization). """ self.init_weights() self._backward_compatibility_gradient_checkpointing...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
def _backward_compatibility_gradient_checkpointing(self): if self.supports_gradient_checkpointing and getattr(self.config, "gradient_checkpointing", False): self.gradient_checkpointing_enable() # Remove the attribute now that is has been consumed, so it's no saved in the config. ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Push the model to your namespace with the name "my-custom-bert". model.push_to_hub("my-custom-bert") ``` """ if isinstance(tags, str): tags = [tags] if self.model_tags is None: self.model_tags = [] for tag in tags: if tag not in sel...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Args: torch_dtype (`torch.dtype`, *optional*): Override the default `torch.dtype` and load the model under this dtype. """ # when we init a model from within another model (e.g. VLMs) and dispatch on FA2 # a warning is raised that dtype should be fp16. Since we never ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if config._attn_implementation_internal is not None: # In this case, the config has been created with the attn_implementation set by the user, which we # should respect. attn_implementation = config._attn_implementation_internal else: attn_implementation = None ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
logger.info("Detected DeepSpeed ZeRO-3: activating zero.init() for this model") # this immediately partitions the model across all gpus, to avoid the overhead in time # and memory copying it on CPU or each GPU first init_contexts = [deepspeed.zero.Init(config_dict_or_path=deepspeed_c...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
@classmethod def _autoset_attn_implementation( cls, config, use_flash_attention_2: bool = False, torch_dtype: Optional[torch.dtype] = None, device_map: Optional[Union[str, Dict[str, int]]] = None, check_device_map: bool = True, ): """ Automatically...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Here we use config._attn_implementation_internal to check whether the attention implementation was explicitely set by the user. # The property `PretrainedConfig._attn_implementation` is never `None`, for backward compatibility (always fall back on "eager"). # The `hasattr` here is used as some Transfo...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
)
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if not isinstance(config._attn_implementation, dict) and config._attn_implementation not in [ "eager" ] + list(ALL_ATTENTION_FUNCTIONS.keys()): message = f'Specified `attn_implementation="{config._attn_implementation}"` is not supported. The only possible arguments are `attn_...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# If a config is passed with a preset attn_implementation, we skip the automatic dispatch and use the user-provided config, with hard checks that the requested attention implementation is available. requested_attn_implementation = config._attn_implementation_internal
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Composite models consisting of several PretrainedModels have to specify attention impl as a dict # where keys are sub-config names. But most people will specify one `str` which means that should dispatch it # for all sub-models. # Below we check if a config is composite and manually prepare a ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
sub_config._attn_implementation_internal = curr_attn_implementation
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if use_flash_attention_2: logger.warning_once( 'The model was loaded with use_flash_attention_2=True, which is deprecated and may be removed in a future release. Please use `attn_implementation="flash_attention_2"` instead.' ) config._attn_implementation = "flash_atte...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if config._attn_implementation == "flash_attention_2": cls._check_and_enable_flash_attn_2( config, torch_dtype=torch_dtype, device_map=device_map, hard_check_only=False, check_device_map=check_device_map, ) e...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if ( torch.version.hip is not None and config._attn_implementation == "sdpa" and torch.cuda.device_count() > 1 ): logger.warning_once( "Using the `SDPA` attention implementation on multi-gpu setup with ROCM may lead to perfo...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
@classmethod 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...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
logger.info(f"Instantiating {cls.__name__} model under default dtype {dtype}.") dtype_orig = torch.get_default_dtype() torch.set_default_dtype(dtype) return dtype_orig @property def base_model(self) -> nn.Module: """ `torch.nn.Module`: The main body of the model. ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Returns: `bool`: Whether this model can generate sequences with `.generate()`. """ # Directly inherits `GenerationMixin` -> can generate if "GenerationMixin" in str(cls.__bases__): return True # Model class overwrites `generate` (e.g. time series models) -> can ge...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
f"{cls.__name__} has generative capabilities, as `prepare_inputs_for_generation` is explicitly " "overwritten. However, it doesn't directly inherit from `GenerationMixin`. From 👉v4.50👈 onwards, " "`PreTrainedModel` will NOT inherit from `GenerationMixin`, and this model will lose the a...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
"to update it." ) return True # Otherwise, can't generate return False
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
@classmethod 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: """ ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
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. """ if not cls._supports_flash_attn_2: raise ValueError( f"{cls.__name__} do...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if importlib.util.find_spec("flash_attn") is None: raise ImportError(f"{preface} the package flash_attn seems to be not installed. {install_message}")
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
flash_attention_version = version.parse(importlib.metadata.version("flash_attn")) if torch.version.cuda: if flash_attention_version < version.parse("2.1.0"): raise ImportError( f"{preface} you need flash_attn package version to be greater or equal ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
f"{preface} you need flash_attn package version to be greater or equal than 2.0.4. Make sure to have that version installed - detected version {flash_attention_version}. {install_message}" ) else: raise ImportError(f"{preface} Flash Attention 2 is not available. {...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
_is_bettertransformer = getattr(cls, "use_bettertransformer", False) if _is_bettertransformer: raise ValueError( "Flash Attention 2 and BetterTransformer API are not compatible. Please make sure to disable BetterTransformers by doing model.reverse_bettertransformer()" )
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if torch_dtype is None: logger.warning_once( "You are attempting to use Flash Attention 2.0 without specifying a torch dtype. This might lead to unexpected behaviour" ) elif torch_dtype is not None and torch_dtype not in [torch.float16, torch.bfloat16]: logger...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# The check `torch.empty(0).device.type != "cuda"` is needed as the model may be initialized after `torch.set_default_device` has been called, # or the model may be initialized under the context manager `with torch.device("cuda"):`. if check_device_map and device_map is None and torch.empty(0).device.ty...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
"or initialising the model on CPU and then moving it to GPU." ) elif ( check_device_map and device_map is not None and isinstance(device_map, dict) and ("cpu" in device_map.values() or "disk" in device_map.values()) ): raise Val...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
@classmethod def _check_and_enable_sdpa(cls, config, hard_check_only: bool = False) -> PretrainedConfig: """ Checks the availability of SDPA for a given model.
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
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. """ if hard_check_only: if not cls._supports_sdpa: raise ValueError( ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
"PyTorch SDPA requirements in Transformers are not met. Please install torch>=2.1.1." )
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if not is_torch_sdpa_available() or not cls._supports_sdpa: return config _is_bettertransformer = getattr(cls, "use_bettertransformer", False) if _is_bettertransformer: return config if not hard_check_only: config._attn_implementation = "sdpa" return...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
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. """ if hard_check_only: if not cls._supports_flex_attn: raise ValueError( ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
"PyTorch Flex Attention requirements in Transformers are not met. Please install torch>=2.5.0." )
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if not is_torch_flex_attn_available() or not cls._supports_flex_attn: return config if not hard_check_only: config._attn_implementation = "flex_attention" return config def enable_input_require_grads(self): """ Enables the gradients for the input embeddings...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
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: return base_model.get_input_embeddings() else: raise NotImplementedError def set_inpu...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
def _init_weights(self, module): """ Initialize the weights. This method should be overridden by derived class and is the only initialization method that will be called when loading a checkpoint using `from_pretrained`. Any attempt to initialize outside of this function will be u...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
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.get_text_config(decoder=True), "tie_word_embeddings", True): output_embeddings = self.get_output_embeddings() if output_...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if getattr(self.config, "is_encoder_decoder", False) and getattr(self.config, "tie_encoder_decoder", False): if hasattr(self, self.base_model_prefix): self = getattr(self, self.base_model_prefix) tied_weights = self._tie_encoder_decoder_weights( self.encoder, self...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
@staticmethod def _tie_encoder_decoder_weights( encoder: nn.Module, decoder: nn.Module, base_model_prefix: str, base_encoder_name: str ): uninitialized_encoder_weights: List[str] = [] tied_weights: List[str] = [] if decoder.__class__ != encoder.__class__: logger.info(...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
def tie_encoder_to_decoder_recursively( decoder_pointer: nn.Module, encoder_pointer: nn.Module, module_name: str, base_encoder_name: str, uninitialized_encoder_weights: List[str], depth=0, total_decoder_name="", total_encode...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
encoder_pointer.bias = decoder_pointer.bias return
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
encoder_modules = encoder_pointer._modules decoder_modules = decoder_pointer._modules if len(decoder_modules) > 0: assert ( len(encoder_modules) > 0 ), f"Encoder module {encoder_pointer} does not match decoder module {decoder_pointer}"
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
all_encoder_weights = {module_name + "/" + sub_name for sub_name in encoder_modules.keys()} encoder_layer_pos = 0 for name, module in decoder_modules.items(): if name.isdigit(): encoder_name = str(int(name) + encoder_layer_pos) ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
elif name not in encoder_modules: continue elif depth > 500: raise ValueError( "Max depth of recursive function `tie_encoder_to_decoder` reached. It seems that there is" " a circular dependency be...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
) all_encoder_weights.remove(module_name + "/" + encoder_name)
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
uninitialized_encoder_weights += list(all_encoder_weights) # tie weights recursively tie_encoder_to_decoder_recursively( decoder, encoder, base_model_prefix, base_encoder_name, uninitialized_encoder_weights ) if len(uninitialized_encoder_weights) > 0: logger.war...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if getattr(output_embeddings, "bias", None) is not None: output_embeddings.bias.data = nn.functional.pad( output_embeddings.bias.data, ( 0, output_embeddings.weight.shape[0] - output_embeddings.bias.shape[0], ), ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Returns: `List[str]`: List of modules that should not be split """ _no_split_modules = set() modules_to_check = [self] while len(modules_to_check) > 0: module = modules_to_check.pop(-1) # if the module does not appear in _no_split_modules, we also chec...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
return list(_no_split_modules)
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
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`. ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Arguments: new_num_tokens (`int`, *optional*): The new number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. If not provided or `None`, just returns a po...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128. For more details about this, or help on choosing the correct value for resizing, refer to t...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Setting `mean_resizing` to `True` is useful when increasing the size of the embeddings of causal language models, where the generated tokens' probabilities won't be affected by the added embeddings because initializing the new embeddings with the old embeddings' mean will reduce the kl-d...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Since we are basically resuing the same old embeddings with new weight values, gathering is required is_quantized = hasattr(self, "hf_quantizer") and self.hf_quantizer is not None if is_deepspeed_zero3_enabled() and not is_quantized: import deepspeed with deepspeed.zero.Gather...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
def _resize_token_embeddings(self, new_num_tokens, pad_to_multiple_of=None, mean_resizing=True): old_embeddings = self.get_input_embeddings() new_embeddings = self._get_resized_embeddings( old_embeddings, new_num_tokens, pad_to_multiple_of, mean_resizing ) if hasattr(old_embe...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
with deepspeed.zero.GatheredParameters(new_embeddings.weight, modifier_rank=None): new_num_tokens = new_embeddings.weight.shape[0] else: new_num_tokens = new_embeddings.weight.shape[0]
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# if word embeddings are not tied, make sure that lm head is resized as well if ( self.get_output_embeddings() is not None and not self.config.get_text_config(decoder=True).tie_word_embeddings ): old_lm_head = self.get_output_embeddings() if isinstance(old...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
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...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. If not provided or `None`, just returns a pointer to the input tokens `torch.nn.Embedding` module of the model without doing anything. pad_to_multiple_of (`i...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128. For more details about this, or help on choosing the correct value for resizing, refer to t...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Setting `mean_resizing` to `True` is useful when increasing the size of the embeddings of causal language models, where the generated tokens' probabilities will not be affected by the added embeddings because initializing the new embeddings with the old embeddings' mean will reduce the k...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if pad_to_multiple_of is not None: if not isinstance(pad_to_multiple_of, int): raise ValueError( f"Asking to pad the embedding matrix to a multiple of `{pad_to_multiple_of}`, which is not and integer. Please make sure to pass an integer" ) if n...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
" https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#requirements-tc" )
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if new_num_tokens is None: return old_embeddings is_quantized = hasattr(self, "hf_quantizer") and self.hf_quantizer is not None if is_deepspeed_zero3_enabled() and not is_quantized: import deepspeed with deepspeed.zero.GatheredParameters(old_embeddings.weight, modif...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Build new embeddings # When using DeepSpeed ZeRO-3, we shouldn't create new embeddings with DeepSpeed init # because the shape of the new embedding layer is used across various modeling files # as well as to update config vocab size. Shape will be 0 when using DeepSpeed init leading #...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
elif new_num_tokens > old_num_tokens and mean_resizing: # initialize new embeddings (in particular added tokens). The new embeddings will be initialized # from a multivariate normal distribution that has old embeddings' mean and covariance. # as described in this article: https://nl...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
with deepspeed.zero.GatheredParameters([old_embeddings.weight], modifier_rank=None): self._init_added_embeddings_weights_with_mean( old_embeddings, new_embeddings, old_embedding_dim, old_num_tokens, added_num_tokens ) else: self...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
params = [old_embeddings.weight, new_embeddings.weight] with deepspeed.zero.GatheredParameters(params, modifier_rank=0): new_embeddings.weight.data[:n, :] = old_embeddings.weight.data[:n, :] else: new_embeddings.weight.data[:n, :] = old_embeddings.weight.data[:n, :] ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
params = [old_embeddings.weight, new_embeddings.weight] with deepspeed.zero.GatheredParameters(params, modifier_rank=0): old_embeddings.weight = new_embeddings.weight old_embeddings.num_embeddings = new_embeddings.weight.data.shape[0] # If the new number of t...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
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...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. If not provided or `None`, just returns a pointer to the input tokens `torch.nn.Linear` module of the model without doing anything. transposed (`bool`, *optional*, defau...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Setting `mean_resizing` to `True` is useful when increasing the size of the embeddings of causal language models, where the generated tokens' probabilities will not be affected by the added embeddings because initializing the new embeddings with the old embeddings' mean will reduce the k...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
with deepspeed.zero.GatheredParameters(old_lm_head.weight, modifier_rank=None): old_num_tokens, old_lm_head_dim = ( old_lm_head.weight.size() if not transposed else old_lm_head.weight.t().size() ) else: old_num_tokens, old_lm_head_dim = ( ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py