o
    `۷i3                     @   s  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rBd dlmZ e eZe	d>deded	ee fd
dZed?dddefddZed@defddZed@defddZG dd dZ G dd dZ!G dd dZ"edd Z#ed@defd d!Z$G d"d# d#Z%G d$d% d%Z&G d&d' d'Z'ed@defd(d)Z(d*d+ Z)e	,		-				dAd.eded/ed0ed1ed	ee d2ee d3ee d4efd5d6Z*eed7d8d9d:dBd;ee defd<d=Z+dS )C    N)TYPE_CHECKINGAnyOptional)
Deprecated)DeveloperAPI	PublicAPI)TensorShapeTensorStructType
TensorType)AlgorithmConfigdata	frameworkdevicec                    sX   |dkrddl m} || |dS |dkr$t \} }t fd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
     | S N)convert_to_tensor)stf O/home/ubuntu/vllm_env/lib/python3.10/site-packages/ray/rllib/utils/framework.py<lambda>/   s   
 z#convert_to_tensor.<locals>.<lambda>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   r   r   r      s   
r      configr   num_gpus_requestedc                 C   s   | j dkrHt \}}|dkrCddlm} | }t|dkr,t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#   devicesr   r   r   
get_device5   s    


r2   Ferrorc                 C   sT   dt jv rtd dS zddl}ddl}W ||fS  ty)   | r&tdY dS w )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)r3   r9   r:   r   r   r   try_import_jaxi   s   



r<   c                 C   s  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zd	dl}W n tyE   | r>td
d|df Y S w z |j	j
}|j|jj |s]|  |  |j|jj W n tyq   |}Y nw t|dszd}nd|jdd v rd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.   )_TFStubr5   r6   r7   r8   sysmodulesr@   r;   compatv1loggingset_verbosityERRORdisable_v2_behaviorenable_resource_variablesWARNAttributeErrorhasattrrA   )r3   tf_stubwas_imported	tf_module
tf1_moduleversionr   r   r   r      sB   









r   c                   @   s   e Zd ZdddZdd ZdS )rC   returnNc                 C   s   t  | _d S r   )
_KerasStubkerasselfr   r   r   __init__   s   z_TFStub.__init__c                 C   s   dS )NFr   rX   r   r   r   __bool__   s   z_TFStub.__bool__rU   N)__name__
__module____qualname__rZ   r[   r   r   r   r   rC      s    
rC   c                   @   s   e Zd ZdddZdS )rV   rU   Nc                 C   s
   t | _d S r   )_FakeTfClassStubModelrX   r   r   r   rZ      s   
z_KerasStub.__init__r\   r]   r^   r_   rZ   r   r   r   r   rV      s    rV   c                   @      e Zd Zdd ZdS )r`   c                 O      t d)Nz:Could not import `tensorflow`. Try pip install tensorflow.r;   rY   akwr   r   r   rZ         z_FakeTfClassStub.__init__Nrb   r   r   r   r   r`          r`   c                    s    fdd}|S )zqConditional decorator for @tf.function.

    Use @tf_function(tf) instead to avoid errors if tf is not installed.c                    s    d u s   r
| S  | S r   )executing_eagerlyfunction)funcrR   r   r   	decorator   s   
ztf_function.<locals>.decoratorr   )rR   ro   r   rn   r   tf_function   s   rp   c              
   C   sV   dt jv rtd dS zddl}|W S  ty* } z| r|W Y d}~dS d}~w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.
    r=   z7Not importing TensorFlow Probability for test purposes.Nr   )r5   r6   r7   r8   tensorflow_probabilityr;   )r3   tfper   r   r   try_import_tfp   s   

rt   c                   @   rc   )_NNStubc                 O   s   d | _ t| _t | _d S r   )
functional_FakeTorchClassStubModule_ParallelStubparallelrf   r   r   r   rZ     s   z_NNStub.__init__Nrb   r   r   r   r   ru     rj   ru   c                   @   rc   )rw   c                 O   rd   )Nz0Could not import `torch`. Try pip install torch.re   rf   r   r   r   rZ     ri   z_FakeTorchClassStub.__init__Nrb   r   r   r   r   rw     rj   rw   c                   @   rc   )ry   c                 O   s   t | _t | _d S r   )rw   DataParallelDistributedDataParallelrf   r   r   r   rZ     s   
z_ParallelStub.__init__Nrb   r   r   r   r   ry     rj   ry   c                 C   s^   dt jv rtd t S zddl}ddlm} ||fW S  ty.   | r)tdt  Y S 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]`.)	r5   r6   r7   r8   _torch_stubsr   torch.nnnnr;   )r3   r   r   r   r   r   r&   "  s   



r&   c                  C   s   t  } d | fS r   )ru   )r   r   r   r   r~   B  s   r~   r   unnamed-variablevalue	trainabletf_nametorch_tensorshapedtyperU   c                 C   s  |dv r9ddl }|pt| dt| tr|jn	t| tr|jnd}|jjj	|f| ||d|du r3i S d|iS |dkr|du rt
 \}	}
t| tjsQt| } |	| }||	jtjfv rc| }n||	jtjfv rp| }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)r@   getattr
isinstancefloatfloat32intint32rF   rG   get_variabler&   npndarrayarray
from_numpyfloat64doubletorequires_grad)r   r   r   r   r   r   r   r   r   r   r   var_r   r   r   r   G  sL   $	






r   z+rllib/utils/framework.py::get_activation_fnz(rllib/models/utils.py::get_activation_fnT)oldnewr3   namec                 C   s   d S r   r   )r   r   r   r   r   get_activation_fn  s   r   r   )r    )F)r   Fr   FNNN)Nr   ),rH   r5   rD   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   	getLoggerr]   r7   strr   r   r2   boolr<   r   rC   rV   r`   rp   rt   ru   rw   ry   r&   r~   r   r   r   r   r   r   <module>   s    
3B

		J 