o
    }oi                     @  sR  d Z ddlmZ ddl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 ddlmZmZ ddlmZ ddlmZ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mZm Z  ddl!Z!ddl"Z"ddl#Z#ddl$m%Z%m&Z& ddl$m'Z( ddl$m)Z)m*Z*m+Z+ ddl,m-Z-m.Z. ddl/Z/ddl0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7m8Z8 ddl9m:Z: ddl;m<Z< ddl=m>Z> ddl?m@Z@mAZA g dZBdaCdaDdZEg dZFd;dd ZGd<d#d$ZHd=d'd(ZId)d* ZJd+d, ZKeG d-d. d.ZLG d/d0 d0e
ZMG d1d2 d2e
ZNG d3d4 d4e
ZOeeG d5d6 d6ZPG d7d8 d8eMeNeOe1ZQG d9d: d:ZRdS )>z3Interfaces common to all Neural Modules and Models.    )annotationsN)ABCabstractmethod)MappingSequence)contextmanager)	dataclassfield)Enum)total_ordering)Path)AnyDictListOptionalTupleUnion)_CACHED_NO_EXISTHfApi)	get_token)hf_hub_downloadsnapshot_downloadtry_to_load_from_cache)
DictConfig	OmegaConf)HuggingFaceFileIO) NEMO_DEFAULT_MODEL_CARD_TEMPLATE)SaveRestoreConnector)
NeuralTypeNeuralTypeComparisonResult)logging)maybe_download_from_cloud)resolve_cache_dir)import_class_by_pathmaybe_update_config_version)TypingFileIOModelSerialization	typecheckPretrainedModelInfoT)znemo.collections.z
nemo.core.znemo.utils.znemo.lightning.ztests.collections.z	torch.nn.ztorch.optim.ztorch.utils.data.zlightning.pytorch.callbacks.zlightning.pytorch.loggers.zlightning.pytorch.strategies.zlightning.pytorch.accelerators.z
omegaconf.z	megatron.target_pathstrreturnboolc                   s$   t  tsdS t fddtD S )NFc                 3  s    | ]}  |V  qd S N)
startswith).0prefixr+    L/home/ubuntu/.local/lib/python3.10/site-packages/nemo/core/classes/common.py	<genexpr>R   s    z%_is_target_allowed.<locals>.<genexpr>)
isinstancer,   anyALLOWED_TARGET_PREFIXESr3   r4   r3   r5   _is_target_allowedO   s   
r:   config_noder   c                 C  s   t | tr(d| v r| d }t|std| d|  D ]\}}t| qd S t | tr;t | ts=| D ]
}t| q4d S d S d S )N_target_z Instantiation of unsafe target 'z' is blocked. The '_target_' must point to a class or function within an approved namespace. This restriction is in place to prevent potential arbitrary code execution.)r7   r   r:   
ValueErroritems"_validate_config_targets_recursiver   r,   )r;   r+   keyvalueitemr4   r4   r5   r?   U   s   



r?   configr   c                 O  s*   | durt |  tjj| g|R i |S )z
    A wrapper around hydra.utils.instantiate that first validates all _target_
    fields in the config against an allow-list of prefixes.
    N)r?   hydrautilsinstantiate)rC   argskwargsr4   r4   r5   safe_instantiatef   s   rI   c                   C     t S )z/
    Getter method for typechecking state.
    _TYPECHECK_ENABLEDr4   r4   r4   r5   is_typecheck_enabledp      rM   c                   C  rJ   )z9
    Getter method for typechecking semantics state.
    !_TYPECHECK_SEMANTIC_CHECK_ENABLEDr4   r4   r4   r5   is_semantic_typecheck_enabledw   rN   rQ   c                   @  s   e Zd ZU dZded< ded< eddZded< eddZded	< eddZd
ed< eddZ	ded< eddZ
ded< dd ZdS )TypecheckMetadataaq  
    Metadata class for input/output neural types.

    # Primary attributes
    original_types: Preserve the dictionary of type information provided.

    ignore_collections: For backward compatibility, container support can be disabled explicitly
        using this flag. When set to True, all nesting is ignored and nest-depth checks are skipped.

    # Derived attributed
    mandatory_types: Sub-dictionary of `original_types` which contains only those types which
        are mandatory to include when calling the function.

    base_types: Dictionary of flattened `str: NeuralType` definitions, disregarding the nest level
        details into appropriate arguments.

    container_depth: Dictionary mapping `str: int` - such that the valid depth of the nest of this
        neural type is recorded.

    has_container_types: Bool flag declaring if any of the neural types declares a container nest
        in its signature.

    is_singular_container_type: Bool flag declaring if this is a single Neural Type with a container
        nest in its signature. Required for supporting python list expansion in return statement.

    zDict[str, NeuralType]original_typesr.   ignore_collectionsF)initmandatory_types
base_typeszDict[str, int]container_depthhas_container_typesis_singular_container_typec                 C  s  d}| j  D ]}t|ttfrd} nq|| _| jr&t| j dkr&d| _nd| _| jrpi | _i | _	| j 
 D ]7\}}d}t|ttfrdt|dkrUtd| d| d|d }|d7 }t|ttfsD|| j|< || j	|< q7n| j | _dd	 | j D | _	d
d	 | j
 D | _d S )NFT   r   zNeural Type `z`: z definition contains more than one element when declaring the nested container structure.
Please ensure that you have only 1 NeuralType inside of the entire nested structure definition.c                 S  s   i | ]}|d qS )r   r4   )r1   type_keyr4   r4   r5   
<dictcomp>       z3TypecheckMetadata.__post_init__.<locals>.<dictcomp>c                 S  s   i | ]
\}}|j s||qS r4   )optional)r1   r\   type_valr4   r4   r5   r]      s
    
)rS   valuesr7   listtuplerY   lenrZ   rW   rX   r>   	TypeErrorkeysrV   )selfrY   r`   r\   depthr4   r4   r5   __post_init__   s>   
zTypecheckMetadata.__post_init__N)__name__
__module____qualname____doc____annotations__r	   rV   rW   rX   rY   rZ   ri   r4   r4   r4   r5   rR   ~   s   
 rR   c                   @  sX   e Zd ZdZedddZedddZdd
dZdddZddddZ	ddddZ
dS )r%   z<
    An interface which endows module with neural types
    r-   Optional[Dict[str, NeuralType]]c                 C     dS )z/Define these to enable input neural type checksNr4   rg   r4   r4   r5   input_types      zTyping.input_typesc                 C  rp   )z0Define these to enable output neural type checksNr4   rq   r4   r4   r5   output_types   rs   zTyping.output_typesNFc                 K  s<  |durt ||d}t|}t|j}t||k s t||kr0tdt| d| d| d| D ]\}}||vrHtd| d|  t|d	rt r|j| 	|j
tjtjfvr|| 	|j
 d
d||  d|j
 d| g}	t|j| jj D ]\}
}|	|
d d|
 d|d  d|d   qt|j
jj D ]\}
}|	d|
 d|d  d|d   qtd|	t|dr|j}|j| j}|}|durt|t|krtd| d| jj d|j| j d| q4t|tst|trt|D ]\}}	 | j||d|d q	q4dS dS )a  
        This function does a few things.

        1) It ensures that len(self.input_types <non-optional>) <= len(kwargs) <= len(self.input_types).
        2) For each (keyword name, keyword value) passed as input to the wrapped function:
            - Check if the keyword name exists in the list of valid self.input_types names.
            - Check if keyword value has the `neural_type` property.
                - If it does, then perform a comparative check and assert that neural types
                    are compatible (SAME or GREATER).
            - Check if keyword value is a container type (list or tuple). If yes,
                then perform the elementwise test of neural type above on each element
                of the nested structure, recursively.

        Args:
            input_types: Either the `input_types` defined at class level, or the local function
                overridden type definition.
            ignore_collections: For backward compatibility, container support can be disabled explicitly
                using this flag. When set to True, all nesting is ignored and nest-depth checks are skipped.
            kwargs: Dictionary of argument_name:argument_value pairs passed to the wrapped
                function upon call.
        NrS   rT   z$Number of input arguments provided (z#) is not as expected. Function has z total inputs with z mandatory inputs.zInput argument z? has no corresponding input_type match. Existing input_types = neural_typez :zInput type expected : zInput type found : z
Argument:    z  input param_z : r   z: r[   
shape!Input shape mismatch occured for  in module  : 
Input shape expected =  | 
Input shape found : rh   name)rR   rd   rV   re   r>   rf   hasattrrQ   rW   comparerv   r   SAMEGREATER	enumerateelements_typetype_parametersinsertappendjoinry   axes	__class__rj   r7   rb   rc   _Typing__check_neural_type)rg   rr   rT   rH   metadatatotal_input_typesmandatory_input_typesr@   rA   	error_msgi
dict_tuplevalue_shape
type_shaper   indvalr4   r4   r5   _validate_input_types   st   


,&

zTyping._validate_input_typesc              	   C  s  |durt ||d}t|j }t|j }t|ttfr"|}n|g}|jr)n t|t|ks9t|t|k rIt	d
t|t|t||t|tst|tsz	|d d |_W n	 tye   Y nw t|dr|j}|d d j}	|d d }
|	durt|t|	krt	d|
 d| jj d	|	 d
| dS dS dS |jrd}t|dkrt|tkrd}t|D ]\}}| j||||d d d qdS t|D ]\}}| j||d|| d d qdS dS )a  
        This function does a few things.

        1) It ensures that len(out_object) == len(self.output_types).
        2) If the output is a tensor (or list/tuple of list/tuple ... of tensors), it
            attaches a neural_type to it. For objects without the neural_type attribute,
            such as python objects (dictionaries and lists, primitive data types, structs),
            no neural_type is attached.

        Note: tensor.neural_type is only checked during _validate_input_types which is
        called prior to forward().

        Args:
            output_types: Either the `output_types` defined at class level, or the local function
                overridden type definition.
            ignore_collections: For backward compatibility, container support can be disabled explicitly
                using this flag. When set to True, all nesting is ignored and nest-depth checks are skipped.
            out_objects: The outputs of the wrapped function.
        Nru   a<  Number of output arguments provided ({}) is not as expected. It should be larger or equal than {} and less or equal than {}.
This can be either because insufficient/extra number of output NeuralTypes were provided,or the provided NeuralTypes {} should enable container support (add '[]' to the NeuralType definition)r   r[   ry   "Output shape mismatch occured for r{    : 
Output shape expected =  | 
Output shape found : r~   )rR   rb   rW   r>   rV   r7   rc   rZ   rd   re   formatrv   	Exceptionr   ry   r   r   rj   typer   _Typing__attach_neural_type)rg   out_objectsrT   rt   r   out_types_listmandatory_out_types_listout_containerr   r   r   rh   r   resr4   r4   r5   !_attach_and_validate_output_types<  s^   	 
Xz(Typing._attach_and_validate_output_typesr   rR   rh   intr   r,   c           	   
   C  s$  t |ts
t |tr|D ]}| j|||d |d qdS |j| }|js>||j| kr>td| d| d| d|j|  t|drct	 rc|
|jtjtjfvrct|
|j d	| d
|j t|dr|j}|j}|durt|t|krtd| d| jj d| d| dS dS dS )a  
        Recursively tests whether the obj satisfies the semantic neural type assertion.
        Can include shape checks if shape information is provided.

        Args:
            obj: Any python object that can be assigned a value.
            metadata: TypecheckMetadata object.
            depth: Current depth of recursion.
            name: Optional name used of the source obj, used when an error occurs.
        r[   )r   NzWhile checking input neural types,
Nested depth of value did not match container specification:
Current nested depth of NeuralType '' (): 
Expected nested depth : rv   z : 
Input type expected = z | 
Input type found : ry   rz   r{   r|   r}   )r7   rc   rb   r   rW   rT   rX   re   r   rQ   r   rv   r   r   r   ry   r   rd   r   rj   	rg   objr   rh   r   elemr`   r   r   r4   r4   r5   __check_neural_type  s\   


zTyping.__check_neural_typec           	   
   C  s   t |ts
t |tr|D ]}| j|||d |d qdS |j| }|js>||j| kr>td| d| d| d|j|  z||_W n	 t	yL   Y nw t
|drv|j}|j}|durxt|t|krztd	| d
| jj d| d| dS dS dS )aq  
        Recursively attach neural types to a given object - as long as it can be assigned some value.

        Args:
            obj: Any python object that can be assigned a value.
            metadata: TypecheckMetadata object.
            depth: Current depth of recursion.
            name: Optional name used of the source obj, used when an error occurs.
        r[   r~   NzWhile attaching output neural types,
Nested depth of value did not match container specification:
Current nested depth of NeuralType 'r   r   r   ry   r   r{   r   r   )r7   rc   rb   r   rW   rT   rX   re   rv   r   r   ry   r   rd   r   rj   r   r4   r4   r5   __attach_neural_type  sF   



zTyping.__attach_neural_type)r-   ro   )NF)FNr/   )r   rR   rh   r   r   r,   )rj   rk   rl   rm   propertyrr   rt   r   r   r   r   r4   r4   r4   r5   r%      s    

Xp6r%   c                   @  s2   e Zd ZeddddZdd	d
Zedd ZdS )r(   NrC   'DictConfig'trainerOptional['Trainer']c           
   
   C  s  t rt|trtj|dd}t|}t|d t|}d|v s%d|v r1d|v r1t r1t|d}nd|v r=t r=t|d}nd}d	}d|v r|d }d}z t	|}t
| |rW| }t|}|re|||d
}n||d}W n( ty } zt }	d| d| d|	 }t|d  W Y d}~nd}~ww |du rzt| }|r| ||d
}n| |d}W n ty } z	|rt| |d}~ww t|ds||_|S )z8Instantiates object using DictConfig-based configurationTresolveclstargetparamsrC   r<   N )cfgr   )r   z*Model instantiation failed!
Target class:	z
Error(s):	rx   z
Falling back to `cls`._cfg)
_HAS_HYDRAr7   r   r   to_containercreate
set_structr$   rI   r#   
issubclassr(   _inspect_signature_for_trainerr   	traceback
format_excr    debugerrorr   r   )
r   rC   r   instance
prev_errortarget_cls_pathimported_clsaccepts_traineretbr4   r4   r5   from_config_dict  s^   




	



zSerialization.from_config_dictr-   c                 C  sf   t | dr/| jdur/tr)t| jtr)tj| jdd}t|}t|d t	|}|| _| jS t
d)z3Returns object's configuration to config dictionaryr   NTr   z[to_config_dict() can currently only return object._cfg but current object does not have it.)r   r   r   r7   r   r   r   r   r   r$   NotImplementedError)rg   rC   r4   r4   r5   to_config_dictQ  s   
zSerialization.to_config_dictc                 C  s,   t |drt|j}d|jv rdS dS dS )N__init__r   TF)r   inspect	signaturer   
parameters)r   	check_clsr   r4   r4   r5   r   d  s   

z,Serialization._inspect_signature_for_trainerr/   )rC   r   r   r   )r-   r   )rj   rk   rl   classmethodr   r   r   r4   r4   r4   r5   r(     s    
Ar(   c                   @  sJ   e Zd ZdddZe						ddddZedddZdddZdS )r&   	save_pathr,   c                 C     t  )a5  
        Standardized method to save a tarfile containing the checkpoint, config, and any additional artifacts.
        Implemented via :meth:`nemo.core.connectors.save_restore_connector.SaveRestoreConnector.save_to`.

        Args:
            save_path: str, path to where the file should be saved.
        r   )rg   r   r4   r4   r5   save_toq  s   zFileIO.save_toNTFrestore_pathoverride_config_pathOptional[str]map_locationOptional['torch.device']strictr.   return_configr   r   save_restore_connectorr   c                 C  r   )a  
        Restores model instance (weights and configuration) from a .nemo file

        Args:
            restore_path: path to .nemo file from which model should be instantiated
            override_config_path: path to a yaml config that will override the internal
                config file or an OmegaConf / DictConfig object representing the model config.
            map_location: Optional torch.device() to map the instantiated model to a device.
                By default (None), it will select a GPU if available, falling back to CPU otherwise.
            strict: Passed to load_state_dict. By default True
            return_config: If set to true, will return just the underlying config of the restored
                model as an OmegaConf DictConfig object without instantiating the model.
            trainer: An optional Trainer object, passed to the model constructor.
            save_restore_connector: An optional SaveRestoreConnector object that defines the implementation
                of the restore_from() method.
        r   )r   r   r   r   r   r   r   r   r4   r4   r5   restore_from{  s   zFileIO.restore_frompath2yaml_filec                 C  s&   t | trt|}| j|dS t )z
        Instantiates an instance of NeMo Model from YAML config file.
        Weights will be initialized randomly.
        Args:
            path2yaml_file: path to yaml file with model configuration

        Returns:

        r   )r   r(   r   loadr   r   )r   r   confr4   r4   r5   from_config_file  s   

zFileIO.from_config_filec                 C  sb   t | dr.t| j| _t|ddd}tj| j|dd W d   dS 1 s'w   Y  dS t )z
        Saves current instance's configuration to YAML config file. Weights will not be saved.
        Args:
            path2yaml_file: path2yaml_file: path to yaml file where model model configuration will be saved

        Returns:
        r   wutf-8)encodingT)rC   fr   N)r   r$   r   openr   saver   )rg   r   foutr4   r4   r5   to_config_file  s   
"zFileIO.to_config_file)r   r,   )NNTFNN)r   r,   r   r   r   r   r   r.   r   r.   r   r   r   r   )r   r,   )rj   rk   rl   r   r   r   r   r   r4   r4   r4   r5   r&   p  s    

r&   c                   @  s^   e Zd ZU ded< ded< ded< dZded< dZded	< d
d Zdd Zdd Zdd Z	dS )r*   r,   pretrained_model_namedescriptionlocationNz'Model'class_	List[str]aliasesc                 C  sN   | j j}djdi | j}| jd urdjdd|i| j}| d| d}|S )Nz_pretrained_model_name={pretrained_model_name},
	description={description},
	location={location}z{extras},
	class_={class_}extrasz(
	z
)r4   )r   rj   r   __dict__r   )rg   baser   representationr4   r4   r5   __repr__  s   
zPretrainedModelInfo.__repr__c                 C  s   t | j}|S r/   )hashr   )rg   location_hashr4   r4   r5   __hash__  s   
zPretrainedModelInfo.__hash__c                 C  s   t | t |kp| j|jkS r/   )r   r   rg   otherr4   r4   r5   __eq__  s   zPretrainedModelInfo.__eq__c                 C  s   | j |j k S r/   r   r   r4   r4   r5   __lt__  s   zPretrainedModelInfo.__lt__)
rj   rk   rl   rn   r   r   r   r   r   r   r4   r4   r4   r5   r*     s   
 r*   c                   @  s~   e Zd ZdZeed+ddZed,ddZe			
	
				
	
		d-d.ddZed/d0dd Z	ed/d0d!d"Z
	
d1d2d)d*Zd
S )3r'   z[
    Abstract class offering interface which should be implemented by all NeMo models.
    r-   #Optional[List[PretrainedModelInfo]]c                 C  rp   )aj  
        Should list all pre-trained models available via NVIDIA NGC cloud.
        Note: There is no check that requires model names and aliases to be unique. In the case of a collision,
        whatever model (or alias) is listed first in the this returned list will be instantiated.

        Returns:
            A list of PretrainedModelInfo entries
        Nr4   )r   r4   r4   r5   list_available_models  s   zModel.list_available_modelsr   c                 C  s&   g }|   durdd |   D }|S )z
        Returns the list of model names available via NVIDIA NGC cloud,
        to get the complete model description use list_available_models()
        Returns:
            A list of model names
        Nc                 S  s   g | ]}|j qS r4   r   )r1   modelr4   r4   r5   
<listcomp>  r^   z3Model.get_available_model_names.<locals>.<listcomp>)r  )r   model_namesr4   r4   r5   get_available_model_names  s   zModel.get_available_model_namesFNT
model_namer,   refresh_cacher.   r   r   r   r   r   r   r   r   r   r   return_model_fileOptional[bool]c
              	   C  sr   |du rt  }d|v r| j||d\}
}tj|r||_n	| j||d\}
}|	r+|S |
j|||||||d}|S )a  
        Instantiates an instance of NeMo from NVIDIA NGC cloud
        Use restore_from() to instantiate from a local .nemo file.
        Args:
            model_name: string key which will be used to find the module.
            refresh_cache: If set to True, then when fetching from cloud, this will re-fetch the file
                from cloud even if it is already found in a cache locally.
            override_config_path: path to a yaml config that will override the internal
                config file
            map_location: Optional torch.device() to map the instantiated model to a device.
                By default (None), it will select a GPU if available, falling back to CPU otherwise.
            strict: Passed to torch.load_state_dict. By default true.
            return_config: If set to true, will return just the underlying config of the restored
                model as an OmegaConf DictConfig object without instantiating the model.
            return_model_file: If set to true, will return just the downloaded model file in cache

        Returns:
            A model instance of a particular model class or its underlying config (if return_config is set).
        N/)r  r  )r   r   r   r   r   r   r   )r   !_get_hf_hub_pretrained_model_infoospathisdirmodel_extracted_dir_get_ngc_pretrained_model_infor   )r   r  r  r   r   r   r   r   r   r	  r   nemo_model_file_in_cacher   r4   r4   r5   from_pretrained  s0    

	zModel.from_pretrainedTuple[type, str]c                 C  s  d}d}d}|   }|dur?|   D ],}d}|j|krd}n|jdur1|jD ]
}	|	|kr0d} nq&|r>|j}|j}|j} nq|du rKtd| d|dd }
||
d}t	
t |
dd	  }t|| d
 }t||
|||d}td |du r| }||fS )a  
        Resolve the NGC model pretrained information given a model name.
        Assumes the model subclass implements the `list_available_models()` inherited method.

        Args:
            model_name: Str name of the model. Must be the original name or an alias of the model, without any '/'.
            refresh_cache: Bool, determines whether cache must be refreshed (model is re-downloaded).

        Returns:
            A tuple of details describing :
            -   The resolved class of the model. This requires subclass to implement PretrainedModelInfo.class_.
                If the class cannot be resolved, default to the class that called this method.
            -   The path to the NeMo model (.nemo file) in some cached directory.
        NFTzModel zW was not found. Check cls.list_available_models()
for the list of all available models.r  r   r   )urlfilename	cache_dir	subfolderr  z/Instantiating model from pre-trained checkpoint)r  r   r   r   r   r   FileNotFoundErrorsplitreplacer   joinpathr"   hashlibmd5encode	hexdigestr!   r    info)r   r  r  location_in_the_cloudr   r   modelspretrained_model_infofoundaliasr  r  r  cache_subfolderr  r4   r4   r5   r  A  sH   





z$Model._get_ngc_pretrained_model_infoc              
   C  s  | dd d }|st||d}|dur|tur| |fS t }t|d}|j||dd}|r>t||d	tj||d
}| |fS |j	||dd}t
t d| }	g }
|jD ]}|j }d|vscd|vri|
|j qTt|
}
d|
}
t|
d }
tj|	|
}tj|	rtt|	}|dkrtd||	 td| d t j!|	dd tj|std| d|  tj"|dd t#|d	tj|||d|d}| |fS )a  
        Resolve the HuggingFace Hub model pretrained information given a model name.
        The model name must be of general syntax ``{source_repo}/{model_name}``.

        Note:
            The ``{source_repo}`` need not be ``nvidia``, it can be any public repository, even external to Nvidia.
            This allows public, externally contributed models to be run freely using Nvidia NeMo.

        Args:
            model_name: Str name of the model. Must be the original name or an alias of the model, without any '/'.
            refresh_cache: Bool, determines whether cache must be refreshed (model is re-downloaded).

        Returns:
            A tuple of details describing :
            -   The resolved class of the model. Since the source is external to NeMo, always default to using
                the calling class. Depend on target class resolution by restore_from() for calling the correct class.
            -   The path to the NeMo model (.nemo file) in some cached directory (managed by HF Hub).
        r  r  z.nemo)repo_idr  N)tokenr  )r*  r  	repo_typenemo)r*  r  library_namelibrary_versionforce_downloadr+  T)r*  r+  files_metadatahf_hub_cachereadmegitr   r   r   z$Found {} files in cache directory {}z(Deleting old cache directory for model `z#` in order to prevent duplicates...)ignore_errorszDownloading z from HuggingFace Hub to path: )exist_okF)r*  r.  r/  r0  r  	local_dirlocal_dir_use_symlinksr+  )$r  r   r   get_hf_tokenr   file_existsr   r-  __version__	repo_infor   r  r"   siblings	rfilenamelowerr   blob_idsortedr   r  r   r!  r"  r  r  existsrd   listdirr    r#  r   shutilrmtreemakedirsr   )r   r  r  resolved_model_filenamer  hf_tokenapinemo_file_existsr<  r  r)  siblingr  r   num_files_in_dirr4   r4   r5   r  {  sh   
6



z'Model._get_hf_hub_pretrained_model_infohfr   templatetemplate_kwargsOptional[Dict[str, str]]objectc                 C  sD   |du r	t t}|du ri }|dkr| j||dS td| d)z
        Generates a ModelCard for the current model. This method is called when pushing the model to the Hub.

        Returns:
            An object that can be represented as a str representation of the model card, usually in Markdown format.
        NrM  )rN  rO  zModel card type z not supported.)copydeepcopyr   _get_hf_model_cardr=   )rg   r   rN  rO  r4   r4   r5   generate_model_card  s   	
zModel.generate_model_card)r-   r  )r-   r   )FNNTFNNF)r  r,   r  r.   r   r   r   r   r   r.   r   r.   r   r   r   r   r	  r
  )F)r  r,   r  r.   r-   r  )rM  NN)r   r,   rN  r,   rO  rP  r-   rQ  )rj   rk   rl   rm   r   r   r  r  r  r  r  rU  r4   r4   r4   r5   r'     s.    B9`r'   c                   @  s   e Zd ZdZG dd deZejejdfd"d
dZdd Zdd Z	e
jedd#ddZed$d%ddZeedd Zed$d%ddZeedd Zed$d%dd Zd!S )&r)   a  
    A decorator which performs input-output neural type checks, and attaches
    neural types to the output of the function that it wraps.

    Requires that the class inherit from :class:`~nemo.core.Typing` in order to perform
    type checking, and will raise an error if that is not the case.

    # Usage (Class level type support)

    .. code-block:: python

        @typecheck()
        def fn(self, arg1, arg2, ...):
            ...

    # Usage (Function level type support)

    .. code-block:: python

        @typecheck(input_types=..., output_types=...)
        def fn(self, arg1, arg2, ...):
            ...

    Points to be noted:

    1) The brackets () in `@typecheck()` are necessary.

        You will encounter a TypeError: __init__() takes 1 positional argument but X
        were given without those brackets.

    2) The function can take any number of positional arguments during definition.

        When you call this function, all arguments must be passed using kwargs only.

    c                   @  s   e Zd ZdZdZdS )ztypecheck.TypeStatez
        Placeholder to denote the default value of type information provided.
        If the constructor of this decorator is used to override the class level type definition,
        this enum value indicate that types will be overridden.
        r   N)rj   rk   rl   rm   UNINITIALIZEDr4   r4   r4   r5   	TypeState  s    rW  Frr   'Union[TypeState, Dict[str, NeuralType]]rt   rT   r.   c                 C  sJ   || _ || _|| jjkrd| _nd| _|| jjkrd| _nd| _|| _d S )NFT)rr   rt   rW  rV  input_overrideoutput_overriderT   )rg   rr   rt   rT   r4   r4   r5   r   !  s   
ztypecheck.__init__c                 C  s
   |  |S r/   )wrapped_callrg   wrappedr4   r4   r5   __call__6  s   
ztypecheck.__call__c                 C  s   |S r/   r4   r\  r4   r4   r5   unwrapped_call9  s   ztypecheck.unwrapped_callenabledr   r%   c                 C  s  |du rt dt|tst dt|dst|drt d| jtjju r*|j| _| jtjju r5|j| _| j	r<| j}n|j}| j
rF| j}n|j}|du rX|du rX||i |S |durft|dkrftd|jd
|| jd| ||i |}|j|| j|d	 |S )a  
        Wrapper method that can be used on any function of a class that implements :class:`~nemo.core.Typing`.
        By default, it will utilize the `input_types` and `output_types` properties of the class inheriting Typing.

        Local function level overrides can be provided by supplying dictionaries as arguments to the decorator.

        Args:
            input_types: Union[TypeState, Dict[str, NeuralType]]. By default, uses the global `input_types`.
            output_types: Union[TypeState, Dict[str, NeuralType]]. By default, uses the global `output_types`.
            ignore_collections: Bool. Determines if container types should be asserted for depth checks, or
                if depth checks are skipped entirely.

        NzDOnly classes which inherit nemo.core.Typing can use this decorator !input_portsoutput_portsziTyping requires override of `input_types()` and `output_types()`, not `input_ports() and `output_ports()`r   z=All arguments must be passed by kwargs only for typed methods)rr   rT   )rt   rT   r   r4   )RuntimeErrorr7   r%   r   rr   r)   rW  rV  rt   rY  rZ  rd   re   r   rT   r   )rg   r]  r   rG   rH   rr   rt   outputsr4   r4   r5   r[  <  s8   
ztypecheck.wrapped_callTra  c                 C     | a dS )z
        Global method to enable/disable typechecking.

        Args:
            enabled: bool, when True will enable typechecking.
        NrK   r`  r4   r4   r5   set_typecheck_enabled}     	ztypecheck.set_typecheck_enabledc                	   c  6    t jdd zdV  W t jdd dS t jdd w )z]
        Context manager that temporarily disables type checking within its context.
        Fr`  NT)r)   rg  r4   r4   r4   r5   disable_checks  
   ztypecheck.disable_checksc                 C  rf  )z
        Global method to enable/disable semantic typechecking.

        Args:
            enabled: bool, when True will enable semantic typechecking.
        NrO   r`  r4   r4   r5   set_semantic_check_enabled  rh  z$typecheck.set_semantic_check_enabledc                	   c  ri  )zf
        Context manager that temporarily disables semantic type checking within its context.
        Fr`  NT)r)   rl  r4   r4   r4   r5   disable_semantic_checks  rk  z!typecheck.disable_semantic_checksc                 C  s6   t |  | rtjjjj jt _d S tjjjj jt _d S r/   )	r)   rg  r-  coreclassescommonr[  r^  r_  r`  r4   r4   r5   enable_wrapping  s   
ztypecheck.enable_wrappingN)rr   rX  rt   rX  rT   r.   )r   r%   )T)ra  r.   )rj   rk   rl   rm   r
   rW  rV  r   r^  r_  wrapt	decoratorrM   r[  staticmethodrg  r   rj  rl  rm  rq  r4   r4   r4   r5   r)     s.    $
@



r)   )r+   r,   r-   r.   )r;   r   )rC   r   )Srm   
__future__r   rR  r  r   r  rD  r   abcr   r   collections.abcr   r   
contextlibr   dataclassesr   r	   enumr
   	functoolsr   pathlibr   typingr   r   r   r   r   r   rD   torchrr  huggingface_hubr   r   r   r9  r   r   r   	omegaconfr   r   r-  $nemo.core.classes.mixins.hf_io_mixinr   %nemo.core.config.templates.model_cardr   +nemo.core.connectors.save_restore_connectorr   nemo.core.neural_typesr   r   
nemo.utilsr    nemo.utils.cloudr!   nemo.utils.data_utilsr"   nemo.utils.model_utilsr#   r$   __all__rL   rP   r   r9   r:   r?   rI   rM   rQ   rR   r%   r(   r&   r*   r'   r)   r4   r4   r4   r5   <module>   sp    



V  ;bI$  