o
    )jZ                     @   s   d dl 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 d dlZd dlmZ d dlmZ d dlmZm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 e ZG dd deejjZdS )    N)deepcopy)partial)AnyCallableDictListOptionalUnion)version)nn)DataParallelDistributedDataParallel)save_checkpointsave_configurationsave_pretrained)func_receive_dict_inputs)
get_logger   )Modelc                       s   e Zd ZdZd fdd	Zdeeef fddZ			d d
dZ	deeef fddZ
dd Zdd Zdd Zdeedddefdeeejf deeee f dedee def
ddZdd Z  ZS )!
TorchModelz' Base model interface for pytorch

    Nc                    s,   t  j|g|R i | tjj|  d S N)super__init__torchr   Module)selfZ	model_dirargskwargs	__class__ h/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/modelscope/models/base/base_torch_model.pyr      s   zTorchModel.__init__returnc                 O   s<   t | jr| | j|d fi |S | | j|i |S )Nr   )r   forwardpostprocessr   r   r   r    r    r!   __call__   s   
zTorchModel.__call__Tparamsc              	   C   s   t |ttfr
|j}tj|dd dd}|d ur3||vr+d|v r+d}td| d ||v r3|| }td|jj	 d	| d
| d t
| D ]\}}|dr`|||dd  < || qJ|j||d td |S )Nc                 S   s   | S r   r    )Zstoragelocr    r    r!   <lambda>/   s    z-TorchModel._load_pretrained.<locals>.<lambda>T)Zmap_locationZweights_onlyr'   z	Loading: z does not exist, use params.zLoading z model from z, with param key: [z].zmodule.   )strictzload model done.)
isinstancer   r   moduler   loadloggerinfor   __name__r   items
startswithpopZload_state_dict)r   netZ	load_pathr+   Z	param_keyZload_netkvr    r    r!   _load_pretrained&   s4   



zTorchModel._load_pretrainedc                 O   s   t r   )NotImplementedErrorr%   r    r    r!   r#   D   s   zTorchModel.forwardc                 C   s   |    dS )z
        A method executed at the end of each model initialization, to execute code that needs the model's
        modules properly initialized (such as weight initialization).
        N)init_weightsr   r    r    r!   	post_initG   s   zTorchModel.post_initc                 C   s   |  | j d S r   )apply_init_weightsr;   r    r    r!   r:   N   s   zTorchModel.init_weightsc                 C   s   t |tjr|jjjddd |jdur|jj  dS dS t |tjr?|jjjddd |j	dur=|jj|j	   dS dS t |tj
rT|jj  |jjd dS dS )zInitialize the weightsg        g{Gz?)meanZstdNg      ?)r,   r   ZLinearweightdataZnormal_ZbiasZzero_Z	EmbeddingZpadding_idxZ	LayerNormZfill_)r   r-   r    r    r!   r>   R   s   

zTorchModel._init_weightsF)Z	with_metatarget_foldersave_checkpoint_namessave_functionconfigsave_config_functionc                 K   sH   |du rt | dr| j}t| |||fi | |dur"||| dS dS )a  save the pretrained model, its configuration and other related files to a directory,
            so that it can be re-loaded

        Args:
            target_folder (Union[str, os.PathLike]):
            Directory to which to save. Will be created if it doesn't exist.

            save_checkpoint_names (Union[str, List[str]]):
            The checkpoint names to be saved in the target_folder

            save_function (Callable, optional):
            The function to use to save the state dictionary.

            config (Optional[dict], optional):
            The config for the configuration.json, might not be identical with model.config

            save_config_function (Callble, optional):
            The function to use to save the configuration.

        Ncfg)hasattrrG   r   )r   rB   rC   rD   rE   rF   r   r    r    r!   r   b   s   zTorchModel.save_pretrainedc                 K   s@   t tjt dkrtj| fi |S tdtj d | S )zCompile torch model with torch>=2.0

        Args:
            kwargs:
                backend: The backend param of torch.compile
                mode: The mode param of torch.compile
        z	2.0.0.devzFTorch compiling needs torch version >= 2.0.0, your torch version is : z, returns original model)r
   parser   __version__compiler/   warning)r   r   r    r    r!   rK      s   zTorchModel.compiler   )Tr'   )r1   
__module____qualname____doc__r   r   strr   r&   r8   r#   r<   r:   r>   r   r   r   r	   osPathLiker   r   r   dictr   rK   __classcell__r    r    r   r!   r      s:    


%r   ) rQ   copyr   	functoolsr   typingr   r   r   r   r   r	   r   	packagingr
   r   Ztorch.nn.parallelr   r   Zmodelscope.utils.checkpointr   r   r   Zmodelscope.utils.file_utilsr   Zmodelscope.utils.loggerr   Z
base_modelr   r/   r   r   r    r    r    r!   <module>   s    