o
    ߥi#                     @   s   d dl Z d dlmZ d dlmZm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mZ d dlmZ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#m$Z$ e! Z%ed Z&G dd deZ'dS )    N)ABCabstractmethod)AnyDictListOptionalUnion)snapshot_download)Tasks)build_backbonebuild_model)can_load_by_mstry_to_load_hf_model)Config
ConfigDict)DEFAULT_MODEL_REVISIONInvoke	ModelFile)verify_device)
get_logger)register_modelhub_reporegister_plugins_repo)ztorch.Tensorz	tf.Tensorc                
   @   s   e Zd ZdZdd Zdeeef fddZe	deeef fddZ
d	eeef deeef fd
dZedd Zeeddfdedee dedefddZ		ddeeejf deeee f dee fddZdS )ModelzBase model interface.
    c                 O   s$   || _ |dd}t| || _d S )Ndevicegpu)	model_dirgetr   _device_name)selfr   argskwargsdevice_name r"   U/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/models/base/base_model.py__init__   s   
zModel.__init__returnc                 O   s   |  | j|i |S )N)postprocessforwardr   r   r    r"   r"   r#   __call__"   s   zModel.__call__c                 O   s   dS )z
        Run the forward pass for a model.

        Returns:
            Dict[str, Any]: output from the model forward pass
        Nr"   r(   r"   r"   r#   r'   %   s   zModel.forwardinputsc                 K   s   |S )a$   Model specific postprocess and convert model output to
        standard model outputs.

        Args:
            inputs:  input data

        Return:
            dict of results:  a dict containing outputs of model, each
                output should have the standard output name.
        r"   )r   r*   r    r"   r"   r#   r&   /   s   zModel.postprocessc                 K   s   | di |S )a   Define the instantiation method of a model,default method is by
            calling the constructor. Note that in the case of no loading model
            process in constructor of a task model, a load_model method is
            added, and thus this method is overloaded
        Nr"   r"   )clsr    r"   r"   r#   _instantiate<   s   zModel._instantiateNmodel_name_or_pathrevisioncfg_dictr   c                 K   s  | d}|dur|d | tj}|dur|tj ntj}|dd}t|r0|}	n|du r8tddtj|f }t||||d}	t	
d|	  t|	tj}
d}|dur_|}ntj|
rjt|
}t|d	d}d	|v ry|d	}t|d
t }t|drt|ds|j|_t|dd}t|tr|drd|dd  }|dd}|du rt|	||rd}d}|dv rt|	||fi |}|dur|dd}|du r|dur||}|S |du rtdtj d|	|_t| d t!|	| dd |" D ]	\}}|||< q|dur||_#|t$j%u r%d|_&t'|}nt(||d}t|dr5|j)|_)t|ds>||_*|dd ||_+|	|_|S )as  Instantiate a model from local directory or remote model repo. Note
        that when loading from remote, the model revision can be specified.

        Args:
            model_name_or_path(str): A model dir or a model id to be loaded
            revision(str, `optional`): The revision used when the model_name_or_path is
                a model id of the remote hub. default `master`.
            cfg_dict(Config, `optional`): An optional model config. If provided, it will replace
                the config read out of the `model_name_or_path`
            device(str, `optional`): The device to load the model.
            **kwargs:
                task(str, `optional`): The `Tasks` enumeration value to replace the task value
                    read out of config in the `model_name_or_path`. This is useful when the model to be loaded is not
                    equal to the model saved.
                    For example, load a `backbone` into a `text-classification` model.
                    Other kwargs will be directly fed into the `model` key, to replace the default configs.
                use_hf(bool, `optional`):
                    If set to True, it will initialize the model using AutoModel or AutoModelFor* from hf.
                    If set to False, the model is loaded using the modelscope mode.
                    If set to None, the loading mode will be automatically selected.
                ignore_file_pattern(List[str], `optional`):
                    This parameter is passed to snapshot_download
                device_map(str | Dict[str, str], `optional`):
                    This parameter is passed to AutoModel or AutoModelFor*
                torch_dtype(torch.dtype, `optional`):
                    This parameter is passed to AutoModel or AutoModelFor*
                config(PretrainedConfig, `optional`):
                    This parameter is passed to AutoModel or AutoModelFor*
        Returns:
            A model instance.

        Examples:
            >>> from modelscope.models import Model
            >>> Model.from_pretrained('damo/nlp_structbert_backbone_base_std', task='text-classification')
        model_prefetchedNignore_file_patternTz9Expecting model is pre-fetched locally, but is not found.z%s/%s)
user_agentr1   zinitialize model from taskmodel
model_typetyper   cuda   use_hfF>   NT
device_map`z` file not found.pluginsallow_remote)	task_namepipelinecfgr   ),r   popr   KEY
PRETRAINEDospexistsRuntimeErrorr	   loggerinfojoinr   CONFIGURATIONospathr   	from_filegetattrr   hasattrr5   r6   
isinstancestr
startswithr   r   toFileNotFoundErrorr   r   safe_getr   itemsr   r
   backboneinit_backboner   r   r?   r@   name)r+   r-   r.   r/   r   r    
prefetched
invoked_byr1   local_model_dirconfiguration_pathr@   r>   	model_cfgr5   r9   r4   r:   kvr"   r"   r#   from_pretrainedE   s   
*






zModel.from_pretrainedtarget_foldersave_checkpoint_namesconfigc                 K   s   t d)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

            config (Optional[dict], optional):
            The config for the configuration.json, might not be identical with model.config
        z>save_pretrained method need to be implemented by the subclass.)NotImplementedError)r   rb   rc   rd   r    r"   r"   r#   save_pretrained   s   zModel.save_pretrained)NN)__name__
__module____qualname____doc__r$   r   rQ   r   r)   r   r'   r&   classmethodr,   r   r   r   ra   r   rK   PathLiker   dictrf   r"   r"   r"   r#   r      s@    "	
 r   )(rK   os.pathrL   rD   abcr   r   typingr   r   r   r   r    modelscope.hub.snapshot_downloadr	   modelscope.metainfor
   modelscope.models.builderr   r    modelscope.utils.automodel_utilsr   r   modelscope.utils.configr   r   modelscope.utils.constantr   r   r   modelscope.utils.devicer   modelscope.utils.loggerr   modelscope.utils.pluginsr   r   rG   Tensorr   r"   r"   r"   r#   <module>   s    