
    bi):                         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mZ d dlmZmZ ddlmZmZmZ dhZd	 Ze G d
 de             Ze G d de             Ze G d de             Zy)    N)asdict	dataclassfield)OptionalUnion)hf_hub_download)PushToHubMixinhttp_user_agent   )CONFIG_NAMEPeftTypeTaskType	peft_typec                     t        j                  | j                        j                  }t	        |j                               t	        |j                               z
  }|D ]  }||=  ||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keys        F/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/peft/config.py_check_and_remove_unused_kwargsr      sf     #,,S\\:EEFKKM*S1E1J1J1L-MM  3K$$$    c                   V   e Zd ZU dZ edddi      Zee   ed<    edddi      Z	ee
   ed<    eddd	i      Zee   ed
<   d ZdefdZdeddfdZed        Zeddedee   fd       Zedefd       Zed        Zedefd       Zed        Zedefd       Zedefd       Zy)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.defaultmetadata	task_typezThe type of PEFT model.r   zEAn auto mapping dict to help retrieve the base model class if needed.auto_mappingc                     | j                   K| j                   t        t              vr/t        d| j                    ddj	                  t               d      y y )NzInvalid task type: 'z,'. Must be one of the following task types: z, .)r%   listr   
ValueErrorjoinselfs    r   __post_init__zPeftConfigMixin.__post_init__@   sX    NN&T^^4>-Q&t~~&66bcgclclmucvbwwxy  .R&r   returnc                     t        |       S )zS
        Returns the configuration for your adapter model as a dictionary.
        )r   r,   s    r   to_dictzPeftConfigMixin.to_dictG   s     d|r   save_directoryc                 &   t         j                  j                  |      rt        d| d      t        j                  |d       |j                  dd      }| j                         }|j                         D ]$  \  }}t        |t              st        |      ||<   & t         j                  j                  |t              }|||d<   t        |d      5 }|j                  t        j                   |d	d
             ddd       y# 1 sw Y   yxY w)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)ospathisfileAssertionErrormakedirspopr1   items
isinstancer   r)   r+   r   openwritejsondumps)	r-   r2   r   r5   output_dictr   valueoutput_pathwriters	            r   save_pretrainedzPeftConfigMixin.save_pretrainedM   s     77>>.) ?>2BBe!fgg
NT2"JJ':DAlln%++- 	/JC%%#';C 	/ ggll>;? (*;K' +s# 	LvLLKTJK	L 	L 	Ls   (DDc                    ddl m} d|v r|d   }||   }n| }	  |di |}|S # t        $ r}dt        |      vr|t	        ||      \  }}t
        j                  t        |j                                     s t        d| j                   dt
         d      t        j                  dt        |       d	|j                   d
        |j                  di |}Y d}~|S d}~ww xY 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: r(   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`).N )peft.mappingrL   	TypeErrorstrr   MIN_EXPECTED_CONFIG_KEYSissubsetr   r   __name__warningswarnsortedfrom_peft_type)	r   r   rL   r   
config_clsconfigexcfiltered_kwargsr   s	            r   rW   zPeftConfigMixin.from_peft_typen   s    	=" & {+I4Y?JJ	B)&)F4 3  	B 43s8C	1PQ[]c1d.O.+44S9M9M9O5PQ3<<.(f/03 
 MM/7H0I/J+V`ViViUj k  /Z..AAF3	Bs   # 	C"B+CC"pretrained_model_name_or_path	subfolderc                 P   | t         j                  j                  ||      n|}| j                  |      \  }}}d|vrt	               |d<   t         j                  j                  t         j                  j                  |t                    r%t         j                  j                  |t              }n	 t        |t        fd|i|}| j                  |      }
i ||
} | j                  di |} | j                  di |S # t        $ r}	t        dt         d| d      |	d}	~	ww xY w)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_agentr]   Can't find '' at ''rM   )r:   r;   r+   _split_kwargsr
   r<   r   r   	Exceptionr*   from_json_filecheck_kwargsrW   )r   r\   r]   r   r;   hf_hub_download_kwargsclass_kwargs_config_filerZ   loaded_attributess              r   from_pretrainedzPeftConfigMixin.from_pretrained   s2    $ GGLL6	B. 	 362C2CF2K/a553B3D"<077>>"'',,t[9:'',,t[9Kn-1;JSWm  ..{;6L6$56!!!+F+!s!!+F++  n <}FC`Baab!cdjmmns   2D   	D%	D  D%path_json_filec                     t        |      5 }t        j                  |      }ddd       dv rt        j                  d       |d= |S # 1 sw Y   'xY w)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.)rB   rD   loadrT   rU   )r   rm   r   filejson_objects        r   re   zPeftConfigMixin.from_json_file   s]     .! 	*T))D/K	* {*MM M ,-	* 	*s   AAc                     i }i }i }|j                         D ]R  \  }}|t        j                  t              j                  v r|||<   1|t        | j                        v r|||<   N|||<   T |||fS N)r@   r   r   r   r   r)   __annotations__)r   r   rg   rh   other_kwargsr   rG   s          r   rc   zPeftConfigMixin._split_kwargs   s    !# ,,. 	*JCg''8CCC.3&s+S0011$)S!$)S!	* &|\AAr   model_idc                    |j                  dd       }| t        j                  j                  ||      n|}t        j                  j	                  t        j                  j                  |t
                    r%t        j                  j                  |t
              }n	 t        |t
        fi |}| j                  |      }|d   S # t        $ r t        dt
         d| d      w xY w)Nr]   r`   ra   rb   r   )
getr:   r;   r+   r<   r   r   rd   r*   re   )r   rw   rg   r]   r;   rj   rk   s          r   _get_peft_typezPeftConfigMixin._get_peft_type   s     +..{DA	4=4Irww||Hi0x77>>"'',,t[9:'',,t[9KP- -  ..{; --	  P <}F8*A!NOOPs   C  C%c                     |S )zCheck kwargs before initializing the config instance.

        Subclasses can override this method to add specific checks.

        rM   )r   r   s     r   rf   zPeftConfigMixin.check_kwargs  s	     r   c                      y)V
        Utility method to check if the configuration is for prompt learning.
        FrM   r,   s    r   is_prompt_learningz"PeftConfigMixin.is_prompt_learning  s    
 r   c                      y)z1Return True if this is an adaption prompt config.FrM   r,   s    r   is_adaption_promptz"PeftConfigMixin.is_adaption_prompt!  s     r   rt   )rS   
__module____qualname____doc__r   r%   r   r   ru   r   r   r&   dictr.   r1   rP   rJ   classmethodrW   rl   re   rc   rz   rf   propertyboolr~   r   rM   r   r   r    r    .   s]    %*$&J]A^$_Ix!_$)$&JcAd$eIx!e#((op$L(4.  Lc L LB > >@ !,C !,HUXM !, !,F C  ( B B .. .0   D   D  r   r    c                       e Zd ZU dZ edddi      Zee   ed<    edddi      Z	ee   ed<    eddd	i      Z
eeeef      ed
<    edddi      Zeeeef      ed<    edddi      Zeed<   y)
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"   base_model_name_or_pathz'The specific base model version to use.revisionz	Peft typer   z	Task typer%   FzWhether to use inference modeinference_mode)rS   r   r   r   r   r   r   rP   ru   r   r   r   r   r%   r   r   r   rM   r   r   r   r   '  s     .3(LM.Xc]  $DFDm;noHhsmo05dfVaMb0cIxc8m,-c05dfVaMb0cIxc8m,-c &Ba9bcNDcr   r   c                      e Zd ZU dZ edddi      Zeed<    edddi      Zeed<    eddd	i      Z	e
e   ed
<    edddi      Ze
e   ed<    edddi      Ze
e   ed<    edddi      Ze
ee      ed<   edefd       Zy)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"   num_virtual_tokensz<The hidden embedding dimension of the base transformer model	token_dimz Number of transformer submodules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.modules_to_saver/   c                      y)r}   TrM   r,   s    r   r~   z'PromptLearningConfig.is_prompt_learning\  s    
 r   )rS   r   r   r   r   r   intru   r   r   r   r   r   r   r)   rP   r   r   r~   rM   r   r   r   r   ;  s    
 $DFD^;_``(fgIs  16(JK1  */tvOjFk)l#l %dfFd=e fJf+0 6
,OXd3i(  D  r   r   )r   rD   r:   rT   dataclassesr   r   r   typingr   r   huggingface_hubr   transformers.utilsr	   r
   utilsr   r   r   rQ   r   r    r   r   rM   r   r   <module>r      s      	  0 0 " + > 2 2 (= % un u up d d d& %: % %r   