o
    i1                     @   s   d dl Z d dlmZmZmZmZ d dlmZmZ d dl	Z	g dZ
edddZG dd	 d	ee ZG d
d dee ZG dd dee ZG dd dee ZG dd dee ZG dd deee  ZdS )    N)IterableIteratorSequenceSized)GenericTypeVar)BatchSamplerRandomSamplerSamplerSequentialSamplerSubsetRandomSamplerWeightedRandomSampler_T_coT)	covariantc                   @   s"   e Zd ZdZdee fddZdS )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 may provide a :meth:`__len__` method that returns the length of the returned iterators.

    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`.
    returnc                 C   s   t N)NotImplementedErrorself r   Z/sda-disk/www/egybert/egybert_env/lib/python3.10/site-packages/torch/utils/data/sampler.py__iter__B   s   zSampler.__iter__N)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r
      s    %r
   c                   @   sL   e Zd ZU dZeed< deddfddZdee fddZ	defd	d
Z
dS )r   zSamples elements sequentially, always in the same order.

    Args:
        data_source (Sized): data source to sample from. Must implement __len__.
    data_sourcer   Nc                 C   s
   || _ d S r   )r   )r   r   r   r   r   __init__j      
zSequentialSampler.__init__c                 C   s   t tt| jS r   )iterrangelenr   r   r   r   r   r   m   s   zSequentialSampler.__iter__c                 C   
   t | jS r   )r!   r   r   r   r   r   __len__p   r   zSequentialSampler.__len__)r   r   r   r   r   __annotations__r   r   intr   r#   r   r   r   r   r   a   s   
 r   c                	   @   sz   e Zd ZU dZeed< eed< 			ddedededB ddfdd	Ze	defd
dZ
dee fddZdefddZdS )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 (Sized): data source to sample from. Must implement __len__.
        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   replacementFNnum_samplesr   c                 C   s^   || _ || _|| _|| _t| jtstd| j t| jtr%| jdkr-t	d| j d S )N;replacement should be a boolean value, but got replacement=r   Dnum_samples should be a positive integer value, but got num_samples=)
r   r&   _num_samples	generator
isinstancebool	TypeErrorr'   r%   
ValueError)r   r   r&   r'   r+   r   r   r   r      s   

zRandomSampler.__init__c                 C   s   | j d u r
t| jS | j S r   )r*   r!   r   r   r   r   r   r'      s   

zRandomSampler.num_samplesc                 c   s   t | j}| jd u r#ttjdtjd  }t	 }|
| n| j}| jrWt| jd D ]}tj|dtj|d E d H  q0tj|| jd ftj|d E d H  d S t| j| D ]}tj||d E d H  q^tj||d d | j|  E d H  d S )Nr   dtype    )r2   )highsizer1   r+   r+   )r!   r   r+   r%   torchemptyint64random_item	Generatormanual_seedr&   r    r'   randinttolistrandperm)r   nseedr+   _r   r   r   r      s6   




zRandomSampler.__iter__c                 C      | j S r   r'   r   r   r   r   r#         zRandomSampler.__len__)FNN)r   r   r   r   r   r$   r-   r%   r   propertyr'   r   r   r#   r   r   r   r   r	   t   s(   
 
r	   c                   @   sV   e Zd ZU dZee ed< ddee ddfddZdee fddZ	defd	d
Z
dS )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                 C   s   || _ || _d S r   )rG   r+   )r   rG   r+   r   r   r   r      s   
zSubsetRandomSampler.__init__c                 c   s2    t jt| j| jd D ]}| j| V  qd S Nr5   )r6   r?   r!   rG   r+   r>   )r   ir   r   r   r      s   zSubsetRandomSampler.__iter__c                 C   r"   r   )r!   rG   r   r   r   r   r#      r   zSubsetRandomSampler.__len__r   )r   r   r   r   r   r%   r$   r   r   r   r#   r   r   r   r   r      s   
 r   c                	   @   sp   e Zd ZU dZejed< eed< eed< 		dde	e
 dededdfdd	Zdee fd
dZdefddZdS )r   a  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]
    weightsr'   r&   TNr   c                 C   s   t |trt |ts|dkrtd| t |ts!td| tj|tjd}t|jdkr:tdt	|j || _
|| _|| _|| _d S )Nr   r)   r(   r0      z=weights should be a 1d sequence but given weights have shape )r,   r%   r-   r/   r6   	as_tensordoubler!   shapetuplerJ   r'   r&   r+   )r   rJ   r'   r&   r+   weights_tensorr   r   r   r      s.   

zWeightedRandomSampler.__init__c                 c   s2    t j| j| j| j| jd}t| E d H  d S rH   )r6   multinomialrJ   r'   r&   r+   r   r>   )r   rand_tensorr   r   r   r     s
   zWeightedRandomSampler.__iter__c                 C   rC   r   rD   r   r   r   r   r#     rE   zWeightedRandomSampler.__len__)TN)r   r   r   r   r6   Tensorr$   r%   r-   r   floatr   r   r   r#   r   r   r   r   r      s$   
 

 r   c                   @   sZ   e Zd ZdZdee ee B dededdfddZde	e
e  fd	d
ZdefddZdS )r   a  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                 C   sX   t |trt |ts|dkrtd| t |ts!td| || _|| _|| _d S )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,   r%   r-   r/   rU   rV   rW   )r   rU   rV   rW   r   r   r   r   4  s   


zBatchSampler.__init__c                 c   sz    t | j}| jr |g| j }t|ddiD ]}g |V  qd S g t|| j}|r;|V  g t|| j}|s+d S d S )NstrictF)r   rU   rW   rV   zip	itertoolsislice)r   sampler_iterargsbatch_droplastbatchr   r   r   r   M  s   
zBatchSampler.__iter__c                 C   s0   | j rt| j| j S t| j| j d | j S )NrK   )rW   r!   rU   rV   r   r   r   r   r#   Z  s   zBatchSampler.__len__)r   r   r   r   r
   r%   r   r-   r   r   listr   r#   r   r   r   r   r     s    
r   )rZ   collections.abcr   r   r   r   typingr   r   r6   __all__r   r
   r%   r   r	   r   r   r`   r   r   r   r   r   <module>   s   	
EKI