o
    ॵi                     @   s   d dl Z d dl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 d dlmZ d dlmZ d d	lmZ eje	jd
G dd deZdS )    N)Optional)version)Hooks)HOOKS)CheckpointProcessor)Hook)Priority)
get_logger)module_namec                   @   sv   e Zd ZdZejZdZdZ			dde	e
 de	e de	e fd	d
Zdd Zdd Zedd Ze		dddZdS )LoadCheckpointHooka  Load a checkpoint file at the beginning of training or evaluating.

    This hook does not need to be configured or saved in the config file.
    User should use it by:
    >>> trainer.train('some-checkpoint', load_all_state=True)
    or
    >>> trainer.evaluate('some-checkpoint')
    instead.

    Args:
        checkpoint_file (str): The checkpoint file to be loaded.
        load_all_state (bool): Load all states(optimizer, epoch, lr_scheduler, random_state, etc.) when loading old
            training state file or not. The model's state dict will only be loaded if False.
        strict (bool): If strict, any unmatched keys will cause an error.
    Fz1.3.1NTcheckpoint_fileload_all_statestrictc                 C   s*   || _ d | _d| _|| _|| _t | _d S )NF)r   	rng_stateneed_load_rng_stater   r   r   	processor)selfr   r   r    r   m/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/trainers/hooks/checkpoint/load_checkpoint_hook.py__init__+   s   zLoadCheckpointHook.__init__c                 C   sX   t |ds
t | _n|j| _| jd ur*| | j|| j| j}|d| _| j| _	d S d S )Nloggerr   )
hasattrr	   r   r   load_checkpointr   r   getr   r   )r   trainermetar   r   r   
before_run8   s   



zLoadCheckpointHook.before_runc                 C   s   | j r>| jd ur6t| jd  tj| jd  tj| jd  tj	 r1tjj
| jd  d| _ d S | jd d S d S )NrandomnumpycpucudaFzlRandom state cannot be found in checkpoint file, this may cause a random data order or model initialization.)r   r   r   setstatenp	set_statetorchset_rng_stater    is_availableset_rng_state_allr   info)r   r   r   r   r   before_train_iterD   s   


z$LoadCheckpointHook.before_train_iterc                 C   s   | d| j| _| d| j| _| d| j| _d}| jD ]5}t|drRt|ddrR|j d| }||v r@|| |i  n| j	
d	|j d
| d |d7 }qd S )Nepochiter
inner_iterr   load_state_dict_should_saveT-zThe state_dict of hook z
 at index z% is not found in the checkpoint file.   )r   _epoch_iter_inner_iterhooksr   getattr	__class__r-   r   warning)r   r   ihookkeyr   r   r   _restore_training_stateS   s"   
z*LoadCheckpointHook._restore_training_statec                 C   s   |  j ||||}|r| || |durG|d}|dur5t|ttjk r5|j	dtj d |j
d| d|d d|  |S )	a  A static method to load checkpoint files.

        Args:
            filename(str): An absolute model bin file(pth or bin) or a dir path with a file prefix(like epoch_1).
            trainer(`EpochBasedTrainer`): The trainer instance.
            load_all_state(`bool`): Load all states including the trainer states.
            strict(`bool`): Load module state dict strictly.

        Returns:
            A dict containing the train states saved by `_create_training_state`
        N
modelscopezPThe unique pth file is split into a model file and a trainer file since version zd,consider re-training your model or using a converting script to split the single pth file into two.zCheckpoint z saving time: timez, modelscope version: )r   load_checkpointsr;   r   r   parser   _TWO_PTH_FILE_VERSIONr   r7   r(   )clsfilenamer   r   r   r   _versionr   r   r   r   f   s.   
z"LoadCheckpointHook.load_checkpoint)NTF)TF)__name__
__module____qualname____doc__r   HIGHPRIORITYr.   r@   r   strboolr   r   r)   staticmethodr;   classmethodr   r   r   r   r   r      s.    

r   )r   typingr   r   r"   r$   	packagingr   modelscope.metainfor   !modelscope.trainers.hooks.builderr   9modelscope.trainers.hooks.checkpoint.checkpoint_processorr   modelscope.trainers.hooks.hookr   "modelscope.trainers.hooks.priorityr   modelscope.utils.loggerr	   register_moduler   r   r   r   r   <module>   s   