o
    1 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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 e/home/app/PaddleOCR-VL-test/.venv_paddleocr/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()`!)Zray.rllib.utils.torch_utilsr   try_import_tftreeZ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!)Zframework_strtry_import_torchZray.air._internal.torch_utilsr!   lenrayZ_privateZworker_modeZWORKER_MODEZlocal_gpu_idxcudaZdevice_countr   r   )r   r    r   r   r!   Zdevicesr   r   r   
get_device5   s    


r(   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.
    Z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)r)   r.   r/   r   r   r   try_import_jaxi   s   



r1   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 purposesNZ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.   )_TFStubr*   r+   r,   r-   sysmodulesr4   r0   compatv1loggingZset_verbosityERRORZdisable_v2_behaviorZenable_resource_variablesWARNAttributeErrorhasattrr5   )r)   Ztf_stubZwas_imported	tf_moduleZ
tf1_moduleversionr   r   r   r      sB   









r   c                   @   s   e Zd ZdddZdd ZdS )r7   returnNc                 C   s   t  | _d S r   )
_KerasStubZkerasselfr   r   r   __init__   s   z_TFStub.__init__c                 C   s   dS )NFr   rE   r   r   r   __bool__   s   z_TFStub.__bool__rC   N)__name__
__module____qualname__rG   rH   r   r   r   r   r7      s    
r7   c                   @   s   e Zd ZdddZdS )rD   rC   Nc                 C   s
   t | _d S r   )_FakeTfClassStubZModelrE   r   r   r   rG      s   
z_KerasStub.__init__rI   rJ   rK   rL   rG   r   r   r   r   rD      s    rD   c                   @      e Zd Zdd ZdS )rM   c                 O      t d)Nz:Could not import `tensorflow`. Try pip install tensorflow.r0   rF   akwr   r   r   rG         z_FakeTfClassStub.__init__NrN   r   r   r   r   rM          rM   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   )Zexecuting_eagerlyfunction)funcrA   r   r   	decorator   s   
ztf_function.<locals>.decoratorr   )rA   rZ   r   rY   r   tf_function   s   r[   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.
    r2   z7Not importing TensorFlow Probability for test purposes.Nr   )r*   r+   r,   r-   Ztensorflow_probabilityr0   )r)   tfper   r   r   try_import_tfp   s   

r^   c                   @   rO   )_NNStubc                 O   s   d | _ t| _t | _d S r   )Z
functional_FakeTorchClassStubModule_ParallelStubZparallelrR   r   r   r   rG     s   z_NNStub.__init__NrN   r   r   r   r   r_     rV   r_   c                   @   rO   )r`   c                 O   rP   )Nz0Could not import `torch`. Try pip install torch.rQ   rR   r   r   r   rG     rU   z_FakeTorchClassStub.__init__NrN   r   r   r   r   r`     rV   r`   c                   @   rO   )rb   c                 O   s   t | _t | _d S r   )r`   ZDataParallelZDistributedDataParallelrR   r   r   r   rG     s   
z_ParallelStub.__init__NrN   r   r   r   r   rb     rV   rb   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.
    Z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]`.)	r*   r+   r,   r-   _torch_stubsr   Ztorch.nnnnr0   )r)   r   rd   r   r   r   r#   "  s   



r#   c                  C   s   t  } d | fS r   )r_   )rd   r   r   r   rc   B  s   rc   r   unnamed-variablevalue	trainabletf_nametorch_tensorshapedtyperC   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   Nrk   )Zinitializerrk   rg   rj   r   T)r4   getattr
isinstancefloatZfloat32intZint32r:   r;   get_variabler#   npZndarrayarrayZ
from_numpyZfloat64doubletoZrequires_grad)rf   r   rg   rh   ri   r   rj   rk   r   r   r   Zvar_r   r   r   rp   G  sL   $	






rp   z+rllib/utils/framework.py::get_activation_fnz(rllib/models/utils.py::get_activation_fnT)oldnewr)   namec                 C   s   d S r   r   )rw   r   r   r   r   get_activation_fn  s   rx   r   )r   )F)r   Fre   FNNN)Nr   ),r<   r*   r8   typingr   r   r   numpyrq   r   r%   Zray._common.deprecationr   Zray.rllib.utils.annotationsr   r   Zray.rllib.utils.typingr   r	   r
   Z%ray.rllib.algorithms.algorithm_configr   	getLoggerrJ   r,   strr   ro   r(   boolr1   r   r7   rD   rM   r[   r^   r_   r`   rb   r#   rc   rp   rx   r   r   r   r   <module>   s    
3B

		J