o
    *jh                     @   s  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 d dlmZm	Z	m
Z
 d dlmZmZmZmZ d dlZd dlZd dl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! d dl"m#Z# d dl$m%Z% e# Z&e Z'dd Z(					d'dejj)de*dee dee dee+ de,de,ddfddZ-		d(dedefddZ.		d(ddZ/defd d!Z0		d(d"ee*ej1f d#e*d$efd%d&Z2dS ))    N)OrderedDict)copytreeignore_patternsrmtree)CallableDictOptionalUnion)nn)	Optimizer)_LRScheduler)FileLocalStorage)ConfigJSONIteratorEncoder)ConfigFields	ModelFile)copytree_py37)
get_logger)	is_masterc                 C   s8   t  }|  D ]
\}}| ||< qt| dt  |_|S )zCopy a model state_dict to cpu.

    Args:
        state_dict (OrderedDict): Model weights on GPU.

    Returns:
        OrderedDict: Model weights on GPU.
    	_metadata)r   itemscpugetattrr   )
state_dictZstate_dict_cpukeyval r   \/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/modelscope/utils/checkpoint.pyweights_to_cpu   s
   	r   Tmodelfilename	optimizerlr_schedulermeta	with_meta
with_modelreturnc                 C   s  i }|s
|s
t d|r|du ri }nt|ts!tdt| ddlm} |j|t	 d t| t
jjjr;| j} t| drL| jdurL|j| jd ||d	< t|tr\| |d
< nt|trvi |d
< | D ]\}	}
|
 |d
 |	< qi|durt|dr| |d< |rt| t
jjjr| j} t|  }|s|}n||d< t }t
|| t| | W d   dS 1 sw   Y  dS )af  Save checkpoint to file.

    The checkpoint will have 3 fields: ``meta``, ``state_dict`` and
    ``optimizer``. By default, ``meta`` will contain version and time info.

    Args:
        model (Module): Module whose params are to be saved.
        filename (str): Checkpoint filename.
        optimizer (:obj:`Optimizer`, optional): Optimizer to be saved.
        lr_scheduler(:obj:`_LRScheduler`, optional): LRScheduler to be saved.
        meta (dict, optional): Metadata to be saved in checkpoint.
        with_meta (bool, optional): Save meta info.
        with_model(bool, optional): Save model states.
    z;Save meta by "with_meta=True" or model by "with_model=True"Nz%meta must be a dict or None, but got r   )__version__)
modelscopetimeCLASSES)r+   r$   r"   r   r#   )
ValueError
isinstancedict	TypeErrortyper)   r(   updater*   asctimetorchr
   ZparallelZDistributedDataParallelmodulehasattrr+   r   r   r   r   ioBytesIOsaver   writegetvalue)r    r!   r"   r#   r$   r%   r&   
checkpointr(   nameZoptimZ_weightsfr   r   r   save_checkpoint/   sL   



"r>   c           	      C   s  t j| std|  dtj| ddd}|d ur]d|v rUt|tr+||d  n2t|t	rT|d }|
 D ]\}}||v rH|||  q8td| d|   q8ntd	|   |d urud
|v rm||d
  ntd|   |d urd|vr|n|d }|| |di S )NzCheckpoint file z does not exist!r   TZmap_locationZweights_onlyr"   zThe state dict of optimizer z% cannot be found in checkpoint file: z@The state dict of optimizer cannot be found in checkpoint file: r#   zCThe state dict of lr_scheduler cannot be found in checkpoint file: r   r$   )ospathexistsr,   r3   loadr-   r   Zload_state_dictr.   r   loggerwarningget)	r!   r    r"   r#   r;   Zoptimizer_dictr   Zoptimizer_insr   r   r   r   load_checkpointv   s>   


rG   c                    s   dd  dd 	ddd fdd	}		
	
ddd	
ddddfdd	}t j|tj}tj|ddd}|durFt| || ||ddd\}	}
}}t	ddd
re|| 	dj
 | |	|
||dS )a{  
    Load model checkpoint file and feed the parameters into the model.
    Args:
        model_to_load: The model to be load
        model_local_dir: The actual checkpoint dir on local disk.
        default_dtype: Set the default float type by 'torch.set_default_dtype'
        load_state_fn: An optional load_state_fn used to load state_dict into the model.

    Returns:

    c           	      S   s   t  }|  D ](\}}||v r+d||g}|||< || tt|t|g }q|||< qg }t|dkr<| }|||fS )N.r   )r   r   joinremovelistsetlencopy)	state_dictshead_prefix!expected_keys_without_head_prefixmissing_keysZnew_state_dictr<   r4   Zname_with_headmissing_head_keysr   r   r   _add_head_prefix_to_state_dict   s   


zBload_task_model_checkpoint.<locals>._add_head_prefix_to_state_dictc                 S   s   g }|rF|D ]?}|}	|r| d| }	n|r"d |ddd  }	|	|v rE||	 j}
| | j}||
krE||| | j||	 jf | |= q|S )NrH      )rI   splitshapeappend)rO   model_state_dictZloaded_keysprefixadd_prefix_to_modelremove_prefix_from_modelignore_mismatched_sizesZmismatched_keyZcheckpoint_keyZ	model_keyZmodel_shapeZcheckpoint_shaper   r   r   _find_mismatched_keys   s(   	


z9load_task_model_checkpoint.<locals>._find_mismatched_keysNc           
         s   g }g }  D ]$}d }d|v r|dd}d|v r |dd}|r,|| || qt||D ]\}	}|	|< q2tdd  d urO_g  |d ura|| ||d  d  S ddtj	f fd	d
| |d  S )Ngammaweightbetabiasr   )rZ   head_prefix_keyslocal_metadata
error_msgs r4   c                    sn   d u ri n	 |d d i }||dg g  f}| j|  | j D ]\}}|d ur4||| d  q#d S )NTrH   )rF   Z_load_from_state_dictZ_modulesr   )r4   rZ   rd   argsr<   childre   rC   metadatar   r   r   rC     s   
zMload_task_model_checkpoint.<locals>._load_state_dict_into_model.<locals>.loadrZ   )rf   )
keysreplacerX   zippopr   rN   r   r
   Module)
r    r   start_prefixrc   load_state_fnZold_keysZnew_keysr   Znew_keyold_keyr   rj   r   _load_state_dict_into_model   s@   


z?load_task_model_checkpoint.<locals>._load_state_dict_into_modelc           $         s  |   }t| }t| }| jtdkr0tfdd|D }tfdd|D }	nd}d}	| o8|	}
|o=|	 }|
rSfdd|D  fdd|D }n|r`fd	d|D }g  tt|t| }tt|t| }| j}g }g }g }t }t }t|dkrt|dkrt	|t
r|g}|D ]tfd
d|D |< q|D ]fdd|D }|| ||< qtt|t| }tt|t| }dd }dd }|d ur|D ]fdd|D }q|d ur|D ]fdd|D }q|r| |||
d}|D ]}| | qt }t|dkrA|D ]}|| s?|||| |\}}}|||< q(d}| }t }t| jdkr_t| | js_|r_| jd }t| jdkrt| | jr|st| | j}|D ]
}t| |||< qyt fdd|D rtd|||||
|}||||}t|dkr|D ]} ||  || d |}!||! qt|dkrd|}"td| jj d|" t|dkrtd| jj d| d| jj d| jj d	 n&t|dkrtd| jj d| d| jj d ntd| jj d  t|dkr6td!| jj d"| d# nt|dkrMtd$| jj d%| jj d& t|dkrld'd(d |D }#td!| jj d)|# d# ||||fS )*Nr   c                 3       | ]}|  V  qd S N
startswith.0srl   r   r   	<genexpr>'      

zGload_task_model_checkpoint.<locals>._load_checkpoint.<locals>.<genexpr>c                 3   rv   rw   rx   rz   rl   r   r   r}   )  r~   Fc                    s   g | ]	}|  s|qS r   rx   rz   rl   r   r   
<listcomp>4  s
    
zHload_task_model_checkpoint.<locals>._load_checkpoint.<locals>.<listcomp>c                    s2   g | ]}|  rd |d dd n|qS rH   rU   Nry   rI   rV   rz   rl   r   r   r   7  s    $c                    s   g | ]	}d   |gqS )rH   )rI   rz   rl   r   r   r   =  s    c                 3   rv   rw   rx   rz   prefix_headr   r   r}   R  r~   c                    s.   g | ]}|  rd |d dd qS r   r   rz   r   r   r   r   V  s    _keys_to_ignore_on_load_missing"_keys_to_ignore_on_load_unexpectedc                        g | ]}t  |d u r|qS rw   researchr{   kpatr   r   r   m      c                    r   rw   r   r   r   r   r   r   s  r   )rZ   
add_prefixremove_prefixrf   rH   c                 3   s    | ]}| v V  qd S rw   r   r{   r   )%expected_keys_not_base_model_prefixedr   r   r}     s    zjThe state dictionary of the model you are trying to load is corrupted. Are you sure it was properly saved?z
	z#Error(s) in loading state_dict for z:
	zESome weights of the model checkpoint were not used when initializing z: z,
- This IS expected if you are initializing z from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForTokenClassification model from a BertForPreTraining model).
- This IS NOT expected if you are initializing z from the checkpoint of a model that you expect to be exactly identical (initializing a BertForTokenClassification model from a BertForTokenClassification model).z0
- This IS Not expected if you are initializing z from the checkpoint of a model with a same task while the structure is different (e.g. initializing a BertForTokenClassification model from a BertForTokenClassification model).z9All model checkpoint weights were used when initializing z.
zSome weights of zK were not initialized from the model checkpoint and are newly initialized: zo
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.zAll the weights of z were initialized from the model checkpoint If your task is similar to the task the model of the checkpoint was trained on, you can already use z* for predictions without further training.
c              	   S   s*   g | ]\}}}d | d| d| dqS )z- z: found shape z in the checkpoint and z in the model instantiatedr   )r{   r   Zshape1Zshape2r   r   r   r     s    zl were not initialized from the model checkpoint and are newly initialized because the shapes did not match:
)r   rK   rm   Zbase_model_prefixrM   anyrL   rP   r.   r-   strextendrp   Z_init_weightsr5   r   r,   rI   RuntimeError	__class____name__rD   rE   info)$r    r   rs   r]   
_fast_initrY   Zexpected_keysZkeys_from_pretrainedZpretrained_has_prefix_moduleZmodel_expects_prefix_moduler\   r[   rR   unexpected_keysZprefix_headsZ&expected_head_keys_without_head_prefixrS   Zunexpected_head_keysZpretrained_has_prefix_headrc   rQ   r   r   Zuninitialized_modulesr4   Zmissing_head_keys_by_headrP   rr   model_to_loadZheads_to_loadmismatched_keysre   headZlocal_error_msgs	error_msgZmismatched_warning)rT   r^   ru   kwargsretrieve_modules_from_names)r   r   rZ   r   r   _load_checkpoint  s  














	
	
z4load_task_model_checkpoint.<locals>._load_checkpointFc           	      S   s   t dd |D }|t dd |D }g }|  D ]4\}}|r5||r2d|ddd  n|}n|rFt|dkrDd||gn|}||v rO|| q|S )Nc                 S   s$   g | ]}d  |d dd qS )rH   Nrg   )rI   rV   r   r   r   r   r     s   $ zSload_task_model_checkpoint.<locals>.retrieve_modules_from_names.<locals>.<listcomp>c                 S   s0   g | ]}|d    rd|ddd qS )rg   rH   N)isdigitrI   rV   r   r   r   r   r     s    
rH   rU   r   )rL   unionZnamed_modulesry   rI   rV   rM   rX   )	r    namesrZ   r   r   Zmodule_keysZretrieved_modulesr<   r4   r   r   r   r     s*   
z?load_task_model_checkpoint.<locals>.retrieve_modules_from_namesc                 S   s   |rt |j | _n|j| _t| dd d ur1t j| jjd| jj	d | jj	d  fdd| j_t
| drAt
|drC|j| _d S d S d S )Nrb   r   Zconstantout_featuresnum_embeddings)r
   	Parameterr`   cloner   Z
functionalpadrb   datarW   r5   r   r   )output_embeddingsinput_embeddingsZtorchscriptr   r   r   _tie_or_clone_weights  s*   

z9load_task_model_checkpoint.<locals>._tie_or_clone_weightsc                    s6   |r| j  }|d ur| j } || d S d S d S rw   )r   Zget_output_embeddingsencoderZget_input_embeddings)r    tie_word_embeddingsr   r   )r   r   r   tie_weights  s   

z/load_task_model_checkpoint.<locals>.tie_weightsr   Tr?   )rs   r]   r   r   r   )r    rR   r   r   re   rw   )NFF)F)r@   rA   rI   r   ZTORCH_MODEL_BIN_FILEr3   rC   Zset_default_dtyper   rF   r   )r   Zmodel_local_dirZdefault_dtypers   r   r   r   Z	ckpt_filer   rR   r   r   re   r   )rT   r^   ru   r   r   r   r   load_task_model_checkpoint   s@   #
6 T


r   configc                 C   sd   t |tr	| }tj|vrd|tj i|tj< tj|dtd}t	j
| tj}t| | d S )Nr0      )indentcls)r-   r   to_dictr   Zpipelinetaskjsondumpsr   r@   rA   rI   r   CONFIGURATIONstorager9   encode)target_folderr   Zcfg_strconfig_filer   r   r   save_configuration>  s   

r   r   save_checkpoint_namesave_functionc           
   
   K   s  |du s	t |tstd|du stj|rtd| d|du r'tdtj||}|g}t|}|	t
j |	d |	d t| drh| jdurht rhtjjd	kr[t}nt}|| j|t| d
d z|| |fi | W dS  ty }	 ztdt|	j d|	 dd}	~	ww )a  save the pretrained model, its configuration and other related files to a directory, so that it can be re-loaded

    Args:
        model (Model): Model whose params are to be saved.

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

        save_checkpoint_name (str):
        The checkpoint name to be saved in the target_folder

        save_function (Callable):
        The function to use to save the state dictionary.
    Nz'A valid save function must be passed inzProvided path (z#) should be a directory, not a filez6At least pass in one checkpoint name for saving methodz*.safetensorsz.*	model_dir   T)ignoredirs_exist_okz)During saving checkpoints, the error of "z
 with msg z thrown)r-   r   	Exceptionr@   rA   isfiler,   rI   rL   addr   r   r5   r   r   sysversion_infominorr   r   r   r0   r   )
r    r   r   r   r   Zoutput_ckpt_pathZorigin_file_to_be_ignoredZignore_file_setZcopytree_funcer   r   r   save_pretrainedH  sN   


r   )NNNTT)NN)3r6   r@   r   r   r*   collectionsr   shutilr   r   r   typingr   r   r   r	   r   r3   r
   Ztorch.optimr   Ztorch.optim.lr_schedulerr   Zmodelscope.fileior   r   Zmodelscope.utils.configr   r   Zmodelscope.utils.constantr   r   Zmodelscope.utils.file_utilsr   Zmodelscope.utils.loggerr   Zmodelscope.utils.torch_utilsr   rD   r   r   rq   r   r.   boolr>   rG   r   r   PathLiker   r   r   r   r   <module>   s   
I
+
   "