
    &`i                     *   d dl Z d dlZd dlmZmZmZmZmZ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mZ d dlmZ d d	lmZ d d
lmZ  e j        e          Z	 ddee         dedeegef         deeeef                  fdZ G d d          ZdS )    N)AnyCallableDictListOptionalTuple)ray_constants)flatten_dict)is_nan)MAX)
CheckpointCheckpointConfig)_TrainingResult)_delete_fs_path)*TUNE_ONLY_STORE_CHECKPOINT_SCORE_ATTRIBUTElistitemkeycheckpoint_to_report_indexc                 b   |pi }d}|t          |           k     r || |                    ||          }}||k    sD||k    r?|                    | |         j        d          |                    |j        d          k    rn|dz  }|t          |           k     |                     ||           dS )ad  Insert an item into a sorted list with a custom key function.

    Args:
        list: The list to insert the item into.
        item: The item to insert.
        key: The key function to use to sort the list.
        checkpoint_to_report_index: A dictionary mapping checkpoints to report indices.
            Used to break ties when scores are equal.
    r      N)lenget
checkpointinsert)r   r   r   r   ilist_item_keyitem_keys          z/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/train/_internal/checkpoint_manager.py_insert_into_sorted_listr       s     "<!Ar	A
c$ii--"%#d1g,,D		x8##X%%*..tAw/A1EE(,,T_a@@A A 	Q c$ii-- 	KK4    c                       e Zd ZdZdee         fdZed             Zde	fdZ
de	deeej        f         fd	Zedee	         fd
            Zedee	         fd            Zedee	         fd            ZdS )_CheckpointManagera  Checkpoint manager that handles checkpoint book-keeping for a trial.

    The main purpose of this abstraction is to keep the top K checkpoints based on
    recency/a user-provided metric.

    NOTE: This class interacts with `_TrainingResult` objects, which are
    (checkpoint, metrics) pairs. This is to order checkpoints by metrics.

    Args:
        checkpoint_config: Defines how many and which checkpoints to keep.
    checkpoint_configc                     |pt                      | _        g | _        d | _        | j        j        ,| j        j        dk    rt          d| j        j                   d S d S )Nr   z`num_to_keep` must >= 1, got: )r   _checkpoint_config_checkpoint_results_latest_checkpoint_resultnum_to_keep
ValueError)selfr$   s     r   __init__z_CheckpointManager.__init__=   s    "3"I7G7I7I ;= 
 EI& #/;'3q889*69 9   <;88r!   c                     | j         S N)r&   r+   s    r   r$   z$_CheckpointManager.checkpoint_configQ   s    &&r!   checkpoint_resultc                 z   || _         | j        j        }t          j        t
          d          r0||j        v r||j        |         ini }t          |j        |          }|&||j        v rt          | j
        || j                   n| j
                            |           | j        j        t          | j
        d| j        j                            }|| j         hz
  fd| j
        D             | _
        D ]A}|j        }t                              d|           t#          |j        |j                   @dS dS )a  Register new checkpoint and add to bookkeeping.

        This method will register a new checkpoint and add it to the internal
        bookkeeping logic. This means the checkpoint manager will decide if
        this checkpoint should be kept, and if older or worse performing
        checkpoints should be deleted.

        Args:
            checkpoint: Tracked checkpoint object to add to bookkeeping.
        F)r   metricsN)r   c                     g | ]}|v|	S  r4   ).0r0   results_to_deletes     r   
<listcomp>z:_CheckpointManager.register_checkpoint.<locals>.<listcomp>   s/     ( ( (%$,=== "===r!   zDeleting checkpoint: )fsfs_path)r(   r&   checkpoint_score_attributer	   env_boolr   r2   r   r   r    r'   _get_checkpoint_scoreappendr)   setloggerdebugr   
filesystempath)r+   r0   
score_attrr2   worst_resultsr   r6   s         @r   register_checkpointz&_CheckpointManager.register_checkpointU   s    *;&,G
!"LeTT 		 !2!::: .6zBCC 
 !0,7! ! !
 !j4E4M&M&M %(!.     $++,=>>>".:()OD,C,O+O)OP M !.1O0P P( ( ( ()-)A( ( (D$ &7 S S!.9
4jAAA:#8*/RRRRR% ;:S Sr!   r   returnc                 <   | j         j        }|r~t          |j                  }	 ||         }no# t          $ rS t          |                                          }t                              d| d|            t          d          }Y nw xY wt          d          }| j         j
        }|t          k    rdnd}||z  }t          |t          j                  st          d| d| d          t!          |          st!          |           |fnd	t          d          fS )
ab  Get the score for a checkpoint, according to checkpoint config.

        If `mode="min"`, the metric is negated so that the lowest score is
        treated as the best.

        Returns:
            Tuple: A tuple of (not_is_nan: bool, score: numbers.Number).
                This score orders: nan values < float("-inf") < valid numeric metrics
        zResult dict has no key: zQ. checkpoint_score_attr must be set to a key in the result dict. Valid keys are: z-infg      ?g      z=Unable to persist checkpoint for checkpoint_score_attribute: z with value z#. This attribute must be numerical.F)r&   r:   r
   r2   KeyErrorr   keysr?   errorfloatcheckpoint_score_orderr   
isinstancenumbersNumberr*   r   )	r+   r   r:   flat_metricsr0   
valid_keysrL   order_factorcheckpoint_scores	            r   r<   z(_CheckpointManager._get_checkpoint_score   s    &*%<%W"% 	.'
(:;;L	2$01K$L!! 2 2 2!,"3"3"5"566
A/I A A4>A A  
 %*&MM!!!2 !&f!%!8!O4;;ss'*;;*GN;; 	5-5 5 $5 5 5   *++(()))+;<<v'	
s   - AB
	B
c                 .    | j         r| j         d         nd S )N)r'   r/   s    r   best_checkpoint_resultz)_CheckpointManager.best_checkpoint_result   s    /3/GQt'++TQr!   c                     | j         S r.   )r(   r/   s    r   latest_checkpoint_resultz+_CheckpointManager.latest_checkpoint_result   s    --r!   c                 \    | j         j        | j        S | j        | j         j         d          S r.   )r&   r)   r'   r/   s    r   best_checkpoint_resultsz*_CheckpointManager.best_checkpoint_results   s4    ".6++')@)L(L(N(NOOr!   N)__name__
__module____qualname____doc__r   r   r,   propertyr$   r   rE   r   boolrN   rO   r<   rV   rX   r   rZ   r4   r!   r   r#   r#   0   s<       
 
(3C*D    ( ' ' X'7S_ 7S 7S 7S 7Sr.
).
	tW^#	$.
 .
 .
 .
` R(A R R R XR .(?*C . . . X. Po)> P P P XP P Pr!   r#   r.   ) loggingrN   typingr   r   r   r   r   r   ray._privater	   ray._private.dictr
   ray.air._internal.utilr   ray.air.configr   	ray.trainr   r   ray.train._internal.sessionr   ray.train._internal.storager   ray.train.constantsr   	getLoggerr[   r?   intr    r#   r4   r!   r   <module>rm      s     = = = = = = = = = = = = = = = = & & & & & & * * * * * * ) ) ) ) ) )       2 2 2 2 2 2 2 2 7 7 7 7 7 7 7 7 7 7 7 7 J J J J J J		8	$	$ CG	 


 
?#S(	) !)j#o)> ?	   >ZP ZP ZP ZP ZP ZP ZP ZP ZP ZPr!   