o
    NiB                     @  s   d dl mZ d dl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mZ d dlZd dlmZ d dlmZmZ d dlmZ dd	lmZmZmZ d
hZdd ZdddZdddZe
G dd deZ e
G dd de Z!e
G dd de!Z"dS )    )annotationsN)asdict	dataclassfield)OptionalUnion)hf_hub_download)PushToHubMixinhttp_user_agent)__version__   )CONFIG_NAMEPeftTypeTaskType	peft_typec                 C  s>   t | jj}t| t|  }|D ]}||= q||fS )a  Make PEFT configs forward-compatible by removing unused kwargs that were added in later PEFT versions.

    This assumes that removing the unused kwargs will not affect the default behavior.

    Returns the filtered kwargs and the set of removed keys.
    )inspect	signature__init__
parameterssetkeys)clskwargssignature_parametersunexpected_kwargskey r   ?/home/ubuntu/.local/lib/python3.10/site-packages/peft/config.py_check_and_remove_unused_kwargs%   s
   r   versionstrreturnboolc                 C  s   t j| jd uS N)	packagingr   Versiondev)r   r   r   r   _is_dev_version4   s   r'   pkg_name
str | Nonec                 C  s~   zt j| }W n t jjy   Y d S w |jpg D ]"}|jdkr<t||	 }|
d}|r<d|v r<|d   S qd S )Nzdirect_url.jsonvcs_info	commit_id)	importlibmetadatadistributionPackageNotFoundErrorfilesnamejsonloadslocate_file	read_textget)r(   distpath
direct_urlr*   r   r   r   _get_commit_hash9   s   

r:   c                   @  s  e Zd ZU dZedddidZded< edddidZd	ed
< edddidZded< edddidZ	ded< dd Z
ed3ddZd4ddZd5ddZedd Zed6d7d"d#Zed8d%d&Zed'd( Zed9d*d+Zed,d- Zed:d/d0Zed:d1d2ZdS );PeftConfigMixinaC  
    This is the base configuration class for PEFT adapter models. It contains all the methods that are common to all
    PEFT adapter models. This class inherits from [`~transformers.utils.PushToHubMixin`] which contains the methods to
    push your model to the Hub. The method `save_pretrained` will save the configuration of your adapter model in a
    directory. The method `from_pretrained` will load the configuration of your adapter model from a directory.

    Args:
        peft_type (Union[[`~peft.utils.config.PeftType`], `str`]): The type of Peft method to use.
    NhelpzThe type of task.defaultr-   zOptional[TaskType]	task_typezThe type of PEFT model.zOptional[PeftType]r   zEAn auto mapping dict to help retrieve the base model class if needed.zOptional[dict]auto_mappingz'PEFT version, leave empty to auto-fill.Optional[str]peft_versionc                 C  sR   | j d ur| j ttvrtd| j  ddt d| jd u r'|  | _d S d S )NzInvalid task type: 'z,'. Must be one of the following task types: z, .)r?   listr   
ValueErrorjoinrB   _get_peft_versionselfr   r   r   __post_init___   s   
zPeftConfigMixin.__post_init__r!   r    c                  C  s\   t } t| s| S ztd}|d u rd}W n ty$   td d}Y nw | d|  } | S )NpeftUNKNOWNzA dev version of PEFT is used but there was an error while trying to determine the commit hash. Please open an issue: https://github.com/huggingface/peft/issues@)r   r'   r:   	Exceptionwarningswarn)r   git_hashr   r   r   rG   h   s    z!PeftConfigMixin._get_peft_versiondictc                 C  s   t | S )zS
        Returns the configuration for your adapter model as a dictionary.
        )r   rH   r   r   r   to_dict~   s   zPeftConfigMixin.to_dictsave_directoryNonec           	      K  s   t j|rtd| dt j|dd |dd}|  }| D ]\}}t|t	r2t
|||< q#t j|t}|durB||d< t|d}|tj|d	dd
 W d   dS 1 s^w   Y  dS )a  
        This method saves the configuration of your adapter model in a directory.

        Args:
            save_directory (`str`):
                The directory where the configuration will be saved.
            kwargs (additional keyword arguments, *optional*):
                Additional keyword arguments passed along to the [`~transformers.utils.PushToHubMixin.push_to_hub`]
                method.
        zProvided path (z#) should be a directory, not a fileT)exist_okauto_mapping_dictNr@   w   )indent	sort_keys)osr8   isfileAssertionErrormakedirspoprS   items
isinstancer   rD   rF   r   openwriter2   dumps)	rI   rT   r   rW   output_dictr   valueoutput_pathwriterr   r   r   save_pretrained   s   
"zPeftConfigMixin.save_pretrainedc           	   
   K  s   ddl m} d|v r|d }|| }n| }z
|di |}W |S  tym } zBdt|vr/|t||\}}tt| sKtd| j	 dt dt
dt| d	|j	 d
 |jdi |}W Y d}~|S d}~ww )a  
        This method loads the configuration of your adapter model from a set of kwargs.

        The appropriate configuration type is determined by the `peft_type` argument. If `peft_type` is not provided,
        the calling class type is instantiated.

        Args:
            kwargs (configuration keyword arguments):
                Keyword arguments passed along to the configuration initialization.
        r   )PEFT_TYPE_TO_CONFIG_MAPPINGr   z"got an unexpected keyword argumentzThe z> config that is trying to be loaded is missing required keys: rC   zUnexpected keyword arguments z for class a,  , these are ignored. This probably means that you're loading a configuration file that was saved using a higher version of the library and additional parameters have been introduced since. It is highly recommended to upgrade the PEFT version before continuing (e.g. by running `pip install -U peft`).Nr   )peft.mappingrk   	TypeErrorr    r   MIN_EXPECTED_CONFIG_KEYSissubsetr   r   __name__rO   rP   sortedfrom_peft_type)	r   r   rk   r   
config_clsconfigexcfiltered_kwargsr   r   r   r   rr      s2   

zPeftConfigMixin.from_peft_typepretrained_model_name_or_path	subfolderc              
   K  s   |durt j||n|}| |\}}}d|vrt |d< t jt j|tr1t j|t}n&zt|tfd|i|}W n tyV }	 zt	dt d| d|	d}	~	ww | 
|}
i ||
}| jdi |}| jdi |S )a  
        This method loads the configuration of your adapter model from a directory.

        Args:
            pretrained_model_name_or_path (`str`):
                The directory or the Hub repository id where the configuration is saved.
            kwargs (additional keyword arguments, *optional*):
                Additional keyword arguments passed along to the child class initialization.
        N
user_agentrx   Can't find '' at ''r   )r\   r8   rF   _split_kwargsr
   r]   r   r   rN   rE   from_json_filecheck_kwargsrr   )r   rw   rx   r   r8   hf_hub_download_kwargsclass_kwargs_config_fileru   loaded_attributesr   r   r   from_pretrained   s2   


zPeftConfigMixin.from_pretrainedpath_json_filec                 K  sN   t |}t|}W d   n1 sw   Y  d|v r%td |d= |S )z
        Loads a configuration file from a json file.

        Args:
            path_json_file (`str`):
                The path to the json file.
        Nruntime_configzzThe configuration file contains a `runtime_config` key. This is ignored. Runtime configurations are only valid at runtime.)rc   r2   loadrO   rP   )r   r   r   filejson_objectr   r   r   r~   
  s   
	zPeftConfigMixin.from_json_filec                 C  sb   i }i }i }|  D ]!\}}|ttjv r|||< q
|t| jv r'|||< q
|||< q
|||fS r#   )ra   r   r   r   r   rD   __annotations__)r   r   r   r   other_kwargsr   rg   r   r   r   r}     s   



zPeftConfigMixin._split_kwargsmodel_idc              	   K  s   | dd }|d urtj||n|}tjtj|tr&tj|t}nzt|tfi |}W n tyC   tdt d| dw | 	|}|d S )Nrx   rz   r{   r|   r   )
r6   r\   r8   rF   r]   r   r   rN   rE   r~   )r   r   r   rx   r8   r   r   r   r   r   _get_peft_type/  s    

zPeftConfigMixin._get_peft_typec                 K  s   |S )zCheck kwargs before initializing the config instance.

        Subclasses can override this method to add specific checks.

        r   )r   r   r   r   r   r   H  s   zPeftConfigMixin.check_kwargsr"   c                 C     dS )V
        Utility method to check if the configuration is for prompt learning.
        Fr   rH   r   r   r   is_prompt_learningQ     z"PeftConfigMixin.is_prompt_learningc                 C  r   )z1Return True if this is an adaption prompt config.Fr   rH   r   r   r   is_adaption_promptX  s   z"PeftConfigMixin.is_adaption_prompt)r!   r    )r!   rR   )rT   r    r!   rU   r#   )rw   r    rx   rA   )r   r    )r   r    r!   r"   )rp   
__module____qualname____doc__r   r?   r   r   r@   rB   rJ   staticmethodrG   rS   rj   classmethodrr   r   r~   r}   r   r   propertyr   r   r   r   r   r   r;   L   s:   
 
	

!
@#

r;   c                   @  s   e Zd ZU dZedddidZded< edddidZded	< eddd
idZded< edddidZ	ded< edddidZ
ded< dS )
PeftConfiga  
    This is the base configuration class to store the configuration of a [`PeftModel`].

    Args:
        peft_type (Union[[`~peft.utils.config.PeftType`], `str`]): The type of Peft method to use.
        task_type (Union[[`~peft.utils.config.TaskType`], `str`]): The type of task to perform.
        inference_mode (`bool`, defaults to `False`): Whether to use the Peft model in inference mode.
    Nr<   z"The name of the base model to use.r=   rA   base_model_name_or_pathz'The specific base model version to use.revisionz	Peft typezOptional[Union[str, PeftType]]r   z	Task typezOptional[Union[str, TaskType]]r?   FzWhether to use inference moder"   inference_mode)rp   r   r   r   r   r   r   r   r   r?   r   r   r   r   r   r   ^  s   
 	r   c                   @  s   e Zd ZU dZedddidZded< edddidZded	< eddd
idZded< edddidZ	ded< edddidZ
ded< edddidZded< edddZdS )PromptLearningConfigaY  
    This is the base configuration class to store the configuration of [`PrefixTuning`], [`PromptEncoder`], or
    [`PromptTuning`].

    Args:
        num_virtual_tokens (`int`): The number of virtual tokens to use.
        token_dim (`int`): The hidden embedding dimension of the base transformer model.
        num_transformer_submodules (`int`): The number of transformer submodules in the base transformer model.
        num_attention_heads (`int`): The number of attention heads in the base transformer model.
        num_layers (`int`): The number of layers in the base transformer model.
    Nr<   zNumber of virtual tokensr=   intnum_virtual_tokensz<The hidden embedding dimension of the base transformer model	token_dimz Number of transformer submoduleszOptional[int]num_transformer_submoduleszNumber of attention headsnum_attention_headszNumber of transformer layers
num_layersa&  List of extra modules to be set as trainable and saved in the final checkpoint. For example, in Sequence Classification or Token Classification tasks, the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved. The module(s) will be fully fine-tuned.zOptional[list[str]]modules_to_saver!   r"   c                 C  r   )r   Tr   rH   r   r   r   r     r   z'PromptLearningConfig.is_prompt_learningr   )rp   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  s$   
 
r   )r   r    r!   r"   )r(   r    r!   r)   )#
__future__r   importlib.metadatar,   r   r2   r\   rO   dataclassesr   r   r   typingr   r   packaging.versionr$   huggingface_hubr   transformers.utilsr	   r
   rK   r   utilsr   r   r   rn   r   r'   r:   r;   r   r   r   r   r   r   <module>   s2   

  