
    sgo>              	       ,   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Z ej                  d      Zd ZdZdddeeee
e	e
d	f   f   ef      fd
Zdddeeee
e	e
d	f   f   ef      fdZdddeeee
e	e
d	f   f   ef      fdZdddeeee
e	e
d	f   f   ef      fdZdddeeee
e	e
d	f   f   ef      fdZdddeeee
e	e
d	f   f   ef      fdZdddeeee
e	e
d	f   f   ef      fdZej0                  eiZeee
e	e
d	f   f   ef   ed<    ej6                  e      5  ddlZeeej>                  <   eeej@                  ejB                  ejD                  f<   ddd       eee#<   eee$<   eee%<   eee&<   d Z'y# 1 sw Y   !xY w)aL  Contains definitions of the methods used by the _BaseDataLoaderIter workers.

These methods are used 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Unionz[SaUO]c           
         t        |       }t        | t        j                        r| S |j                  dk(  rm|j
                  dk7  r^|j
                  dk7  rO|j
                  dk(  r+t        j                  | j                  j                        | S t        j                  |       S t        | t        j                  j                        r	 t        | t        j                  j                        rCt        j                  |       }|j!                  | D ci c]  }|t#        | |          c}       |S  || D ci c]  }|t#        | |          c}      S t        | t&              rt)        | d      r |d | D         S t        | t&              r| D cg c]  }t#        |       c}S t        | t        j                  j*                        rt        | t        t,        f      s|	 t        | t        j                  j.                        r8t        j                  |       }t1        |       D ]  \  }}t#        |      ||<    |S  || D cg c]  }t#        |       c}      S | S c c}w c c}w # t$        $ r& | D ci c]  }|t#        | |          nc c}w c}cY S w xY wc c}w c c}w # t$        $ r" | D cg c]  }t#        |       nc c}w c}cY S w xY w)a  
    Convert 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:
        >>> # xdoctest: +SKIP
        >>> # Example with `int`
        >>> default_convert(0)
        0
        >>> # Example with NumPy array
        >>> 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])]
    numpystr_string_ndarray_fieldsc              3   2   K   | ]  }t        |        y wN)default_convert).0ds     R/var/www/html/venv/lib/python3.12/site-packages/torch/utils/data/_utils/collate.py	<genexpr>z"default_convert.<locals>.<genexpr>W   s     <!?1-<s   )type
isinstancetorchTensor
__module____name__np_str_obj_array_patternsearchdtypestr	as_tensorcollectionsabcMappingMutableMappingcopyupdater   	TypeErrortuplehasattrSequencebytesMutableSequence	enumerate)data	elem_typeclonekeyr   is         r   r   r      sh   B T
I$%'&()+ )+(//

?KKt$$	D+//11	2	E$ > >? 		$N#c?49#==NO T!Rc#tCy'A"A!RSS
 
D%	 WT9%=<t<==	D%	 ,01q"11	D+//22	3JsEl=	6$ ? ?@ 		$%dO 2DAq.q1E!H2 d!C/!"4!CDD ? O "S 	E @DDCc33DDD	E 2 "D 	6 1551OA&555	6s   	AI& I'I& 0I& 6I!I& JAJ" ;J" JJ" 
I& &J3J
		JJJ" "K/K	KKz\default_collate: batch must contain tensors, numpy arrays, numbers, dicts or lists; found {}collate_fn_mapr4   .c                D   | d   }t        |      }3|v r |   |       S D ]  }t        ||      s |   |       c S  t        |t        j                  j                        r	 t        |t        j                  j
                        rUt        j                  |      }|j                  |D ci c]!  }|t        | D cg c]  }||   	 c}      # c}}       |S  ||D ci c]!  }|t        | D cg c]  }||   	 c}      # c}}      S t        |t              r t        |d      r |fdt        |  D         S t        |t        j                  j                        rt        |       }t        t!        |            t#        fd|D              st%        d      t'        t        |        }	t        |t              r|	D 
cg c]  }
t        |
       c}
S 	 t        |t        j                  j(                        r:t        j                  |      }t+        |	      D ]  \  }}
t        |
      ||<    |S  ||	D 
cg c]  }
t        |
       c}
      S t        t,        j/                  |            c c}w c c}}w c c}w c c}}w # t        $ r? |D ci c]'  }|t        | D cg c]  }||   	 nc c}w c}      ) nc c}}w c}}cY S w xY wc c}
w c c}
w # t        $ r$ |	D 
cg c]  }
t        |
       nc c}
w c}
cY S w xY w)a  
    General collate function that handles collection type of element within each batch.

    The function also 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:
        >>> def collate_tensor_fn(batch, *, collate_fn_map):
        ...     # Extend this function to handle batch of tensors
        ...     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   r3   r   c              3   8   K   | ]  }t        |         yw)r3   N)collate)r   samplesr4   s     r   r   zcollate.<locals>.<genexpr>   s#       ??s   c              3   :   K   | ]  }t        |      k(    y wr   )len)r   elem	elem_sizes     r   r   zcollate.<locals>.<genexpr>   s     9d3t9	)9s   z5each element in list of batch should be of equal size)r   r   r!   r"   r#   r$   r%   r&   r7   r'   r(   r)   zipr*   iterr:   nextallRuntimeErrorlistr,   r-   default_collate_err_msg_formatformat)batchr4   r;   r/   collate_typer0   r1   r   it
transposedr8   r2   r<   s    `          @r   r7   r7   v   s8   @ 8DT
I!&,>),U>RR* 	L$-3~l3. 	 $//0	$ > >? 		$
 $(	   W-23QsV3N   
 $(	   W-23QsV3N   
D%	 WT9%="E{
 	
 
D+//22	3%[RM	9b99VWW#u+&
dE"  * ? 
dKOO$C$CD !IIdOE&/
&; S
7#*7>#RaS L$ ,6 ' $GNK  299)D
EEG 4 4  	
   We4af44^TT  	. 
  
 $. GNC  s   -A	J 6J
JJ
	J &J -J
<JJ
J K(*AK2 K2 K-"K2 J
J J
J K%+K:KKK%$K%-K2 2L?L	LLc                   | d   }d }|j                   rt        d      |j                  t        j                  t        j
                  t        j                  t        j                  t        j                  hv rt        d      t        j                  j                  j                         t        d | D              }|j                         j                  ||j                        } |j!                  |      j"                  t%        |       gt'        |j)                                }t        j*                  | d|      S )Nr   zBatches of nested tensors are not currently supported by the default collate_fn; please provide a custom collate_fn to handle them appropriately.zBatches of sparse tensors are not currently supported by the default collate_fn; please provide a custom collate_fn to handle them appropriately.c              3   <   K   | ]  }|j                           y wr   )numel)r   xs     r   r   z$collate_tensor_fn.<locals>.<genexpr>  s     -!AGGI-s   )device)out)	is_nestedrA   layoutr   
sparse_coo
sparse_csr
sparse_bsr
sparse_csc
sparse_bscutilsr.   get_worker_infosum_typed_storage_new_sharedrM   newresize_r:   rB   sizestack)rE   r4   r;   rN   rK   storages         r   collate_tensor_fnr`      s   
 8D
C~~O
 	
 {{  O
 	
 {{'')5 -u--%%'33E$++3N'dhhw''E
GT$))+5FG;;uaS))    c                   | d   }t         j                  |j                  j                        (t	        t
        j                  |j                              t        | D cg c]  }t        j                  |       c}|      S c c}w )Nr   r3   )
r   r   r   r   r'   rC   rD   r7   r   r    )rE   r4   r;   bs       r   collate_numpy_array_fnrd     se    
 8D&&tzz~~6B6==djjIJJ61EOOA&6~VV6s    Bc                ,    t        j                  |       S r   )r   r    rE   r4   s     r   collate_numpy_scalar_fnrg      s    
 ??5!!ra   c                L    t        j                  | t         j                        S )N)r   )r   tensorfloat64rf   s     r   collate_float_fnrk   (  s    
 <<U]]33ra   c                ,    t        j                  |       S r   )r   ri   rf   s     r   collate_int_fnrm   0  s    
 <<ra   c                    | S r    rf   s     r   collate_str_fnrp   8  s	    
 Lra   default_collate_fn_mapc                 $    t        | t              S )a  
    Take in a batch of data and put 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:
        >>> # xdoctest: +SKIP
        >>> # 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:
        >>> 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(CustomType, collate_customtype_fn)
        >>> default_collate(batch)  # Handle `CustomType` automatically
    r3   )r7   rq   )rE   s    r   default_collaters   Q  s    z 5)?@@ra   )(__doc__r!   
contextlibr%   retypingr   r   r   r   r   r   r   compiler   r   rC   r7   r`   rd   rg   rk   rm   rp   r   rq   __annotations__suppressImportErrorr
   npr   bool_numberobject_floatintr   r+   rs   ro   ra   r   <module>r      s      	 ? ?  &2::i0 Vt  OSzF T%eD#I.>(>"?"IJKzF@ OS* T%eD#I.>(>"?"IJK*F OS
W T%eD#I.>(>"?"IJK
W  OS" T%eD#I.>(>"?"IJK" OS4 T%eD#I.>(>"?"IJK4 OS T%eD#I.>(>"?"IJK OS T%eD#I.>(>"?"IJK 
LL#I U4tSy)9#9:HDE  Z% X *@2::& AXBHHbii<=X !1 u , s , s  . u =AX Xs   0:F

F