o
    di<                     @   s   d 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	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 d	d
lmZ d	dlmZ eeZG dd deZdS )zConfiguration base class.    N)AnyDictListTupleUnion)version)PretrainedConfig)__version__)custom_object_save)cached_filedownload_urlextract_commit_hashis_remote_url   )loggingc                	   @   s   e Zd ZdZdZdZedd Zddee	e
jf defdd	Zed
ee	 de	fddZedee	e
jf deee	ef ee	ef f fddZedee	e
jf deee	ef ee	ef f fddZedee	ef ddfddZdee	ef fddZdS )
BaseConfigz
    Base class for configuration classes that need to respect the same API than PretrainedConfig but with a different
    configuration file name.
    zconfig.jsonc                 C   s   t | jdd  dS )N.r   z
(.*)\.json)recompileFULL_CONFIGURATION_FILEsplit)cls r   i/lsinfo/ai/hellotax_ai/llm_service/venv_embed/lib/python3.10/site-packages/optimum/configuration_utils.py_re_configuration_file.   s   z!BaseConfig._re_configuration_fileFsave_directorypush_to_hubc           
      K   s  t j|rtd| dt j|dd |r\|dd}|d|t jjd }| j|fi |}|	d	d}|	d
d}|durWt
dt |durQtd||d
< |}| |}| jdurht| || d t j|| j}	| j|	dd td|	  |r| j|||||d dS dS )a4  
        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:
                Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
        zProvided path (z#) should be a directory, not a fileT)exist_okcommit_messageNrepo_iduse_auth_tokentokennThe `use_auth_token` argument is deprecated and will be removed soon. Please use the `token` argument instead.LYou cannot use both `use_auth_token` and `token` arguments at the same time.)config)use_diffzConfiguration saved in )r   r"   )ospathisfileAssertionErrormakedirspopr   sep_create_repogetwarningswarnFutureWarning
ValueError_get_files_timestamps_auto_classr
   joinCONFIG_NAMEto_json_fileloggerinfo_upload_modified_files)
selfr   r   kwargsr   r   r!   r"   files_timestampsoutput_config_filer   r   r   save_pretrained3   s:   



zBaseConfig.save_pretrainedconfiguration_filesreturnc           
      C   s   i }|   }|D ]}||}|dur| d }|||< qt| }| j}tt}	|D ]}t||	kr<|| }q. |S |S )a  
        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.
        Nr   )	r   searchgroupssortedkeysr7   r   parser	   )
r   rA   configuration_files_mapr   	file_namerC   vavailable_versionsconfiguration_fileoptimum_versionr   r   r   get_configuration_filem   s    


z!BaseConfig.get_configuration_filepretrained_model_name_or_pathc                 K   sl   t |}| j|fi |\}}d|v r|d |d< d|v r2| |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.

        _commit_hashrA   _configuration_file)copydeepcopy_get_config_dictrN   )r   rO   r=   original_kwargsconfig_dictrL   r   r   r   get_config_dict   s   

zBaseConfig.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rbtdt |d ur`td|}|du rktd d|d}|d urx||d< t|}tj	
|}tj	tj	||r|}d}nFt|r|}t|}n;| d| j}zt|||||||	|||
||d}t||}W n ty     ty   td| d| d| dw z| |}W n tjtfy   td| dw |rtd|  ||fS td| d |  ||fS )!N	cache_dirforce_downloadFresume_downloadproxiesr!   r"   local_files_onlyrevisiontrust_remote_code	subfolder _from_pipeline
_from_autorP   r#   r$   TzgThe 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_pipelinerQ   )
rX   rY   r[   rZ   r\   r"   
user_agentr]   r_   rP   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 filez"It looks like the config file at 'z' is not a valid JSON file.zloading configuration file z from cache at )r,   r0   r1   r2   r3   r9   warningstrr'   r(   isdirr)   r6   r   r   r7   r   r   EnvironmentError	Exception_dict_from_json_filejsonJSONDecodeErrorUnicodeDecodeErrorr:   )r   rO   r=   rX   rY   rZ   r[   r!   r"   r\   r]   r^   r_   from_pipelinerd   commit_hashrf   is_localresolved_config_filerL   rV   r   r   r   rT      s   

	
zBaseConfig._get_config_dictrV   r   c           
      K   s2  | dd}| dd | dd d|v r d|v r |d |d< | di |}t|dr7dd	 |j D |_d
|v rbd|v rb|d
 }|d durM|d ng }t||krbtd| d|d  dg }| D ]\}}	t||rt|||	 |dkr|| qh|D ]}| |d qt	| |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_kwargsFrb   Nra   rP   pruned_headsc                 S   s   i | ]	\}}t ||qS r   )int).0keyvaluer   r   r   
<dictcomp>*  s    z(BaseConfig.from_dict.<locals>.<dictcomp>
num_labelsid2labelzYou passed along `num_labels=z(` with an incompatible id to label map: zX. Since those arguments are inconsistent with each other, you should remove one of them.torch_dtyper   )
r,   hasattrru   itemslenr3   setattrappendr9   r:   )
r   rV   r=   rt   r%   r{   r|   	to_removerx   ry   r   r   r   	from_dict  s<   



zBaseConfig.from_dictc                 C   s^   t | j}t| jdr| jj|d< d|v r|d= d|v r |d= t|d< t|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.
        
model_typer5   rP   transformers_versionrM   )	rR   rS   __dict__r~   	__class__r   transformers_version_strr	   dict_torch_dtype_to_str)r<   outputr   r   r   to_dictF  s   
zBaseConfig.to_dictN)F)__name__
__module____qualname____doc__r7   r   classmethodr   r   rh   r'   PathLikeboolr@   r   rN   r   r   r   rW   rT   r   r   r   r   r   r   r   %   s0    
: `6r   )r   rR   rm   r'   r   r0   typingr   r   r   r   r   	packagingr   transformersr   r	   r   !transformers.dynamic_module_utilsr
   transformers.utilsr   r   r   r   utilsr   
get_loggerr   r9   r   r   r   r   r   <module>   s    
