o
    `۷i5                     @   s  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 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 d	Zed
efddZdejdefddZ dedejfddZ!edej"j#defddZ$edej"j#defddZ%ededej"j#fddZ&ededej"j#fddZ'ede
e deeef fd d!Z(ed"eeef defd#d$Z)e	%d*d&eeef d'e*de	eeef  fd(d)Z+dS )+    N)OrderedDict)AnyDictOptionalSequenceTypeUnion)DeveloperAPI)NotSerializable)FlexDict)RepeatedSimplex__not_serializable__objc                 C   s   t | trdd |  D S t | trtdd | D S t | tr(dd | D S t | tjr2t| S t | tjr<t	| S t | tj
rFt| S t | tjrPt| S t | tjrk|  }t|D ]
\}}t|||< q^|S | S )zConvert an object that is a numpy type to a python type.

    If the object is not a numpy type, it is returned unchanged.

    Args:
        obj: The object to convert.
    c                 S      i | ]	\}}|t |qS  "convert_numpy_to_python_primitives).0keyvalr   r   S/home/ubuntu/vllm_env/lib/python3.10/site-packages/ray/rllib/utils/serialization.py
<dictcomp>   s    z6convert_numpy_to_python_primitives.<locals>.<dictcomp>c                 s   s    | ]}t |V  qd S )Nr   r   r   r   r   r   	<genexpr>#   s    z5convert_numpy_to_python_primitives.<locals>.<genexpr>c                 S      g | ]}t |qS r   r   r   r   r   r   
<listcomp>%       z6convert_numpy_to_python_primitives.<locals>.<listcomp>)
isinstancedictitemstuplelistnpintegerintfloatingfloatbool_boolstr_strndarraytolist	enumerater   )r   retivr   r   r   r      s,   
	

r   arrayreturnc                 C   s.   t  }t||  tt| 	dS )zPack numpy ndarray into Base64 encoded strings for serialization.

    This function uses numpy.save() instead of pickling to ensure
    compatibility.

    Args:
        array: numpy ndarray.

    Returns:
        b64 escaped string.
    ascii)
ioBytesIOr$   savebase64	b64encodezlibcompressgetvaluedecode)r3   bufr   r   r   _serialize_ndarray7   s   r@   
b64_stringc                 C   s    t jttt| ddS )zUnpack b64 escaped string into numpy ndarray.

    This function assumes the unescaped bytes are of npy format.

    Args:
        b64_string: Base64 escaped string.

    Returns:
        numpy ndarray.
    T)allow_pickle)r$   loadr6   r7   r;   
decompressr9   	b64decode)rA   r   r   r   _deserialize_ndarrayH   s   rF   spacec                 C   s  | du rdS dt jjdtfdd}dt jjdtfdd}dt jjdtfdd	}dt jjdtfd
d}dt jjdtfdd}dt jjdtfdd}dtdtfdd}dt	dtfdd}dt
dtfdd}	dddtfdd}
t| t jjrw|| S t| t jjr|| S t| t jjr|| S t| t jjr|| S t| t jjr|| S t| t jjr|| S t| t jjr|
| S t| tr|| S t| t	r|| S t| t
r|	| S tdt| )zSerialize a gym Space into a JSON-serializable dict.

    Args:
        space: gym.spaces.Space

    Returns:
        Serialized JSON string.
    Nspr4   c                 S   s"   dt | jt | j| j| jjdS )Nbox)rG   lowhighshapedtype)r@   rJ   rK   _shaperM   r,   rH   r   r   r   _boxe   s   zgym_space_to_dict.<locals>._boxc                 S   s,   dt | jd}t| drt | j|d< |S )NdiscreterG   nstart)r&   rS   hasattrrT   )rH   dr   r   r   	_discreten   s   
z$gym_space_to_dict.<locals>._discretec                 S   s   d| j dS )Nmulti-binaryrR   )rS   rO   r   r   r   _multi_binaryx   s   z(gym_space_to_dict.<locals>._multi_binaryc                 S   s   dt | j| jjdS )Nmulti-discrete)rG   nvecrM   )r@   r[   rM   r,   rO   r   r   r   _multi_discrete~   s   z*gym_space_to_dict.<locals>._multi_discretec                 S   s   ddd | j D dS )Nr"   c                 S   r   r   gym_space_to_dictr   rH   r   r   r   r      r   z5gym_space_to_dict.<locals>._tuple.<locals>.<listcomp>rG   spacesra   rO   r   r   r   _tuple   s   z!gym_space_to_dict.<locals>._tuplec                 S   s   ddd | j  D dS )Nr    c                 S   r   r   r]   r   krH   r   r   r   r          z4gym_space_to_dict.<locals>._dict.<locals>.<dictcomp>r`   )ra   r!   rO   r   r   r   _dict   s   z gym_space_to_dict.<locals>._dictc                 S   s   d| j | j| jjdS )Nsimplex)rG   rL   concentrationrM   )rN   ri   rM   r,   rO   r   r   r   _simplex   s
   z#gym_space_to_dict.<locals>._simplexc                 S   s   dt | j| jdS )Nrepeated)rG   child_spacemax_len)r^   rl   rm   rO   r   r   r   	_repeated   s   z$gym_space_to_dict.<locals>._repeatedc                 S   s(   ddi}| j D ]
\}}t|||< q|S )NrG   	flex_dict)ra   r^   )rH   rV   re   sr   r   r   
_flex_dict   s
   z%gym_space_to_dict.<locals>._flex_dictgym.spaces.Textc                 S   sB   t | dd }|d u rt | dd }|d u rtdd| j| j|dS )Ncharacter_setcharsetz9Text space must have a character_set or charset attributetext)rG   
min_length
max_lengthrt   )getattr
ValueErrorrv   rw   )rH   rt   r   r   r   _text   s   z gym_space_to_dict.<locals>._textz&Unknown space type for serialization, )gymra   Boxr   DiscreteMultiBinaryMultiDiscreteTupler   r   r   r   Textry   type)rG   rP   rW   rY   r\   rc   rg   rj   rn   rq   rz   r   r   r   r^   X   sB   
	



r^   c                 C   s(   dt | i}d| jv rt| j|d< |S NrG   original_space)r^   __dict__space_to_dictr   )rG   rV   r   r   r   r      s   
r   rV   c                    s>  | du rdS dt fdd dt dtjjf fdd}dt dtjjf fdd	}dt dtjjf fd
d}dt dtjjf fdd}dt dtjjfdd}dt dtjjfdd}dt dtf fdd}dt dtfdd}dt dt	fdd}	dt ddf fdd}
|||||||||	|
d
}| d }||vrt
d||| | S )zDe-serialize a dict into gym Space.

    Args:
        str: serialized JSON str.

    Returns:
        De-serialized gym space.
    NrV   c                 S   s,   |   }|d= d|v rt|d |d< |S )z?Common updates to the dict before we use it to construct spacesrG   rM   )copyr$   rM   rV   r0   r   r   r   __common   s
   z%gym_space_from_dict.<locals>.__commonr4   c                    s>   |   }|t| d t| d d tjjdi  |S )NrJ   rK   )rJ   rK   r   )r   updaterF   r{   ra   r|   r   r   r   r   rP      s   

z!gym_space_from_dict.<locals>._boxc                       t jjdi  | S Nr   )r{   ra   r}   rV   r   r   r   rW         z&gym_space_from_dict.<locals>._discretec                    r   r   )r{   ra   r~   r   r   r   r   rY      r   z*gym_space_from_dict.<locals>._multi_binaryc                    s4   |   }|dt|d i tjjdi  |S )Nr[   r   )r   r   rF   r{   ra   r   r   r   r   r   r\      s   z,gym_space_from_dict.<locals>._multi_discretec                 S   s    dd | d D }t jj|dS )Nc                 S   r   r   gym_space_from_dictr_   r   r   r   r     r   z7gym_space_from_dict.<locals>._tuple.<locals>.<listcomp>ra   rb   )r{   ra   r   rV   ra   r   r   r   rc     s   z#gym_space_from_dict.<locals>._tuplec                 S   s(   t dd | d  D }tjj|dS )Nc                 S   r   r   r   rd   r   r   r   r     rf   z6gym_space_from_dict.<locals>._dict.<locals>.<dictcomp>ra   rb   )r   r!   r{   ra   r   r   r   r   r   rg   
  s   
z"gym_space_from_dict.<locals>._dictc                    s   t di  | S r   r   r   r   r   r   rj     s   z%gym_space_from_dict.<locals>._simplexc                 S   s   t | d }t|| d dS )Nrl   rm   )rl   rm   )r   r   )rV   rl   r   r   r   rn     s   z&gym_space_from_dict.<locals>._repeatedc                 S   s   dd |   D }t|dS )Nc                 S   s"   i | ]\}}|d kr|t |qS )rG   r   )r   re   rp   r   r   r   r   !  s   " z;gym_space_from_dict.<locals>._flex_dict.<locals>.<dictcomp>rb   )r!   r   r   r   r   r   rq      s   
z'gym_space_from_dict.<locals>._flex_dictrr   c                    r   r   )r{   ra   r   r   r   r   r   rz   $  r   z"gym_space_from_dict.<locals>._text)
rI   rQ   rX   rZ   r"   r    rh   rk   ro   ru   rG   z)Unknown space type for de-serialization, )r   r{   ra   r|   r}   r~   r   r   r   r   ry   )rV   rP   rW   rY   r\   rc   rg   rj   rn   rq   rz   	space_map
space_typer   r   r   r      s8   

	
r   c                 C   sZ   t | d }d| v r+d| d v sJ t| d d tr$t | d |_|S t| d |_|S r   )r   r   r,   r   space_from_dict)rV   rG   r   r   r   r   ;  s   r   argskwargsc                 C   s   | D ]"}z
t t | W q ty$ } z
td| d| d}~ww | D ]'\}}z
t t | W q) tyP } ztd| d| d| d}~ww dS )a  Check if parameters to a function are serializable by ray.

    Args:
        args: arguments to be checked.
        kwargs: keyword arguments to be checked.

    Raises:
        NoteSerializable if either args are kwargs are not serializable
            by ray.
    zVRLModule constructor arguments must be serializable. Found non-serializable argument: z .
Original serialization error: Nz^RLModule constructor arguments must be serializable. Found non-serializable keyword argument: z = )raygetput	TypeErrorr
   r!   )r   r   argere   r2   r   r   r   !check_if_args_kwargs_serializableJ  s:   r   type_c                 C   s   t | tr| S | jd | j S )zConverts a type into its full classpath ([module file] + "." + [class name]).

    Args:
        type_: The type to convert.

    Returns:
        The full classpath of the given type, e.g. "ray.rllib.algorithms.ppo.PPOConfig".
    .)r   r,   
__module____qualname__)r   r   r   r   serialize_typen  s   
r   Fmoduleerrorc                 C   s   t | tr| S t | trBz| dd\}}t|} t| |W S  ttt	t
fyA } z|r6t
d|  d|W Y d}~| S d}~ww t
d|  d)aV  Resolves a class path to a class.
    If the given module is already a class, it is returned as is.
    If the given module is a string, it is imported and the class is returned.

    Args:
        module: The classpath (str) or type to resolve.
        error: Whether to throw a ValueError if `module` could not be resolved into
            a class. If False and `module` is not resolvable, returns None.

    Returns:
        The resolved class or `module` (if `error` is False and no resolution possible).

    Raises:
        ValueError: If `error` is True and `module` cannot be resolved.
    r      z2Could not deserialize the given classpath `module=z` into a valid python class! Make sure you have all necessary pip packages installed and all custom modules are in your `PYTHONPATH` env variable.Nz
`module` (z$ must be type or string (classpath)!)r   r   r,   rsplit	importlibimport_modulerx   ModuleNotFoundErrorImportErrorAttributeErrorry   )r   r   module_path
class_namer   r   r   r   deserialize_type  s&   






r   )F),r9   r   r6   r;   collectionsr   typingr   r   r   r   r   r   	gymnasiumr{   numpyr$   r   ray.rllib.utils.annotationsr	   ray.rllib.utils.errorr
   ray.rllib.utils.spaces.flexdictr   ray.rllib.utils.spaces.repeatedr   ray.rllib.utils.spaces.simplexr   NOT_SERIALIZABLEr   r-   r,   r@   rF   ra   Spacer^   r   r   r   r   r   r*   r   r   r   r   r   <module>   sP     !wb #
