a
    Ž¥»a  ã                   @   sf  U d Z ddl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mZ ddlZddlZddlmZ ddlmZ ddlmZ ddlmZmZmZmZmZmZ ddlmZ e	d	d
d�Ze	dƒZee gdf Z!eee gef Z"ej#j$Z$e"e%d< ej&j'Z'G dd„ de(ƒZ)G dd„ deƒZ*G dd„ de
e ƒZ+G dd„ de(ƒZ,G dd„ de,ƒZ-G dd„ de,ƒZ.dS )a  Definition of the DataLoader and associated iterators that subclass _BaseDataLoaderIter

To support these two classes, in `./_utils` we define many utility methods and
functions to be run in multiprocessing. E.g., the data loading worker loop is
in `./_utils/worker.py`.
é    N)ÚAnyÚCallableÚTypeVarÚGenericÚSequenceÚListÚOptional)ÚExceptionWrapper)Ústring_classesé   )ÚIterableDatasetÚSamplerÚSequentialSamplerÚRandomSamplerÚBatchSamplerÚDataset)Ú_utilsÚT_coT)Ú	covariantÚTÚdefault_collatec                   @   s    e Zd ZdZdZedd„ ƒZdS )Ú_DatasetKindr   r   c                 C   s2   | t jkrtj ||||¡S tj ||||¡S d S ©N)r   ÚMapr   ÚfetchZ_MapDatasetFetcherZ_IterableDatasetFetcher)ÚkindÚdatasetZauto_collationÚ
collate_fnÚ	drop_last© r   úU/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/utils/data/dataloader.pyÚcreate_fetcher/   s    
z_DatasetKind.create_fetcherN)Ú__name__Ú
__module__Ú__qualname__r   ÚIterableÚstaticmethodr!   r   r   r   r    r   +   s   r   c                       s(   e Zd ZdZ‡ fdd„Zdd„ Z‡  ZS )Ú_InfiniteConstantSamplerz¸Analogous to ``itertools.repeat(None, None)``.
    Used as sampler for :class:`~torch.utils.data.IterableDataset`.

    Args:
        data_source (Dataset): dataset to sample from
    c                    s   t t| ƒ d ¡ d S r   )Úsuperr'   Ú__init__©Úself©Ú	__class__r   r    r)   ?   s    z!_InfiniteConstantSampler.__init__c                 c   s   d V  q d S r   r   r*   r   r   r    Ú__iter__B   s    z!_InfiniteConstantSampler.__iter__)r"   r#   r$   Ú__doc__r)   r.   Ú__classcell__r   r   r,   r    r'   7   s   r'   c                       s*  e Zd ZU dZee ed< ee ed< eed< e	ed< e	ed< e
ed< eed< eed	< ed
 ed< dZd'dddœee ee e	ee eee  eee e	e	e
ee ee	dœdd„Zd
dœdd„Zedd„ ƒZejdd„ ƒZ‡ fdd„Zd
dœdd„Zedd „ ƒZed!d"„ ƒZedœd#d$„Zd%d&„ Z‡  ZS )(Ú
DataLoaderaÒ  
    Data loader. Combines a dataset and a sampler, and provides an iterable over
    the given dataset.

    The :class:`~torch.utils.data.DataLoader` supports both map-style and
    iterable-style datasets with single- or multi-process loading, customizing
    loading order and optional automatic batching (collation) and memory pinning.

    See :py:mod:`torch.utils.data` documentation page for more details.

    Args:
        dataset (Dataset): dataset from which to load the data.
        batch_size (int, optional): how many samples per batch to load
            (default: ``1``).
        shuffle (bool, optional): set to ``True`` to have the data reshuffled
            at every epoch (default: ``False``).
        sampler (Sampler or Iterable, optional): defines the strategy to draw
            samples from the dataset. Can be any ``Iterable`` with ``__len__``
            implemented. If specified, :attr:`shuffle` must not be specified.
        batch_sampler (Sampler or Iterable, optional): like :attr:`sampler`, but
            returns a batch of indices at a time. Mutually exclusive with
            :attr:`batch_size`, :attr:`shuffle`, :attr:`sampler`,
            and :attr:`drop_last`.
        num_workers (int, optional): how many subprocesses to use for data
            loading. ``0`` means that the data will be loaded in the main process.
            (default: ``0``)
        collate_fn (callable, optional): merges a list of samples to form a
            mini-batch of Tensor(s).  Used when using batched loading from a
            map-style dataset.
        pin_memory (bool, optional): If ``True``, the data loader will copy Tensors
            into CUDA pinned memory before returning them.  If your data elements
            are a custom type, or your :attr:`collate_fn` returns a batch that is a custom type,
            see the example below.
        drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,
            if the dataset size is not divisible by the batch size. If ``False`` and
            the size of dataset is not divisible by the batch size, then the last batch
            will be smaller. (default: ``False``)
        timeout (numeric, optional): if positive, the timeout value for collecting a batch
            from workers. Should always be non-negative. (default: ``0``)
        worker_init_fn (callable, optional): If not ``None``, this will be called on each
            worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as
            input, after seeding and before data loading. (default: ``None``)
        generator (torch.Generator, optional): If not ``None``, this RNG will be used
            by RandomSampler to generate random indexes and multiprocessing to generate
            `base_seed` for workers. (default: ``None``)
        prefetch_factor (int, optional, keyword-only arg): Number of samples loaded
            in advance by each worker. ``2`` means there will be a total of
            2 * num_workers samples prefetched across all workers. (default: ``2``)
        persistent_workers (bool, optional): If ``True``, the data loader will not shutdown
            the worker processes after a dataset has been consumed once. This allows to
            maintain the workers `Dataset` instances alive. (default: ``False``)


    .. warning:: If the ``spawn`` start method is used, :attr:`worker_init_fn`
                 cannot be an unpicklable object, e.g., a lambda function. See
                 :ref:`multiprocessing-best-practices` on more details related
                 to multiprocessing in PyTorch.

    .. warning:: ``len(dataloader)`` heuristic is based on the length of the sampler used.
                 When :attr:`dataset` is an :class:`~torch.utils.data.IterableDataset`,
                 it instead returns an estimate based on ``len(dataset) / batch_size``, with proper
                 rounding depending on :attr:`drop_last`, regardless of multi-process loading
                 configurations. This represents the best guess PyTorch can make because PyTorch
                 trusts user :attr:`dataset` code in correctly handling multi-process
                 loading to avoid duplicate data.

                 However, if sharding results in multiple workers having incomplete last batches,
                 this estimate can still be inaccurate, because (1) an otherwise complete batch can
                 be broken into multiple ones and (2) more than one batch worth of samples can be
                 dropped when :attr:`drop_last` is set. Unfortunately, PyTorch can not detect such
                 cases in general.

                 See `Dataset Types`_ for more details on these two types of datasets and how
                 :class:`~torch.utils.data.IterableDataset` interacts with
                 `Multi-process data loading`_.

    .. warning:: See :ref:`reproducibility`, and :ref:`dataloader-workers-random-seed`, and
                 :ref:`data-loading-randomness` notes for random seed related questions.
    r   Ú
batch_sizeÚnum_workersÚ
pin_memoryr   ÚtimeoutÚsamplerÚprefetch_factorÚ_BaseDataLoaderIterÚ	_iteratorFr   Nr   é   )r7   Úpersistent_workers)r   r2   Úshuffler6   Úbatch_samplerr3   r   r4   r   r5   Úworker_init_fnr7   r;   c                C   s2  t j d¡ |dk rtdƒ‚|
dk r,tdƒ‚|dkrD|dkrDtdƒ‚|dksPJ ‚|rd|dkrdtdƒ‚|| _|| _|| _|| _|
| _|| _	|| _
t|tƒrètj| _|dur¸td	 |¡ƒ‚qð|d urÐtd
 |¡ƒ‚qð|d urðtd |¡ƒ‚ntj| _|d u�r|�rtdƒ‚|d u�rD|dk�s2|�s2|d u�s2|	�r:tdƒ‚d }d}	n|d u �r\|	�r\tdƒ‚|d u �r˜| jtjk�r|tƒ }n|�r�t||d�}nt|ƒ}|d u�r¸|d u �r¸t|||	ƒ}|| _|	| _|| _|| _|| _|d u �rú| j�ròtjj}ntjj}|| _ || _!d| _"d | _#d | _$|  %¡  t  &ddd¡ d S )Nzpython.data_loaderr   zXnum_workers option should be non-negative; use num_workers=0 to disable multiprocessing.z%timeout option should be non-negativer:   zpprefetch_factor option could only be specified in multiprocessing.let num_workers > 0 to enable multiprocessing.z/persistent_workers option needs num_workers > 0FzXDataLoader with IterableDataset: expected unspecified shuffle option, but got shuffle={}zXDataLoader with IterableDataset: expected unspecified sampler option, but got sampler={}zdDataLoader with IterableDataset: expected unspecified batch_sampler option, but got batch_sampler={}z1sampler option is mutually exclusive with shuffler   z[batch_sampler option is mutually exclusive with batch_size, shuffle, sampler, and drop_lastzVbatch_size=None option disables auto-batching and is mutually exclusive with drop_last©Ú	generatorTZ
DataloaderZenabledÚTrue)'ÚtorchZ_CZ_log_api_usage_onceÚ
ValueErrorr   r3   r7   r4   r5   r>   Úmultiprocessing_contextÚ
isinstancer   r   r%   Ú_dataset_kindÚformatr   r'   r   r   r   r2   r   r6   r=   r@   Ú_auto_collationr   Úcollater   Zdefault_convertr   r;   Ú_DataLoader__initializedÚ_IterableDataset_len_calledr9   Úcheck_worker_number_rationalityZ	set_vital)r+   r   r2   r<   r6   r=   r3   r   r4   r   r5   r>   rD   r@   r7   r;   r   r   r    r)   ¢   s�    	
ÿÿÿÿÿÿ
 



zDataLoader.__init__©Úreturnc                 C   s&   | j dkrt| ƒS |  ¡  t| ƒS d S ©Nr   )r3   Ú_SingleProcessDataLoaderIterrL   Ú_MultiProcessingDataLoaderIterr*   r   r   r    Ú_get_iterator,  s    
zDataLoader._get_iteratorc                 C   s   | j S r   )Ú$_DataLoader__multiprocessing_contextr*   r   r   r    rD   3  s    z"DataLoader.multiprocessing_contextc                 C   s~   |d urt| j dkrdt|tƒrFt ¡ }||vr<td ||¡ƒ‚t |¡}t|tj	j
ƒsttd |¡ƒ‚ntd | j ¡ƒ‚|| _d S )Nr   zpmultiprocessing_context option should specify a valid start method in {!r}, but got multiprocessing_context={!r}z‹multiprocessing_context option should be a valid context object or a string specifying the start method, but got multiprocessing_context={}zmmultiprocessing_context can only be used with multi-process loading (num_workers > 0), but got num_workers={})r3   rE   r
   ÚmultiprocessingZget_all_start_methodsrC   rG   Zget_contextÚpython_multiprocessingÚcontextZBaseContextÚ	TypeErrorrS   )r+   rD   Zvalid_start_methodsr   r   r    rD   7  s&    

þÿ
þþc                    s8   | j r"|dv r"td || jj¡ƒ‚tt| ƒ ||¡ d S )N)r2   r=   r6   r   r   r;   z6{} attribute should not be set after {} is initialized)rJ   rC   rG   r-   r"   r(   r1   Ú__setattr__)r+   ÚattrÚvalr,   r   r    rX   P  s
    ÿzDataLoader.__setattr__c                 C   sD   | j r8| jdkr8| jd u r&|  ¡ | _n| j | ¡ | jS |  ¡ S d S rO   )r;   r3   r9   rR   Ú_resetr*   r   r   r    r.   Z  s    
zDataLoader.__iter__c                 C   s
   | j d uS r   )r=   r*   r   r   r    rH   i  s    zDataLoader._auto_collationc                 C   s   | j r| jS | jS d S r   )rH   r=   r6   r*   r   r   r    Ú_index_samplerm  s    zDataLoader._index_samplerc                 C   sd   | j tjkrVt| jƒ }| _| jd urRddlm} | j	rD|| j }n||| j ƒ}|S t| j
ƒS d S )Nr   )Úceil)rF   r   r%   Úlenr   rK   r2   Úmathr]   r   r\   )r+   Úlengthr]   r   r   r    Ú__len__y  s    
zDataLoader.__len__c                 C   s¶   dd„ }| j r| j dkrd S d }d}ttdƒrXztt d¡ƒ}d}W n tyV   Y n0 |d u rtt ¡ }|d urt|}|d u r”t ||| j |ƒ¡ d S | j |kr²t ||| j |ƒ¡ d S )Nc                 S   s0   | d urd  | |rdnd¡nd}d  ||¡}|S )Nz|Our suggested max number of worker in current system is {}{}, which is smaller than what this DataLoader is going to create.Ú z% (`cpuset` is not taken into account)zUDataLoader is not able to compute a suggested max number of worker in current system.zæThis DataLoader will create {} worker processes in total. {} Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.)rG   )Znum_worker_suggestZnum_worker_createdÚcpuset_checkedZsuggested_max_worker_msgÚwarn_msgr   r   r    Ú_create_warning_msg±  s    ûÿ
üú	ÿûzGDataLoader.check_worker_number_rationality.<locals>._create_warning_msgr   FÚsched_getaffinityT)	r3   ÚhasattrÚosr^   rf   Ú	ExceptionÚ	cpu_countÚwarningsÚwarn)r+   re   Zmax_num_worker_suggestrc   rj   r   r   r    rL   –  s8    
ý
ýz*DataLoader.check_worker_number_rationality)r   FNNr   NFFr   NNN)r"   r#   r$   r/   r   r   Ú__annotations__r   ÚintÚboolÚfloatr   rJ   r   Ú_collate_fn_tÚ_worker_init_fn_tr)   rR   ÚpropertyrD   ÚsetterrX   r.   rH   r\   ra   rL   r0   r   r   r,   r    r1   G   sX   
O       úø
ø 




r1   c                   @   sl   e Zd Zeddœdd„Zd dœdd„Zdd	d
„Zdd„ Zdd„ Ze	dœdd„Z
e
Zedœdd„Zdd„ ZdS )r8   N)ÚloaderrN   c                 C   s°   |j | _|j| _|j| _|j| _|j| _|j| _|j| _	|j
| _|joNtj ¡ | _|j| _|j| _t| jƒ| _tjdtjd�j|jd� ¡ | _|j| _d| _d  | j!j"¡| _#d S )Nr   )Zdtyper?   r   z!enumerate(DataLoader)#{}.__next__)$r   Ú_datasetrF   rK   rH   r   Ú
_drop_lastr\   r3   Ú_num_workersr7   Ú_prefetch_factorr4   rB   ÚcudaZis_availableÚ_pin_memoryr5   Ú_timeoutr   Ú_collate_fnÚiterÚ_sampler_iterÚemptyÚint64Zrandom_r@   ÚitemÚ
_base_seedr;   Ú_persistent_workersÚ_num_yieldedrG   r-   r"   Ú_profile_name©r+   ru   r   r   r    r)   å  s      z_BaseDataLoaderIter.__init__rM   c                 C   s   | S r   r   r*   r   r   r    r.   ÷  s    z_BaseDataLoaderIter.__iter__Fc                 C   s   t | jƒ| _d| _|j| _d S rO   )r~   r\   r   r…   rK   )r+   ru   Ú
first_iterr   r   r    r[   ú  s    z_BaseDataLoaderIter._resetc                 C   s
   t | jƒS r   )Únextr   r*   r   r   r    Ú_next_indexÿ  s    z_BaseDataLoaderIter._next_indexc                 C   s   t ‚d S r   )ÚNotImplementedErrorr*   r   r   r    Ú
_next_data  s    z_BaseDataLoaderIter._next_datac                 C   s²   t jj | j¡�Ž | jd u r$|  ¡  |  ¡ }|  jd7  _| j	t
jkrŒ| jd urŒ| j| jkrŒd | j| j| j¡}| jdkr‚|d7 }t |¡ |W  d   ƒ S 1 s¤0    Y  d S )Nr   zwLength of IterableDataset {} was reported to be {} (when accessing len(dataloader)), but {} samples have been fetched. r   zâFor multiprocessing data-loading, this could be caused by not properly configuring the IterableDataset replica at each worker. Please see https://pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset for examples.)rB   ZautogradZprofilerZrecord_functionr†   r   r[   rŒ   r…   rF   r   r%   rK   rG   rv   rx   rk   rl   )r+   Údatard   r   r   r    Ú__next__  s$    
ÿ
þþ

z_BaseDataLoaderIter.__next__c                 C   s
   t | jƒS r   )r^   r\   r*   r   r   r    ra     s    z_BaseDataLoaderIter.__len__c                 C   s   t d| jjƒ‚d S )Nz{} cannot be pickled)r‹   r-   r"   r*   r   r   r    Ú__getstate__  s    z _BaseDataLoaderIter.__getstate__)F)r"   r#   r$   r1   r)   r.   r[   rŠ   rŒ   r   rŽ   r‰   rn   ra   r�   r   r   r   r    r8   ä  s   
r8   c                       s$   e Zd Z‡ fdd„Zdd„ Z‡  ZS )rP   c                    sN   t t| ƒ |¡ | jdksJ ‚| jdks,J ‚t | j| j| j	| j
| j¡| _d S rO   )r(   rP   r)   r|   rx   r   r!   rF   rv   rH   r}   rw   Ú_dataset_fetcherr‡   r,   r   r    r)   '  s    ÿz%_SingleProcessDataLoaderIter.__init__c                 C   s*   |   ¡ }| j |¡}| jr&tj |¡}|S r   )rŠ   r�   r   r{   r   r4   )r+   Úindexr�   r   r   r    rŒ   /  s
    z'_SingleProcessDataLoaderIter._next_data)r"   r#   r$   r)   rŒ   r0   r   r   r,   r    rP   &  s   rP   c                       sv   e Zd ZdZ‡ fdd„Zd‡ fdd„	Zejfdd„Zd	d
„ Z	dd„ Z
dd„ Zdd„ Zddd„Zdd„ Zdd„ Z‡  ZS )rQ   zHIterates once over the DataLoader's dataset, as specified by the samplerc                    s´  t t| ƒ |¡ | jdksJ ‚| jdks,J ‚|jd u r<t}n|j}|j| _t	 
t| jƒ¡| _| ¡ | _d| _d| _| ¡ | _g | _g | _t| jƒD ]|}| ¡ }| ¡  |jtjj| j| j|| j| j| j| j| j| j| j|| j| j fd�}d|_!| "¡  | j #|¡ | j #|¡ q’| j$�rht% ¡ | _&t' ¡ | _(t%j)tj*j+| j| j(t,j- .¡ | j&fd�}d|_!| "¡  || _/n| j| _(tj0 1t2| ƒt3dd„ | jD ƒƒ¡ tj0 4¡  d| _| j5|dd� d S )Nr   F)ÚtargetÚargsTc                 s   s   | ]}|j V  qd S r   )Úpid©Ú.0Úwr   r   r    Ú	<genexpr>­  ó    z:_MultiProcessingDataLoaderIter.__init__.<locals>.<genexpr>)rˆ   )6r(   rQ   r)   rx   ry   rD   rT   r>   Z_worker_init_fnÚ	itertoolsÚcycleÚrangeÚ_worker_queue_idx_cycleÚQueueÚ_worker_result_queueÚ_worker_pids_setÚ	_shutdownÚEventÚ_workers_done_eventÚ_index_queuesÚ_workersÚcancel_join_threadÚProcessr   ÚworkerZ_worker_looprF   rv   rH   r}   rw   rƒ   r„   ÚdaemonÚstartÚappendr{   Ú	threadingÚ_pin_memory_thread_done_eventÚqueueÚ_data_queueÚThreadr4   Z_pin_memory_looprB   rz   Zcurrent_deviceÚ_pin_memory_threadÚsignal_handlingZ_set_worker_pidsÚidÚtupleZ_set_SIGCHLD_handlerr[   )r+   ru   rD   ÚiZindex_queuer—   Zpin_memory_threadr,   r   r    r)   m  s`    



üþ

þþ"
z'_MultiProcessingDataLoaderIter.__init__Fc                    sÆ   t ƒ  ||¡ d| _d| _i | _d| _dd„ t| jƒD ƒ| _|s¤t| jƒD ]}| j	|  
tj ¡ ¡ qJ| j}|dkr¤|  ¡ \}}t|tjjƒrl|d u sšJ ‚|d8 }qlt| j| j ƒD ]}|  ¡  q´d S )Nr   c                 S   s   g | ]}d ‘qS )Tr   ©r–   rµ   r   r   r    Ú
<listcomp>Â  r™   z9_MultiProcessingDataLoaderIter._reset.<locals>.<listcomp>r   )r(   r[   Ú	_send_idxÚ	_rcvd_idxÚ
_task_infoÚ_tasks_outstandingrœ   rx   Ú_workers_statusr¤   Úputr   r¨   Z_ResumeIterationÚ	_get_datarE   ry   Ú_try_put_index)r+   ru   rˆ   ÚidxZresume_iteration_cntZ
return_idxZreturn_dataÚ_r,   r   r    r[   ²  s"    
z%_MultiProcessingDataLoaderIter._resetc                    s>  z| j j|d�}d|fW S  t�y8 } �zg }t| jƒD ].\}}| j| r:| ¡ s:| |¡ |  |¡ q:t	|ƒdkršd 
dd„ |D ƒ¡}td |¡ƒ|‚t|tjƒr´W Y d }~dS dd l‰ dd l}zd	}	‡ fd
d„t|	ƒD ƒ}
W n> t�y  } z$|j|jk�rtdƒd ‚W Y d }~n
d }~0 0 ‚ W Y d }~n
d }~0 0 d S )N©r5   Tr   z, c                 s   s   | ]}t |jƒV  qd S r   )Ústrr”   r•   r   r   r    r˜   ê  r™   z?_MultiProcessingDataLoaderIter._try_get_data.<locals>.<genexpr>z1DataLoader worker (pid(s) {}) exited unexpectedly)FNé
   c                    s   g | ]}ˆ   ¡ ‘qS r   )ÚNamedTemporaryFiler¶   ©Útempfiler   r    r·   ö  r™   z@_MultiProcessingDataLoaderIter._try_get_data.<locals>.<listcomp>a  Too many open files. Communication with the workers is no longer possible. Please increase the limit using `ulimit -n` in the shell or change the sharing strategy by calling `torch.multiprocessing.set_sharing_strategy('file_system')` at the beginning of your code)r¯   Úgetri   Ú	enumerater¥   r¼   Úis_aliver«   Ú_mark_worker_as_unavailabler^   ÚjoinÚRuntimeErrorrG   rE   r®   ÚEmptyrÇ   Úerrnorœ   ÚOSErrorZEMFILE)r+   r5   r�   ÚeZfailed_workersÚ	worker_idr—   Zpids_strrÏ   Zfds_limit_marginÚfsr   rÆ   r    Ú_try_get_dataÑ  s6    

ÿúz,_MultiProcessingDataLoaderIter._try_get_datac                 C   s~   | j dkr4|  | j ¡\}}|r"|S td | j ¡ƒ‚nF| jrd| j ¡ rZ|  ¡ \}}|r:|S q:tdƒ‚n|  ¡ \}}|rd|S qdd S )Nr   z%DataLoader timed out after {} secondsz%Pin memory thread exited unexpectedly)r|   rÔ   rÍ   rG   r{   r±   rÊ   )r+   Úsuccessr�   r   r   r    r¾   c  s    


z(_MultiProcessingDataLoaderIter._get_datac                 C   sD  | j | jk rR| j| j  }|d }t|ƒdksd| j| r8qd| j| j = |  j d7  _ q | js`|  ¡  t‚t| j| j  ƒdkr”| j | j ¡d }|  	|¡S | j
s¤| jdks¨J ‚|  ¡ \}}|  jd8  _| jtjk�r
t|tjjƒ�r
| jrôd| j|j< n|  |j¡ |  ¡  q || j k�r,| j|  |f7  < q | j|= |  	|¡S q d S )Nr   r:   r   F)r¹   r¸   rº   r^   r¼   r„   Ú_shutdown_workersÚStopIterationÚpopÚ_process_datar¡   r»   r¾   rF   r   r%   rE   r   r¨   Z_IterableDatasetStopIterationrÒ   rË   r¿   )r+   ÚinforÒ   r�   rÀ   r   r   r    rŒ   „  s6    	

z)_MultiProcessingDataLoaderIter._next_datac                 C   s¨   | j | j| j k sJ ‚z|  ¡ }W n ty6   Y d S 0 t| jƒD ]}t| jƒ}| j| rB qdqBd S | j	|  
| j|f¡ |f| j| j< |  j d7  _ |  jd7  _d S ©Nr   )r»   ry   rx   rŠ   r×   rœ   r‰   r�   r¼   r¤   r½   r¸   rº   )r+   r‘   rÁ   Zworker_queue_idxr   r   r    r¿   µ  s    

z-_MultiProcessingDataLoaderIter._try_put_indexc                 C   s,   |  j d7  _ |  ¡  t|tƒr(| ¡  |S rÛ   )r¹   r¿   rE   r	   Úreraise)r+   r�   r   r   r    rÙ   É  s
    
z,_MultiProcessingDataLoaderIter._process_datac                 C   sL   | j | s| jr|sJ ‚| j| }| d ¡ d| j |< | j ¡ |ksHJ ‚d S )NF)r¼   r„   r¤   r½   r£   Úis_set)r+   rÒ   ÚshutdownÚqr   r   r    rË   Ð  s
    


z:_MultiProcessingDataLoaderIter._mark_worker_as_unavailablec              
   C   sZ  t j}|du s|d u rd S | j�sVd| _zìt| dƒrh| j ¡  | j d¡ | j 	¡  | j 
¡  | j ¡  | j ¡  tt| jƒƒD ]"}| js”| j| r€| j|dd� q€| jD ]}|j	t jd� qª| jD ]}| 
¡  | ¡  qÄW | jrøt j t| ƒ¡ d| _| jD ]}| ¡ rþ| ¡  qþn@| j�r4t j t| ƒ¡ d| _| jD ]}| ¡ �r:| ¡  �q:0 d S )NTr±   )NN)rÞ   rÂ   F)r   Úpython_exit_statusr¡   rg   r­   ÚsetrŸ   r½   r±   rÌ   r¦   Úcloser£   rœ   r^   r¥   r„   r¼   rË   ÚMP_STATUS_CHECK_INTERVALr¤   r    r²   Z_remove_worker_pidsr³   rÊ   Ú	terminate)r+   rà   rÒ   r—   rß   r   r   r    rÖ   ê  sB    








÷

z0_MultiProcessingDataLoaderIter._shutdown_workersc                 C   s   |   ¡  d S r   )rÖ   r*   r   r   r    Ú__del__/  s    z&_MultiProcessingDataLoaderIter.__del__)F)F)r"   r#   r$   r/   r)   r[   r   rã   rÔ   r¾   rŒ   r¿   rÙ   rË   rÖ   rå   r0   r   r   r,   r    rQ   7  s     7E !1
ErQ   )/r/   rh   r¬   rš   rk   r®   Útypingr   r   r   r   r   r   r   rT   rU   rB   Ztorch.multiprocessingZtorch._utilsr	   Z
torch._sixr
   rb   r   r   r   r   r   r   r   r   r   rn   rr   rq   rI   r   rm   r¨   Zget_worker_infoÚobjectr   r'   r1   r8   rP   rQ   r   r   r   r    Ú<module>   s8   $     B