o
    h                     @   sz   d dl Z d dlmZ d dlmZmZ d dlZd dlmZ	 d dl
mZ d dlmZ dgZeddd	ZG d
d dee ZdS )    N)Iterator)OptionalTypeVar)Dataset)SamplerDistributedSampler_T_coT)	covariantc                   @   s|   e Zd ZdZ					ddedee dee d	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eddfddZdS )r   a'	  Sampler that restricts data loading to a subset of the dataset.

    It is especially useful in conjunction with
    :class:`torch.nn.parallel.DistributedDataParallel`. In such a case, each
    process can pass a :class:`~torch.utils.data.DistributedSampler` instance as a
    :class:`~torch.utils.data.DataLoader` sampler, and load a subset of the
    original dataset that is exclusive to it.

    .. note::
        Dataset is assumed to be of constant size and that any instance of it always
        returns the same elements in the same order.

    Args:
        dataset: Dataset used for sampling.
        num_replicas (int, optional): Number of processes participating in
            distributed training. By default, :attr:`world_size` is retrieved from the
            current distributed group.
        rank (int, optional): Rank of the current process within :attr:`num_replicas`.
            By default, :attr:`rank` is retrieved from the current distributed
            group.
        shuffle (bool, optional): If ``True`` (default), sampler will shuffle the
            indices.
        seed (int, optional): random seed used to shuffle the sampler if
            :attr:`shuffle=True`. This number should be identical across all
            processes in the distributed group. Default: ``0``.
        drop_last (bool, optional): if ``True``, then the sampler will drop the
            tail of the data to make it evenly divisible across the number of
            replicas. If ``False``, the sampler will add extra indices to make
            the data evenly divisible across the replicas. Default: ``False``.

    .. warning::
        In distributed mode, calling the :meth:`set_epoch` method at
        the beginning of each epoch **before** creating the :class:`DataLoader` iterator
        is necessary to make shuffling work properly across multiple epochs. Otherwise,
        the same ordering will be always used.

    Example::

        >>> # xdoctest: +SKIP
        >>> sampler = DistributedSampler(dataset) if is_distributed else None
        >>> loader = DataLoader(dataset, shuffle=(sampler is None),
        ...                     sampler=sampler)
        >>> for epoch in range(start_epoch, n_epochs):
        ...     if is_distributed:
        ...         sampler.set_epoch(epoch)
        ...     train(loader)
    NTr   Fdatasetnum_replicasrankshuffleseed	drop_lastreturnc                 C   s   |d u rt  stdt  }|d u r t  stdt  }||ks(|dk r5td| d|d  d|| _|| _|| _d| _	|| _
| j
rat| j| j dkratt| j| j | j | _ntt| j| j | _| j| j | _|| _|| _d S )Nz,Requires distributed package to be availabler   zInvalid rank z%, rank should be in the interval [0,    ])distis_availableRuntimeErrorget_world_sizeget_rank
ValueErrorr
   r   r   epochr   lenmathceilnum_samples
total_sizer   r   )selfr
   r   r   r   r   r    r    p/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/utils/data/distributed.py__init__B   s2   	
zDistributedSampler.__init__c                 C   s   | j rt }|| j| j  tjt| j|d	 }n	t
tt| j}| jsQ| jt| }|t|kr?||d | 7 }n||t|t|  d | 7 }n|d | j }t|| jksaJ || j| j| j }t|| jkstJ t|S )N)	generator)r   torch	Generatormanual_seedr   r   randpermr   r
   tolistlistranger   r   r   r   r   r   r   iter)r   gindicespadding_sizer    r    r!   __iter__k   s"   zDistributedSampler.__iter__c                 C   s   | j S )N)r   )r   r    r    r!   __len__   s   zDistributedSampler.__len__r   c                 C   s
   || _ dS )a1  
        Set the epoch for this sampler.

        When :attr:`shuffle=True`, this ensures all replicas
        use a different random ordering for each epoch. Otherwise, the next iteration of this
        sampler will yield the same ordering.

        Args:
            epoch (int): Epoch number.
        N)r   )r   r   r    r    r!   	set_epoch   s   
zDistributedSampler.set_epoch)NNTr   F)__name__
__module____qualname____doc__r   r   intboolr"   r   r   r/   r0   r1   r    r    r    r!   r      s2    3
))r   collections.abcr   typingr   r   r$   torch.distributeddistributedr   torch.utils.data.datasetr   torch.utils.data.samplerr   __all__r   r   r    r    r    r!   <module>   s    