
    '}h0                        d dl Z d dl mZ d dlmZmZmZmZmZmZm	Z	m
Z
mZ g dZ edd      Z G d d	e	e         Z G d
 dee         Z G d dee         Z G d dee         Z G d dee         Z G d deee            Zy)    N)Tensor)	IteratorIterableOptionalSequenceListTypeVarGenericSizedUnion)BatchSamplerRandomSamplerSamplerSequentialSamplerSubsetRandomSamplerWeightedRandomSamplerT_coT)	covariantc                   :    e Zd ZdZddee   ddfdZdee   fdZ	y)r   a/  Base class for all Samplers.

    Every Sampler subclass has to provide an :meth:`__iter__` method, providing a
    way to iterate over indices or lists of indices (batches) of dataset elements, and a :meth:`__len__` method
    that returns the length of the returned iterators.

    Args:
        data_source (Dataset): This argument is not used and will be removed in 2.2.0.
            You may still have custom implementation that utilizes it.

    Example:
        >>> # xdoctest: +SKIP
        >>> class AccedingSequenceLengthSampler(Sampler[int]):
        >>>     def __init__(self, data: List[str]) -> None:
        >>>         self.data = data
        >>>
        >>>     def __len__(self) -> int:
        >>>         return len(self.data)
        >>>
        >>>     def __iter__(self) -> Iterator[int]:
        >>>         sizes = torch.tensor([len(x) for x in self.data])
        >>>         yield from torch.argsort(sizes).tolist()
        >>>
        >>> class AccedingSequenceLengthBatchSampler(Sampler[List[int]]):
        >>>     def __init__(self, data: List[str], batch_size: int) -> None:
        >>>         self.data = data
        >>>         self.batch_size = batch_size
        >>>
        >>>     def __len__(self) -> int:
        >>>         return (len(self.data) + self.batch_size - 1) // self.batch_size
        >>>
        >>>     def __iter__(self) -> Iterator[List[int]]:
        >>>         sizes = torch.tensor([len(x) for x in self.data])
        >>>         for batch in torch.chunk(torch.argsort(sizes), len(self)):
        >>>             yield batch.tolist()

    .. note:: The :meth:`__len__` method isn't strictly required by
              :class:`~torch.utils.data.DataLoader`, but is expected in any
              calculation involving the length of a :class:`~torch.utils.data.DataLoader`.
    Ndata_sourcereturnc                 4    |dd l }|j                  d       y y )Nr   zz`data_source` argument is not used and will be removed in 2.2.0.You may still have custom implementation that utilizes it.)warningswarn)selfr   r   s      W/var/www/html/test/engine/venv/lib/python3.12/site-packages/torch/utils/data/sampler.py__init__zSampler.__init__<   s#    "MM W X #    c                     t         N)NotImplementedErrorr   s    r   __iter__zSampler.__iter__C   s    !!r   r    )
__name__
__module____qualname____doc__r   r   r   r   r   r#    r   r   r   r      s2    'RXHUO Xt X"(4. "r   r   c                   J    e Zd ZU dZeed<   deddfdZdee   fdZ	defdZ
y)r   z~Samples elements sequentially, always in the same order.

    Args:
        data_source (Dataset): dataset to sample from
    r   r   Nc                     || _         y r    )r   )r   r   s     r   r   zSequentialSampler.__init__k   s
    &r   c                 P    t        t        t        | j                                    S r    )iterrangelenr   r"   s    r   r#   zSequentialSampler.__iter__n   s    E#d../011r   c                 ,    t        | j                        S r    )r.   r   r"   s    r   __len__zSequentialSampler.__len__q   s    4##$$r   )r$   r%   r&   r'   r   __annotations__r   r   intr#   r0   r(   r   r   r   r   b   s>     'E 'd '2(3- 2% %r   r   c            	       ~    e Zd ZU dZeed<   eed<   	 	 ddededee   ddfdZ	e
defd       Zdee   fd	Zdefd
Zy)r   a  Samples elements randomly. If without replacement, then sample from a shuffled dataset.

    If with replacement, then user can specify :attr:`num_samples` to draw.

    Args:
        data_source (Dataset): dataset to sample from
        replacement (bool): samples are drawn on-demand with replacement if ``True``, default=``False``
        num_samples (int): number of samples to draw, default=`len(dataset)`.
        generator (Generator): Generator used in sampling.
    r   replacementNnum_samplesr   c                 "   || _         || _        || _        || _        t	        | j                  t
              st        d| j                         t	        | j                  t              r| j                  dk  rt        d| j                         y )N;replacement should be a boolean value, but got replacement=r   Dnum_samples should be a positive integer value, but got num_samples=)
r   r4   _num_samples	generator
isinstancebool	TypeErrorr5   r2   
ValueError)r   r   r4   r5   r:   s        r   r   zRandomSampler.__init__   s    &&'"$**D1YZ^ZjZjYklmm$**C0D4D4D4Icdhdtdtcuvww 5Jr   c                 \    | j                   t        | j                        S | j                   S r    )r9   r.   r   r"   s    r   r5   zRandomSampler.num_samples   s-     $t''((   r   c              #     K   t        | j                        }| j                  pt        t	        j
                  dt        j                        j                         j                               }t	        j                         }|j                  |       n| j                  }| j                  rt        | j                  dz        D ]?  }t	        j                  |dt        j                  |      j                         E d {    A t	        j                  || j                  dz  ft        j                  |      j                         E d {    y t        | j                  |z        D ]/  }t	        j                   ||      j                         E d {    1 t	        j                   ||      j                         d | j                  |z   E d {    y 7 7 7 H7 w)Nr(   dtype    )rC   )highsizerB   r:   r:   )r.   r   r:   r2   torchemptyint64random_item	Generatormanual_seedr4   r-   r5   randinttolistrandperm)r   nseedr:   _s        r   r#   zRandomSampler.__iter__   sy      !>>!u{{2U[[9AACHHJKD)I!!$'I4++r12 n ==ae5;;Zcdkkmmmn}}!43C3Cb3H2JRWR]R]irszz|||4++q01 K >>!yAHHJJJK~~a9=DDFG\HXHX[\H\]]] n| K]sJ   C=G"?G AG"GAG"G>G"G G"G"G" G"c                     | j                   S r    r5   r"   s    r   r0   zRandomSampler.__len__       r   )FNN)r$   r%   r&   r'   r   r1   r<   r   r2   r   propertyr5   r   r#   r0   r(   r   r   r   r   u   s    	 ?D>BxE x x&smxGKx !S ! !^(3- ^$   r   r   c                   X    e Zd ZU dZee   ed<   ddee   ddfdZdee   fdZ	defdZ
y)	r   zSamples elements randomly from a given list of indices, without replacement.

    Args:
        indices (sequence): a sequence of indices
        generator (Generator): Generator used in sampling.
    indicesNr   c                      || _         || _        y r    )rY   r:   )r   rY   r:   s      r   r   zSubsetRandomSampler.__init__   s    "r   c              #      K   t        j                  t        | j                        | j                        D ]  }| j                  |     y wNrF   )rG   rP   r.   rY   r:   )r   is     r   r#   zSubsetRandomSampler.__iter__   s;     DLL 1T^^L 	"A,,q/!	"s   AAc                 ,    t        | j                        S r    )r.   rY   r"   s    r   r0   zSubsetRandomSampler.__len__   s    4<<  r   r    )r$   r%   r&   r'   r   r2   r1   r   r   r#   r0   r(   r   r   r   r      sF     c]# #$ #"(3- "! !r   r   c            	       p    e Zd ZU dZeed<   eed<   eed<   	 d
dee	   dededdfdZ
dee   fdZdefd	Zy)r   aN  Samples elements from ``[0,..,len(weights)-1]`` with given probabilities (weights).

    Args:
        weights (sequence)   : a sequence of weights, not necessary summing up to one
        num_samples (int): number of samples to draw
        replacement (bool): if ``True``, samples are drawn with replacement.
            If not, they are drawn without replacement, which means that when a
            sample index is drawn for a row, it cannot be drawn again for that row.
        generator (Generator): Generator used in sampling.

    Example:
        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
        >>> list(WeightedRandomSampler([0.1, 0.9, 0.4, 0.7, 3.0, 0.6], 5, replacement=True))
        [4, 4, 1, 4, 5]
        >>> list(WeightedRandomSampler([0.9, 0.4, 0.05, 0.2, 0.3, 0.1], 5, replacement=False))
        [0, 1, 4, 3, 2]
    weightsr5   r4   Nr   c                    t        |t              rt        |t              s|dk  rt        d|       t        |t              st        d|       t	        j
                  |t        j                        }t        |j                        dk7  r!t        dt        |j                               || _
        || _        || _        || _        y )Nr   r8   r7   rA      z=weights should be a 1d sequence but given weights have shape )r;   r2   r<   r>   rG   	as_tensordoubler.   shapetupler`   r5   r4   r:   )r   r`   r5   r4   r:   weights_tensors         r   r   zWeightedRandomSampler.__init__   s    +s+z+t/Lq cdocpqrr+t,Z[fZghiiE~##$) 3389M9M3N2OQ R R &&&"r   c              #      K   t        j                  | j                  | j                  | j                  | j
                        }t        |j                               E d {    y 7 wr\   )rG   multinomialr`   r5   r4   r:   r,   rO   )r   rand_tensors     r   r#   zWeightedRandomSampler.__iter__   sJ     ''d6F6FHXHXdhdrdrs**,---s   AA( A&!A(c                     | j                   S r    rU   r"   s    r   r0   zWeightedRandomSampler.__len__   rV   r   )TN)r$   r%   r&   r'   r   r1   r2   r<   r   floatr   r   r#   r0   r(   r   r   r   r      sb    $ O 6:# #c #"#>B#$.(3- .   r   r   c                   b    e Zd ZdZdeee   ee   f   dededdfdZ	de
ee      fdZdefd	Zy)
r   ai  Wraps another sampler to yield a mini-batch of indices.

    Args:
        sampler (Sampler or Iterable): Base sampler. Can be any iterable object
        batch_size (int): Size of mini-batch.
        drop_last (bool): If ``True``, the sampler will drop the last batch if
            its size would be less than ``batch_size``

    Example:
        >>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=False))
        [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
        >>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=True))
        [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
    sampler
batch_size	drop_lastr   Nc                     t        |t              rt        |t              s|dk  rt        d|       t        |t              st        d|       || _        || _        || _        y )Nr   zBbatch_size should be a positive integer value, but got batch_size=z7drop_last should be a boolean value, but got drop_last=)r;   r2   r<   r>   rn   ro   rp   )r   rn   ro   rp   s       r   r   zBatchSampler.__init__  sg     *c*jT.Jaablamnoo)T*VW`Vabcc$"r   c              #     K   | j                   rGt        | j                        }	 	 t        | j                        D cg c]  }t        |       }}| 1dg| j                  z  }d}| j                  D ]2  }|||<   |dz  }|| j                  k(  s| d}dg| j                  z  }4 |dkD  r|d |  y y c c}w # t        $ r Y y w xY ww)Nr   rb   )rp   r,   rn   r-   ro   nextStopIteration)r   sampler_iterrS   batchidx_in_batchidxs         r   r#   zBatchSampler.__iter__  s     >>-L9>t9OPAT,/PEPK  C$//)EL|| 2&)l#!4??2K#$LC$//1E2 aM\**   Q$ s?   #CB< B7B< ;C&C7B< <	CCCCc                     | j                   r"t        | j                        | j                  z  S t        | j                        | j                  z   dz
  | j                  z  S )Nrb   )rp   r.   rn   ro   r"   s    r   r0   zBatchSampler.__len__)  sI    
 >>t||$77%7!;OOr   )r$   r%   r&   r'   r   r   r2   r   r<   r   r   r   r#   r0   r(   r   r   r   r      s`    #gclHSM&A B #PS #`d #im #+(49- +.P Pr   r   )rG   r   typingr   r   r   r   r   r	   r
   r   r   __all__r   r   r2   r   r   r   r   r   r(   r   r   <module>r|      s      _ _ _ v&2"gdm 2"`% %&6 GCL 6 r!'#, !,. GCL . b<P749% <Pr   