
    &`i3                        d dl Z d dlZd dlZd dlmZmZm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 d dlmZmZmZ erd dlmZ  e j        e          Ze	 d4deded	ee         fd
            Zed5dddefd            Zed6defd            Zed6defd            Z G d d          Z  G d d          Z! G d d          Z"ed             Z#ed6defd            Z$ G d d          Z% G d d          Z& G d  d!          Z'ed6defd"            Z(d# Z)e	 	 	 	 	 	 	 d7d&eded'ed(ed)ed	ee         d*ee         d+ee         d,efd-            Z* ed.d/d01          d8d2ee         defd3            Z+dS )9    N)TYPE_CHECKINGAnyOptional)
Deprecated)DeveloperAPI	PublicAPI)TensorShapeTensorStructType
TensorType)AlgorithmConfigdata	frameworkdevicec                     |dk    rddl m}  || |          S |dk    r*t                      \  }}t          j        fd|           S t          d| d          )	au  Converts any nested numpy struct into framework-specific tensors.

    Args:
        data: The input data (numpy) to convert to framework-specific tensors.
        framework: The framework to convert to. Only "torch" and "tf2" allowed.
        device: An optional device name (for torch only).

    Returns:
        The converted tensor struct matching the input data.
    torchr   )convert_to_torch_tensor)r   tf2c                 .                         |           S N)convert_to_tensor)stfs    m/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/rllib/utils/framework.py<lambda>z#convert_to_tensor.<locals>.<lambda>/   s    B,@,@,C,C     z
framework=z( not supported in `convert_to_tensor()`!)ray.rllib.utils.torch_utilsr   try_import_tftreemap_structureNotImplementedError)r   r   r   r   _r   s        @r   r   r      s      GGGGGGG&&tF;;;;	e		 ??2q!"C"C"C"CTJJJ
HYHHH  r      configr   num_gpus_requestedc                 
   | j         dk    rt                      \  }}|dk    rddlm}  |            }t	          |          dk    rCt
          j        j                                        t
          j        j        j	        k    r|d         S | j
        |j                                        k     sJ d| j
         d            |                    | j
                  S |                    d          S t          d| j          d	          )
a  Returns a single device (CPU or some GPU) depending on a config.

    Args:
        config: An AlgorithmConfig to extract information from about the device to use.
        num_gpus_requested: The number of GPUs actually requested. This may be the value
            of `config.num_gpus_per_env_runner` when for example calling this function
            from an EnvRunner.

    Returns:
        A single device (or name) given `config` and `num_gpus_requested`.
    r   r   )get_devicesr"   zlocal_gpu_idx z+ is not a valid GPU ID or is not available.cpuz`framework_str` z not supported!)framework_strtry_import_torchray.air._internal.torch_utilsr&   lenray_privateworker_modeWORKER_MODElocal_gpu_idxcudadevice_countr   r    )r#   r$   r   r!   r&   devicess         r   
get_devicer5   5   s    w&&#%%q
 !!AAAAAA "kmmG G!!L'--//3<3F3RRRqz!+ej.E.E.G.GGGG+V%9 + + + HGG ||F$8999<<&&&!Dv3DDD
 
 	
r   Ferrorc                     dt           j        v rt                              d           dS 	 ddl}ddl}n"# t          $ r | rt          d          Y dS w xY w||fS )a*  Tries importing JAX and FLAX and returns both modules (or Nones).

    Args:
        error: Whether to raise an error if JAX/FLAX cannot be imported.

    Returns:
        Tuple containing the jax- and the flax modules.

    Raises:
        ImportError: If error=True and JAX is not installed.
    RLLIB_TEST_NO_JAX_IMPORTz$Not importing JAX for test purposes.)NNr   NzCould not import JAX! RLlib requires you to install at least one deep-learning framework: `pip install [torch|tensorflow|jax]`.)osenvironloggerwarningflaxjaxImportError)r6   r=   r>   s      r   try_import_jaxr@   i   s     "RZ//=>>>z




    	8  
 zz 9s   5 AAc                    t                      }dt          j        v rt                              d           d|dfS dt          j        vrdt          j        d<   d}dt
          j        v rt
          j        d         }d}n,	 d	dl}n&# t          $ r | rt          d
          d|dfcY S w xY w	 |j	        j
        }|j                            |j        j                   |s(|                                 |                                 |j                            |j        j                   n# t"          $ r |}Y nw xY wt%          |d          sd}nd|j        dd         v rdnd}|||fS )a  Tries importing tf and returns the module (or None).

    Args:
        error: Whether to raise an error if tf cannot be imported.

    Returns:
        Tuple containing
        1) tf1.x module (either from tf2.x.compat.v1 OR as tf1.x).
        2) tf module (resulting from `import tensorflow`). Either tf1.x or
        2.x. 3) The actually installed tf version as int: 1 or 2.

    Raises:
        ImportError: If error=True and tf is not installed.
    RLLIB_TEST_NO_TF_IMPORTz*Not importing TensorFlow for test purposesNTF_CPP_MIN_LOG_LEVEL3F
tensorflowTr   zCould not import TensorFlow! RLlib requires you to install at least one deep-learning framework: `pip install [torch|tensorflow|jax]`.__version__r"   z2.   )_TFStubr9   r:   r;   r<   sysmodulesrE   r?   compatv1loggingset_verbosityERRORdisable_v2_behaviorenable_resource_variablesWARNAttributeErrorhasattrrF   )r6   tf_stubwas_imported	tf_module
tf1_moduleversions         r   r   r      s     iiG !BJ..CDDDWd""RZ//-0
)*
 Ls{""K-			'***** 	' 	' 	' !<  
 $&&&&	'	%(
(();)ABBB 	3**,,,00222(();)@AAAA   


 9m,, @y4RaR888!!ay'))s%   ?B  B'&B'+A>D* *D98D9c                       e Zd ZddZd ZdS )rH   returnNc                 ,    t                      | _        d S r   )
_KerasStubkerasselfs    r   __init__z_TFStub.__init__   s    \\


r   c                     dS )NF r_   s    r   __bool__z_TFStub.__bool__   s    ur   r[   N)__name__
__module____qualname__ra   rd   rc   r   r   rH   rH      s7        " " " "    r   rH   c                       e Zd ZddZdS )r]   r[   Nc                     t           | _        d S r   )_FakeTfClassStubModelr_   s    r   ra   z_KerasStub.__init__   s    %


r   re   rf   rg   rh   ra   rc   r   r   r]   r]      s(        & & & & & &r   r]   c                       e Zd Zd ZdS )rk   c                      t          d          )Nz:Could not import `tensorflow`. Try pip install tensorflow.r?   r`   akws      r   ra   z_FakeTfClassStub.__init__   s    VWWWr   Nrm   rc   r   r   rk   rk      s(        X X X X Xr   rk   c                       fd}|S )zqConditional decorator for @tf.function.

    Use @tf_function(tf) instead to avoid errors if tf is not installed.c                 ^                                     r| S                     |           S r   )executing_eagerlyfunction)funcrW   s    r   	decoratorztf_function.<locals>.decorator   s3    	 ; ; = =K!!$'''r   rc   )rW   ry   s   ` r   tf_functionrz      s$    ( ( ( ( ( r   c                     dt           j        v rt                              d           dS 	 ddl}|S # t
          $ r}| r|Y d}~dS d}~ww xY w)zTries importing tfp and returns the module (or None).

    Args:
        error: Whether to raise an error if tfp cannot be imported.

    Returns:
        The tfp module.

    Raises:
        ImportError: If error=True and tfp is not installed.
    rB   z7Not importing TensorFlow Probability for test purposes.Nr   )r9   r:   r;   r<   tensorflow_probabilityr?   )r6   tfpes      r   try_import_tfpr      sx     !BJ..PQQQt,,,,
    	Gttttts   2 
AAAc                       e Zd Zd ZdS )_NNStubc                 R    d | _         t          | _        t                      | _        d S r   )
functional_FakeTorchClassStubModule_ParallelStubparallelrq   s      r   ra   z_NNStub.__init__  s    )%r   Nrm   rc   r   r   r   r     s#        ( ( ( ( (r   r   c                       e Zd Zd ZdS )r   c                      t          d          )Nz0Could not import `torch`. Try pip install torch.rp   rq   s      r   ra   z_FakeTorchClassStub.__init__  s    LMMMr   Nrm   rc   r   r   r   r     s(        N N N N Nr   r   c                       e Zd Zd ZdS )r   c                 6    t           | _        t           | _        d S r   )r   DataParallelDistributedDataParallelrq   s      r   ra   z_ParallelStub.__init__  s    /':$$$r   Nrm   rc   r   r   r   r     s#        ; ; ; ; ;r   r   c                     dt           j        v r(t                              d           t	                      S 	 ddl}ddlm} ||fS # t          $ r" | rt          d          t	                      cY S w xY w)a&  Tries importing torch and returns the module (or None).

    Args:
        error: Whether to raise an error if torch cannot be imported.

    Returns:
        Tuple consisting of the torch- AND torch.nn modules.

    Raises:
        ImportError: If error=True and PyTorch is not installed.
    RLLIB_TEST_NO_TORCH_IMPORTz(Not importing PyTorch for test purposes.r   NzCould not import PyTorch! RLlib requires you to install at least one deep-learning framework: `pip install [torch|tensorflow|jax]`.)	r9   r:   r;   r<   _torch_stubsr   torch.nnnnr?   )r6   r   r   s      r   r)   r)   "  s     $rz11ABBB~~by    	8  
 ~~s   A )A21A2c                  &    t                      } d | fS r   )r   )r   s    r   r   r   B  s    	B8Or   r   unnamed-variablevalue	trainabletf_nametorch_tensorshapedtyper[   c                    |dv rqddl }|pHt          | dt          | t                    r|j        nt          | t
                    r|j        nd          } |j        j        j	        |f| ||d|i nd|iS |dk    r|du rt                      \  }	}
t          | t          j                  st          j        |           } |	                    |           }||	j        t          j        fv r|                                }nS||	j        t          j        fv r|                                }n)||	j        t          j        fv r|                                }|r|                    |          }||_        |S | S )	a  Creates a tf variable, a torch tensor, or a python primitive.

    Args:
        value: The initial value to use. In the non-tf case, this will
            be returned as is. In the tf case, this could be a tf-Initializer
            object.
        framework: One of "tf", "torch", or None.
        trainable: Whether the generated variable should be
            trainable (tf)/require_grad (torch) or not (default: False).
        tf_name: For framework="tf": An optional name for the
            tf.Variable.
        torch_tensor: For framework="torch": Whether to actually create
            a torch.tensor, or just a python value (default).
        device: An optional torch device to use for
            the created torch tensor.
        shape: An optional shape to use iff `value`
            does not have any (e.g. if it's an initializer w/o explicit value).
        dtype: An optional dtype to use iff `value` does
            not have any (e.g. if it's an initializer w/o explicit value).
            This should always be a numpy dtype (e.g. np.float32, np.int64).

    Returns:
        A framework-specific variable (tf.Variable, torch.tensor, or
        python primitive).
    )r   r   r   Nr   )initializerr   r   r   r   T)rE   getattr
isinstancefloatfloat32intint32rK   rL   get_variabler)   npndarrayarray
from_numpyfloat64doubletorequires_grad)r   r   r   r   r   r   r   r   r   r   r!   var_s               r   r   r   G  s   H M!! 
%''BJJ %%%
 
 )ry|(
	
 

 ]rr%(8
 
 	
 
g		,$"6"6#%%q%,, 	$HUOOE&&U]BJ///::<<DDu{BH---88::DDu}bj111;;==D 	#776??D&Lr   z+rllib/utils/framework.py::get_activation_fnz(rllib/models/utils.py::get_activation_fnT)oldnewr6   namec                     d S r   rc   )r   r   s     r   get_activation_fnr     s	     	Dr   r   )r"   )F)r   Fr   FNNN)Nr   ),rM   r9   rI   typingr   r   r   numpyr   r   r,   ray._common.deprecationr   ray.rllib.utils.annotationsr   r   ray.rllib.utils.typingr	   r
   r   %ray.rllib.algorithms.algorithm_configr   	getLoggerrf   r;   strr   r   r5   boolr@   r   rH   r]   rk   rz   r   r   r   r   r)   r   r   r   rc   r   r   <module>r      sL    				 



 / / / / / / / / / /      



 . . . . . . ? ? ? ? ? ? ? ?           FEEEEEE		8	$	$  ! 
 SM   8 0
 0
( 0
c 0
 0
 0
 0
f  $    > >* >* >* >* >* >*D       & & & & & & & &X X X X X X X X
      $    6( ( ( ( ( ( ( (N N N N N N N N
; ; ; ; ; ; ; ;  D    >  
  % #'"&G GGG G 	G
 G SMG K G JG 	G G G GT 52
  
	 	HSM 	S 	 	 	 
	 	 	r   