o
    8wi                     @   s\  U d Z ddlmZ ddlmZ ddlmZmZmZm	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 er=ddlZd
ZdddedefddZeee
je
jdfeee
je
jdfeee
je
jdfgZeeeeeegef f  ed< erddlZeej ef G dd deZ!dededefddZ"dededefddZ#dedefddZ$dS )zUtilities used for collections.    )ABC)partial)TYPE_CHECKINGAnyCallableUnionN)apply_to_collection)Tensor)_NUMPY_AVAILABLE)_DEVICE)cpumpsvaluez
np.ndarraydevicereturnc                 C   s   t | |S )N)torch
from_numpyto)r   r    r   b/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/lightning_fabric/utilities/apply_func.py_from_numpy!   s   r   )dtypeCONVERSION_DTYPESc                   @   s.   e Zd ZdZededeeef fddZdS )_TransferableDataTypea"  A custom type for data that can be moved to a torch device via ``.to(...)``.

    Example:

        >>> isinstance(dict, _TransferableDataType)
        False
        >>> isinstance(torch.rand(2, 3), _TransferableDataType)
        True
        >>> class CustomObject:
        ...     def __init__(self):
        ...         self.x = torch.rand(2, 2)
        ...     def to(self, device):
        ...         self.x = self.x.to(device)
        ...         return self
        >>> isinstance(CustomObject(), _TransferableDataType)
        True

    subclassr   c                 C   s    | t u rt|dd }t|S tS )Nr   )r   getattrcallableNotImplemented)clsr   r   r   r   r   __subclasshook__F   s   z&_TransferableDataType.__subclasshook__N)	__name__
__module____qualname____doc__classmethodr   r   boolr   r   r   r   r   r   2   s     r   batchc                    s8   t  tr
t  dtdtf fdd}t| t|dS )ak  Transfers a collection of data to the given device. Any object that defines a method ``to(device)`` will be
    moved and all other objects in the collection will be left untouched.

    Args:
        batch: A tensor or collection of tensors or anything that has a method ``.to(...)``.
            See :func:`apply_to_collection` for a list of supported collection types.
        device: The device to which the data should be moved

    Return:
        the same collection but with all contained tensors residing on the new device.

    See Also:
        - :meth:`torch.Tensor.to`
        - :class:`torch.device`

    datar   c                    sN   i }t | trt  tjr jtvrd|d< | j fi |}|d ur%|S | S )NTnon_blocking)
isinstancer	   r   r   type_BLOCKING_DEVICE_TYPESr   )r'   kwargsdata_outputr   r   r   batch_tob   s    z%move_data_to_device.<locals>.batch_to)r   function)r)   strr   r   r   r   r   )r&   r   r/   r   r.   r   move_data_to_deviceN   s   

r2   r'   c                 C   s(   t D ]\}}t| |||d} qt| |S )Nr.   )r   r   r2   )r'   r   	src_dtypeconversion_funcr   r   r   convert_to_tensorsq   s   
r5   c                 C   s(   dt dttttf fdd}t| t |S )zRecursively walk through a collection and convert single-item tensors to scalar values.

    Raises:
        ValueError:
            If tensors inside ``metrics`` contains multiple elements, hence preventing conversion to a scalar.

    r   r   c                 S   s$   |   dkrtd|  d|  S )N   zThe metric `zM` does not contain a single element, thus it cannot be converted to a scalar.)numel
ValueErroritem)r   r   r   r   to_item   s
   
z+convert_tensors_to_scalars.<locals>.to_item)r	   r   intfloatr%   r   )r'   r:   r   r   r   convert_tensors_to_scalarsx   s   	r=   )%r#   abcr   	functoolsr   typingr   r   r   r   r   #lightning_utilities.core.apply_funcr   r	   "lightning_fabric.utilities.importsr
    lightning_fabric.utilities.typesr   numpynpr+   r   r%   tensoruint8r;   r<   r   listtuple__annotations__appendndarrayr   r2   r5   r=   r   r   r   r   <module>   s0   $#