U
    0-et!                     @   s   d dl Z d dlZd dlmZ d dlmZ d dlZd dlZd dl	m
Z
 ddlmZmZmZmZmZmZmZmZmZ eddrd dlm  mZ dd	lmZ dd
lmZ eeZdeee  e!e!e"e
dddZ#dddZ$de"dddZ%de"dddZ&dS )    N)Path)List)
GradScaler   )	
MODEL_NAMEOPTIMIZER_NAMERNG_STATE_NAMESCALER_NAMESCHEDULER_NAMEget_pretty_nameis_tpu_availableis_xpu_availablesaveF)Zcheck_device)
get_logger)PartialState)
output_dirmodel_states
optimizers
schedulersprocess_indexscalerc                 C   s  t |D ]R\}}|dkr"t dnt d| d}tj| |}	t||	 td|	  qt |D ]Z\}}
|
 }|dkrt	 dnt	 d| d}tj| |}t|| td|  qdt |D ]Z\}}| }|dkrt
 dnt
 d| d}tj| |}t|| td|  q|dk	r`| }tj| t}t|| td|  i }t d| d	}t |d
< tj |d< t |d< t rtj |d< ntj |d< t rt |d< tj| |}t|| td|  | S )a  
    Saves the current states of the models, optimizers, scaler, and RNG generators to a given directory.

    Args:
        output_dir (`str` or `os.PathLike`):
            The name of the folder to save all relevant weights and states.
        model_states (`List[torch.nn.Module]`):
            A list of model states
        optimizers (`List[torch.optim.Optimizer]`):
            A list of optimizer instances
        schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`):
            A list of learning rate schedulers
        process_index (`int`):
            The current process index in the Accelerator state
        scaler (`torch.cuda.amp.GradScaler`, *optional*):
            An optional gradient scaler instance to save
    r   .bin_zModel weights saved in zOptimizer state saved in zScheduler state saved in NzGradient scaler state saved in .pklrandom_statenumpy_random_seedtorch_manual_seedtorch_xpu_manual_seedtorch_cuda_manual_seedxm_seedzRandom states saved in )	enumerater   ospathjoinr   loggerinfo
state_dictr   r
   r	   torchr   randomgetstatenpZ	get_stateZget_rng_stater   xpuZget_rng_state_allcudar   xm)r   r   r   r   r   r   istateweights_nameZoutput_model_fileoptoptimizer_nameZoutput_optimizer_file	schedulerscheduler_nameZoutput_scheduler_fileZoutput_scaler_filestatesZstates_nameZoutput_states_file r6   Y/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/accelerate/checkpointing.pysave_accelerator_state/   sH    "
"
"

r8   c              	   K   sP  |dkrt d|dkrd}n|dkr.t j}t|D ]T\}}	|dkrPt dnt d| d}
tj| |
}|| jt	j
||d	f| q6td
 t|D ]T\}}|dkrt dnt d| d}tj| |}t	j
||d	}|| | qtd t|D ]L\}}|dkr"t dnt d| d}tj| |}|t	
| qtd |dk	rtj| t}|t	
| td zt	
tj| t d| d}t|d  tj|d  t	|d  t rt	j|d  nt	j|d  t rt|d  td W n  tk
rJ   td Y nX dS )a  
    Loads states of the models, optimizers, scaler, and RNG generators from a given directory.

    Args:
        input_dir (`str` or `os.PathLike`):
            The name of the folder to load all relevant weights and states.
        models (`List[torch.nn.Module]`):
            A list of model instances
        optimizers (`List[torch.optim.Optimizer]`):
            A list of optimizer instances
        schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`):
            A list of learning rate schedulers
        process_index (`int`):
            The current process index in the Accelerator state
        scaler (`torch.cuda.amp.GradScaler`, *optional*):
            An optional *GradScaler* instance to load
        map_location (`str`, *optional*):
            What device to load the optimizer state onto. Should be one of either "cpu" or "on_device".
        load_model_func_kwargs (`dict`, *optional*):
            Additional arguments that can be passed to the model's `load_state_dict` method.
    )Ncpu	on_devicezaUnsupported optimizer map location passed, please choose one of `None`, `'cpu'`, or `'on_device'`Nr9   r:   r   r   r   map_locationz%All model weights loaded successfullyz(All optimizer states loaded successfullyz(All scheduler states loaded successfullyz$GradScaler state loaded successfullyr   r   r   r   r   r   r   z%All random states loaded successfullyzCould not load random states)	TypeErrorr   Zdevicer    r   r!   r"   r#   load_state_dictr'   loadr$   r%   r   r
   r	   r   r(   setstater*   Z	set_stateZset_rng_stater   r+   Zset_rng_state_allr,   r   r-   	Exception)Z	input_dirmodelsr   r   r   r   r<   Zload_model_func_kwargsr.   modelr0   Zinput_model_filer1   r2   Zinput_optimizer_fileZoptimizer_stater3   r4   Zinput_scheduler_fileZinput_scaler_filer5   r6   r6   r7   load_accelerator_statet   sR    "
"
$


 rD   )indexc                 C   sB   t |d| d }tdt|  d|  t|  | dS )zL
    Saves the state of `obj` to `{path}/custom_checkpoint_{index}.pkl`
    Zcustom_checkpoint_r   zSaving the state of z to N)r   r$   r%   r   r'   r   r&   )objr"   rE   Zsave_locationr6   r6   r7   save_custom_state   s    rG   c                 C   sB   | d| d}t dt|  d|  | tj|dd dS )zL
    Loads the state of `obj` at `{path}/custom_checkpoint_{index}.pkl`
    z/custom_checkpoint_r   zLoading the state of z from r9   r;   N)r$   r%   r   r>   r'   r?   )rF   r"   rE   Zload_locationr6   r6   r7   load_custom_state   s    rH   )N)NN)r   )r   )'r!   r(   pathlibr   typingr   numpyr*   r'   Ztorch.cuda.ampr   utilsr   r   r   r	   r
   r   r   r   r   Ztorch_xla.core.xla_modelcoreZ	xla_modelr-   loggingr   r/   r   __name__r$   strdictlistintr8   rD   rG   rH   r6   r6   r6   r7   <module>   s4   ,
	 K  
T
