o
    ߥi/                     @   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)self	model_dirargskwargs	__class__ [/home/ubuntu/.local/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 ur2||vr*d|v r*d}td| d ||v r2|| }td|jj	 d| d	| d
 t
| D ]\}}|dr_|||dd  < || qI|j||d td |S )Nc                 S   s   | S r   r!   )storagelocr!   r!   r"   <lambda>.   s    z-TorchModel._load_pretrained.<locals>.<lambda>)map_locationr(   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popload_state_dict)r   net	load_pathr.   	param_keyload_netkvr!   r!   r"   _load_pretrained&   s0   



zTorchModel._load_pretrainedc                 O   s   t r   )NotImplementedErrorr&   r!   r!   r"   r$   B   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_initE   s   zTorchModel.post_initc                 C   s   |  | j d S r   )apply_init_weightsrB   r!   r!   r"   rA   L   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?)meanstdNg      ?)r/   r   Linearweightdatanormal_biaszero_	Embeddingpadding_idx	LayerNormfill_)r   r0   r!   r!   r"   rE   P   s   

zTorchModel._init_weightsF)	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)hasattrrX   r   )r   rS   rT   rU   rV   rW   r   r!   r!   r"   r   `   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__compiler2   warning)r   r   r!   r!   r"   r\      s   zTorchModel.compiler   )Tr(   )r4   
__module____qualname____doc__r   r   strr   r'   r?   r$   rC   rA   rE   r   r   r   r	   osPathLiker   r   r   dictr   r\   __classcell__r!   r!   r   r"   r      s:    


%r   ) rb   copyr   	functoolsr   typingr   r   r   r   r   r	   r   	packagingr
   r   torch.nn.parallelr   r   modelscope.utils.checkpointr   r   r   modelscope.utils.file_utilsr   modelscope.utils.loggerr   
base_modelr   r2   r   r   r!   r!   r!   r"   <module>   s    