
    &`ir#                        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mZm	Z	m
Z
mZmZmZmZmZmZ d dlZd dlmZ d dlmZ d dlmZ  ej        e          Z ed          Zded	efd
Z	 d'deeg ef         ee
eef         gef         f         dee
eef                  de	dee         d	eg ef         f
dZ G d dee                   Z d(de!fdZ"d Z#d Z$deeee         f         d	eeee         f         fdZ%e j&        dee	         d	ed         fd            Z'de(d	efdZ)ded	efd Z*	 d)d!e+d"e,d	efd#Z-d	e!fd$Z.d(d%e!d	efd&Z/dS )*    N)datetime)
AnyCallableContextManagerDict	GeneratorGenericListOptionalTypeVarUnion)count_required_parameters)UserExceptionWithTraceback)	ObjectRefTbundlereturnc                     |                                  } |                     dd          |                     dd          |                     dd          d}| r| |d<   |S )zConvert a bundle of resources to Ray actor/task arguments.

    >>> bundle_to_remote_args({"GPU": 1, "memory": 1, "custom": 0.1})
    {'num_cpus': 0, 'num_gpus': 1, 'memory': 1, 'resources': {'custom': 0.1}}
    CPUr   GPUmemory)num_cpusnum_gpusr   	resources)copypop)r   argss     o/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/train/v2/_internal/util.pybundle_to_remote_argsr      si     [[]]FJJua((JJua((**Xq)) D
  #"[K    train_loop_per_worker
train_funcconfigtrain_func_contextfn_arg_namec                      t                     }|dk    r| d| d}t          |          |dk    r&pi t          j                    fd            }n t          j                    fd            }|S )a  Validates and constructs the training function to execute.
    Args:
        train_func: The training function to execute.
            This can either take in no arguments or a ``config`` dict.
        config (Optional[Dict]): Configurations to pass into
            ``train_func``. If None then an empty Dict will be created.
        train_func_context: Context manager for user's `train_func`, which executes
            backend-specific logic before and after the training function.
        fn_arg_name (Optional[str]): The name of training function to use for error
            messages.
    Returns:
        A valid training function.
    Raises:
        ValueError: if the input ``train_func`` is invalid.
       z: should take in 0 or 1 required arguments, but it accepts z required arguments instead.c                  b                 5              cd d d            S # 1 swxY w Y   d S N )r#   r"   r$   s   r   train_fnz&construct_train_func.<locals>.train_fnQ   s    ##%% * *!z&))* * * * * * * * * * * * * * * * * *s   $((c                  `                 5                cd d d            S # 1 swxY w Y   d S r)   r*   )r"   r$   s   r   r+   z&construct_train_func.<locals>.train_fnX   s    ##%% $ $!z||$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $s   
#'')r   
ValueError	functoolswraps)r"   r#   r$   r%   num_required_paramserr_msgr+   s   ```    r   construct_train_funcr2   0   s    * 4J??Q A A"A A A 	 !!!a2		$	$	* 	* 	* 	* 	* 	* 
%	$	* 	* 
	$	$	$ 	$ 	$ 	$ 	$ 
%	$	$ Or    c                   *    e Zd ZdZdefdZdefdZdS )ObjectRefWrapperz>Thin wrapper around ray.put to manually control dereferencing.objc                 8    t          j        |          | _        d S r)   )rayput_ref)selfr5   s     r   __init__zObjectRefWrapper.__init__c   s    GCLL			r    r   c                 4    t          j        | j                  S r)   )r7   getr9   )r:   s    r   r=   zObjectRefWrapper.getf   s    wty!!!r    N)__name__
__module____qualname____doc__r   r;   r=   r*   r    r   r4   r4   `   sP        HH!A ! ! ! !"Q " " " " " "r    r4   F
include_msc                 `    d}| r|dz  }t          j                                        |          S )Nz%Y-%m-%d_%H-%M-%Sz.%f)r   todaystrftime)rB   patterns     r   date_strrG   j   s5    !G 5>$$W---r    c                  (    t          j                    S r)   )time	monotonicr*   r    r   time_monotonicrK   q   s    >r    c                       fd}|S )Nc                      j         | _         | S r)   )rA   )func	copy_funcs    r   wrappedz_copy_doc.<locals>.wrappedv   s     (r    r*   )rO   rP   s   ` r   	_copy_docrQ   u   s#         Nr    object_refsc                 T   t          | t                    }|r| n| g} | }i |rJt          j        |d          \  }}|r-t	          |t          j        |                    D ]
\  }}||<   |Jt                    t          |           k    sJ fd| D             }|r|n|d         S )a  This is a safe version of `ray.get` that raises an exception immediately
    if an input task dies, while the others are still running.

    TODO(ml-team, core-team): This is NOT a long-term solution,
    and we should not maintain this function indefinitely.
    This is a mitigation for a Ray Core bug, and should be removed when
    that is fixed.
    See here: https://github.com/ray-project/ray/issues/47204

    Args:
        object_refs: A single or list of object refs to wait on.

    Returns:
        task_outputs: The outputs of the tasks.

    Raises:
        `RayTaskError`/`RayActorError`: if any of the tasks encounter a runtime error
            or fail due to actor/task death (ex: node failure).
    r'   )num_returnsc                      g | ]
}|         S r*   r*   ).0tasktask_to_outputs     r   
<listcomp>z ray_get_safe.<locals>.<listcomp>   s    DDD~d+DDDr    r   )
isinstancelistr7   waitzipr=   len)rR   is_listunreadyreadyrW   task_outputordered_outputsrX   s          @r   ray_get_saferd   }   s    , d++G!(;++{mKGN
 3'q999w 	3%(%?%? 3 3!k'2t$$	  3 ~#k"2"22222DDDDDDDO%=???1+==r    context_managers)NNNc              #      K   t          j                    5 }| D ]}|                     |                        dV  ddd           dS # 1 swxY w Y   dS )z
    Utility to invoke a list of context managers and yield sequentially.

    Args:
        context_managers: List of context managers to invoke.
    N)
contextlib	ExitStackenter_context)re   stackcontext_managers      r   invoke_context_managersrl      s       
			 5/ 	3 	3O 1 12222                 s   'A

AAr5   c                 $    | j          d| j         S )zReturns the full module name of the given object, including its qualified name.

    Args:
        obj: The object (class, function, etc.) whose module name is required.

    Returns:
        Full module and qualified name as a string.
    .)r?   r@   )r5   s    r   get_module_namero      s     n11s/111r    fnc                     t          | t          j                  rt          | j                  S t          | d          r| j        S | j        j        S )a  Returns a readable name for any callable.

    Examples:

        >>> get_callable_name(lambda x: x)
        '<lambda>'
        >>> def foo(a, b): pass
        >>> get_callable_name(foo)
        'foo'
        >>> from functools import partial
        >>> bar = partial(partial(foo, a=1), b=2)
        >>> get_callable_name(bar)
        'foo'
        >>> class Dummy:
        ...     def __call__(self, a, b): pass
        >>> get_callable_name(Dummy())
        'Dummy'
    r>   )rZ   r.   partialget_callable_namerN   hasattrr>   	__class__)rp   s    r   rs   rs      sR    & "i'(( * ))) r: { <  r    eexclude_framesc                     t          j        t          t          j        | j                            |z
             }t
                              d|            t          | |          S )a@  Construct a UserExceptionWithTraceback from a base exception.

    Args:
        e: The base exception to construct a UserExceptionWithTraceback from.
        exclude_frames: The number of frames to exclude from the beginnning of
            the traceback.

    Returns:
        A UserExceptionWithTraceback object.
    )limitzError in training function:
)traceback_str)	traceback
format_excr^   
extract_tb__traceback__loggererrorr   )rv   rw   exc_traceback_strs      r   'construct_user_exception_with_tracebackr      sn     ",I(99::^KL   LLD1BDDEEE%a7HIIIIr    c                  J    ddl m}  	  |              dS # t          $ r Y dS w xY w)z6Check if the current process is a Ray Train V2 worker.r   get_train_fn_utilsTF)/ray.train.v2._internal.execution.train_fn_utilsr   RuntimeErrorr   s    r   _in_ray_train_workerr      sO    RRRRRRt   uus   
 
""raise_in_tune_sessionc                 0     dt           dt           f fd}|S )a  Check that the caller is a Ray Train worker spawned by Ray Train,
    with access to training function utilities.

    Args:
        raise_in_tune_session: Whether to raise a specific error message if the caller
            is in a Tune session. If True, will raise a DeprecationWarning.

    Returns:
        A decorator that performs this check, which raises an error if the caller
        is not a Ray Train worker.
    rp   r   c                 J     t          j                    fd            }|S )Nc                      ddl m} r" |            rt          dj         d          t	                      st          dj         d           | i |S )Nr   )_in_tune_sessionz`ray.train.z` is deprecated when running in a function passed to Ray Tune. Please use the equivalent `ray.tune` API instead. See this issue for more context: https://github.com/ray-project/ray/issues/49454`z` cannot be used outside of a Ray Train training function. You are calling this API from the driver or another non-training process. These utilities are only available within a function launched by `trainer.fit()`.)%ray.tune.trainable.trainable_fn_utilsr   DeprecationWarningr>   r   r   )r   kwargsr   rp   r   s      r   _wrapped_fnz9requires_train_worker.<locals>._wrap.<locals>._wrapped_fn  s    NNNNNN$ )9)9);); (F"+ F F F   ()) "h h h h  
 2t&v&&&r    )r.   r/   )rp   r   r   s   ` r   _wrapz$requires_train_worker.<locals>._wrap  s?    				' 	' 	' 	' 	' 
		'& r    )r   )r   r   s   ` r   requires_train_workerr      s6    ( x      . Lr    )r!   )F)r   )0rg   r.   loggingrI   r{   r   typingr   r   r   r   r   r	   r
   r   r   r   r7   ray.train._internal.utilsr   !ray.train.v2._internal.exceptionsr   	ray.typesr   	getLoggerr>   r   r   dictr   strr2   r4   boolrG   rK   rQ   rd   contextmanagerrl   objectro   rs   BaseExceptionintr   r   r   r*   r    r   <module>r      s                                              


 ? ? ? ? ? ? H H H H H H      		8	$	$ GCLL$ 4    * "9	- -hr1uoxc3h0@!0C'DDE-T#s(^$- '- #	-
 b!e_- - - -`" " " " "wqz " " ". . . . . .    #>y$y/12#>
3S	>#> #> #> #>L >*    	2 	2C 	2 	2 	2 	2!( !s ! ! ! !> -.J JJ&)JJ J J J,d    $ $ $( $ $ $ $ $ $r    