o
    h                     @   s  d Z ddlZddlZddlZddlZddlmZmZmZ ddl	m
Z
 ddlmZ ddlmZ ddlmZ dd	lmZmZmZmZmZmZmZmZmZmZmZ dd
lmZ ee Z!G dd deZ"de#e$ de$fddZ%dddZ&ee"j'e"_'e"j'j dure"j'j j(dddde"j'_ dS dS )z'Configuration base class and utilities.    N)AnyOptionalUnion)version   )__version__)custom_object_save)load_gguf_checkpoint)CONFIG_NAMEPushToHubMixinadd_model_info_to_auto_map"add_model_info_to_custom_pipelinescached_file	copy_funcdownload_urlextract_commit_hashis_remote_urlis_torch_availablelogging)is_timm_config_dictc                       s  e Zd ZU dZdZeed< dZeed< i Ze	ed f ed< dZ
eed< i Ze	eef ed< d	Zee	eef  ed
< d	Zee	eeee  f  ed< d	Zee ed<  fddZ fddZdd ZedefddZejdd ZedefddZedefddZejdefddZedd Zejdd Zd]d eeej f d!efd"d#Z!e"d^d$d%Z#e$							&d_d'eeej f d(eeeej f  d)ed*ed+eeeef  d,edd fd-d.Z%e$d'eeej f dee	eef e	eef f fd/d0Z&e$d'eeej f dee	eef e	eef f fd1d2Z'e$d3e	eef dd fd4d5Z(e$d6eeej f dd fd7d8Z)e$d6eeej f fd9d:Z*d;d< Z+d=d> Z,d?d@ Z-de	eef fdAdBZ.de	eef fdCdDZ/d`dFedefdGdHZ0d`dIeeej f dFefdJdKZ1d3e	eef fdLdMZ2dNefdOdPZ3dQe	eef dd	fdRdSZ4e$dadUdVZ5e"de	eef fdWdXZ6de	eef fdYdZZ7d]dbd[d\Z8  Z9S )cPretrainedConfiga8%  
    Base class for all configuration classes. Handles a few parameters common to all models' configurations as well as
    methods for loading/downloading/saving configurations.

    <Tip>

    A configuration file can be loaded and saved to disk. Loading the configuration file and using this file to
    initialize a model does **not** load the model weights. It only affects the model's configuration.

    </Tip>

    Class attributes (overridden by derived classes):

    - **model_type** (`str`) -- An identifier for the model type, serialized into the JSON file, and used to recreate
      the correct object in [`~transformers.AutoConfig`].
    - **is_composition** (`bool`) -- Whether the config class is composed of multiple sub-configs. In this case the
      config has to be initialized from two or more configs of type [`~transformers.PretrainedConfig`] like:
      [`~transformers.EncoderDecoderConfig`] or [`~RagConfig`].
    - **keys_to_ignore_at_inference** (`List[str]`) -- A list of keys to ignore by default when looking at dictionary
      outputs of the model during inference.
    - **attribute_map** (`Dict[str, str]`) -- A dict that maps model specific attribute names to the standardized
      naming of attributes.
    - **base_model_tp_plan** (`Dict[str, Any]`) -- A dict that maps sub-modules FQNs of a base model to a tensor
      parallel plan applied to the sub-module when `model.tensor_parallel` is called.
    - **base_model_pp_plan** (`Dict[str, Tuple[List[str]]]`) -- A dict that maps child-modules of a base model to a
      pipeline parallel plan that enables users to place the child-module on the appropriate device.

    Common attributes (present in all subclasses):

    - **vocab_size** (`int`) -- The number of tokens in the vocabulary, which is also the first dimension of the
      embeddings matrix (this attribute may be missing for models that don't have a text modality like ViT).
    - **hidden_size** (`int`) -- The hidden size of the model.
    - **num_attention_heads** (`int`) -- The number of attention heads used in the multi-head attention layers of the
      model.
    - **num_hidden_layers** (`int`) -- The number of blocks in the model.

    <Tip warning={true}>

    Setting parameters for sequence generation in the model config is deprecated. For backward compatibility, loading
    some of them will still be possible, but attempting to overwrite them will throw an exception -- you should set
    them in a [~transformers.GenerationConfig]. Check the documentation of [~transformers.GenerationConfig] for more
    information about the individual parameters.

    </Tip>

    Arg:
        name_or_path (`str`, *optional*, defaults to `""`):
            Store the string that was passed to [`PreTrainedModel.from_pretrained`] or
            [`TFPreTrainedModel.from_pretrained`] as `pretrained_model_name_or_path` if the configuration was created
            with such a method.
        output_hidden_states (`bool`, *optional*, defaults to `False`):
            Whether or not the model should return all hidden-states.
        output_attentions (`bool`, *optional*, defaults to `False`):
            Whether or not the model should returns all attentions.
        return_dict (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return a [`~transformers.utils.ModelOutput`] instead of a plain tuple.
        is_encoder_decoder (`bool`, *optional*, defaults to `False`):
            Whether the model is used as an encoder/decoder or not.
        is_decoder (`bool`, *optional*, defaults to `False`):
            Whether to only use the decoder in an encoder-decoder architecture, otherwise it has no effect on decoder-only or encoder-only architectures.
        cross_attention_hidden_size** (`bool`, *optional*):
            The hidden size of the cross-attention layer in case the model is used as a decoder in an encoder-decoder
            setting and the cross-attention hidden dimension differs from `self.config.hidden_size`.
        add_cross_attention (`bool`, *optional*, defaults to `False`):
            Whether cross-attention layers should be added to the model. Note, this option is only relevant for models
            that can be used as decoder models within the [`EncoderDecoderModel`] class, which consists of all models
            in `AUTO_MODELS_FOR_CAUSAL_LM`.
        tie_encoder_decoder (`bool`, *optional*, defaults to `False`):
            Whether all encoder weights should be tied to their equivalent decoder weights. This requires the encoder
            and decoder model to have the exact same parameter names.
        prune_heads (`Dict[int, List[int]]`, *optional*, defaults to `{}`):
            Pruned heads of the model. The keys are the selected layer indices and the associated values, the list of
            heads to prune in said layer.

            For instance `{1: [0, 2], 2: [2, 3]}` will prune heads 0 and 2 on layer 1 and heads 2 and 3 on layer 2.
        chunk_size_feed_forward (`int`, *optional*, defaults to `0`):
            The chunk size of all feed forward layers in the residual attention blocks. A chunk size of `0` means that
            the feed forward layer is not chunked. A chunk size of n means that the feed forward layer processes `n` <
            sequence_length embeddings at a time. For more information on feed forward chunking, see [How does Feed
            Forward Chunking work?](../glossary.html#feed-forward-chunking).

        > Parameters for fine-tuning tasks

        architectures (`List[str]`, *optional*):
            Model architectures that can be used with the model pretrained weights.
        finetuning_task (`str`, *optional*):
            Name of the task used to fine-tune the model. This can be used when converting from an original (TensorFlow
            or PyTorch) checkpoint.
        id2label (`Dict[int, str]`, *optional*):
            A map from index (for instance prediction index, or target index) to label.
        label2id (`Dict[str, int]`, *optional*): A map from label to index for the model.
        num_labels (`int`, *optional*):
            Number of labels to use in the last layer added to the model, typically for a classification task.
        task_specific_params (`Dict[str, Any]`, *optional*):
            Additional keyword arguments to store for the current task.
        problem_type (`str`, *optional*):
            Problem type for `XxxForSequenceClassification` models. Can be one of `"regression"`,
            `"single_label_classification"` or `"multi_label_classification"`.

        > Parameters linked to the tokenizer

        tokenizer_class (`str`, *optional*):
            The name of the associated tokenizer class to use (if none is set, will use the tokenizer associated to the
            model by default).
        prefix (`str`, *optional*):
            A specific prompt that should be added at the beginning of each text before calling the model.
        bos_token_id (`int`, *optional*): The id of the _beginning-of-stream_ token.
        pad_token_id (`int`, *optional*): The id of the _padding_ token.
        eos_token_id (`int`, *optional*): The id of the _end-of-stream_ token.
        decoder_start_token_id (`int`, *optional*):
            If an encoder-decoder model starts decoding with a different token than _bos_, the id of that token.
        sep_token_id (`int`, *optional*): The id of the _separation_ token.

        > PyTorch specific parameters

        torchscript (`bool`, *optional*, defaults to `False`):
            Whether or not the model should be used with Torchscript.
        tie_word_embeddings (`bool`, *optional*, defaults to `True`):
            Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the
            model has a output word embedding layer.
        torch_dtype (`str`, *optional*):
            The `dtype` of the weights. This attribute can be used to initialize the model to a non-default `dtype`
            (which is normally `float32`) and thus allow for optimal storage allocation. For example, if the saved
            model is `float16`, ideally we want to load it back using the minimal amount of memory needed to load
            `float16` weights. Since the config object is stored in plain text, this attribute contains just the
            floating type string without the `torch.` prefix. For example, for `torch.float16` ``torch_dtype` is the
            `"float16"` string.

            This attribute is currently not being used during model loading time, but this may change in the future
            versions. But we can already start preparing for the future by saving the dtype with save_pretrained.

        > TensorFlow specific parameters

        use_bfloat16 (`bool`, *optional*, defaults to `False`):
            Whether or not the model should use BFloat16 scalars (only used by some TensorFlow models).
        tf_legacy_loss (`bool`, *optional*, defaults to `False`):
            Whether the model should use legacy TensorFlow losses. Legacy losses have variable output shapes and may
            not be XLA-compatible. This option is here for backward compatibility and will be removed in Transformers
            v5.
        loss_type (`str`, *optional*):
            The type of loss that the model should use. It should be in `LOSS_MAPPING`'s keys, otherwise the loss will
            be automatically inferred from the model architecture.
     
model_typebase_config_keysub_configsFis_compositionattribute_mapNbase_model_tp_planbase_model_pp_plan_auto_classc                    s2   |t  dv rt  d| }t  || d S Nr   )super__getattribute____setattr__)selfkeyvalue	__class__ t/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/transformers/configuration_utils.pyr#      s   zPretrainedConfig.__setattr__c                    s4   |dkr|t  dv rt  d| }t  |S r    )r!   r"   )r$   r%   r'   r)   r*   r"      s   z!PretrainedConfig.__getattribute__c           
      K   s  | dd| _| dd| _| dd| _| dd| _| dd | _| dd| _| d	d| _| d
i | _| dd| _	| dd| _
| dd| _| dd| _| dd | _| dd| _| dd| _|   D ]\}}t| || || qo| dd | _| dd | _| dd | _| dd | _| jd urt| jtstd| jd urt| jtstd| dd }|d urt| j|krtd| d| j d| j d dd | j D | _n| dd | _| jd ur	t| jtr	t r	dd l }t!|| j| _| d!d | _"| d"d | _#| d#d | _$| d$d | _%| d%d | _&| d&d | _'| d'd | _(| d(d | _)| d)d | _*d*}| j*d ur_| j*|vr_td+| j* d,| d-d d urmtd. t| d/d0| _+| d1d | _,| d2d | _-d| _.| d3d | _/|0d4drt12d5 | D ]*\}}z	t| || W q t3y }	 zt4d6| d7| d8|   |	d }	~	ww d S )9Nreturn_dictToutput_hidden_statesFoutput_attentionstorchscripttorch_dtypeuse_bfloat16tf_legacy_losspruned_headstie_word_embeddingschunk_size_feed_forwardr   is_encoder_decoder
is_decodercross_attention_hidden_sizeadd_cross_attentiontie_encoder_decoderarchitecturesfinetuning_taskid2labellabel2idz)Argument label2id should be a dictionary.z)Argument id2label should be a dictionary.
num_labelsYou passed along `num_labels=(` with an incompatible id to label map: z.. The number of labels will be overwritten to .c                 S      i | ]	\}}t ||qS r)   int.0r%   r&   r)   r)   r*   
<dictcomp>       z-PretrainedConfig.__init__.<locals>.<dictcomp>   tokenizer_classprefixbos_token_idpad_token_ideos_token_idsep_token_iddecoder_start_token_idtask_specific_paramsproblem_type)
regressionsingle_label_classificationmulti_label_classificationzAThe config parameter `problem_type` was not understood: received za but only 'regression', 'single_label_classification' and 'multi_label_classification' are valid.
xla_devicezThe `xla_device` argument has been deprecated in v4.4.0 of Transformers. It is ignored and you can safely remove it from your `config.json` file.name_or_pathr   _commit_hashattn_implementationtransformers_versiongradient_checkpointinga  Passing `gradient_checkpointing` to a config initialization is deprecated and will be removed in v5 Transformers. Using `model.gradient_checkpointing_enable()` instead, or if you are using the `Trainer` API, pass `gradient_checkpointing=True` in your `TrainingArguments`.z
Can't set z with value z for )5popr+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   _get_global_generation_defaultsitemssetattrr:   r;   r<   r=   
isinstancedict
ValueErrorlenloggerwarningr>   strr   torchgetattrrJ   rK   rL   rM   rN   rO   rP   rQ   rR   _name_or_pathrX   _attn_implementation_internal_attn_implementation_autosetrZ   getwarningswarnAttributeErrorerror)
r$   kwargsparameter_namedefault_valuer>   rg   allowed_problem_typesr%   r&   errr)   r)   r*   __init__   s   
zPretrainedConfig.__init__returnc                 C   s   t | dd S )Nri   )rh   r$   r)   r)   r*   rW   E  s   zPretrainedConfig.name_or_pathc                 C   s   t || _d S N)rf   ri   r$   r&   r)   r)   r*   rW   I  s   c                 C   s   | j o| j S )zY
        `bool`: Whether or not return [`~utils.ModelOutput`] instead of tuples.
        )r+   r.   rx   r)   r)   r*   use_return_dictM  s   z PretrainedConfig.use_return_dictc                 C   s
   t | jS )zH
        `int`: The number of labels for classification models.
        )rc   r<   rx   r)   r)   r*   r>   U  s   
zPretrainedConfig.num_labelsr>   c                 C   sZ   t | dr| jd u st| j|kr+dd t|D | _tt| j | j | _d S d S )Nr<   c                 S   s   i | ]}|d | qS )LABEL_r)   )rF   ir)   r)   r*   rG   _  s    z/PretrainedConfig.num_labels.<locals>.<dictcomp>)	hasattrr<   rc   rangera   zipvalueskeysr=   )r$   r>   r)   r)   r*   r>   \  s   " c                 C   s"   t | dr| jd u rdS | jS dS )Nrj   eager)r~   rj   rx   r)   r)   r*   _attn_implementationb  s
   

z%PretrainedConfig._attn_implementationc                 C   s
   || _ d S ry   )rj   rz   r)   r)   r*   r   n  s   
save_directorypush_to_hubc           	      K   s  |  | tj|rtd| d|  }t|dkr(tdt	| t
 tj|dd |rR|dd}|d	|tjjd
 }| j|fi |}| |}| jdur^t| || d tj|t}| j|dd td|  |r| j|||||dd dS dS )aS  
        Save a configuration object to the directory `save_directory`, so that it can be re-loaded using the
        [`~PretrainedConfig.from_pretrained`] class method.

        Args:
            save_directory (`str` or `os.PathLike`):
                Directory where the configuration JSON file will be saved (will be created if it does not exist).
            push_to_hub (`bool`, *optional*, defaults to `False`):
                Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
                repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
                namespace).
            kwargs (`Dict[str, Any]`, *optional*):
                Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
        zProvided path (z#) should be a directory, not a filer   a  Some non-default generation parameters are set in the model config. These should go into either a) `model.generation_config` (as opposed to `model.config`); OR b) a GenerationConfig file (https://huggingface.co/docs/transformers/generation_strategies#save-a-custom-decoding-strategy-with-your-model).This warning will become an exception in the future.
Non-default generation parameters: T)exist_okcommit_messageNrepo_id)configuse_diffzConfiguration saved in token)r   r   )_set_token_in_kwargsospathisfileAssertionError&_get_non_default_generation_parametersrc   rm   rn   rf   UserWarningmakedirsr\   splitsep_create_repo_get_files_timestampsr   r   joinr
   to_json_filerd   info_upload_modified_filesrl   )	r$   r   r   rq   !non_default_generation_parametersr   r   files_timestampsoutput_config_filer)   r)   r*   save_pretrainedr  s>   
	


z PretrainedConfig.save_pretrainedc                 C   s`   |du r
|  dd}|  dd}|dur$tdt |dur"td|}|dur.|| d< dS dS )zTemporary method to deal with `token` and `use_auth_token`.

        This method is to avoid apply the same changes in all model config classes that overwrite `from_pretrained`.

        Need to clean up `use_auth_token` in a follow PR.
        Nr   use_auth_tokenzrThe `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.zV`token` and `use_auth_token` are both specified. Please set only the argument `token`.)r\   rm   rn   FutureWarningrb   )rq   r   r   r)   r)   r*   r     s    	z%PretrainedConfig._set_token_in_kwargsmainpretrained_model_name_or_path	cache_dirforce_downloadlocal_files_onlyr   revisionc                 K   s   ||d< ||d< ||d< ||d< |  || | j|fi |\}}| jr.| j|v r.|| j }d|v rlt| drl|d | jkrl| D ]\}	}
t|
trU|
d| jkrU|
}qB|d | jkrlt	
d|d  d| j d | j|fi |S )	a  
        Instantiate a [`PretrainedConfig`] (or a derived class) from a pretrained model configuration.

        Args:
            pretrained_model_name_or_path (`str` or `os.PathLike`):
                This can be either:

                - a string, the *model id* of a pretrained model configuration hosted inside a model repo on
                  huggingface.co.
                - a path to a *directory* containing a configuration file saved using the
                  [`~PretrainedConfig.save_pretrained`] method, e.g., `./my_model_directory/`.
                - a path or url to a saved configuration JSON *file*, e.g., `./my_model_directory/configuration.json`.
            cache_dir (`str` or `os.PathLike`, *optional*):
                Path to a directory in which a downloaded pretrained model configuration should be cached if the
                standard cache should not be used.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force to (re-)download the configuration files and override the cached versions if
                they exist.
            resume_download:
                Deprecated and ignored. All downloads are now resumed by default when possible.
                Will be removed in v5 of Transformers.
            proxies (`Dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
            token (`str` or `bool`, *optional*):
                The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
                the token generated when running `huggingface-cli login` (stored in `~/.huggingface`).
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
                git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
                identifier allowed by git.

                <Tip>

                To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`.

                </Tip>

            return_unused_kwargs (`bool`, *optional*, defaults to `False`):
                If `False`, then this function returns just the final configuration object.

                If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a
                dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the
                part of `kwargs` which has not been used to update `config` and is otherwise ignored.
            subfolder (`str`, *optional*, defaults to `""`):
                In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
                specify the folder name here.
            kwargs (`Dict[str, Any]`, *optional*):
                The values in kwargs of any keys which are configuration attributes will be used to override the loaded
                values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
                by the `return_unused_kwargs` keyword parameter.

        Returns:
            [`PretrainedConfig`]: The configuration object instantiated from this pretrained model.

        Examples:

        ```python
        # We can't instantiate directly the base class *PretrainedConfig* so let's show the examples on a
        # derived class: BertConfig
        config = BertConfig.from_pretrained(
            "google-bert/bert-base-uncased"
        )  # Download configuration from huggingface.co and cache.
        config = BertConfig.from_pretrained(
            "./test/saved_model/"
        )  # E.g. config (or model) was saved using *save_pretrained('./test/saved_model/')*
        config = BertConfig.from_pretrained("./test/saved_model/my_configuration.json")
        config = BertConfig.from_pretrained("google-bert/bert-base-uncased", output_attentions=True, foo=False)
        assert config.output_attentions == True
        config, unused_kwargs = BertConfig.from_pretrained(
            "google-bert/bert-base-uncased", output_attentions=True, foo=False, return_unused_kwargs=True
        )
        assert config.output_attentions == True
        assert unused_kwargs == {"foo": False}
        ```r   r   r   r   r   zYou are using a model of type z  to instantiate a model of type zN. This is not supported for all configurations of models and can yield errors.)r   get_config_dictr   r~   r   r^   r`   ra   rl   rd   re   	from_dict)clsr   r   r   r   r   r   rq   config_dictkvr)   r)   r*   from_pretrained  s(   V
 z PretrainedConfig.from_pretrainedc                 K   s   |  | t|}| j|fi |\}}|du ri |fS d|v r'|d |d< d|v r>t|d }| j|fd|i|\}}||fS )a  
        From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a
        [`PretrainedConfig`] using `from_dict`.

        Parameters:
            pretrained_model_name_or_path (`str` or `os.PathLike`):
                The identifier of the pre-trained checkpoint from which we want the dictionary of parameters.

        Returns:
            `Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the configuration object.

        NrX   configuration_files_configuration_file)r   copydeepcopy_get_config_dictget_configuration_file)r   r   rq   original_kwargsr   configuration_filer)   r)   r*   r   :  s"   


z PretrainedConfig.get_config_dictc                 K   s  | dd }| dd}| dd }| dd }| dd }| dd}| dd }	| d	d }
| d
d}| dd }| dd}| dd }|dd }|
du rWtd d|d}|d urd||d< t|}tj|}tjtj	||r~|}d}nZt
|r|d u r|n|}t|}nI|d u r| dtn|}z t||||||||||	||d}|d u rd |fW S t||}W n ty     ty   td| d| d| dw z|rt|ddd }n| |}||d< W n tjtfy   td| dw |rtd|  ntd| d|  d |v r*|s*t|d  ||d < d!|v r;|s;t|d! ||d!< d"|vrIt|rId#|d"< ||fS )$Nr   r   Fresume_downloadproxiesr   r   r   trust_remote_code	subfolderr   _from_pipeline
_from_autorX   	gguf_fileTzgThe argument `trust_remote_code` is to be used with Auto classes. It has no effect here and is ignored.r   )	file_typefrom_auto_classusing_pipeliner   )
r   r   r   r   r   r   
user_agentr   r   rX   z!Can't load the configuration of 'z'. If you were trying to load it from 'https://huggingface.co/models', make sure you don't have a local directory with the same name. Otherwise, make sure 'z2' is the correct path to a directory containing a z file)return_tensorsz"It looks like the config file at 'z' is not a valid JSON file.zloading configuration file z from cache at auto_mapcustom_pipelinesr   timm_wrapper)r\   rl   rd   re   rf   r   r   isdirr   r   r   r   r
   r   r   OSError	Exceptionr	   _dict_from_json_filejsonJSONDecodeErrorUnicodeDecodeErrorr   r   r   r   )r   r   rq   r   r   r   r   r   r   r   r   r   from_pipeliner   commit_hashr   r   is_localresolved_config_filer   r   r)   r)   r*   r   ]  s   


	
z!PretrainedConfig._get_config_dictr   c                 K   sv  | dd}| dd | dd d|v r d|v r |d |d< | dd|d< | di |}t|dr?d	d
 |j D |_d|v rjd|v rj|d }|d durU|d ng }t||krjtd| d|d  dg }| D ]/\}}	t||rt||}
t|
trt|	t	r|
j
di |	}	t|||	 |dkr|| qp|D ]}| |d qtd|  |r||fS |S )ao  
        Instantiates a [`PretrainedConfig`] from a Python dictionary of parameters.

        Args:
            config_dict (`Dict[str, Any]`):
                Dictionary that will be used to instantiate the configuration object. Such a dictionary can be
                retrieved from a pretrained checkpoint by leveraging the [`~PretrainedConfig.get_config_dict`] method.
            kwargs (`Dict[str, Any]`):
                Additional parameters from which to initialize the configuration object.

        Returns:
            [`PretrainedConfig`]: The configuration object instantiated from those parameters.
        return_unused_kwargsFr   Nr   rX   rY   r2   c                 S   rB   r)   rC   rE   r)   r)   r*   rG     rH   z.PretrainedConfig.from_dict.<locals>.<dictcomp>r>   r<   r?   r@   zX. Since those arguments are inconsistent with each other, you should remove one of them.r/   zModel config r)   )r\   r~   r2   r^   rc   rb   rh   r`   r   ra   r(   r_   appendrd   r   )r   r   rq   r   r   r>   r<   	to_remover%   r&   current_attrr)   r)   r*   r     sD   



zPretrainedConfig.from_dict	json_filec                 C   s   |  |}| di |S )aQ  
        Instantiates a [`PretrainedConfig`] from the path to a JSON file of parameters.

        Args:
            json_file (`str` or `os.PathLike`):
                Path to the JSON file containing the parameters.

        Returns:
            [`PretrainedConfig`]: The configuration object instantiated from that JSON file.

        Nr)   )r   )r   r   r   r)   r)   r*   from_json_file  s   
zPretrainedConfig.from_json_filec                 C   s>   t |dd}| }W d    n1 sw   Y  t|S )Nutf-8encoding)openreadr   loads)r   r   readertextr)   r)   r*   r     s   

z%PretrainedConfig._dict_from_json_filec                 C   s   t |to
| j|jkS ry   )r`   r   __dict__)r$   otherr)   r)   r*   __eq__     zPretrainedConfig.__eq__c                 C   s   | j j d|   S )N )r(   __name__to_json_stringrx   r)   r)   r*   __repr__  r   zPretrainedConfig.__repr__c                 c   s    | j E d H  d S ry   )r   rx   r)   r)   r*   __iter__  s   zPretrainedConfig.__iter__c           	      C   sd  |   }t   }| js|    ni }i }| D ]Y\}}tt| |dtr2||v r2t|| ts7|| jv rQt	||t| |dd}d|v rL|d |d< |||< q||vso|dkso|dkso||| kso||v rs||
||krs|||< qt| drt| jts| j  n| j|d< |dd}| | d|v r|d= d	|v r|d	= d
|v r|d
= d|v r|d= |S )ar  
        Removes all attributes from the configuration that correspond to the default config attributes for
        better readability, while always retaining the `config` attribute from the class. Serializes to a
        Python dictionary.

        Returns:
            Dict[str, Any]: Dictionary of all the attributes that make up this configuration instance.
        N
config_objr   rZ   
vocab_filequantization_config_pre_quantization_dtyperj   r   r   ri   )to_dictr   r   r(   r^   r`   rh   ra   r   recursive_diff_dictrl   r~   r   r\   dict_torch_dtype_to_str)	r$   r   default_config_dictclass_config_dictserializable_config_dictr%   r&   diff_r)   r)   r*   to_diff_dict"  sL   	





zPretrainedConfig.to_diff_dictc                 C   s   t | j}t| jdr| jj|d< d|v r|d= d|v r |d= d|v r'|d= d|v r.|d= d|v r5|d= t|d< | D ]\}}t|t	rM|
 }|d= |||< q=t| drmt| jtsb| j
 n| j|d< |d	d
}| | |S )z
        Serializes this instance to a Python dictionary.

        Returns:
            `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
        r   r   rX   rj   r   r   rZ   r   r   N)r   r   r   r~   r(   r   r   r^   r`   r   r   r   ra   r\   r   )r$   outputr%   r&   r   r)   r)   r*   r   f  s6   




zPretrainedConfig.to_dictTr   c                 C   s.   |du r	|   }n|  }tj|dddd S )a  
        Serializes this instance to a JSON string.

        Args:
            use_diff (`bool`, *optional*, defaults to `True`):
                If set to `True`, only the difference between the config instance and the default `PretrainedConfig()`
                is serialized to JSON string.

        Returns:
            `str`: String containing all the attributes that make up this configuration instance in JSON format.
        TrI   )indent	sort_keys
)r   r   r   dumps)r$   r   r   r)   r)   r*   r     s   
zPretrainedConfig.to_json_stringjson_file_pathc                 C   sF   t |ddd}|| j|d W d   dS 1 sw   Y  dS )a  
        Save this instance to a JSON file.

        Args:
            json_file_path (`str` or `os.PathLike`):
                Path to the JSON file in which this configuration instance's parameters will be saved.
            use_diff (`bool`, *optional*, defaults to `True`):
                If set to `True`, only the difference between the config instance and the default `PretrainedConfig()`
                is serialized to JSON file.
        wr   r   r   N)r   writer   )r$   r   r   writerr)   r)   r*   r     s   "zPretrainedConfig.to_json_filec                 C   s"   |  D ]
\}}t| || qdS )z
        Updates attributes of this class with attributes from `config_dict`.

        Args:
            config_dict (`Dict[str, Any]`): Dictionary of attributes that should be updated for this class.
        N)r^   r_   )r$   r   r%   r&   r)   r)   r*   update  s   zPretrainedConfig.update
update_strc                 C   s   t dd |dD }| D ]a\}}t| |s!td| dt| |}t|trH| dv r4d}n7| dv r=d	}n.td
| d| dt|t	rRt	|}nt|t
r\t
|}nt|tsktd| d| t| || qdS )a  
        Updates attributes of this class with attributes from `update_str`.

        The expected format is ints, floats and strings as is, and for booleans use `true` or `false`. For example:
        "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"

        The keys to change have to already exist in the config object.

        Args:
            update_str (`str`): String with attributes that should be updated for this class.

        c                 s   s    | ]}| d V  qdS )=N)r   )rF   xr)   r)   r*   	<genexpr>  s    z6PretrainedConfig.update_from_string.<locals>.<genexpr>,zkey z" isn't in the original config dict)true1yyesT)false0nnoFz can't derive true or false from z (key )zIYou can only update int, float, bool or string values in the config, got z	 for key N)ra   r   r^   r~   rb   rh   r`   boollowerrD   floatrf   	TypeErrorr_   )r$   r  dr   r   old_vr)   r)   r*   update_from_string  s*   







z#PretrainedConfig.update_from_stringr  c                 C   s   | dddur1t|d trdd |d  D |d< nt|d ts1t|d dd |d< | D ]}t|trA| | q5dS )a.  
        Checks whether the passed dictionary and its nested dicts have a *torch_dtype* key and if it's not None,
        converts torch.dtype to a string of just the type. For example, `torch.float32` get converted into *"float32"*
        string, which can then be stored in the json format.
        r/   Nc                 S   s$   i | ]\}}|t |d d qS )rA   r   )rf   r   )rF   r   r   r)   r)   r*   rG     s   $ z<PretrainedConfig.dict_torch_dtype_to_str.<locals>.<dictcomp>rA   r   )rl   r`   ra   r^   rf   r   r   r   )r$   r  r&   r)   r)   r*   r     s   

z(PretrainedConfig.dict_torch_dtype_to_str
AutoConfigc                 C   sD   t |ts|j}ddlm  m} t||st| d|| _dS )a  
        Register this class with a given auto class. This should only be used for custom configurations as the ones in
        the library are already mapped with `AutoConfig`.

        <Tip warning={true}>

        This API is experimental and may have some slight breaking changes in the next releases.

        </Tip>

        Args:
            auto_class (`str` or `type`, *optional*, defaults to `"AutoConfig"`):
                The auto class to register this new configuration with.
        r   Nz is not a valid auto class.)	r`   rf   r   transformers.models.automodelsautor~   rb   r   )r   
auto_classauto_moduler)   r)   r*   register_for_auto_class  s   


z(PretrainedConfig.register_for_auto_classc                
   C   s   i dddddddddd	d
d	dddddddddddddddddddd dd	ddd d dd d d dS )N
max_length   
min_lengthr   	do_sampleFearly_stopping	num_beamsr   num_beam_groupsdiversity_penaltyg        temperatureg      ?top_k2   top_p	typical_prepetition_penaltylength_penaltyno_repeat_ngram_sizeencoder_no_repeat_ngram_sizebad_words_idsnum_return_sequences)output_scoresreturn_dict_in_generateforced_bos_token_idforced_eos_token_idremove_invalid_values exponential_decay_length_penaltysuppress_tokensbegin_suppress_tokensr)   r)   r)   r)   r*   r]     sX   	
z0PretrainedConfig._get_global_generation_defaultsc                 C   s   i }d}z|   }W n ty$   | jdd}|| ur |  }nd}Y nw |du r+| nt| |}|   D ]<\}}t||rrd }}	t||}
|
du rMq6|durY|
t||k}n|
|k}	|du ph|du oh|	du }|rrt||||< q6|S )z]
        Gets the non-default generation parameters on the PretrainedConfig instance
        NT)decoderF)r(   rb   get_text_configrh   r]   r^   r~   )r$   r   decoder_attribute_namedefault_configdecoder_configself_decoder_configrr   default_global_valueis_default_in_configis_default_generation_valueparameter_valueis_non_defaultr)   r)   r*   r   -  s8   


z7PretrainedConfig._get_non_default_generation_parametersc           	      C   s   d}d}|r	|}n|| }g }|D ]}t | |r't| |d}|dur'||g7 }qt|dkr6td| dt|dkrEt| |d }|S | }|S )as  
        Returns the config that is meant to be used with text IO. On most models, it is the original config instance
        itself. On specific composite models, it is under a set of valid names.

        Args:
            decoder (`Optional[bool]`, *optional*, defaults to `False`):
                If set to `True`, then only search for decoder config names.
        )r:  	generatortext_config)text_encoderNr   z<Multiple valid text configs were found in the model config: zm. In this case, using `get_text_config()` would be ambiguous. Please specify the desied text config directly.r   )r~   rh   rc   rb   )	r$   r:  "decoder_possible_text_config_names"encoder_possible_text_config_namespossible_text_config_namesvalid_text_config_namestext_config_namerF  config_to_returnr)   r)   r*   r;  Y  s*   	


z PretrainedConfig.get_text_config)Fry   )NFFNr   )T)r  )rw   r   ):r   
__module____qualname____doc__r   rf   __annotations__r   r   ra   r   r  r   r   r   r   r   tuplelistr   r#   r"   rv   propertyrW   setterr{   rD   r>   r   r   r   PathLiker   staticmethodr   classmethodr   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r  r]   r   r;  __classcell__r)   r)   r'   r*   r   /   s   
   q


<	p"h<D0
&,r   r   rw   c                 C   s   i }| D ]}| dr |dr |dkr |dd}|||< qt| }t}tt	}|D ]}t||kr>|| }q0 |S |S )z
    Get the configuration file to use for this version of transformers.

    Args:
        configuration_files (`List[str]`): The list of available configuration files.

    Returns:
        `str`: The configuration file to use.
    zconfig.z.jsonzconfig.json)

startswithendswithremoveprefixremovesuffixsortedr   r
   r   parser   )r   configuration_files_map	file_namer   available_versionsr   rZ   r)   r)   r*   r   |  s   


r   c           	      C   s   i }|dur|   ni }|  D ]8\}}t|t|d}t|tr<||v r<t|| tr<t||| |d}|||< q||vsF||| krJ|||< q|S )a  
    Helper function to recursively take the diff between two nested dictionaries. The resulting diff only contains the
    values from `dict_a` that are different from values in `dict_b`.

    dict_b : the default config dictionary. We want to remove values that are in this one
    Nr   )	r(   r   r^   rh   rf   r`   r   ra   r   )	dict_adict_br   r   defaultr%   r&   	obj_value
diff_valuer)   r)   r*   r     s    
r   r   r  zconfiguration file)objectobject_classobject_filesry   ))rP  r   r   r   rm   typingr   r   r   	packagingr   r   r   dynamic_module_utilsr   modeling_gguf_pytorch_utilsr	   utilsr
   r   r   r   r   r   r   r   r   r   r   utils.genericr   
get_loggerr   rd   r   rS  rf   r   r   r   formatr)   r)   r)   r*   <module>   s<   4
        U
