U
    <c01                  	   @   sB  U d Z ddlZddlZddlZddlZddlmZmZmZm	Z	m
Z
mZ ddlmZ edZdd ZdZdd	eeee
e	e
d
f f ef  d	ddZdd	eeee
e	e
d
f f ef  d	ddZdd	eeee
e	e
d
f f ef  d	ddZdd	eeee
e	e
d
f f ef  d	ddZdd	eeee
e	e
d
f f ef  d	ddZdd	eeee
e	e
d
f f ef  d	ddZdd	eeee
e	e
d
f f ef  d	ddZejeiZeee
e	e
d
f f ef ed< ee, ddlZeeej < eeej!ej"ej#f< W 5 Q R X eee$< eee%< eee< dd Z&dS )a5  "Contains definitions of the methods used by the _BaseDataLoaderIter workers to
collate samples fetched from dataset into Tensor(s).

These **needs** to be in global scope since Py2 doesn't support serializing
static methods.

`default_collate` and `default_convert` are exposed to users via 'dataloader.py'.
    N)CallableDictOptionalTupleTypeUnion)string_classesz[SaUO]c                    sP  t  }t tjr S |jdkr`|jdkr`|jdkr`|jdkrVt jj	dk	rV S t
 S t tjjrz| fdd D W S  tk
r    fdd D  Y S X nt trt d	r|d
d  D  S t t rdd  D S t tjjrHt tsHz|dd  D W S  tk
rD   dd  D  Y S X n S dS )an  
        Function that converts each NumPy array element into a :class:`torch.Tensor`. If the input is a `Sequence`,
        `Collection`, or `Mapping`, it tries to convert each element inside to a :class:`torch.Tensor`.
        If the input is not an NumPy array, it is left unchanged.
        This is used as the default function for collation when both `batch_sampler` and
        `batch_size` are NOT defined in :class:`~torch.utils.data.DataLoader`.

        The general input type to output type mapping is similar to that
        of :func:`~torch.utils.data.default_collate`. See the description there for more details.

        Args:
            data: a single data point to be converted

        Examples:
            >>> # Example with `int`
            >>> default_convert(0)
            0
            >>> # Example with NumPy array
            >>> # xdoctest: +SKIP
            >>> default_convert(np.array([0, 1]))
            tensor([0, 1])
            >>> # Example with NamedTuple
            >>> Point = namedtuple('Point', ['x', 'y'])
            >>> default_convert(Point(0, 0))
            Point(x=0, y=0)
            >>> default_convert(Point(np.array(0), np.array(0)))
            Point(x=tensor(0), y=tensor(0))
            >>> # Example with List
            >>> default_convert([np.array([0, 1]), np.array([2, 3])])
            [tensor([0, 1]), tensor([2, 3])]
    numpyZstr_Zstring_ndarrayNc                    s   i | ]}|t  | qS  default_convert.0keydatar   C/tmp/pip-unpacked-wheel-gikjz4vx/torch/utils/data/_utils/collate.py
<dictcomp>A   s      z#default_convert.<locals>.<dictcomp>c                    s   i | ]}|t  | qS r   r   r   r   r   r   r   D   s      _fieldsc                 s   s   | ]}t |V  qd S Nr   r   dr   r   r   	<genexpr>F   s     z"default_convert.<locals>.<genexpr>c                 S   s   g | ]}t |qS r   r   r   r   r   r   
<listcomp>H   s     z#default_convert.<locals>.<listcomp>c                 S   s   g | ]}t |qS r   r   r   r   r   r   r   K   s     c                 S   s   g | ]}t |qS r   r   r   r   r   r   r   N   s     )type
isinstancetorchTensor
__module____name__np_str_obj_array_patternsearchdtypestr	as_tensorcollectionsabcMapping	TypeErrortuplehasattrSequencer   )r   	elem_typer   r   r   r      s4     

r   z\default_collate: batch must contain tensors, numpy arrays, numbers, dicts or lists; found {}collate_fn_map.c                   s   d }t |}dk	rX|kr0|  dS D ]"}t||r4|  d  S q4t|tjjrz| fdd|D W S  tk
r    fdd|D  Y S X nt|trt|dr|fdd	t  D  S t|tjj	rt
 }tt|tfd
d	|D stdtt  }t|trHfdd|D S z|fdd|D W S  tk
r   fdd|D  Y S X tt|dS )a  
        General collate function that handles collection type of element within each batch
        and opens function registry to deal with specific element types. `default_collate_fn_map`
        provides default collate functions for tensors, numpy arrays, numbers and strings.

        Args:
            batch: a single batch to be collated
            collate_fn_map: Optional dictionary mapping from element type to the corresponding collate function.
              If the element type isn't present in this dictionary,
              this function will go through each key of the dictionary in the insertion order to
              invoke the corresponding collate function if the element type is a subclass of the key.

        Examples:
            >>> # Extend this function to handle batch of tensors
            >>> def collate_tensor_fn(batch, *, collate_fn_map):
            ...     return torch.stack(batch, 0)
            >>> def custom_collate(batch):
            ...     collate_map = {torch.Tensor: collate_tensor_fn}
            ...     return collate(batch, collate_fn_map=collate_map)
            >>> # Extend `default_collate` by in-place modifying `default_collate_fn_map`
            >>> default_collate_fn_map.update({torch.Tensor: collate_tensor_fn})

        Note:
            Each collate function requires a positional argument for batch and a keyword argument
            for the dictionary of collate functions as `collate_fn_map`.
    r   Nr.   c                    s(   i | ]   t  fd dD dqS )c                    s   g | ]}|  qS r   r   r   r   r   r   r      s     &collate.<locals>.<dictcomp>.<listcomp>r.   collater   batchr/   r0   r   r      s      zcollate.<locals>.<dictcomp>c                    s(   i | ]   t  fd dD dqS )c                    s   g | ]}|  qS r   r   r   r0   r   r   r      s     r1   r.   r2   r4   r5   r0   r   r      s      r   c                 3   s   | ]}t | d V  qdS )r.   Nr2   r   Zsamplesr.   r   r   r      s     zcollate.<locals>.<genexpr>c                 3   s   | ]}t | kV  qd S r   )len)r   elem)	elem_sizer   r   r      s     z5each element in list of batch should be of equal sizec                    s   g | ]}t | d qS r.   r2   r7   r.   r   r   r      s     zcollate.<locals>.<listcomp>c                    s   g | ]}t | d qS r;   r2   r7   r.   r   r   r      s     c                    s   g | ]}t | d qS r;   r2   r7   r.   r   r   r      s     )r   r   r&   r'   r(   r)   r*   r+   zipr,   iterr8   nextallRuntimeErrorlistdefault_collate_err_msg_formatformat)r6   r/   r9   r-   Zcollate_typeitZ
transposedr   )r6   r/   r:   r   r3   X   s8    
r3   c                C   st   | d }d }t jj d k	rdtdd | D }| j||jd}||j	t
| ft|  }t j| d|dS )Nr   c                 s   s   | ]}|  V  qd S r   )numel)r   xr   r   r   r      s     z$collate_tensor_fn.<locals>.<genexpr>)device)out)r   utilsr   Zget_worker_infosumstorageZ_new_sharedrG   newZresize_r8   rA   sizestack)r6   r/   r9   rH   rE   rK   r   r   r   collate_tensor_fn   s    "rO   c                C   s@   | d }t |jjd k	r*tt|jtdd | D |dS )Nr   c                 S   s   g | ]}t |qS r   r   r%   )r   br   r   r   r      s     z*collate_numpy_array_fn.<locals>.<listcomp>r.   )r!   r"   r#   r$   r)   rB   rC   r3   )r6   r/   r9   r   r   r   collate_numpy_array_fn   s    rR   c                C   s
   t | S r   rP   r5   r   r   r   collate_numpy_scalar_fn   s    rS   c                C   s   t j| t jdS )N)r#   )r   tensorZfloat64r5   r   r   r   collate_float_fn   s    rU   c                C   s
   t | S r   )r   rT   r5   r   r   r   collate_int_fn   s    rV   c                C   s   | S r   r   r5   r   r   r   collate_str_fn   s    rW   default_collate_fn_mapc                 C   s   t | tdS )a  
        Function that takes in a batch of data and puts the elements within the batch
        into a tensor with an additional outer dimension - batch size. The exact output type can be
        a :class:`torch.Tensor`, a `Sequence` of :class:`torch.Tensor`, a
        Collection of :class:`torch.Tensor`, or left unchanged, depending on the input type.
        This is used as the default function for collation when
        `batch_size` or `batch_sampler` is defined in :class:`~torch.utils.data.DataLoader`.

        Here is the general input type (based on the type of the element within the batch) to output type mapping:

            * :class:`torch.Tensor` -> :class:`torch.Tensor` (with an added outer dimension batch size)
            * NumPy Arrays -> :class:`torch.Tensor`
            * `float` -> :class:`torch.Tensor`
            * `int` -> :class:`torch.Tensor`
            * `str` -> `str` (unchanged)
            * `bytes` -> `bytes` (unchanged)
            * `Mapping[K, V_i]` -> `Mapping[K, default_collate([V_1, V_2, ...])]`
            * `NamedTuple[V1_i, V2_i, ...]` -> `NamedTuple[default_collate([V1_1, V1_2, ...]),
              default_collate([V2_1, V2_2, ...]), ...]`
            * `Sequence[V1_i, V2_i, ...]` -> `Sequence[default_collate([V1_1, V1_2, ...]),
              default_collate([V2_1, V2_2, ...]), ...]`

        Args:
            batch: a single batch to be collated

        Examples:
            >>> # Example with a batch of `int`s:
            >>> default_collate([0, 1, 2, 3])
            tensor([0, 1, 2, 3])
            >>> # Example with a batch of `str`s:
            >>> default_collate(['a', 'b', 'c'])
            ['a', 'b', 'c']
            >>> # Example with `Map` inside the batch:
            >>> default_collate([{'A': 0, 'B': 1}, {'A': 100, 'B': 100}])
            {'A': tensor([  0, 100]), 'B': tensor([  1, 100])}
            >>> # Example with `NamedTuple` inside the batch:
            >>> # xdoctest: +SKIP
            >>> Point = namedtuple('Point', ['x', 'y'])
            >>> default_collate([Point(0, 0), Point(1, 1)])
            Point(x=tensor([0, 1]), y=tensor([0, 1]))
            >>> # Example with `Tuple` inside the batch:
            >>> default_collate([(0, 1), (2, 3)])
            [tensor([0, 2]), tensor([1, 3])]
            >>> # Example with `List` inside the batch:
            >>> default_collate([[0, 1], [2, 3]])
            [tensor([0, 2]), tensor([1, 3])]
            >>> # Two options to extend `default_collate` to handle specific type
            >>> # Option 1: Write custom collate function and invoke `default_collate`
            >>> def custom_collate(batch):
            ...     elem = batch[0]
            ...     if isinstance(elem, CustomType):  # Some custom condition
            ...         return ...
            ...     else:  # Fall back to `default_collate`
            ...         return default_collate(batch)
            >>> # Option 2: In-place modify `default_collate_fn_map`
            >>> def collate_customtype_fn(batch, *, collate_fn_map=None):
            ...     return ...
            >>> default_collate_fn_map.update(CustoType, collate_customtype_fn)
            >>> default_collate(batch)  # Handle `CustomType` automatically
    r.   )r3   rX   )r6   r   r   r   default_collate   s    =rY   )'__doc__r&   
contextlibrer   typingr   r   r   r   r   r   Z
torch._sixr   compiler!   r   rB   r3   rO   rR   rS   rU   rV   rW   r   rX   __annotations__suppressImportErrorr	   npr
   Zbool_numberZobject_floatintrY   r   r   r   r   <module>   s4   	 
?0B00	0000*
