
    &`i              
           d dl Z d dlmZmZmZ erd dlZd dlZ G d de          Z	 e j
        de	           ddd	ed
eedf         deddf
dZdddeeeedf         f         fdZdS )    N)TYPE_CHECKINGAnyTuplec                       e Zd ZdZdS )ZeroCopyTensorsWarningzV
    Warning for unsafe or failed zero-copy tensor serialization/deserialization.
    N)__name__
__module____qualname____doc__     {/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/_private/tensor_serialization_utils.pyr   r   	   s          	Dr   r   once)categorynp_arrayz
np.ndarray	dtype_strshape.
device_strreturnztorch.Tensorc                    	 ddl }n"# t          $ r}t          d          |d}~ww xY w	  |j        |           }|                    d          d         }t	          ||          st          d|           t          ||          } |j        g |                                          }	| j	        |	z  dk    rt          d| j	         d	|	 d
|           |
                    |                              |          }
|
                    |          S # t          $ r8}ddlm}  |d| d| d| dt!          |          j         d| 
          |d}~ww xY w)a  
    Reconstructs a torch.Tensor from a zero-copy NumPy byte array.

    Args:
        np_array: 1D uint8 NumPy array of the original tensor's raw bytes.
        dtype_str: Full string representation of the original tensor's dtype (e.g., 'torch.float32').
        shape: The original shape of the tensor before serialization.
        device_str: String representation of the original device (e.g., 'cpu', 'cuda:0').

    Returns:
        Reconstructed torch.Tensor on the specified device if successful;
        otherwise, returns the input np_array unchanged and issues a warning.

    Raises:
        ImportError/DeserializationError: If deserialization fails for any reason (e.g., missing PyTorch
                            dtype mismatch, shape inconsistency, device error, etc.).
    r   NzBZero-copy tensor deserialization failed: PyTorch is not installed..z%Invalid or unsupported dtype string: )dtypezByte array size (z") is not divisible by dtype size (z) for dtype )device)DeserializationErrorzDFailed to deserialize zero-copy tensor from byte array. Input dtype=z, shape=z	, device=z. Underlying error: z: )torchImportError
from_numpysplithasattr
ValueErrorgetattrtensorelement_sizesizeviewreshapeto	Exceptionray._private.serializationr   typer   )r   r   r   r   r   euint8_tensor
dtype_nameoriginal_dtype
dtype_sizerestored_tensorr   s               r   _zero_copy_tensors_deserializerr2      s   (   P
 
	
'u'11 __S))"-
uj)) 	RPYPPQQQ 
33 "U\"N;;;HHJJ
=:%**CHM C C)C C7@C C   '++N;;CCEJJ !!!444   CCCCCC""9$9 9.39 9>H9 9!%a!19 9569 9
 
 		s(    
&!&C)D 
E3EEr#   c                 "   t          j        dt          d           ddl}|                                                                 }|                                s0t          j        dt          d           |                                }|                    d          }|	                    |j
                  }|                                }t          |t          | j                  t          | j                  t          | j                  ffS )u  Pickle serializer for zero-copy serialization of read-only torch.Tensor.

    This serializer aims to avoid copying tensor data by using a NumPy uint8 view,
    which enables pickle5's out-of-band buffer transmission. However, true zero-copy
    is only possible when the input tensor is already:

    - On CPU,
    - Detached from the computation graph (no gradients),
    - Contiguous in memory.

    If the input tensor does **not** meet these conditions, this function will:

    - Call `.detach()` to remove gradient information,
    - Move the tensor to CPU (copying data if it's on GPU or another device),
    - Make the tensor contiguous (copying data if it's non-contiguous).

    These operations may incur one or two full copies of the tensor data,
    negating zero-copy benefits. A warning is issued in such cases.

    Args:
        tensor: The input torch.Tensor to serialize. Can be on any device,
                with or without gradients, contiguous or not — but zero-copy
                is only achieved if it is already CPU, detached, and contiguous.

    Returns:
        A tuple (deserializer_callable, args_tuple) suitable for pickle.
    zZero-copy tensor serialization is enabled, but it only works safely for read-only tensors (detached, no gradients, contiguous). Modifiable or non-contiguous tensors may cause data corruption.   )
stacklevelr   NzThe input tensor is non-contiguous. A copy will be made to ensure contiguity. For zero-copy serialization, please ensure the tensor is contiguous before passing it (e.g., by calling `.contiguous()`).r   )warningswarnr   r   detachcpuis_contiguous
contiguousr'   r&   uint8numpyr2   strr   tupler   r   )r#   r   
cpu_tensorflat_tensor
uint8_viewr   s         r   zero_copy_tensors_reducerrC   Q   s   8 M	p	    LLL $$&&J##%% -2 #	
 	
 	
 	
  **,,
 $$R((K!!%+..J!!H*FLflFM	-  r   )r6   typingr   r   r   r=   npr   UserWarningr   filterwarningsr>   intr2   rC   r   r   r   <module>rI      s    , , , , , , , , , , LLL	 	 	 	 	[ 	 	 	  )? @ @ @ @::'*:38c?:PS:: : : :z@n @sE#s(O?S9T @ @ @ @ @ @r   