
    &`ii              
          d dl Z d dlZd dlmZmZmZmZmZmZm	Z	 d dl
Zd dlZd dlmZmZmZ d dlmZmZ d dlmZmZ d dlmZmZmZmZmZmZmZmZm Z m!Z! d dl"m#Z#m$Z$  e            \  Z%Z&Z% e            \  Z'Z% e j(        d          Z)eeeee!eeeed		Z*e#ddee+ef         de,de fd            Z- e$d           G d d                      Z. G d d          Z/dS )    N)AnyDictListOptionalTupleTypeUnion)DEPRECATED_VALUE
Deprecateddeprecation_warning)deep_updateforce_tuple)try_import_tftry_import_torch)
EmaStatsItemSeriesStats	ItemStatsLifetimeSumStatsMaxStats	MeanStatsMinStatsPercentilesStats	StatsBaseSumStats)DeveloperAPI	PublicAPIz	ray.rllib)	meanemaminmaxsumlifetime_sumpercentilesitemitem_seriesFstateis_rootreturnc                    | d         }| |g d}|                      dd          du r|dk    rod|d<   |rt          j        | d	                   |d<   nd
|d<   |                      d          d|d<   nd|d<   t          d         }|                    |          }|S t          dd           |dk    rQ| d         0d}| d         |d<   t          j        | d	                   |d<   d|d<   nd}| d	         |d	<   | d         |d<   n|dv r=| d	         |d	<   | d         |d<   |dk    r|                      d          d|d<   npd|d<   nj|A|                      dd          dur)d}| d	         |d	<   | d         |d<   | d         |d<   d|d<   n'|dk    r!| d	         |d	<   | d         |d<   | d         |d<   t          |         }||d<   |                    |          }|S )z+Creates a Stats object from a legacy state.reduce)is_leafr'   latest_mergedclear_on_reduceTFr!   r"   stats_cls_identifiervaluesg        throughput_statsNtrack_throughputsr&   zOLegacy Stats class tracking throughput detected. This is not supported anymore.errorr   	ema_coeffr   valuewindow)r   r    r!   track_throughputr#   )getnpnansumDEFAULT_STATS_CLS_LOOKUP
from_stater   nanmean)r&   r'   cls_identifier	new_state_clsstatss         z/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/rllib/utils/metrics/metrics_logger.pystats_from_legacy_staterD   .   s    8_N ;	 I yy"D))U22U""0>I,- 0,.IeHo,F,F	.)),/	.) yy+,,815	-..16	-.+N;DOO)O44ELa   
 )"N%*;%7Ik"!#E(O!<!<Ig05I,--#N"'/Ih"'/Ih	0	0	0#Ho	(#Ho	(U""uyy1C'D'D'P,0I()),1I())		EIImU$C$C5$P$P&#Ho	(#Ho	(#(#7	- ,9	())	=	(	(#Ho	(#Ho	(#(#7	- #N3D(6I$%OO)O,,EL    alpha)	stabilityc                      e Zd ZdZdefdeeeee	         f                  fdZ
deeeedf         f         defdZ	 	 	 	 	 dAdeeeedf         d	f         dedededef
dZedBdededefd            Zdd	d	d	ed	eeddeeeedf         f         dedeeeef                  dee         deeee         ef                  dee         dee         dee         dee         deeef         dd	fdZd	d	d	d	ed	eeddeeeedf         f         dedee         deeeef                  dee         deeee         ef                  dee         dee         dee         dee         deeef         dd	fdZd	dd	d	d	ed	eed 	deeeeedf         f                  dee         deeeef                  dee         deeee         ef                  dee         dee         dee         dee         dd	fd!Z ed"d#          d$             Zd	d%d&eeeef                  deeeeedf         f                  dd	fd'Zdd	d	d	ed	eeddeeeedf         f         dedeeeef                  dee         deeee         ef                  dee         dee         dee         dee         de	fd(ZdCdedefd)Z ed*d+d
,          dDd-            ZdDd.Z d
d/deedf         d0edd	fd1Z!deeef         fd2Z"d3eeef         dd	fd4Z#d	d5d6Z$d	d
d7d8Z%d9 Z&dCd:Z'	 dEdeeeeedf         f                  deeef         fd;Z(defd<Z) ed=d>d,          d?             Z* ed=d>d,          d@             Z+d	S )FMetricsLoggeraj  A generic class collecting and reducing metrics.

    Use this API to log and merge metrics.
    Metrics should be logged in parallel components with MetricsLogger.log_value().
    RLlib will then aggregate metrics, reduce them and report them.

    The MetricsLogger supports logging anything that has a corresponding reduction method.
    These are defined natively in the Stats classes, which are used to log the metrics.
    Please take a look ray.rllib.utils.metrics.metrics_logger.DEFAULT_STATS_CLS_LOOKUP for the available reduction methods.
    You can provide your own reduce methods by extending ray.rllib.utils.metrics.metrics_logger.DEFAULT_STATS_CLS_LOOKUP and passing it to AlgorithmConfig.logging().

    Notes on architecture:
    In our docstrings we make heavy use of the phrase 'parallel components'.
    This pertains to the architecture of the logging system, where we have one 'root' MetricsLogger
    that is used to aggregate all metrics of n parallel ('non-root') MetricsLoggers that are used to log metrics for each parallel component.
    A parallel component is typically a single Learner, an EnvRunner, or a ConnectorV2 or any other component of which more than one instance is running in parallel.
    We also allow intermediate MetricsLoggers that are no root MetricsLogger but are used to aggregate metrics. They are therefore neither root nor leaf.
    Fstats_cls_lookupc                     i | _         t                      | _        || _        t	          j                    | _        || _        dS )aW  Initializes a MetricsLogger instance.

        Args:
            root: Whether this logger is a root logger. If True, lifetime sums (reduce="lifetime_sum") will not be cleared on reduce().
            stats_cls_lookup: A dictionary mapping reduction method names to Stats classes.
                If not provided, the default lookup (ray.rllib.utils.metrics.metrics_logger.DEFAULT_STATS_CLS_LOOKUP) will be used.
                You can provide your own reduce methods by extending ray.rllib.utils.metrics.metrics_logger.DEFAULT_STATS_CLS_LOOKUP and passing it to AlgorithmConfig.logging().
        N)rB   _DummyRLock_threading_lock_is_root_loggertimeperf_counter_time_when_initializedrJ   )selfrootrJ   s      rC   __init__zMetricsLogger.__init__   s@     
  +}}#&*&7&9&9# 0rE   key.r(   c                 ,    |                      |          S )a&  Returns True, if `key` can be found in self.stats.

        Args:
            key: The key to find in self.stats. This must be either a str (single,
                top-level key) or a tuple of str (nested key).

        Returns:
            Whether `key` could be found in self.stats.
        )_key_in_stats)rR   rU   s     rC   __contains__zMetricsLogger.__contains__   s     !!#&&&rE   NTcompile
throughputlatest_merged_onlyc                 J   |r(| j         s
J d            |                     ||          S dt          t          t          f         ffd}| j        5  | || j                  cddd           S ||                     |d          }n|                     |d          }t          |t                    r#|
                    	          cddd           S t          |t                    r|r ||          cddd           S |cddd           S # 1 swxY w Y   dS )
a  Returns the reduced values found in this MetricsLogger.

        Note that calling this method does NOT cause an actual underlying value list
        reduction, even though reduced values are being returned. It'll keep all
        internal structures as-is. By default, this returns a single reduced value or, if
        the Stats object has no reduce method, a list of values. When when compile is False,
        the result is a list of one or more values.

        Args:
            key: The key/key sequence of the sub-structure of `self`, whose (reduced)
                values to return.
            default: An optional default value in case `key` cannot be found in `self`.
                If default is not provided and `key` cannot be found, throws a KeyError.
            compile: If True, the result is compiled into a single value if possible.
            throughput: If True, the throughput is returned instead of the
                actual (reduced) value.
            latest_merged_only: If True, only considers the latest merged values.
                This parameter only works on aggregation loggers (root or intermediate).

        Returns:
            The (reduced) values of the (possibly nested) sub-structure found under
            the given key or key sequence.
        z0Throughput can only be peeked from a root logger)rU   defaultrB   c                 |    dt           dt          ffd}t          j        ||                                           S )NpathrB   c           
          	 |                               S # t          $ r}t          d| d d|  d          |d }~ww xY w)NrY   r[   zError peeking stats  with compile=	 at path .)peek	Exception
ValueError)r_   rB   erY   r[   s      rC   _peek_with_pathzAMetricsLogger.peek.<locals>._nested_peek.<locals>._peek_with_path   s~     :: '<N &    !   $]u]]G]]VZ]]] s    
A>A)strr   treemap_structure_with_pathcopy)rB   ri   rY   r[   s     rC   _nested_peekz(MetricsLogger.peek.<locals>._nested_peek   sQ    c )        /NNNrE   NT	key_errorFra   )rN   _get_throughputsr   rj   r   rM   rB   _get_key
isinstancer   re   dict)rR   rU   r]   rY   rZ   r[   rn   rB   s      ` `  rC   re   zMetricsLogger.peek   s   >  	C$B BAB B$((S'(BBB	OS#X 	O 	O 	O 	O 	O 	O 	O ! 	# 	#{#|DJ//	# 	# 	# 	# 	# 	# 	# 	# ? MM#M>>EE MM#M??EeY// 	# :: '<N &  	# 	# 	# 	# 	# 	# 	# 	#  t,, # #'<..!	# 	# 	# 	# 	# 	# 	# 	#$ #%	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	#s%   D3AD!D
DDDresultsc                 4    t          j        fd|           S )a  Performs `peek()` on any leaf element of an arbitrarily nested Stats struct.

        Args:
            results: The nested structure of Stats-leafs to be peek'd and returned.
            compile: If True, the result is compiled into a single value if possible.

        Returns:
            A corresponding structure of the peek'd `results` (reduced float/int values;
            no Stats objects).
        c                 ^    t          | t                    r|                               n| S )NrY   )rs   r   re   )srY   s    rC   <lambda>z,MetricsLogger.peek_results.<locals>.<lambda>  s)    Ay1I1IPaffWf---q rE   )rk   map_structure)ru   rY   s    `rC   peek_resultszMetricsLogger.peek_results   s)     !PPPP
 
 	
rE   r   r*   r7   r5   r#   r-   with_throughputthroughput_ema_coeffreduce_per_index_on_aggregater*   r7   r5   r#   r-   r~   r   r   kwargsc                   | j         5  |                     |          s|dk    r|d}|r|dk    st          d          |dk    r|t          dd           d}|	t          urt          d	d
           |t          urt          dd           |dk    r|t          dd           |r|dvrt          dd
           	 | j        |         }n!# t          $ r t          d| d          w xY w|||
d<   |||
d<   |||
d<   |||
d<   | j        |
d<   d|
d<    |di |
}|                     ||           ddd           dS # 1 swxY w Y   dS )zCPrepare the kwargs and create the stats object if it doesn't exist.r   Ng{Gz?r#   z4percentiles is only supported for reduce=percentileszcwindow is not supported for ema reduction. If you want to use a window, use mean reduction instead.Tr3   zreduce_per_index_on_aggregate is deprecated. Aggregation now happens over all valuesof incoming stats objects, treating each incoming value with equal weight.Fzthroughput_ema_coeff is deprecated. Throughput is not smoothed with ema anymorebut calculate once per MetricsLogger.reduce() call.r   zJema_coeff is not supported for mean reduction. Use `reduce='ema'` instead.)r!   r"   zwith_throughput=True is only supported for reduce='sum' or reduce='lifetime_sum'. Use reduce='sum' or reduce='lifetime_sum' instead.zInvalid reduce method 'z(' could not be found in stats_cls_lookupr7   r5   r~   r'   r+    )	rM   rW   rg   r   r
   rJ   KeyErrorrN   _set_key)rR   rU   r*   r7   r5   r#   r-   r~   r   r   r   	stats_clsstats_objects                rC   _maybe_create_stats_objectz(MetricsLogger._maybe_create_stats_object	  s    ! C	1 C	1%%c** A1U??y'8 $I v'>'>$N   U??v'9'}"    "F08HHH'e#    (/???'N"    V## ,+h"&   
 # v5L'L'L' _#    $ 5f =II   $b&bbb  
 %'-F8$(*3F;'*,7F=)".0?F,- %)$8y! %)y!(y22622c<000GC	1 C	1 C	1 C	1 C	1 C	1 C	1 C	1 C	1 C	1 C	1 C	1 C	1 C	1 C	1 C	1 C	1 C	1s+   B7E CEC,,AEE	E	r6   c                    ||d}|d}|t           urt          dd           |dk    r|du rd}d}|                     ||||||||	|
		  	         |                     |          }|                    |           dS )
ax  Logs a new value or item under a (possibly nested) key to the logger.

        Args:
            key: The key (or nested key-tuple) to log the `value` under.
            value: A numeric value, an item to log or a StatsObject containing multiple values to log.
            reduce: The reduction method to apply when compiling metrics at the root logger.
                By default, the reduction methods to choose from here are the keys
                of rllib.utils.metrics.metrics_logger.DEFAULT_STATS_CLS_LOOKUP.
                You can provide your own reduce methods by extending
                rllib.utils.metrics.metrics_logger.DEFAULT_STATS_CLS_LOOKUP and passing it to AlgorithmConfig.logging()).
            window: An optional window size to reduce over.
                If not None, then the reduction operation is only applied to the most
                recent `window` items, and - after reduction - the internal values list
                under `key` is shortened to hold at most `window` items (the most
                recent ones). Must be None if `ema_coeff` is provided.
                If None (and `ema_coeff` is None), reduction must not be "mean".
            ema_coeff: An optional EMA coefficient to use if `reduce` is "mean"
                and no `window` is provided. Note that if both `window` and `ema_coeff`
                are provided, an error is thrown. Also, if `ema_coeff` is provided,
                `reduce` must be "mean".
                The reduction formula for EMA is:
                EMA(t1) = (1.0 - ema_coeff) * EMA(t0) + ema_coeff * new_value
                Defaults to 0.01.
            percentiles: If reduce is `None`, we can compute the percentiles of the
                values list given by `percentiles`. Defaults to [0, 0.5, 0.75, 0.9, 0.95,
                0.99, 1] if set to True. When using percentiles, a window must be provided.
                This window should be chosen carefully. RLlib computes exact percentiles and
                the computational complexity is O(m*n*log(n/m)) where n is the window size
                and m is the number of parallel metrics loggers involved (for example,
                m EnvRunners).
            clear_on_reduce: Deprecated. Use reduce="lifetime_sum" instead.
                If True, all values under `key` will be cleared after
                `self.reduce()` is called. Setting this to True is useful for cases,
                in which the internal values list would otherwise grow indefinitely,
                for example if reduce is None and there is no `window` provided.
            with_throughput: Whether to track a throughput estimate together with this
                metric. This is supported by default only for `reduce=sum` and `reduce=lifetime_sum`.
            throughput_ema_coeff: Deprecated argument. Throughput is not smoothed with ema anymore
                but calculate once per MetricsLogger.reduce() call.
            reduce_per_index_on_aggregate: Deprecated argument. Aggregation now happens over all values
                of incoming stats objects once per MetricsLogger.reduce() call, treating each incoming value with equal weight.
        Nr   r   zrclear_on_reduce is deprecated. Use reduce='lifetime_sum' for sums. Provide a custom reduce method for other cases.Fr3   r!   r"   r}   )r
   r   r   rr   push)rR   rU   r6   r*   r7   r5   r#   r-   r~   r   r   r   rB   s                rC   	log_valuezMetricsLogger.log_value]  s    v >f0F>F"222 E   
 U??%77#F"O 	''#++!5*G 	( 
	
 
	
 
	
 c""

5rE   r   )	rU   r*   r7   r5   r#   r-   r~   r   r   c       	   
         	
 t          |t                    sJ d| d            t          |          
 	f
d} j        5  t	          j        ||           ddd           dS # 1 swxY w Y   dS )a  Logs all leafs of a possibly nested dict of values or Stats objects to this logger.

        Traverses through all leafs of `stats_dict` and - if a path cannot be found in
        this logger yet, will add the `Stats` found at the leaf under that new key.
        If a path already exists, will merge the found leaf (`Stats`) with the ones
        already logged before. This way, `stats_dict` does NOT have to have
        the same structure as what has already been logged to `self`, but can be used to
        log values under new keys or nested key paths.

        Passing a dict of stats objects allows you to merge dictionaries of stats objects that
        have been reduced by other, parallel components.

        See MetricsLogger.log_value for more details on the arguments.
        z`stats_dict` (z) must be dict!c                    
 t          t          j        |                     z   }	                    ||

  
         d S )N)	r6   r*   r7   r5   r#   r-   r~   r   r   )r   rk   flattenr   )r_   stat_or_valueextended_keyr-   r5   r#   
prefix_keyr*   r   rR   r   r7   r~   s      rC   _mapz$MetricsLogger.log_dict.<locals>._map  sb    %DL4F4F(G(GGLNN##' / /%9.K      rE   N)rs   rt   r   rM   rk   rl   )rR   
value_dictrU   r*   r7   r5   r#   r-   r~   r   r   r   r   s   `  ```````` @rC   log_dictzMetricsLogger.log_dict  s   8 
 
 	8 	87J777	8 	8 
 !%%
	 	 	 	 	 	 	 	 	 	 	 	 	 	  ! 	; 	;(z:::	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	;s   A55A9<A9	aggregate)newr4   c                      | j         |i |S N)r   rR   argsr   s      rC   merge_and_log_n_dictsz#MetricsLogger.merge_and_log_n_dicts  s    t~t.v...rE   )rU   stats_dictsc                T   	
 t                      d
fd	
	fd	g }|D ]0} 	|          } 
|          }|                    |           1D ]Њ fd|D             }                      j        d          }t	          |t
                    rdn|}|F|d                              j        dd	
          }|j        r|	                     j
                   n|j        rJ d d            |                    |                                |           dS )a  Merges n stats_dicts and logs result by merging on the time axis with existing stats.

        The n stats_dicts should be generated by n parallel components such that merging their
        respective stats in parallel is meaningful. Stats can be aggregated at root or intermediate loggers.
        This will replace most internal values with the result of the merge.
        For exceptions, see the documentation of the individual stats classes `merge` methods.

        Args:
            stats_dicts: List of n stats dicts to be merged and then logged.
            key: Optional top-level key under which to log all keys/key sequences
                found in the n `stats_dicts`.
        r   c                 L   t          | t                    r1i }|                                 D ]\  }} |||fz             ||<   |S t          | t                    r2                    |           t          |           dk    r| d         S | S                     |           | S N   r   )rs   rt   itemslistaddlen)dr_   new_dictrU   r6   all_keystraverse_and_add_pathss        rC   r   z7MetricsLogger.aggregate.<locals>.traverse_and_add_paths  s    !T"" "#'')) Q QJC$:$:5$#-$P$PHSMMAt$$ T"""q66Q;;Q4K T"""rE   c                     t          |t                    r|| iS t          |          dk    r|d          | |dd                    iS |d         | iS r   )rs   rj   r   )
stats_dictrU   build_nested_dicts     rC   r   z2MetricsLogger.aggregate.<locals>.build_nested_dict  sc    #s## ,Z((SAA 1 1*c!""g F FGGA
++rE   Nc                 l    g | ]0}                     |                               |           1S )rB   )rW   rr   ).0ry   rU   rR   s     rC   
<listcomp>z+MetricsLogger.aggregate.<locals>.<listcomp>&  sR       %%c%33c++  rE   FrB   rp   r   )r'   r+   )init_overrideszCannot aggregate into key 'zg' because it was created by direct logging. Aggregation keys must be separate from direct logging keys.)incoming_stats)r   )setappendrr   rB   rs   rt   clonerN   has_throughputs$initialize_throughput_reference_timerQ   r+   merger   )rR   r   rU   incoming_stats_dicts_with_keyr   r   structure_under_key	own_statsr   r   r   s   ` `     @@@rC   r   zMetricsLogger.aggregate  s   $ 55	 	 	 	 	 	 	 	, 	, 	, 	, 	, )+%% 	= 	=J..z3??
//
;;J)00<<<< !	* !	*C    6  N #'--4:QV-"W"W ##6==VCV    +1-33/3/CPU#V#V 4  	 , BB3   ")^ ^ ^  ^  ^  ^^ ^) OO>O:::MM#y))))C!	* !	*rE   c                h    |                      |||||||||		  	         |                     |          S )a  Measures and logs a time delta value under `key` when used with a with-block.

        Args:
            key: The key (or tuple of keys) to log the measured time delta under.
            reduce: The reduction method to apply when compiling metrics at the root logger.
                By default, the reduction methods to choose from here are the keys
                of rllib.utils.metrics.metrics_logger.DEFAULT_STATS_CLS_LOOKUP.
                You can provide your own reduce methods by extending rllib.utils.metrics.metrics_logger.DEFAULT_STATS_CLS_LOOKUP and passing it to AlgorithmConfig.logging()).
            window: An optional window size to reduce over.
                If not None, then the reduction operation is only applied to the most
                recent `window` items, and - after reduction - the internal values list
                under `key` is shortened to hold at most `window` items (the most
                recent ones).
                Must be None if `ema_coeff` is provided.
                If None (and `ema_coeff` is None), reduction must not be "mean".
            ema_coeff: An optional EMA coefficient to use if `reduce` is "mean"
                and no `window` is provided. Note that if both `window` and `ema_coeff`
                are provided, an error is thrown. Also, if `ema_coeff` is provided,
                `reduce` must be "mean".
                The reduction formula for EMA is:
                EMA(t1) = (1.0 - ema_coeff) * EMA(t0) + ema_coeff * new_value
            percentiles: If reduce is `None`, we can compute the percentiles of the
                values list given by `percentiles`. Defaults to [0, 0.5, 0.75, 0.9, 0.95,
                0.99, 1] if set to True. When using percentiles, a window must be provided.
                This window should be chosen carefully. RLlib computes exact percentiles and
                the computational complexity is O(m*n*log(n/m)) where n is the window size
                and m is the number of parallel metrics loggers involved (for example,
                m EnvRunners).
            clear_on_reduce: Deprecated. Use reduce="lifetime_sum" instead.
                If True, all values under `key` will be cleared after
                `MetricsLogger.reduce()` is called. Setting this to True is useful for cases,
                in which the internal values list would otherwise grow indefinitely,
                for example if reduce is None and there is no `window` provided.
            with_throughput: Whether to track a throughput estimate together with this
                metric. This is only supported for `reduce=sum` and `reduce=lifetime_sum`.
                The current throughput estimate of a key can be obtained
                through: `MetricsLogger.peek(key, throughput=True)`.
            throughput_ema_coeff: Deprecated argument. Throughput is not smoothed with ema anymore
                but calculate once per MetricsLogger.reduce() call.
            reduce_per_index_on_aggregate: Deprecated argument. Aggregation now happens over all values
                of incoming stats objects once per MetricsLogger.reduce() call, treating each incoming value with equal weight.
        r}   )r   rr   )
rR   rU   r*   r7   r5   r#   r-   r~   r   r   s
             rC   log_timezMetricsLogger.log_timeG  sQ    p 	''#++!5*G 	( 
	
 
	
 
	
 }}S!!!rE   c                     dt           dt          ffd}| j        5  t          j        || j                  cddd           S # 1 swxY w Y   dS )aF  Reduces all logged values based on their settings and returns a result dict.

        Note to user: Do not call this method directly! This should be called only by RLlib when aggregating stats.

        Args:
            compile: If True, the result is compiled into a single value if possible.
                If it is not possible, the result is a list of values.
                If False, the result is a list of one or more values.

        Returns:
            A dict containing all ever logged nested keys to this MetricsLogger with the leafs being the reduced stats.
        r_   rB   c           
          	 |                               S # t          $ r}t          d| d d|  d          |d }~ww xY w)Nrx   zError reducing stats rb   rc   rd   )r*   rf   rg   )r_   rB   rh   rY   s      rC   _reducez%MetricsLogger.reduce.<locals>._reduce  so    ||G|444    ZEZZZZSWZZZ s    
A=AN)rj   r   rM   rk   rl   rB   )rR   rY   r   s    ` rC   r*   zMetricsLogger.reduce  s    	# 	i 	 	 	 	 	 	 ! 	E 	E/DD	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	Es   AAAr   zcUse log_value with reduce='item' or another reduction method with a window of the appropriate size.)r   helpr4   c                     d S r   r   r   s      rC   	set_valuezMetricsLogger.set_value  s	     	rE   c                 T    | j         5  i | _        ddd           dS # 1 swxY w Y   dS )z-Resets all data stored in this MetricsLogger.N)rM   rB   rR   s    rC   resetzMetricsLogger.reset  sv    ! 	 	DJ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   !!ro   rp   c                2    |                      ||           dS )a  Deletes the given `key` from this metrics logger's stats.

        Args:
            key: The key or key sequence (for nested location within self.stats),
                to delete from this MetricsLogger's stats.
            key_error: Whether to throw a KeyError if `key` cannot be found in `self`.

        Raises:
            KeyError: If `key` cannot be found in `self` AND `key_error` is True.
        N)_del_key)rR   rp   rU   s      rC   deletezMetricsLogger.delete  s     	c9%%%%%rE   c                     i fd}| j         5  t          j        || j                   ddd           n# 1 swxY w Y   diS )zReturns the current state of `self` as a dict.

        Note that the state is merely the combination of all states of the individual
        `Stats` objects stored under `self.stats`.
        c                 \    |                                 d                    |           <   d S )N--)	get_statejoin)r_   rB   r   s     rC   r   z%MetricsLogger.get_state.<locals>._map  s'    *///*;*;Jtyy'''rE   NrB   )rM   rk   rl   rB   )rR   r   r   s     @rC   r   zMetricsLogger.get_state  s     
	< 	< 	< 	< 	< ! 	; 	;(tz:::	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; $$s   7;;r&   c                    | j         5  i | _        |d                                         D ]\  }}d|v rC|d         }|| j        v sJ d| d            | j        |         }|                    |          }nt          || j                  }|                     |                    d          |           	 ddd           dS # 1 swxY w Y   dS )	zuSets the state of `self` to the given `state`.

        Args:
            state: The state to set `self` to.
        rB   r.   zStats class identifier z not found in stats_cls_lookup. This can happen if you are loading a stats from a checkpoint that was created with a different stats class lookup.r2   )r&   r'   r   N)	rM   rB   r   rJ   r=   rD   rN   r   split)rR   r&   flat_keystats_stater?   rA   rB   s          rC   	set_statezMetricsLogger.set_state  sS    ! 	; 	;DJ).w)=)=)?)? ; ;%+)[88%01G%HN&$*???? T  T  T  T @??0@D OO+O>>EE 4)43G  E hnnT22E::::!;	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	;s   B.CCCr   c                    t          t          j        |                    }||n| j        }|D ]}||vr dS ||         }dS )NFT)r   rk   r   rB   )rR   r   rB   _dictrU   s        rC   rW   zMetricsLogger._key_in_stats  sZ    t|H5566*
 	 	C%uu#JEEtrE   r   c                    t          t          j        |                    }||n| j        }|D ]*}	 ||         }# t          $ r}|r|i cY d }~c S d }~ww xY w|S r   )r   rk   r   rB   r   )rR   r   rB   rp   r   rU   rh   s          rC   rr   zMetricsLogger._get_key  s    t|H5566*
 	 	Cc
    GIIIIIIII	
 s   ;
AA
AAc                 6   t          t          j        |                    }| j        5  | j        }t          |          D ]?\  }}|t          |          dz
  k    r|||<    d d d            d S ||vri ||<   ||         }@	 d d d            d S # 1 swxY w Y   d S Nr   )r   rk   r   rM   rB   	enumerater   )rR   r   rB   r   irU   s         rC   r   zMetricsLogger._set_key  s   t|H5566! 	# 	#JE#H-- 
# 
#3 H)))!&E#J	# 	# 	# 	# 	# 	# 	# 	# e##!#E#Jc

#	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	#s   8B.BBBc                 X   t          t          j        |                    }| j        5  | j        }	 t          |          D ]4\  }}|t          |          dz
  k    r||=  d d d            d S ||         }5n# t          $ r}|r|Y d }~nd }~ww xY wd d d            d S # 1 swxY w Y   d S r   )r   rk   r   rM   rB   r   r   r   )rR   r   rp   r   r   rU   rh   s          rC   r   zMetricsLogger._del_key  sN   t|H5566! 	 	JE'11 ' 'FAsCMMA---!#J	 	 	 	 	 	 	 	 "#JEE	'
     G    	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s@   B.A7-	A76B7
BB
B
BBB#&B#c                    d }| j         5  ||                     |d          }t          |t                    r-|j        st          d| d          |j        cddd           S |i k    r|cddd           S  ||          cddd           S i fd}t          j        || j	                   rn|cddd           S # 1 swxY w Y   dS )a  Returns throughput values for Stats that have throughput tracking enabled.

        If no key is provided, returns a nested dict containing throughput values for all Stats
        that have throughput tracking enabled. If a key is provided, returns the throughput value
        for that specific key or nested structure.

        The throughput values represent the rate of change of the corresponding metrics per second.
        For example, if a metric represents the number of steps taken, its throughput value would
        represent steps per second.

        Args:
            key: Optional key or nested key path to get throughput for. If provided, returns just
                the throughput value for that key or nested structure. If None, returns a nested dict
                with throughputs for all metrics.
            default: Default value to return if no throughput values are found.
        Returns:
            If key is None: A nested dict with the same structure as self.stats but with "_throughput"
                appended to leaf keys and throughput values as leaf values. Only includes entries for
                Stats objects that have throughput tracking enabled.

            If key is provided: The throughput value for that specific key or nested structure.
        c                     d }i }t          j        |           D ]T\  }} |||          \  }}t          |t                    r+|}|dd         D ]}||vri ||<   ||         }|||d         <   U|S )z@Helper function to calculate throughputs for a nested structure.c                     t          |t                    r4|j        r-t          |           }|d d         |d         dz   fz   |j        fS | |fS )N_throughputsrs   r   r   r   throughputs)r_   r6   rU   s      rC   
_transformzOMetricsLogger._get_throughputs.<locals>._nested_throughputs.<locals>._transform@  s^    eY// UE4I U%d++Css8s2w'?&AA5CTTTU{"rE   Nr   )rk   flatten_with_pathrs   float)	rB   r   resultr_   r6   new_path	new_valuer   ks	            rC   _nested_throughputsz;MetricsLogger._get_throughputs.<locals>._nested_throughputs=  s    # # # F#5e<< 4 4e&0ju&=&=#)i// 4"E%crc] ) )E>>')E!H %a*3E(2,'MrE   NFro   zKey 'z+' does not have throughput tracking enabledc                     t          |t                    r_|j        rZt          |           }|d d         |d         dz   fz   }}|d d         D ]}||vri ||<   ||         }|j        ||d         <   d S d S d S )Nr   _throughputr   )r_   rB   rU   r   r   r   s        rC   r   z,MetricsLogger._get_throughputs.<locals>._maph  s    eY// 7E4I 7%d++Ccrc(c"g&=%??C'E "X ) )E>>')E!H %a%*%6E#b'NNN7 7 7 7rE   )
rM   rr   rs   r   r   rg   r   rk   rl   rB   )rR   rU   r]   r   rB   r   r   s         @rC   rq   zMetricsLogger._get_throughputs#  s   4	 	 	. ! $	; $	;cU;;eY// 6 0 (TCTTT   !,$	; $	; $	; $	; $	; $	; $	; $	; b[["$	; $	; $	; $	; $	; $	; $	; $	;  /.u55!$	; $	; $	; $	; $	; $	; $	; $	;$ K7 7 7 7 7 (tz:::"-:;;7I$	; $	; $	; $	; $	; $	; $	; $	; $	; $	; $	; $	; $	; $	; $	; $	; $	; $	;s$   AC(C<
C&CC
C
c                     |                                  }|                     d          }t          ||pi d           fd |          S )aH  Compiles all current values and throughputs into a single dictionary.

        This method combines the results of all stats and throughputs into a single
        dictionary, with throughput values having a "_throughput" suffix. This is useful
        for getting a complete snapshot of all metrics and their throughputs in one call.

        Returns:
            A nested dictionary containing both the current values and throughputs for all
            metrics. The structure matches self.stats, with throughput values having
            "_throughput" suffix in their keys.
        Trx   )new_keys_allowedc                     t          | t                    r,i }|                                 D ]\  }} |          ||<   |S t          | t                    rt	          |           dk    r| d         S | S | S r   )rs   rt   r   r   r   )r   r   rU   r6   traverse_dicts       rC   r   z,MetricsLogger.compile.<locals>.traverse_dict  s    !T"" "#'')) 9 9JC$1M%$8$8HSMMAt$$ q66Q;;Q4K rE   )rq   r*   r   )rR   r   r/   r   s      @rC   rY   zMetricsLogger.compilez  sp     ++-- T**FK-2EEEE	 	 	 	 	 }V$$$rE    z$Tensor mode is not required anymore.c                     d S r   r   r   s    rC   activate_tensor_modez"MetricsLogger.activate_tensor_mode  	     	rE   c                     d S r   r   r   s    rC   deactivate_tensor_modez$MetricsLogger.deactivate_tensor_mode  r   rE   )NNTFF)TF)r(   N)NN),__name__
__module____qualname____doc__r<   r   r   rj   r   r   rT   r	   r   boolrX   r   re   staticmethodr|   r
   intr   r   r   r   r   r   r   r   r   r*   r   r   r   r   r   rW   rr   r   r   rq   rY   r   r   r   rE   rC   rI   rI   t   s)        *  %1 1 #d9o%&
1 1 1 18
'c5c?&: ; 
' 
' 
' 
' 
' 26 #(E# E#3c3h-.E# 	E#
 E# !E# 
E# E# E# E#N 
 
c 
D 
C 
 
 
 \
( .2%)8<*:*.0@8HR1 R1 R13c3h'(R1 	R1
 sEz*+R1 E?R1 eDItO45R1 "$R1 "$R1 'uoR1 (0~R1 sCx.R1 
R1 R1 R1 R1r !%.2%)8<*:*.0@8HW W W3c3h'(W W
 W sEz*+W E?W eDItO45W "$W "$W 'uoW (0~W sCx.W 
W W W Wz 6: &.2%)8<*:*.0@8H3; 3; 3; eCsCx012	3;
 3; sEz*+3; E?3; eDItO453; "$3; "$3; 'uo3; (0~3; 
3; 3; 3; 3;j ZKu---/ / .-/ 6:	V* V* V*$sCx.)V* eCsCx012	V*
 
V* V* V* V*x .2%)8<*:*.0@8HD" D" D"3c3h'(D" 	D"
 sEz*+D" E?D" eDItO45D" "$D" "$D" 'uoD" (0~D" 
D" D" D" D"LE Ed Et E E E E2 Zr  
   
   
 ?C & & &5c? &t &t & & & &%4S> % % % %";tCH~ ;$ ; ; ; ;6 04      +/$     # # #"   " JNU; U;E#uS#X"678U;	tU{	U; U; U; U;n#% #% #% #% #%J Z3  
  
 Z3  
  
  rE   rI   c                   (    e Zd ZddZd Zd Zd ZdS )	rL   Tr   c                     dS )NTr   )rR   blockingtimeouts      rC   acquirez_DummyRLock.acquire  s    trE   c                     d S r   r   r   s    rC   releasez_DummyRLock.release      rE   c                     | S r   r   r   s    rC   	__enter__z_DummyRLock.__enter__  s    rE   c                     d S r   r   )rR   exc_type	exc_value	tracebacks       rC   __exit__z_DummyRLock.__exit__  r  rE   N)Tr   )r   r   r   r  r  r  r  r   rE   rC   rL   rL     sU                   rE   rL   r   )0loggingrO   typingr   r   r   r   r   r   r	   numpyr:   rk   ray._common.deprecationr
   r   r   ray.rllib.utilsr   r   ray.rllib.utils.frameworkr   r   ray.rllib.utils.metrics.statsr   r   r   r   r   r   r   r   r   r   ray.util.annotationsr   r   _tftorch	getLoggerloggerr<   rj   r   rD   rI   rL   r   rE   rC   <module>r     si     @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @      U U U U U U U U U U 4 4 4 4 4 4 4 4 E E E E E E E E                        9 8 8 8 8 8 8 8=??2qq		;	'	' $#"
 
  B B4S> BD BY B B B BJ Wx x x x x x x xv         rE   