text
stringlengths
1
1.02k
class_index
int64
0
10.8k
source
stringlengths
85
188
# Build new lm head new_lm_head_shape = (old_lm_head_dim, new_num_tokens) if not transposed else (new_num_tokens, old_lm_head_dim) has_new_lm_head_bias = old_lm_head.bias is not None # When using DeepSpeed ZeRO-3, we shouldn't create new embeddings with DeepSpeed init # because the shap...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
elif new_num_tokens > old_num_tokens and mean_resizing: # initialize new lm_head weights (in particular added tokens). The new lm_head weights # will be initialized from a multivariate normal distribution that has old embeddings' mean and covariance. # as described in this article: h...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
params = [old_lm_head.weight] if has_new_lm_head_bias: params += [old_lm_head.bias] with deepspeed.zero.GatheredParameters(params, modifier_rank=None): self._init_added_lm_head_weights_with_mean( old_lm_head, new_lm_head, ol...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if is_deepspeed_zero3_enabled() and not is_quantized: import deepspeed params = [old_lm_head.weight, old_lm_head.bias, new_lm_head.weight, new_lm_head.bias] with deepspeed.zero.GatheredParameters(params, modifier_rank=0): self._copy_lm_head_original_to_resized( ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
def _init_added_embeddings_weights_with_mean( self, old_embeddings, new_embeddings, old_embedding_dim, old_num_tokens, added_num_tokens ): old_embeddings_weight = old_embeddings.weight.data.to(torch.float32) mean_embeddings = torch.mean(old_embeddings_weight, axis=0) old_centered_emb...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Check if the covariance is positive definite. eigenvalues = torch.linalg.eigvals(covariance) is_covariance_psd = bool( (covariance == covariance.T).all() and not torch.is_complex(eigenvalues) and (eigenvalues > 0).all() ) if is_covariance_psd: # If covariances i...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
mean_embeddings[None, :].repeat(added_num_tokens, 1).to(old_embeddings.weight.dtype) )
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
def _init_added_lm_head_weights_with_mean( self, old_lm_head, new_lm_head, old_lm_head_dim, old_num_tokens, added_num_tokens, transposed=False, ): if transposed: # Transpose to the desired shape for the function. new_lm_head.wei...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
def _init_added_lm_head_bias_with_mean(self, old_lm_head, new_lm_head, added_num_tokens): bias_mean = torch.mean(old_lm_head.bias.data, axis=0, dtype=torch.float32) bias_std = torch.std(old_lm_head.bias.data, axis=0).to(torch.float32) new_lm_head.bias.data[-1 * added_num_tokens :].normal_(mean=b...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
def resize_position_embeddings(self, new_num_position_embeddings: int): raise NotImplementedError( f"`resize_position_embeddings` is not implemented for {self.__class__}`. To implement it, you should " f"overwrite this method in the class {self.__class__} in `modeling_{self.__class__.__m...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
def init_weights(self): """ If needed prunes and maybe initializes weights. If using a custom `PreTrainedModel`, you need to implement any initialization logic in `_init_weights`. """ # Prune heads if needed if self.config.pruned_heads: self.prune_heads(self.c...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Arguments: heads_to_prune (`Dict[int, List[int]]`): Dictionary with keys being selected layer indices (`int`) and associated values being the list of heads to prune in said layer (list of `int`). For instance {1: [0, 2], 2: [2, 3]} will prune heads 0 and 2 on ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Note that in other frameworks this feature can be referred to as "activation checkpointing" or "checkpoint activations". We pass the `__call__` method of the modules instead of `forward` because `__call__` attaches all the hooks of the module. https://discuss.pytorch.org/t/any-different-between...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# For old GC format (transformers < 4.35.0) for models that live on the Hub # we will fall back to the overwritten `_set_gradient_checkpointing` method _is_using_old_format = "value" in inspect.signature(self._set_gradient_checkpointing).parameters if not _is_using_old_format: self....
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if getattr(self, "_hf_peft_config_loaded", False): # When using PEFT + gradient checkpointing + Trainer we need to make sure the input has requires_grad=True # we do it also on PEFT: https://github.com/huggingface/peft/blob/85013987aa82aa1af3da1236b6902556ce3e483e/src/peft/peft_model.py#L334 ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Apply it on the top-level module in case the top-level modules supports it # for example, LongT5Stack inherits from `PreTrainedModel`. if hasattr(self, "gradient_checkpointing"): self._gradient_checkpointing_func = gradient_checkpointing_func self.gradient_checkpointing = enabl...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
def gradient_checkpointing_disable(self): """ Deactivates gradient checkpointing for the current model.
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Note that in other frameworks this feature can be referred to as "activation checkpointing" or "checkpoint activations". """ if self.supports_gradient_checkpointing: # For old GC format (transformers < 4.35.0) for models that live on the Hub # we will fall back to the ove...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
"Please update to the new format on your modeling file. To use the new format, you need to completely remove the definition of the method `_set_gradient_checkpointing` in your model." ) self.apply(partial(self._set_gradient_checkpointing, value=False))
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if getattr(self, "_hf_peft_config_loaded", False): self.disable_input_require_grads() @property def is_gradient_checkpointing(self) -> bool: """ Whether gradient checkpointing is activated for this model or not. Note that in other frameworks this feature can be referred to ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
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...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Arguments: save_directory (`str` or `os.PathLike`): Directory to which to save. Will be created if it doesn't exist. is_main_process (`bool`, *optional*, defaults to `True`): Whether the process calling this is the main process or not. Useful when in distributed t...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
The function to use to save the state dictionary. Useful on distributed training like TPUs when one need to replace `torch.save` by another method. push_to_hub (`bool`, *optional*, defaults to `False`): Whether or not to push your model to the Hugging Face model hub after sav...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
<Tip warning={true}> If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard which will be bigger than `max_shard_size`. </Tip>
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
safe_serialization (`bool`, *optional*, defaults to `True`): Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`). variant (`str`, *optional*): If specified, weights are saved in the format pytorch_model.<variant>.bin. ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
kwargs (`Dict[str, Any]`, *optional*): Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method. """ use_auth_token = kwargs.pop("use_auth_token", None) ignore_metadata_errors = kwargs.pop("ignore_metadata_errors", False)
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if use_auth_token is not None: warnings.warn( "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.", FutureWarning, ) if token is not None: raise ValueError( ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if hf_quantizer is not None and not _hf_peft_config_loaded and not quantization_serializable: raise ValueError( f"The model is quantized with {hf_quantizer.quantization_config.quant_method} and is not serializable - check out the warnings from" " the logger on the traceback t...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
os.makedirs(save_directory, exist_ok=True) if push_to_hub: commit_message = kwargs.pop("commit_message", None) repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1]) repo_id = self._create_repo(repo_id, **kwargs) files_timestamps = self._get_files...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Unset attn implementation so it can be set to another one when loading back model_to_save.config._attn_implementation_autoset = False # If we have a custom model, we copy the file defining it in the folder and set the attributes so it can be # loaded from the Hub. if self._auto_class ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Save the config if is_main_process: if not _hf_peft_config_loaded: # If the model config has set attributes that should be in the generation config, move them there. misplaced_generation_parameters = model_to_save.config._get_non_default_generation_parameters() ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
setattr(model_to_save.config, param_name, None)
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
model_to_save.config.save_pretrained(save_directory) if self.can_generate(): model_to_save.generation_config.save_pretrained(save_directory) if _hf_peft_config_loaded: logger.info( "Detected adapters on the model, saving the model in the PEFT ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if len(active_adapter) > 1: raise ValueError( "Multiple active adapters detected, saving multiple active adapters is not supported yet. You can save adapters separately one by one " "by iteratively calling `model.set_adapter(adapter_name)` then `model....
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Save the model if state_dict is None: # if any model parameters are offloaded, make module map if ( hasattr(self, "hf_device_map") and len(set(self.hf_device_map.values())) > 1 and ("cpu" in self.hf_device_map.values() or "disk" in self.h...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Translate state_dict from smp to hf if saving with smp >= 1.10 if IS_SAGEMAKER_MP_POST_1_10: for smp_to_hf, _ in smp.state.module_manager.translate_functions: state_dict = smp_to_hf(state_dict) # Handle the case where some state_dict keys shouldn't be saved if self...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if safe_serialization: # Safetensors does not allow tensor aliasing. # We're going to remove aliases before saving ptrs = collections.defaultdict(list) for name, tensor in state_dict.items(): # Sometimes in the state_dict we have non-tensor objects. ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# These are all the pointers of shared tensors if hasattr(self, "hf_device_map"): # if the model has offloaded parameters, we must check using find_tied_parameters() tied_params = find_tied_parameters(self) if tied_params: tied_names = tied...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Recursively descend to find tied weight keys _tied_weights_keys = _get_tied_weight_keys(self) error_names = [] to_delete_names = set() for names in shared_ptrs.values(): # Removing the keys which are declared as known duplicates on # load...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
shared_names, disjoint_names = _find_disjoint(shared_ptrs.values(), state_dict) # Those are actually tensor sharing but disjoint from each other, we can safely clone them # Reloaded won't have the same property, but it shouldn't matter in any meaningful way. for name in disjoint_name...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# When not all duplicates have been cleaned, still remove those keys, but put a clear warning. # If the link between tensors was done at runtime then `from_pretrained` will not get # the key back leading to random tensor. A proper warning will be shown # during reload (if applicable)...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if len(error_names) > 0: raise RuntimeError( f"The weights trying to be saved contained shared tensors {error_names} that are mismatching the transformers base configuration. Try saving using `safe_serialization=False` or remove this tensor sharing.", ) # Sha...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
filename_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(".safetensors", "{suffix}.safetensors") state_dict_split = split_torch_state_dict_into_shards( state_dict, filename_pattern=filename_pattern, max_shard_size=max_shard_size ) # Save index if sharded index ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# make sure that file to be deleted matches format of sharded file, e.g. pytorch_model-00001-of-00005 filename_no_suffix = filename.replace(".bin", "").replace(".safetensors", "") reg = re.compile(r"(.*?)-\d{5}-of-\d{5}")
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if ( filename.startswith(weights_no_suffix) and os.path.isfile(full_filename) and filename not in state_dict_split.filename_to_tensors.keys() and is_main_process and reg.fullmatch(filename_no_suffix) is not None ): ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# remake shard with onloaded parameters if necessary if module_map: if accelerate_version < version.parse("0.31"): raise ImportError( f"You need accelerate version to be greater or equal than 0.31 to save models with offloaded parameters. Detected ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if safe_serialization: # At some point we will need to deal better with save_function (used for TPU and other distributed # joyfulness), but for now this enough. safe_save_file(shard, os.path.join(save_directory, shard_file), metadata={"format": "pt"}) else: ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if index is None: path_to_weights = os.path.join(save_directory, weights_name) logger.info(f"Model weights saved in {path_to_weights}") else: save_index_file = SAFE_WEIGHTS_INDEX_NAME if safe_serialization else WEIGHTS_INDEX_NAME save_index_file = os.path.join(sav...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if push_to_hub: # Eventually create an empty model card model_card = create_and_tag_model_card( repo_id, self.model_tags, token=token, ignore_metadata_errors=ignore_metadata_errors ) # Update model card if needed: model_card.save(os.path.join(...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if tags: kwargs["tags"] = tags return super().push_to_hub(*args, **kwargs) def get_memory_footprint(self, return_buffers=True): r""" Get the memory footprint of a model. This will return the memory footprint of the current model in bytes. Useful to benchmark the memory f...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Arguments: return_buffers (`bool`, *optional*, defaults to `True`): Whether to return the size of the buffer tensors in the computation of the memory footprint. Buffers are tensors that do not require gradients and not registered as parameters. E.g. mean and std in batch ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
@wraps(torch.nn.Module.cuda) def cuda(self, *args, **kwargs): if getattr(self, "quantization_method", None) == QuantizationMethod.HQQ: raise ValueError("`.cuda` is not supported for HQQ-quantized models.") # Checks if the model has been loaded in 4-bit or 8-bit with BNB if getatt...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
f"The current device is `{self.device}`. If you intended to move the model, please install bitsandbytes >= 0.43.2." ) else: return super().cuda(*args, **kwargs)
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
@wraps(torch.nn.Module.to) def to(self, *args, **kwargs): # For BNB/GPTQ models, we prevent users from casting the model to another dtype to restrict unwanted behaviours. # the correct API should be to load the model with the desired dtype directly through `from_pretrained`. dtype_present_in...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if getattr(self, "quantization_method", None) == QuantizationMethod.HQQ: raise ValueError("`.to` is not supported for HQQ-quantized models.") # Checks if the model has been loaded in 4-bit or 8-bit with BNB if getattr(self, "quantization_method", None) == QuantizationMethod.BITS_AND_BYTES: ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if getattr(self, "is_loaded_in_8bit", False): raise ValueError( "`.to` is not supported for `8-bit` bitsandbytes models. Please use the model as it is, since the" " model has already been set to the correct devices and casted to the correct `dtype`." ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
"You cannot cast a GPTQ model in a new `dtype`. Make sure to load the model using `from_pretrained` using the desired" " `dtype` by passing the correct `torch_dtype` argument." ) return super().to(*args, **kwargs)
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
def half(self, *args): # Checks if the model is quantized if getattr(self, "is_quantized", False): raise ValueError( "`.half()` is not supported for quantized model. Please use the model as it is, since the" " model has already been casted to the correct `dtyp...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
@classmethod def from_pretrained( cls: Type[SpecificPreTrainedModelType], pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None, cache_dir: Optional[Union[str, os.PathLike]] = None, ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
The warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning task. The warning *Weights from XXX not used in YYY* means that the layer XX...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. - A path to a *directory* containing model weights saved using [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`. - A path or url to a *tensorflo...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
- `None` if you are both providing the configuration and state dictionary (resp. with keyword arguments `config` and `state_dict`). model_args (sequence of positional arguments, *optional*): All remaining positional arguments will be passed to the underlying model's `__...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
- an instance of a class derived from [`PretrainedConfig`], - a string or path valid as input to [`~PretrainedConfig.from_pretrained`]. Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using [`~PreTrainedModel.save_pretrained`] and [`~PreTrainedModel.from_pretrained`] is not a simpler option. cache_dir (`U...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
ignore_mismatched_sizes (`bool`, *optional*, defaults to `False`): Whether or not to raise an error if some of the weights from the checkpoint do not have the same size as the weights of the model (if for instance, you are instantiating a model with 10 labels from a check...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
output_loading_info(`bool`, *optional*, defaults to `False`): Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. local_files_only(`bool`, *optional*, defaults to `False`): Whether or not to only look at local files (i.e., d...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
<Tip> To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`. </Tip> mirror (`str`, *optional*): Mirror source to accelerate downloads in China. If you are from China and have an accessibility problem, you ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
</Tip> attn_implementation (`str`, *optional*): The attention implementation to use in the model (if relevant). Can be any of `"eager"` (manual implementation of the attention), `"sdpa"` (using [`F.scaled_dot_product_attention`](https://pytorch.org/docs/master/generated/torch.nn.functional.s...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
low_cpu_mem_usage(`bool`, *optional*): Tries not to use more than 1x model size in CPU memory (including peak memory) while loading the model. Generally should be combined with a `device_map` (such as `"auto"`) for best results. This is an experimental feature and a subje...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
1. `torch.float16` or `torch.bfloat16` or `torch.float`: load in a specified `dtype`, ignoring the model's `config.torch_dtype` if one exists. If not specified - the model will get loaded in `torch.float` (fp32). 2. `"auto"` - A `torch_dtype` entry in the `config.jso...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
For some models the `dtype` they were trained in is unknown - you may try to check the model's paper or reach out to the authors and ask them to add this information to the model's card and to insert the `torch_dtype` entry in `config.json` on the hub. </Tip> ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For more information about each option see [designing a device map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map). max_memory (`Dict`, ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
`True` when there is some disk offload. offload_buffers (`bool`, *optional*): Whether or not to offload the buffers with the model parameters. quantization_config (`Union[QuantizationConfigMixin,Dict]`, *optional*): A dictionary of configuration parameters or a Qu...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
If specified load weights from `variant` filename, *e.g.* pytorch_model.<variant>.bin. `variant` is ignored when using `from_tf` or `from_flax`. use_safetensors (`bool`, *optional*, defaults to `None`): Whether or not to use `safetensors` checkpoints. Defaults to `None`. If n...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
weights_only (`bool`, *optional*, defaults to `True`): Indicates whether unpickler should be restricted to loading only tensors, primitive types, dictionaries and any types added via torch.serialization.add_safe_globals(). When set to False, we can load wrapper tensor sub...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
- If a configuration is provided with `config`, `**kwargs` will be directly passed to the underlying model's `__init__` method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided, `kwargs` will ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
Examples: ```python >>> from transformers import BertConfig, BertModel
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
>>> # Download model and configuration from huggingface.co and cache. >>> model = BertModel.from_pretrained("google-bert/bert-base-uncased") >>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable). >>> model = BertModel.from_pretrained("./test/sa...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
>>> model = BertModel.from_pretrained("google-bert/bert-base-uncased", from_flax=True) ```
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
* `low_cpu_mem_usage` algorithm: This is an experimental function that loads the model using ~1x model size CPU memory Here is how it works: 1. save which state_dict keys we have 2. drop state_dict before the model is created, since the latter takes 1x model size CPU memory 3....
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
""" state_dict = kwargs.pop("state_dict", None) from_tf = kwargs.pop("from_tf", False) from_flax = kwargs.pop("from_flax", False) resume_download = kwargs.pop("resume_download", None) proxies = kwargs.pop("proxies", None) output_loading_info = kwargs.pop("output_loading_i...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
offload_state_dict = kwargs.pop("offload_state_dict", False) offload_buffers = kwargs.pop("offload_buffers", False) load_in_8bit = kwargs.pop("load_in_8bit", False) load_in_4bit = kwargs.pop("load_in_4bit", False) quantization_config = kwargs.pop("quantization_config", None) subf...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
gguf_file = kwargs.pop("gguf_file", None) # Cache path to the GGUF file gguf_path = None tp_plan = kwargs.pop("tp_plan", None) if tp_plan is not None and tp_plan != "auto": # TODO: we can relax this check when we support taking tp_plan from a json file, for example. ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if token is not None and adapter_kwargs is not None and "token" not in adapter_kwargs: adapter_kwargs["token"] = token if use_safetensors is None and not is_safetensors_available(): use_safetensors = False if trust_remote_code is True: logger.warning( ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if commit_hash is None: if not isinstance(config, PretrainedConfig): # We make a call to the config file first (which may be absent) to get the commit hash as soon as possible resolved_config_file = cached_file( pretrained_model_name_or_path, ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
commit_hash = getattr(config, "_commit_hash", None)
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if is_peft_available(): _adapter_model_path = adapter_kwargs.pop("_adapter_model_path", None) if _adapter_model_path is None: _adapter_model_path = find_adapter_config_file( pretrained_model_name_or_path, cache_dir=cache_dir, ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# change device_map into a map if we passed an int, a str or a torch.device if isinstance(device_map, torch.device): device_map = {"": device_map} elif isinstance(device_map, str) and device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: try: dev...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if device_map is not None: if low_cpu_mem_usage is None: low_cpu_mem_usage = True elif not low_cpu_mem_usage: raise ValueError("Passing along a `device_map` requires `low_cpu_mem_usage=True`") if low_cpu_mem_usage: if is_deepspeed_zero3_enable...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# handling bnb config from kwargs, remove after `load_in_{4/8}bit` deprecation. if load_in_4bit or load_in_8bit: if quantization_config is not None: raise ValueError( "You can't pass `load_in_4bit`or `load_in_8bit` as a kwarg when passing " "`q...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# preparing BitsAndBytesConfig from kwargs config_dict = {k: v for k, v in kwargs.items() if k in inspect.signature(BitsAndBytesConfig).parameters} config_dict = {**config_dict, "load_in_4bit": load_in_4bit, "load_in_8bit": load_in_8bit} quantization_config, kwargs = BitsAndBytesConf...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if is_offline_mode() and not local_files_only: logger.info("Offline mode: forcing local_files_only=True") local_files_only = True
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Load config if we don't provide a configuration if not isinstance(config, PretrainedConfig): config_path = config if config is not None else pretrained_model_name_or_path config, model_kwargs = cls.config_class.from_pretrained( config_path, cache_dir=cac...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Please see: https://github.com/huggingface/transformers/issues/28038
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Overwrite `config._attn_implementation` by the one from the kwargs --> in auto-factory # we pop attn_implementation from the kwargs but this handles the case where users # passes manually the config to `from_pretrained`. config = copy.deepcopy(config) kwarg_attn_imp = ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
hf_quantizer = AutoHfQuantizer.from_config( config.quantization_config, pre_quantized=pre_quantized, ) else: hf_quantizer = None if hf_quantizer is not None: hf_quantizer.validate_environment( torch_dtype=torch_dtype, ...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Force-set to `True` for more mem efficiency if low_cpu_mem_usage is None: low_cpu_mem_usage = True logger.warning("`low_cpu_mem_usage` was None, now default to True since model is quantized.") is_quantized = hf_quantizer is not None # This variable will fla...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
if pretrained_model_name_or_path is not None and gguf_file is None: pretrained_model_name_or_path = str(pretrained_model_name_or_path) is_local = os.path.isdir(pretrained_model_name_or_path) if is_local: if from_tf and os.path.isfile( os.path.join(...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_NAME) ): # Load from a Flax checkpoint in priority if from_flax archive_file = os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_NAME) elif use_safetensors is not...
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
# Load from a sharded safetensors checkpoint archive_file = os.path.join( pretrained_model_name_or_path, subfolder, _add_variant(SAFE_WEIGHTS_INDEX_NAME, variant) ) is_sharded = True elif not use_safetensors and os.path....
230
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py