o
    i e#                     @   sd   d Z ddlZddlm  mZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ dZG dd	 d	ZdS )
zTraining state management.    N)backend)distributed_file_utils)	mode_keys)%support_on_demand_checkpoint_callback   c                   @   sP   e Zd ZdZdZdZ		dddZddd	Zd
d Zdd Z	dd Z
dd ZdS )WorkerTrainingStatea  Training state management class.

    This class provides apis for backing up and restoring the training state.
    This allows model and epoch and batch information to be saved periodically
    and restore for fault-tolerance, also known as preemption-recovery purpose.
    epochNc                 C   s*  |ot |j| _|| _|| _tjtj| jtj	ddd| _
tjtj| jtj	ddd| _t| j
| j t| j| j tjj| j| j
| j| jjd}tjj|tj|dtd| _t|| jj}| jjjjrm| j| _n
tjj||td| _| jrtjj| jjj | j| _!| j| j!_"| j!| j_#d S d S )N)dtypeckpt_saved_epoch)initial_valuenameckpt_saved_batch)modelr   r   train_counterchief)	directorymax_to_keep)$r   distribute_strategy_enable_save_before_preemption_model
_save_freqtfVariableconstantCKPT_SAVED_EPOCH_UNUSED_VALUEint64_ckpt_saved_epochCKPT_SAVED_BATCH_UNUSED_VALUE_ckpt_saved_batchr   	set_valuetrain
Checkpoint_train_counterCheckpointManagerospathjoinMAX_CHECKPOINT_TO_KEEPread_checkpoint_managerr   write_dirpathextendedshould_checkpointwrite_checkpoint_manager
distributeexperimentalPreemptionCheckpointHandlercluster_resolverpreemption_handler_read_checkpoint_manager_preemption_handler)selfr   checkpoint_dir	save_freqsave_before_preemption_arg
checkpointwrite_checkpoint_dir r;   Y/var/www/myenv/lib/python3.10/site-packages/keras/src/distribute/worker_training_state.py__init__0   sl   
zWorkerTrainingState.__init__r   c                 C   s&   | j  rt| j j| jj dS dS )zBack up the current state of training into a checkpoint file.

        Args:
          epoch: The current epoch information to be saved.
          batch: The current batch(step) information to be saved.
        N)r-   saver   remove_temp_dirpathr   r   r   )r5   r	   batchr;   r;   r<   back_up   s   
zWorkerTrainingState.back_upc                 C   s(   | j r| j jd7  _| j  d S d S )Nr   )r   r2   _run_counter&_check_preemption_and_maybe_checkpointr5   r;   r;   r<   backup_if_preempted   s   z'WorkerTrainingState.backup_if_preemptedc                 C   s   | j s
| j  dS dS )a  Restore the training state from the backed up checkpoint file.

        Returns:
          True if the training state is successfully restored. False if the
          training state doesn't need to be restored, or error occurred so it
          can't.
        N)r   r)   restore_or_initializerD   r;   r;   r<   restore   s   
zWorkerTrainingState.restorec                 C   sB   | j | ju rztjj| j j W dS  tjjy   Y dS w dS )zDelete the backup directories.

        Delete the backup directories which should not exist after `fit()`
        successfully finishes.
        N)	r-   r)   r   iogfilermtreer   errorsNotFoundErrorrD   r;   r;   r<   delete_backup   s   z!WorkerTrainingState.delete_backupc                 C   s   d}t | j}t | j}|tjjkrC| jst| j	t
r;|dkr7||d kr1|d }d}||fS |}|d }||fS |dkrC|d }||fS )a  Maybe load 1st epoch from checkpoint, considering worker recovery.

        When `_ckpt_saved_epoch` attribute exists and is not
        `CKPT_SAVED_EPOCH_UNUSED_VALUE`, this is under multi-worker training
        setting and indicates the worker is recovering from previous failure. In
        this case, infer `initial_epoch` from `self._ckpt_saved_epoch` to
        continue previous unfinished training from certain epoch.

        Args:
          steps_per_epoch: The number of steps per epoch value.
          initial_epoch: The original initial_epoch user passes in in `fit()`.
          mode: The mode for running `model.fit()`.

        Returns:
          If the training is recovering from previous failure under multi-worker
          training setting, return the (epoch, step) the training is supposed to
          continue at. Otherwise, return the `initial_epoch, initial_step` the
          user passes in.
        r   r   )r   evalr   r   r   ModeKeysTRAINr   
isinstancer   int)r5   steps_per_epochinitial_epochmodeinitial_stepr	   r@   r;   r;   r<   %maybe_load_initial_counters_from_ckpt   s$   z9WorkerTrainingState.maybe_load_initial_counters_from_ckpt)r	   N)r   )__name__
__module____qualname____doc__r   r   r=   rA   rE   rG   rM   rW   r;   r;   r;   r<   r   "   s    	

Tr   )r[   r%   tensorflow.compat.v2compatv2r   	keras.srcr   keras.src.distributer   keras.src.utilsr   +keras.src.distribute.distributed_file_utilsr   r(   r   r;   r;   r;   r<   <module>   s   