
    &`iL                        d dl Z d dlZd dlZd dlZd dl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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mZmZmZ d dl m!Z! d d	l"m#Z#m$Z$ d d
l%m&Z&m'Z' d dl(Z( ej)        e*          Z+d Z, ej                    Z-e& G d de                      Z.e&e/dddfdeg ef         deee/         eee/                  f         de0de0dee         de1fd            Z2e& G d d                      Z3e& G d de4                      Z5e&d             Z6d Z7d Z8e&defd            Z9d ed!e:d"e:d#e:fd$Z;d%e:d&e:dee         fd'Z< e'd()          	 	 	 	 	 d>d-eee0e:f                  d.e=d/e0d0e0d1ee=         f
d2            Z>e&	 	 d?d3ed4ee         d5e0fd6            Z?d7 Z@ e'            	 d@d9ee:         d:eeeef                  d;ed<e1fd=            ZAdS )A    N)defaultdict)datetime)Number)Thread)AnyCallableDictListOptionalSequenceTypeUnion)deep_updateflatten_dictmerge_dictsunflatten_dictunflatten_list_dictunflattened_lookup)SafeFallbackEncoder)is_nanis_nan_or_inf)DeveloperAPI	PublicAPIc                  6    	 dd l } n# t          $ r d } Y nw xY w| S Nr   )GPUtilImportError)r   s    g/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/tune/utils/util.py_import_gputilr   "   s;       Ms    c                   <     e Zd ZdZd	 fd	Zd Zd Zd Zd Z xZ	S )
UtilMonitora4  Class for system usage utilization monitoring.

    It keeps track of CPU, RAM, GPU, VRAM usage (each gpu separately) by
    pinging for information every x seconds in a separate thread.

    Requires psutil and GPUtil to be installed. Can be enabled with
    Tuner(param_space={"log_sys_usage": True}).
    Tffffff?c                    d| _         t                      }|| _        ||rt                              d           t
          |rt                              d           |	t
          d S t          t          |                                            || _	        t          t                    | _        t          j                    | _        d| _        |r|                                  d S d S )NTz)Install gputil for GPU system monitoring.z-Install psutil to monitor system performance.)stoppedr   r   loggerwarningpsutilsuperr!   __init__delayr   listvalues	threadingLocklockdaemonstart)selfr1   r*   r   	__class__s       r   r)   zUtilMonitor.__init__8   s    !!>e>NNFGGG>e>NNJKKK>fnFk4  ))+++
!$''N$$	 	JJLLLLL	 	    c                    | j         5  t          | j        d                             t	          t          j        d                                | j        d                             t	          t          j                    j                             | j        g }	 | j        	                                }n*# t          $ r t                              d           Y nw xY w|D ]}| j        dt          |j                  z                                t	          |j                             | j        dt          |j                  z                                t	          |j                             d d d            d S # 1 swxY w Y   d S )Ncpu_util_percent)intervalram_util_percentzGPUtil failed to retrieve GPUs.gpu_util_percentvram_util_percent)r/   r'   r,   appendfloatcpu_percentvirtual_memorypercentr   getGPUs	Exceptionr%   debugstridload
memoryUtil)r2   gpu_listgpus      r   _read_utilizationzUtilMonitor._read_utilizationM   s   Y 	 	!./66&,d;;;<<   ./66&/119::   {&D#{2244HH  D D DLL!BCCCCCD#  CK 2S[[ @AHHch   K 3c#&kk ABIIcn--   %	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s7   BFB76F7$CFCBFFFc                    | j         ri S | j        5  t          j        | j                  }| j                                        D ]
\  }}|d d = 	 d d d            n# 1 swxY w Y   dd |                                D             iS )Nperfc                 d    i | ]-\  }}t          |          d k    |t          j        |          .S )r   )lennpmean).0kvs      r   
<dictcomp>z(UtilMonitor.get_data.<locals>.<dictcomp>l   s2    TTT41aQRSBGAJJr4   )r$   r/   copydeepcopyr,   items)r2   
ret_valueskeyvals       r   get_datazUtilMonitor.get_datad   s    < 	IY 	 	t{33J K--//  SFF	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 TT:3C3C3E3ETTTUUs   >AA #A c                     d| _         | j         s6|                                  t          j        | j                   | j         4d S d S NF)r$   rI   timesleepr*   r2   s    r   runzUtilMonitor.runn   sW    , 	#""$$$Jtz""" , 	# 	# 	# 	# 	#r4   c                     d| _         d S )NT)r$   r_   s    r   stopzUtilMonitor.stopt   s    r4   )Tr"   )
__name__
__module____qualname____doc__r)   rI   rZ   r`   rb   __classcell__)r3   s   @r   r!   r!   -   s              *  .V V V# # #      r4   r!         fnexception_typenum_retries
sleep_timetimeoutreturnc                     t          j                     fd}t          |          D ]}                                 t          j        |          }d|_        |                                 |                    |           |                                r6t          
                    d|dz    d| dt           d	d                       n                                s dS t          j        |           d
S )Nc                      	               d S # $ r9} t                               |                                             Y d } ~ d S d } ~ ww xY wN)r%   r&   set)eerroredrk   rj   s    r   _try_fnzretry_fn.<locals>._try_fn   sa    	BDDDDD 	 	 	NN1KKMMMMMMMMM	s   
 A.AA)targetT)rn   zProcess timed out (try ri   /z): rc   F)r-   Eventrangeclearr   r0   r1   joinis_aliver%   rB   getattris_setr]   r^   )	rj   rk   rl   rm   rn   rv   iprocru   s	   ``      @r   retry_fnr   x   s4    oG       ;  w///

		'	"""==?? 	LL3!A# 3 3 3 32z4003 3    !! 	44 	
: 5r4   c            	           e Zd ZdZ eej                            dd                    ZdZ		 	 	 dde
dee         d	ee
         d
efdZd Zd ZdS )warn_if_slowa)  Prints a warning if a given operation is slower than 500ms.

    Example:
        >>> from ray.tune.utils.util import warn_if_slow
        >>> something = ... # doctest: +SKIP
        >>> with warn_if_slow("some_operation"): # doctest: +SKIP
        ...    ray.get(something) # doctest: +SKIP
    TUNE_WARN_THRESHOLD_Sg      ?zTThe `{name}` operation took {duration:.3f} s, which may be a performance bottleneck.NFname	thresholdmessagedisablec                 h    || _         |p| j        | _        |p| j        | _        d| _        || _        d S r\   )r   DEFAULT_THRESHOLDr   DEFAULT_MESSAGEr   too_slowr   )r2   r   r   r   r   s        r   r)   zwarn_if_slow.__init__   s;     	"<d&<6$"6r4   c                 6    t          j                     | _        | S rr   )r]   r1   r_   s    r   	__enter__zwarn_if_slow.__enter__   s    Y[[
r4   c                    t          j                     }| j        rd S || j        z
  | j        k    rZ|t          z
  dk    rNd| _        || j        z
  }t                              | j        	                    | j
        |                     d S d S d S )Ng      N@T)r   duration)r]   r   r1   r   START_OF_TIMEr   r%   r&   r   formatr   )r2   typevalue	tracebacknowr   s         r   __exit__zwarn_if_slow.__exit__   s    ikk< 	Fdn,,}1Dt1K1K DMTZ'HNN4<..DI.QQRRRRR -,1K1Kr4   )NNF)rc   rd   re   rf   r<   osenvirongetr   r   rC   r   boolr)   r   r    r4   r   r   r      s          bjnn-DcJJKK	1  &*!%  E? #	
      S S S S Sr4   r   c                       e Zd Zd Zd Zd Zd Zd Zed             Z	ed             Z
ed             Zd	 Zd
 Zd Zd ZdS )Teec                 0    || _         || _        d| _        d S r\   )stream1stream2_handling_warning)r2   r   r   s      r   r)   zTee.__init__   s      "'r4   c                     | j         rd S d| d| d}|d| d| z  }d| _         t                              |           d| _         d S )NzValueError when calling 'z' on stream (z). zargs: z	 kwargs: TF)r   r%   r&   )r2   opsargskwargsmsgs         r   _warnz	Tee._warn   so    
 ! 	FA"AA1AAA///v///!%s!&r4   c                     | j         | j        fD ]8}	  |j        |i | # t          $ r |                     d|||           Y 5w xY wd S )Nseek)r   r   r   
ValueErrorr   r2   r   r   r   s       r   r   zTee.seek   s|    ,- 	4 	4A4''''' 4 4 4

61dF333334	4 	4    "AAc                     | j         | j        fD ]8}	  |j        |i | # t          $ r |                     d|||           Y 5w xY wd S )Nwrite)r   r   r   r   r   r   s       r   r   z	Tee.write   |    ,- 	5 	5A5((((( 5 5 5

7AtV444445	5 	5r   c                     | j         | j        fD ]8}	  |j        |i | # t          $ r |                     d|||           Y 5w xY wd S )Nflush)r   r   r   r   r   r   s       r   r   z	Tee.flush   r   r   c                 \    t          | j        d          r| j        j        S | j        j        S )Nencoding)hasattrr   r   r   r_   s    r   r   zTee.encoding   ,    4<,, 	)<((|$$r4   c                 \    t          | j        d          r| j        j        S | j        j        S )Nerror)r   r   r   r   r_   s    r   r   z	Tee.error   s,    4<)) 	&<%%|!!r4   c                 \    t          | j        d          r| j        j        S | j        j        S )Nnewlines)r   r   r   r   r_   s    r   r   zTee.newlines  r   r4   c                     t           rr   NotImplementedErrorr_   s    r   detachz
Tee.detach      !!r4   c                     t           rr   r   r2   r   r   s      r   readzTee.read  r   r4   c                     t           rr   r   r   s      r   readlinezTee.readline  r   r4   c                     t           rr   r   r   s      r   tellzTee.tell  r   r4   N)rc   rd   re   r)   r   r   r   r   propertyr   r   r   r   r   r   r   r   r4   r   r   r      s        ' ' '' ' '4 4 45 5 55 5 5 % % X%
 " " X"
 % % X%
" " "" " "" " "" " " " "r4   r   c                  N    t          j                                        d          S )Nz%Y-%m-%d_%H-%M-%S)r   todaystrftimer   r4   r   date_strr     s    >$$%8999r4   c                 .    | t          j        d          fS )zConverts obj to a form that can be pinned in object store memory.

    Currently only numpy arrays are pinned in memory, if you have a strong
    reference to the array value.
    ri   )rN   zerosobjs    r   _to_pinnabler     s     !r4   c                     | d         S )z"Retrieve from _to_pinnable format.r   r   r   s    r   _from_pinnabler   (  s     q6Mr4   	trainablec                    ddl mm} fd}t          d|  d           	  |dt	          |           z   | d           t          d	           d
S # t
          $ r}t          d|            Y d}~nd}~ww xY wt          dt	          |            d           t          j        |           }t                      }|j	        r8t          dt          |j	                   d            ||j	        |d            |j        r8t          dt          |j                   d            ||j        |d            |st          d           |S t          d| d           |S )a  Utility for detecting why your trainable function isn't serializing.

    Args:
        trainable: The trainable object passed to
            tune.Tuner(trainable). Currently only supports
            Function API.

    Returns:
        bool | set of unserializable objects.

    Example:

    .. code-block:: python

        import threading
        # this is not serializable
        e = threading.Event()

        def test():
            print(e)

        diagnose_serialization(test)
        # should help identify that 'e' should be moved into
        # the `test` scope.

        # correct implementation
        def test():
            e = threading.Event()
            print(e)

        assert diagnose_serialization(test) is True

    r   )_check_serializabilityregister_trainablec                 R   |                                  D ]\  }}d }	  ||           d}nL# t          $ r?}d}|j        j         dt	          |           }|                    |           Y d }~nd }~ww xY w |t	          |           d| d|            |r ||           d S )NPASSEDFAILEDz: z[name='z'']... )rV   rA   r3   rc   rC   add)	objectsfailure_setprintervar_namevariabler   statusrt   r   s	           r   check_variablesz/diagnose_serialization.<locals>.check_variablesS  s    ")--// 	 	HhC*&&x:::! * * *!-99Q99))))))))* Gs8}}FFXFFfFFGGG 	 	s   -
A65A11A6zTrying to serialize z...z__test:F)warnzSerialization succeeded!TzSerialization failed: NzIInspecting the scope of the trainable by running `inspect.getclosurevars(z)`...z	Detected z. global variables. Checking serializability...c                 &    t          d| z             S Nz   printr   s    r   <lambda>z(diagnose_serialization.<locals>.<lambda>t  s    eai@P@P r4   z0 nonlocal variables. Checking serializability...c                 &    t          d| z             S r   r   r   s    r   r   z(diagnose_serialization.<locals>.<lambda>{  s    %PQ	BRBR r4   zNothing was found to have failed the diagnostic test, though serialization did not succeed. Feel free to raise an issue on github.zVariable(s) z was found to be non-serializable. Consider either removing the instantiation/imports of these objects or moving them into the scope of the trainable. )ray.tune.registryr   r   r   rC   rA   inspectgetclosurevarsrs   globalsrM   	nonlocals)r   r   r   rt   closurer   r   s         @r   diagnose_serializationr   .  s-   F MLLLLLLL     

/
/
/
/000,9s9~~5yuMMMM()))t , , ,*q**++++++++, 
	9#&y>>	9 	9 	9   $Y//G%%K R*GO,, * * *	
 	
 	
 	6P6PQQQ T*G-.. * * *	
 	
 	
 	);8R8RSSS 	
 	
 	

 ;   	
 	
 	
 s   -A 
A8A33A8statecheckpoint_dir	file_nametmp_file_namec                 4   ddl m} t          j                            ||          }t          |d          5 }|                    | |           ddd           n# 1 swxY w Y   t          j        |t          j                            ||                     dS )aS  Atomically saves the state object to the checkpoint directory.

    This is automatically used by Tuner().fit during a Tune job.

    Args:
        state: Object state to be serialized.
        checkpoint_dir: Directory location for the checkpoint.
        file_name: Final name of file.
        tmp_file_name: Temporary name of file.
    r   Nwb)ray.cloudpicklecloudpickler   pathr|   opendumpreplace)r   r   r   r   r   tmp_search_ckpt_pathfs          r   _atomic_saver    s     *)))))7<<FF	"D	)	) #Q"""# # # # # # # # # # # # # # # J#RW\\.)%L%LMMMMMs   AA!Adirpathckpt_patternc                    ddl m} t          j        t          j                            | |                    }|sdS t          |          }t          |d          5 }|                    |          }ddd           n# 1 swxY w Y   |S )ah  Returns the most recently modified checkpoint.

    Assumes files are saved with an ordered name, most likely by
    :obj:atomic_save.

    Args:
        dirpath: Directory in which to look for the checkpoint file.
        ckpt_pattern: File name pattern to match to find checkpoint
            files.

    Returns:
        (dict) Deserialized state dict.
    r   Nrb)	r   r   globr   r   r|   maxr   rE   )r  r  r   
full_pathsmost_recent_checkpointr   checkpoint_states          r   _load_newest_checkpointr    s     *)))))27<<>>??J  __	$d	+	+ /q&++A../ / / / / / / / / / / / / / /s   A>>BBbeta)	stability{Gz?      gpu_idtarget_utilretrydelay_sgpu_memory_limitc                 L   
 t                      }|t          d           ,t          j                    }|st          d          |d          d
t	           t
                    r'                                 rt                      n8d
n5t	           t                    s t          dt                      d          
fd	fd
|
                                D             } |vrt            d| d          t          t          |                    D ]x}t           fd|
                                D                       }	|	j        |k    r;t                              d| d|	j        d           t!          j        |           v dS t          d          )aO  Checks if a given GPU has freed memory.

    Requires ``gputil`` to be installed: ``pip install gputil``.

    Args:
        gpu_id: GPU id or uuid to check.
            Must be found within GPUtil.getGPUs(). If none, resorts to
            the first item returned from `ray.get_gpu_ids()`.
        target_util: The utilization threshold to reach to unblock.
            Set this to 0 to block until the GPU is completely free.
        retry: Number of times to check GPU limit. Sleeps `delay_s`
            seconds between checks.
        delay_s: Seconds to wait before check.

    Returns:
        bool: True if free.

    Raises:
        RuntimeError: If GPUtil is not found, if no GPUs are detected
            or if the check fails.

    Example:

    .. code-block:: python

        def tune_func(config):
            tune.utils.wait_for_gpu()
            train()

        tuner = tune.Tuner(
            tune.with_resources(
                tune_func,
                resources={"gpu": 1}
            ),
            tune_config=tune.TuneConfig(num_samples=10)
        )
        tuner.fit()

    Nz3GPUtil must be installed if calling `wait_for_gpu`.zPNo GPU ids found from `ray.get_gpu_ids()`. Did you set Tune resources correctly?r   rD   uuidzgpu_id (z) must be type str/int.c                 $    t          |           S rr   )r~   )ggpu_attrs    r   	gpu_id_fnzwait_for_gpu.<locals>.gpu_id_fn  s     q(###r4   c                 &    h | ]} |          S r   r   )rP   r  r  s     r   	<setcomp>zwait_for_gpu.<locals>.<setcomp>  s!    666yy||666r4   z% not found in set of available GPUs: zt. `wait_for_gpu` takes either GPU ordinal ID (e.g., '0') or UUID (e.g., 'GPU-04546190-b68d-65ac-101b-035f8faed77d').c              3   :   K   | ]} |          k    |V  d S rr   r   )rP   r  r  r  s     r   	<genexpr>zwait_for_gpu.<locals>.<genexpr>  s5      PP19O9O!9O9O9O9OPPr4   zWaiting for GPU util to reach z. Util: z0.3fTzGPU memory was not freed.)r   RuntimeErrorrayget_gpu_ids
isinstancerC   isdigitintr   r   r@   rz   nextrF   r%   infor]   r^   )r  r  r  r  r  r   gpu_id_listgpu_idsr   
gpu_objectr  r  s   `         @@r   wait_for_gpur+    s   ^ F~PQQQ~o'' 	8   QH&# K>> 	 [[FF
 HH$$ KIDLLIIIJJJ$ $ $ $ $
 7666V^^%5%5666GW G GG G G G
 
 	
 3u:: 	 	PPPPPV^^%5%5PPPPP
 ;..KK6 6 6#.56 6   Jw44
2
3
33r4   trainable_clsconfignum_gpusc                    t          j                    s
J d             t          j        |          |           }|                    |          }|                    |          }ddlm} t          d          D ]-}t          j        |j                                                  }.|                    |          s
J d            t          j        |j                            |j	                                                             t          j        |j                                                  }||         dk    sJ t          j        |j                                                  }||         d	k    sJ d
S )a  Helper method to check if your Trainable class will resume correctly.

    Args:
        trainable_cls: Trainable class for evaluation.
        config: Config to pass to Trainable when testing.
        num_gpus: GPU resources to allocate when testing.
        use_object_store: Whether to save and restore to Ray's object
            store. Recommended to set this to True if planning to use
            algorithms that pause training (i.e., PBT, HyperBand).
    zNeed Ray to be initialized.)r.  )r-  r   )TRAINING_ITERATIONrh   zQValidation will not pass because it requires `training_iteration` to be returned.   r  T)
r!  is_initializedremoteray.air.constantsr0  rz   r   trainrestoresave)	r,  r-  r.  
remote_clstrainable_1trainable_2r0  _ress	            r   validate_save_restorer=     s~     >>!>>>.X...}==J##6#22K##6#22K4444441XX 2 2gk'..001177%&&  	 &
 GK&&{'7'>'>'@'@AABBB
'+#**,,
-
-C!"a''''
'+#**,,
-
-C!"a''''4r4   c                     t          j        |           }d}	 |                    i            n@# t          $ r3}t                              t          |                     d}Y d}~nd}~ww xY w|S )zCheck if func({}) works.TFN)r   	signaturebindrA   r%   rB   rC   )funcfunc_siguse_config_singlert   s       r   _detect_config_singlerD  J  s     &&H"b " " "SVV!" s   . 
A+)A&&A+Tparameter_namespoints_to_evaluateevaluated_rewardsvalidate_point_name_lengthsc                    |rt          |t                    s/t          d                    t	          |                              |D ]}t          |t
          t          f          st          d| d          |r[t          |          t          |           k    s;t          d                    |          d                    |           z   dz             |r|rt          |t                    s/t          d                    t	          |                              t          |          t          |          k    s?t          d                    |          d	                    |          z   dz             d
S d
S d
S )a5  Generic validation of a Searcher's warm start functionality.
    Raises exceptions in case of type and length mismatches between
    parameters.

    If ``validate_point_name_lengths`` is False, the equality of lengths
    between ``points_to_evaluate`` and ``parameter_names`` will not be
    validated.
    z1points_to_evaluate expected to be a list, got {}.z9points_to_evaluate expected to include list or dict, got .zDim of point {}z and parameter_names {}z do not match.z0evaluated_rewards expected to be a list, got {}.zDim of evaluated_rewards {}z and points_to_evaluate {}N)r#  r+   	TypeErrorr   r   dictrM   r   )rE  rF  rG  rH  points        r   validate_warmstartrN  V  s     ,d33 	CJJ+,,   
 ( 	 	EedD\22 $ $ $ $  
 + CJJ#oBVBV4V4V %,,U33/66GGH&'    / +T22 	BII*++   
 $%%-?)@)@@@-445FGG.556HIIJ"#      A@r4   )Nr  r  r  Nr   )T)BrT   r  r   loggingr   r-   r]   collectionsr   r   numbersr   r   typingr   r   r	   r
   r   r   r   r   numpyrN   r!  ray._private.dictr   r   r   r   r   r   ray.air._internal.jsonr   ray.air._internal.utilr   r   ray.util.annotationsr   r   r'   	getLoggerrc   r%   r   r   r!   rA   r%  r   r   r   objectr   r   r   r   r   rC   r  r  r<   r+  r=  rD  rN  r   r4   r   <module>rZ     s       				      # # # # # #                   M M M M M M M M M M M M M M M M M M M M     



                7 6 6 6 6 6 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 		8	$	$   	 G G G G G& G G GT  IR $$ $S$$y/8DO+DDE$ $ 	$
 f$ 
$ $ $ $N (S (S (S (S (S (S (S (SV I" I" I" I" I"& I" I" I"X : : :     \h \ \ \ \~N Nc Nc NRU N N N N(S      2 V(,(,a4 a4U38_%a4a4 a4 	a4
 uoa4 a4 a4 a4H  "& &&TN& & & & &R	 	 	 
 )-	/ /#Y/U4:.// / "&	/ / / / / /r4   