a
    ßñhãÊ  ã                   @   sä   d dl mZ d dlZd dl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
 d dlmZ e ¡ r|d dlmZ d dlmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZ d dlmZmZ dd„ Zdd„ ZG dd„ deƒZdS )é    )ÚcontextmanagerNé   )Úcomm)Ú_get_default_group)ÚReduceOpé   )ÚModule)Ú	replicate)Úscatter_kwargsÚgather)Úparallel_apply)Ú_get_device_indexÚ_get_all_device_indicesc                 C   sR   t | tjƒr| gS t | ttfƒr0tjtt| ƒŽ S t | t	ƒrNtjtt|  
¡ ƒŽ S g S )zI
    Recursively find all tensors contained in the specified object.
    )Ú
isinstanceÚtorchZTensorÚlistÚtupleÚ	itertoolsÚchainÚmapÚ_find_tensorsÚdictÚvalues)Úobj© r   ú]/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/nn/parallel/distributed.pyr      s    
r   c                  C   sJ   g d¢} d}| D ],}|t jv r(t j| nd}|d||f 7 }qt|ƒ d S )N).ZRANKZ
LOCAL_RANKZ
WORLD_SIZEZMASTER_PORTZMASTER_ADDRZCUDA_VISIBLE_DEVICESZGLOO_SOCKET_IFNAMEZGLOO_DEVICE_TRANSPORTZNCCL_SOCKET_IFNAMEZNCCL_BLOCKING_WAITZ
NCCL_DEBUGZNCCL_DEBUG_SUBSYSZNCCL_IB_DISABLEZNCCL_P2P_DISABLEZNCCL_P2P_LEVELZNCCL_SHM_DISABLEZNCCL_SOCKET_NTHREADSZNCCL_NSOCKS_PERTHREADZNCCL_BUFFSIZEZNCCL_NTHREADSZ
NCCL_RINGSZNCCL_MAX_NCHANNELSZNCCL_MIN_NCHANNELSZNCCL_CHECKS_DISABLEZNCCL_CHECK_POINTERSZNCCL_LAUNCH_MODEZNCCL_IB_HCAZNCCL_IB_TIMEOUTZNCCL_IB_RETRY_CNTZNCCL_IB_GID_INDEXZ
NCCL_IB_SLZ
NCCL_IB_TCZNCCL_IB_AR_THRESHOLDZNCCL_IB_CUDA_SUPPORTZNCCL_NET_GDR_LEVELZNCCL_NET_GDR_READZNCCL_SINGLE_RING_THRESHOLDZNCCL_LL_THRESHOLDZNCCL_TREE_THRESHOLDZ	NCCL_ALGOZ
NCCL_PROTOZNCCL_IGNORE_CPU_AFFINITYZNCCL_DEBUG_FILEZNCCL_COLLNET_ENABLEZNCCL_TOPO_FILEZNCCL_TOPO_DUMP_FILEÚ zN/Az
env:%s=%s
)ÚosÚenvironÚprint)Zrelevant_env_varsZformatted_outputÚvarÚvaluer   r   r   Ú_dump_DDP_relevant_env_vars$   s    1r"   c                	       s
  e Zd ZdZd<‡ fdd„	Zd=d	d
„Zdd„ Zdd„ Z‡ fdd„Zdd„ Z	e
dd„ ƒZdd„ Zdd„ Zdd„ Zdd„ Zd>‡ fdd„	Zdd „ Zd!d"„ Zd#d$„ Zd%d&„ Zd'd(„ Zd)d*„ Ze
d?d+d,„ƒZeed-œd.d/„Zd@d0d1„Zd2d3„ Zd4d5„ Zd6d7„ Zd8d9„ Zd:d;„ Z ‡  Z!S )AÚDistributedDataParallelaO2  Implements distributed data parallelism that is based on
    ``torch.distributed`` package at the module level.

    This container parallelizes the application of the given module by
    splitting the input across the specified devices by chunking in the batch
    dimension. The module is replicated on each machine and each device, and
    each such replica handles a portion of the input. During the backwards
    pass, gradients from each node are averaged.

    The batch size should be larger than the number of GPUs used locally.

    See also: :ref:`distributed-basics` and :ref:`cuda-nn-ddp-instead`.
    The same constraints on input as in :class:`torch.nn.DataParallel` apply.

    Creation of this class requires that ``torch.distributed`` to be already
    initialized, by calling :func:`torch.distributed.init_process_group`.

    ``DistributedDataParallel`` is proven to be significantly faster than
    :class:`torch.nn.DataParallel` for single-node multi-GPU data
    parallel training.

    To use ``DistributedDataParallel`` on a host with N GPUs, you should spawn
    up ``N`` processes, ensuring that each process exclusively works on a single
    GPU from 0 to N-1. This can be done by either setting
    ``CUDA_VISIBLE_DEVICES`` for every process or by calling:

        >>> torch.cuda.set_device(i)

    where i is from 0 to N-1. In each process, you should refer the following
    to construct this module:

        >>> torch.distributed.init_process_group(
        >>>     backend='nccl', world_size=N, init_method='...'
        >>> )
        >>> model = DistributedDataParallel(model, device_ids=[i], output_device=i)

    In order to spawn up multiple processes per node, you can use either
    ``torch.distributed.launch`` or ``torch.multiprocessing.spawn``.

    .. note ::
        Please refer to `PyTorch Distributed Overview <https://pytorch.org/tutorials/beginner/dist_overview.html>`__
        for a brief introduction to all features related to distributed training.

    .. note:: ``nccl`` backend is currently the fastest and highly recommended
        backend when using GPUs. This applies to both single-node and
        multi-node distributed training.

    .. note:: This module also supports mixed-precision distributed training.
        This means that your model can have different types of parameters such
        as mixed types of ``fp16`` and ``fp32``, the gradient reduction on these
        mixed types of parameters will just work fine.

    .. note:: If you use ``torch.save`` on one process to checkpoint the module,
        and ``torch.load`` on some other processes to recover it, make sure that
        ``map_location`` is configured properly for every process. Without
        ``map_location``, ``torch.load`` would recover the module to devices
        where the module was saved from.

    .. note:: When a model is trained on ``M`` nodes with ``batch=N``, the
        gradient will be ``M`` times smaller when compared to the same model
        trained on a single node with ``batch=M*N`` (because the gradients
        between different nodes are averaged). You should take this into
        consideration when you want to obtain a mathematically equivalent
        training process compared to the local training counterpart.

    .. note::
        Parameters are never broadcast between processes. The module performs
        an all-reduce step on gradients and assumes that they will be modified
        by the optimizer in all processes in the same way. Buffers
        (e.g. BatchNorm stats) are broadcast from the module in process of rank
        0, to all other replicas in the system in every iteration.

    .. note::
        If you are using DistributedDataParallel in conjunction with the
        :ref:`distributed-rpc-framework`, you should always use
        :meth:`torch.distributed.autograd.backward` to compute gradients and
        :class:`torch.distributed.optim.DistributedOptimizer` for optimizing
        parameters.

        Example::

            >>> import torch.distributed.autograd as dist_autograd
            >>> from torch.nn.parallel import DistributedDataParallel as DDP
            >>> from torch import optim
            >>> from torch.distributed.optim import DistributedOptimizer
            >>> from torch.distributed.rpc import RRef
            >>>
            >>> t1 = torch.rand((3, 3), requires_grad=True)
            >>> t2 = torch.rand((3, 3), requires_grad=True)
            >>> rref = rpc.remote("worker1", torch.add, args=(t1, t2))
            >>> ddp_model = DDP(my_model)
            >>>
            >>> # Setup optimizer
            >>> optimizer_params = [rref]
            >>> for param in ddp_model.parameters():
            >>>     optimizer_params.append(RRef(param))
            >>>
            >>> dist_optim = DistributedOptimizer(
            >>>     optim.SGD,
            >>>     optimizer_params,
            >>>     lr=0.05,
            >>> )
            >>>
            >>> with dist_autograd.context() as context_id:
            >>>     pred = ddp_model(rref.to_here())
            >>>     loss = loss_func(pred, loss)
            >>>     dist_autograd.backward(context_id, loss)
            >>>     dist_optim.step()

    .. warning::
        Constructor, forward method, and differentiation of the output (or a
        function of the output of this module) are distributed synchronization
        points. Take that into account in case different processes might be
        executing different code.

    .. warning::
        This module assumes all parameters are registered in the model by the
        time it is created. No parameters should be added nor removed later.
        Same applies to buffers.

    .. warning::
        This module assumes all parameters are registered in the model of each
        distributed processes are in the same order. The module itself will
        conduct gradient ``allreduce`` following the reverse order of the
        registered parameters of the model. In other words, it is users'
        responsibility to ensure that each distributed process has the exact
        same model and thus the exact same parameter registration order.

    .. warning::
        This module allows parameters with non-rowmajor-contiguous strides.
        For example, your model may contain some parameters whose
        :class:`torch.memory_format` is ``torch.contiguous_format``
        and others whose format is ``torch.channels_last``.  However,
        corresponding parameters in different processes must have the
        same strides.

    .. warning::
        This module doesn't work with :func:`torch.autograd.grad` (i.e. it will
        only work if gradients are to be accumulated in ``.grad`` attributes of
        parameters).

    .. warning::
        If you plan on using this module with a ``nccl`` backend or a ``gloo``
        backend (that uses Infiniband), together with a DataLoader that uses
        multiple workers, please change the multiprocessing start method to
        ``forkserver`` (Python 3 only) or ``spawn``. Unfortunately
        Gloo (that uses Infiniband) and NCCL2 are not fork safe, and you will
        likely experience deadlocks if you don't change this setting.

    .. warning::
        Forward and backward hooks defined on :attr:`module` and its submodules
        won't be invoked anymore, unless the hooks are initialized in the
        :meth:`forward` method.

    .. warning::
        You should never try to change your model's parameters after wrapping
        up your model with ``DistributedDataParallel``. Because, when
        wrapping up your model with ``DistributedDataParallel``, the constructor
        of ``DistributedDataParallel`` will register the additional gradient
        reduction functions on all the parameters of the model itself at the
        time of construction. If you change the model's parameters afterwards,
        gradient redunction functions no longer match the correct set of
        parameters.

    .. warning::
        Using ``DistributedDataParallel`` in conjunction with the
        :ref:`distributed-rpc-framework` is experimental and subject to change.

    .. warning::
        The ``gradient_as_bucket_view`` mode  does not yet work with Automatic
        Mixed Precision (AMP). AMP maintains stashed gradients that are used for
        unscaling gradients. With ``gradient_as_bucket_view=True``, these
        stashed gradients will point to communication buckets in the first
        iteration. In the next iteration, the communication buckets are mutated
        and thus these stashed gradients will be unexpectedly mutated as well,
        which might lead to wrong results.

    Args:
        module (Module): module to be parallelized
        device_ids (list of int or torch.device): CUDA devices. This should
                   only be provided when the input module resides on a single
                   CUDA device. For single-device modules, the i'th
                   :attr:`module` replica is placed on ``device_ids[i]``. For
                   multi-device modules and CPU modules, ``device_ids`` must be
                   ``None`` or an empty list, and input data for the forward
                   pass must be placed on the correct device. (default: all
                   visible devices for single-device modules)
        output_device (int or torch.device): Device location of output for
                      single-device CUDA modules. For multi-device modules and
                      CPU modules, it must be ``None``, and the module itself
                      dictates the output location. (default: ``device_ids[0]``
                      for single-device modules)
        broadcast_buffers (bool): Flag that enables syncing (broadcasting)
                          buffers of the module at beginning of the ``forward``
                          function. (default: ``True``)
        process_group: The process group to be used for distributed data
                       all-reduction. If ``None``, the default process group, which
                       is created by :func:`torch.distributed.init_process_group`,
                       will be used. (default: ``None``)
        bucket_cap_mb: ``DistributedDataParallel`` will bucket parameters into
                       multiple buckets so that gradient reduction of each
                       bucket can potentially overlap with backward computation.
                       :attr:`bucket_cap_mb` controls the bucket size in
                       MegaBytes (MB). (default: 25)
        find_unused_parameters (bool): Traverse the autograd graph from all
                               tensors contained in the return value of the
                               wrapped module's ``forward`` function. Parameters
                               that don't receive gradients as part of this
                               graph are preemptively marked as being ready to
                               be reduced. Note that all ``forward`` outputs
                               that are derived from module parameters must
                               participate in calculating loss and later the
                               gradient computation. If they don't, this wrapper
                               will hang waiting for autograd to produce
                               gradients for those parameters. Any outputs
                               derived from module parameters that are otherwise
                               unused can be detached from the autograd graph
                               using ``torch.Tensor.detach``. (default: ``False``)
        check_reduction: This argument is deprecated.
        gradient_as_bucket_view (bool): This is a prototype feature and subject
                      to changes. When set to ``True``, gradients will be views
                      pointing to different offsets of ``allreduce`` communication
                      buckets. This can reduce peak memory usage, where the
                      saved memory size will be equal to the total gradients
                      size. Moreover, it avoids the overhead of copying between
                      gradients and ``allreduce`` communication buckets. When
                      gradients are views, ``detach_()`` cannot be called on the
                      gradients. If hitting such errors, please fix it by
                      referring to the :meth:`~torch.optim.Optimizer.zero_grad`
                      function in ``torch/optim/optimizer.py`` as a solution.


    Attributes:
        module (Module): the module to be parallelized.

    Example::

        >>> torch.distributed.init_process_group(backend='nccl', world_size=4, init_method='...')
        >>> net = torch.nn.DistributedDataParallel(model, pg)
    Nr   Té   Fc                    sª  t t| ƒ ¡  tdd„ | ¡ D ƒƒs,J dƒ‚tdd„ | ¡ D ƒƒdk| _dd„ | ¡ D ƒ}t|ƒdkstJ d |¡ƒ‚t|ƒd	 | _	| j	d
ks’| jrÈ|sš|rºJ d ||dd„ | ¡ D ƒ¡ƒ‚d | _
d | _n>|d u rÖtƒ }ttdd„ |ƒƒ| _
|d u rú|d	 }t|dƒ| _|d u �rtƒ | _n|| _|| _|| _t| j ¡ ƒd	 j| _|| _|| _d| _d| _d| _|
| _|	�rvt d¡ tdƒ| _t|d d ƒ| _| jd	d� |   ¡  d S )Nc                 s   s   | ]}|j V  qd S ©N©Úrequires_grad©Ú.0Úpr   r   r   Ú	<genexpr>X  ó    z3DistributedDataParallel.__init__.<locals>.<genexpr>zhDistributedDataParallel is not needed when a module doesn't have any parameter that requires a gradient.c                 S   s   h | ]
}|j ’qS r   ©Údevicer(   r   r   r   Ú	<setcomp>]  r,   z3DistributedDataParallel.__init__.<locals>.<setcomp>r   c                 S   s   h | ]}|j j’qS r   )r.   Útyper(   r   r   r   r/   ^  r,   zuDistributedDataParallel's input module must be on the same type of devices, but input module parameters locate in {}.r   Úcpuz«DistributedDataParallel device_ids and output_device arguments only work with single-device GPU modules, but got device_ids {}, output_device {}, and module parameters {}.c                 S   s   h | ]
}|j ’qS r   r-   r(   r   r   r   r/   j  r,   c                 S   s
   t | dƒS )NT)r   )Úxr   r   r   Ú<lambda>s  r,   z2DistributedDataParallel.__init__.<locals>.<lambda>TFzhThe `check_reduction` argument in `DistributedDataParallel` module is deprecated. Please avoid using it.i   i   ©Úauthoritative_rank)!Úsuperr#   Ú__init__ÚanyÚ
parametersÚlenZis_multi_device_moduleÚformatr   Údevice_typeÚ
device_idsÚoutput_devicer   r   r   r   Úprocess_groupÚdimÚmoduler.   Úbroadcast_buffersÚfind_unused_parametersÚrequire_backward_grad_syncÚrequire_forward_param_syncÚddp_join_enabledÚgradient_as_bucket_viewÚwarningsÚwarnÚintÚbroadcast_bucket_sizeÚbucket_bytes_capÚ_sync_params_and_buffersÚ_ddp_init_helper)ÚselfrA   r=   r>   r@   rB   r?   Zbucket_cap_mbrC   Zcheck_reductionrG   Zdistinct_device_types©Ú	__class__r   r   r7   N  s\    ÿÿý
ÿü

ÿ
z DistributedDataParallel.__init__c                 C   s2   t | j ¡  ¡ ƒ}t|ƒdkr.|  || j|¡ d S ©Nr   )r   rA   Z
state_dictr   r:   Ú _distributed_broadcast_coalescedrK   )rO   r5   Zmodule_statesr   r   r   rM   ž  s    ýz0DistributedDataParallel._sync_params_and_buffersc              
      s°  ddd„‰ | j rìt| j ƒdkrìt d¡ t| j| j dd�| _| j| jd< | jdd… D ]’}t| j ¡ ˆ |ƒƒD ]x\}}|j	t
ju rÞ| ¡ | ¡ krÞt
 ¡ �4 | | ¡  | ¡ | ¡ ¡ |¡¡ W d  ƒ n1 sÔ0    Y  |j|_qnqVn
| jg| _‡ fd	d
„| jD ƒ| _dd
„ | jD ƒ| _‡ fdd
„| jD ƒ}dd
„ |D ƒ‰ dd„ ‰‡fdd
„|D ƒ}t ˆ d tj| jg|d ¡}t ˆ tt|ƒƒ| j|| j| j| j¡| _ |  !| j¡ dS )aR  
        Initialization helper function that does the following:

        (1) replicating the module from device[0] to the other devices
        (2) bucketing the parameters for reductions
        (3) resetting the bucketing states
        (4) registering the grad hooks
        (5) passing a handle of DDP to SyncBatchNorm Layer
        Tc                 s   s8   dd„ }|r|   ¡ n| gD ]} || ƒD ]
}|V  q&qd S )Nc                 s   s4   t | dƒr| j ¡ n
| jdd�}|D ]
}|V  q$d S )NÚ_former_parametersF©Úrecurse)ÚhasattrrT   r   r9   )ÚmZpsr*   r   r   r   Úmodel_parameters²  s    ÿ
þzVDistributedDataParallel._ddp_init_helper.<locals>.parameters.<locals>.model_parameters©Úmodules)rX   rV   rY   r*   r   r   r   r9   ±  s    z<DistributedDataParallel._ddp_init_helper.<locals>.parametersr   a–  Single-Process Multi-GPU is not the recommended mode for DDP. In this mode, each DDP instance operates on multiple devices and creates multiple module replicas within one process. The overhead of scatter/gather and GIL contention in every forward pass can slow down training. Please consider using one DDP instance per device or per module replica by explicitly setting device_ids or CUDA_VISIBLE_DEVICES. )Údetachr   Nc                    s   g | ]}t ˆ |ƒƒ‘qS r   ©r   ©r)   rX   ©r9   r   r   Ú
<listcomp>à  r,   z<DistributedDataParallel._ddp_init_helper.<locals>.<listcomp>c                 S   s   g | ]}t | ¡ ƒ‘qS r   )r   Úbuffersr^   r   r   r   r`   á  r,   c                    s"   g | ]}‡ fd d„|  ¡ D ƒ‘qS )c                    s0   g | ](}t d d„ ˆ |dd�ƒD ]}||f‘qqS )c                 S   s   | j S r%   r&   )Ú	parameterr   r   r   r3   é  r,   zPDistributedDataParallel._ddp_init_helper.<locals>.<listcomp>.<listcomp>.<lambda>FrU   )Úfilter)r)   rA   rb   r_   r   r   r`   å  s   
þþzGDistributedDataParallel._ddp_init_helper.<locals>.<listcomp>.<listcomp>rZ   ©r)   Zreplicar_   r   r   r`   ä  s   ú
þc                 S   s   g | ]}t d d„ |D ƒƒ‘qS )c                 s   s   | ]\}}|V  qd S r%   r   )r)   Ú_rb   r   r   r   r+   ï  r,   úFDistributedDataParallel._ddp_init_helper.<locals>.<listcomp>.<genexpr>r]   rd   r   r   r   r`   î  s   ÿc                 S   s,   t | tjjƒr| jS t | tjjƒr(| jS dS )NF)r   r   ÚnnZ	EmbeddingÚsparseZEmbeddingBag)rA   r   r   r   Úproduces_sparse_gradientó  s
    zJDistributedDataParallel._ddp_init_helper.<locals>.produces_sparse_gradientc                    s"   g | ]}t ‡ fd d„|D ƒƒ‘qS )c                 3   s   | ]\}}ˆ |ƒV  qd S r%   r   )r)   rA   re   ©ri   r   r   r+   ý  r,   rf   r]   rd   rj   r   r   r`   ü  s   ÿ)T)"r=   r:   rH   rI   r	   rA   Ú_module_copiesÚzipr9   Zlayoutr   ZstridedZstrideÚno_gradÚset_ÚcloneZ
as_stridedÚsizeÚcopy_r'   Úmodules_paramsÚmodules_buffersÚdistZ"_compute_bucket_assignment_by_sizeZ_DEFAULT_FIRST_BUCKET_BYTESrL   ZReducerr   Úreversedr?   rC   rG   ÚreducerÚ_passing_sync_batchnorm_handle)rO   Zmodule_copyÚparamZ
copy_paramZmodules_and_parametersZexpect_sparse_gradientZbucket_indicesr   )r9   ri   r   rN   ¦  sZ    
ÿ
ÿþ$

ù
þ	
þ	
ý
ù
z(DistributedDataParallel._ddp_init_helperc                 C   s$   |   ¡  t | j¡}|d= |d= |S )Nr?   rv   )Ú_check_default_groupÚcopyÚ__dict__)rO   Úattrsr   r   r   Ú__getstate__  s
    z$DistributedDataParallel.__getstate__c                    s@   t ƒ | _tt| ƒ |¡ | j dd¡ | j dd¡ |  ¡  d S )NrE   TrD   )r   r?   r6   r#   Ú__setstate__r{   Ú
setdefaultrN   )rO   ÚstaterP   r   r   r~      s
    z$DistributedDataParallel.__setstate__c                 C   s@   d}z| j tƒ krd}W n ty.   d}Y n0 |r<tdƒ‚d S )NFTzÈDDP Pickling/Unpickling are only supported when using DDP with the default process group. That is, when you have called init_process_group and have not passed process_group argument to DDP constructor)r?   r   ÚRuntimeError)rO   Zpickle_not_supportedr   r   r   ry   (  s    
z,DistributedDataParallel._check_default_groupc                 c   s*   | j }d| _ zdV  W || _ n|| _ 0 dS )aM  
        A context manager to disable gradient synchronizations across DDP
        processes. Within this context, gradients will be accumulated on module
        variables, which will later be synchronized in the first
        forward-backward pass exiting the context.

        Example::

            >>> ddp = torch.nn.DistributedDataParallel(model, pg)
            >>> with ddp.no_sync():
            >>>   for input in inputs:
            >>>     ddp(input).backward()  # no synchronization, accumulate grads
            >>> ddp(another_input).backward()  # synchronize grads
        FN)rD   )rO   Zold_require_backward_grad_syncr   r   r   Úno_sync7  s
    zDistributedDataParallel.no_syncc                 O   s8  | j r8tjd| jd�}tj|| jdd�}| j || j	¡ | j 
¡ rLt d¡ | jrZ|  ¡  | j rl| jdd� | jrÚ|  ||| j¡\}}t| jƒdkr®| j|d i |d ¤Ž}qê|  | jd t|ƒ… ||¡}|  || j¡}n| j|i |¤Ž}t ¡ �r.| j�r.d| _| j�r | j tt|ƒƒ¡ n| j g ¡ nd| _|S )	Nr   r-   T©ÚgroupZasync_opz4Reducer buckets have been rebuilt in this iteration.F©Úis_joined_rankr   )rF   r   Úonesr.   rt   Ú
all_reducer?   rv   Z_set_forward_pass_work_handleÚ%ddp_join_divide_by_initial_world_sizeÚ_rebuild_bucketsÚloggingÚinforE   Ú_sync_paramsÚ)_check_global_requires_backward_grad_syncr=   Úscatterr:   rA   r   rk   r   r>   Zis_grad_enabledrD   rC   Zprepare_for_backwardr   r   )rO   ÚinputsÚkwargsr‡   ÚworkÚoutputÚoutputsr   r   r   ÚforwardN  s8    ÿÿ


zDistributedDataParallel.forwardc                 C   s   t |||| jd�S ©N)r@   )r
   r@   )rO   r�   r‘   r=   r   r   r   r�   ‚  s    zDistributedDataParallel.scatterc                 C   s   t |||| jd t|ƒ… ƒS r%   )r   r=   r:   )rO   Zreplicasr�   r‘   r   r   r   r   …  s    z&DistributedDataParallel.parallel_applyc                 C   s   t ||| jd�S r–   )r   r@   )rO   r”   r>   r   r   r   r   ˆ  s    zDistributedDataParallel.gatherc                    s2   t t| ƒ |¡ | jdd … D ]}| |¡ q| S )Nr   )r6   r#   Útrainrk   )rO   ÚmoderA   rP   r   r   r—   ‹  s    zDistributedDataParallel.trainc                 C   s(   t jd| jd�}tj|| jd� | ¡ S )Nr   r-   )r„   )r   Úzerosr.   rt   rˆ   r?   Úitem)rO   Zall_active_procsr   r   r   Ú(_schedule_shadow_all_reduce_for_fwd_pass”  s
    ÿz@DistributedDataParallel._schedule_shadow_all_reduce_for_fwd_passc                 C   sF   |s| j rtjd| jd�}ntjd| jd�}tj|| jdd�}||fS )Nr   r-   Trƒ   )rD   r   r‡   r.   r™   rt   rˆ   r?   )rO   r†   Zrequires_sync_tensorr’   r   r   r   rŽ   �  s    
ÿzADistributedDataParallel._check_global_requires_backward_grad_syncc                 C   s:   |   ¡ r6t | j¡}|  |d¡}|  | jd | j|¡ d S )NFr   )Úwill_sync_module_buffersrt   Úget_rankr?   Ú_find_common_rankrS   rs   rK   )rO   Úmy_rankr5   r   r   r   Ú_check_and_sync_module_buffersª  s    ÿz6DistributedDataParallel._check_and_sync_module_buffersc                 C   s,   t  | j¡}|  ||¡| _| j| jd� d S )Nr4   )rt   r�   r?   rž   Z_authoritative_rankrM   )rO   Úis_last_joinerrŸ   r   r   r   Ú_sync_final_model´  s    z)DistributedDataParallel._sync_final_modelc                 C   sR   g }| j  ¡ }|D ](}dd„ |D ƒ}| j |¡}| |¡ q|D ]}| ¡  q@d S )Nc                 S   s   g | ]}t  |¡‘qS r   )r   Z
zeros_like)r)   Útr   r   r   r`   Ê  s   zJDistributedDataParallel._match_all_reduce_for_bwd_pass.<locals>.<listcomp>)rv   Zget_bucket_tensorsr?   Ú	allreduceÚappendÚwait)rO   Zallreduce_workZall_bucket_tensorsZbucket_tensorsZzero_tensorsr’   r   r   r   Ú_match_all_reduce_for_bwd_pass¾  s    
ÿz6DistributedDataParallel._match_all_reduce_for_bwd_passc                 C   s   | j  ¡ }| j |¡ d S r%   )rv   Z_get_local_used_mapsr?   r¤   )rO   Zlocally_used_param_mapsr   r   r   Ú_match_unused_params_allreduceÓ  s    
z6DistributedDataParallel._match_unused_params_allreducec                 c   sj  �z`z6| j r"t| j ƒdkr"tdƒ‚d}|| _|| _dV  W n, tyf } zd}|‚W Y d}~n
d}~0 0 W |�rf|�sfd}d}d}d}t d¡ |�sV||krÈt 	| j
¡}	t d	|› d
|	› d|› d�¡ |  ¡ }
|
dkrÞd}q�|ræd}| j ¡  |  ¡  | jdd�\}}| ¡  | ¡ dk}|| _|�s*q�|  ¡  | j�rB|  ¡  | j ¡  |d7 }q�|  |¡ �n|�rd|�sdd}d}d}d}t d¡ |�sZ||k�rÄt 	| j
¡}	t d	|› d
|	› d|› d�¡ |  ¡ }
|
dk�rÜd}nz|�ræd}| j ¡  |  ¡  | jdd�\}}| ¡  | ¡ dk}|| _|�s,�qŠ|  ¡  | j�rD|  ¡  | j ¡  |d7 }�qŠ|  |¡ 0 dS )aŠ  
        A context manager to be used in conjunction with an instance of
        :class:`torch.nn.parallel.DistributedDataParallel` to be
        able to train with uneven inputs across participating processes.

        This context manager will keep track of already-joined DDP processes,
        and "shadow" the forward and backward passes by inserting collective
        communication operations to match with the ones created by non-joined
        DDP processes. This will ensure each collective call has a corresponding
        call by already-joined DDP processes, preventing hangs or errors that
        would otherwise happen when training with uneven inputs across
        processes.

        Once all DDP processes have joined, the context manager will broadcast
        the model corresponding to the last joined process to all processes to
        ensure the model is the same across all processes
        (which is guaranteed by DDP).

        To use this to enable training with uneven inputs across processes,
        simply wrap this context manager around your training loop. No further
        modifications to the model or data loading is required.

        .. warning::
            This module works only with the multi-process, single-device usage
            of :class:`torch.nn.parallel.DistributedDataParallel`,
            which means that a single process works on a single GPU.

        .. warning::
            This module currently does not support custom distributed collective
            operations in the forward pass, such as ``SyncBatchNorm`` or other
            custom defined collectives in the model's forward pass.

        Args:
            divide_by_initial_world_size (bool): If ``True``, will divide
                gradients by the initial ``world_size`` DDP training was launched
                with. If ``False``, will compute the effective world size
                (number of ranks that have not depleted their inputs yet) and
                divide gradients by that during allreduce. Set
                ``divide_by_initial_world_size=True`` to ensure every input
                sample including the uneven inputs have equal weight in terms of
                how much they contribute to the global gradient. This is
                achieved by always dividing the gradient by the initial
                ``world_size`` even when we encounter uneven inputs. If you set
                this to ``False``, we divide the gradient by the remaining
                number of nodes. This ensures parity with training on a smaller
                ``world_size`` although it also means the uneven inputs would
                contribute more towards the global gradient. Typically, you
                would want to set this to ``True`` for cases where the last few
                inputs of your training job are uneven. In extreme cases, where
                there is a large discrepancy in the number of inputs, setting
                this to ``False`` might provide better results.
            enable (bool): Whether to enable uneven input detection or not. Pass
                in ``enable=False`` to disable in cases where you know that
                inputs are even across participating processes. Default is
                ``True``.


        Example::

          >>>  import torch
          >>>  import torch.distributed as dist
          >>>  import os
          >>>  import torch.multiprocessing as mp
          >>>  import torch.nn as nn
          >>>  # On each spawned worker
          >>>  def worker(rank):
          >>>      dist.init_process_group("nccl", rank=rank, world_size=2)
          >>>      torch.cuda.set_device(rank)
          >>>      model = nn.Linear(1, 1, bias=False).to(rank)
          >>>      model = torch.nn.parallel.DistributedDataParallel(
          >>>          model, device_ids=[rank], output_device=rank
          >>>      )
          >>>      # Rank 1 gets one more input than rank 0.
          >>>      inputs = [torch.tensor([1]).float() for _ in range(10 + rank)]
          >>>      with model.join():
          >>>          for _ in range(5):
          >>>              for inp in inputs:
          >>>                  loss = model(inp).sum()
          >>>                  loss.backward()
          >>>  # Without the join() API, the below synchronization will hang
          >>>  # blocking for rank 1's allreduce to complete.
          >>>  torch.cuda.synchronize(device=rank)
        r   zÒDDP join() API does not support Single-Process Multi-GPU
                    mode training. The recommended approach for DDP training is
                    to spawn a single process that works on a single GPU.FNTr   iè  Úoncez+Detected uneven input skew of greater than z. This means that rank z has at least zz fewer inputs than other currently active ranks. This level of skew could lead to performance degradation during training.r…   )r=   r:   Ú
ValueErrorrF   r‰   Ú	ExceptionrH   Úsimplefilterrt   r�   r?   rI   r›   rv   rŠ   r    rŽ   r¦   rš   rE   r§   rC   r¨   Z_push_all_rebuilt_paramsr¢   )rO   Zdivide_by_initial_world_sizeÚenableZ	has_errorÚeZall_procs_joinedr¡   ÚiZWARN_THRESHOLDrŸ   Znum_active_procsr’   Zshould_sync_backwards_tensorZshould_sync_backwardsr   r   r   Újoin×  sÀ    Uÿ

ÿÿþÿ
ÿý

È

ÿÿþÿ

ÿý
zDistributedDataParallel.join)r€   Úhookc                 C   s   |   |¡ t | j||¡ dS )a(  
        Register a communication hook which is an enhancement that provides a
        flexible hook to users where they can specify how DDP aggregates gradients
        across multiple workers.

        This hook would be very useful for researchers to try out new ideas. For
        example, this hook can be used to implement several algorithms like GossipGrad
        and gradient compression which involve different communication strategies for
        parameter syncs while running Distributed DataParallel training.

        Arguments:
            state (object): state is passed to the hook and can be used to maintain
                            and update any state information that users would like to
                            maintain as part of the training process. Examples: error
                            feedback in gradient compression, peers to communicate with
                            next in GossipGrad etc.
            hook (callable): is defined as:
                             hook(state: object, bucket: dist._GradBucket) -> torch.futures.Future:

                             This function is called once the bucket is ready. The
                             hook can perform whatever processing is needed and return
                             a Future indicating completion of any async work (ex: allreduce).
                             If the hook doesn't perform any communication, it can also
                             just return a completed Future. The Future should hold the
                             new value of grad bucket's tensors. Once a bucket is ready,
                             c10d reducer would call this hook and use the tensors returned
                             by the Future and copy grads to individual parameters.

                             We also provide an API called ``get_future`` to retrieve a
                             Future associated with the completion of ``c10d.ProcessGroup.work``.

        .. warning ::
            Grad bucket's tensors will not be predivided by world_size. User is responsible
            to divide by the world_size in case of operations like allreduce.

        .. warning ::
            DDP communication hook can only be registered once and should be registered
            before calling backward.

        .. warning ::
            The Future object that hook returns should contain a result that has the same
            shape with the tensors inside grad bucket.

        .. warning ::
            DDP communication hook does not support single-process multiple-device mode.
            Gradbucket tensors should consist of only a single tensor.

        .. warning ::
            ``get_future`` API supports only NCCL backend and will return a ``torch._C.Future``
            which is an internal type and should be used with caution. It can still be used by
            ``_register_comm_hook`` API, but it is subject to some subtle differences compared
            to ``torch.futures.Future``.

        .. warning ::
            DDP communication hook is experimental and subject to change.

        Example::
            Below is an example of a noop hook that returns back the same tensors:

            >>> def noop(state: object, bucket: dist._GradBucket): -> torch.futures.Future
            >>>     fut = torch.futures.Future()
            >>>     fut.set_result(bucket.get_tensors())
            >>>     return fut

            >>> ddp._register_comm_hook(state = None, hook = noop)

        Example::
            Below is an example of a Parallel SGD algorithm where gradients are encoded before
            allreduce, and then decoded after allreduce.

            >>> def encode_and_decode(state: object, bucket: dist._GradBucket): -> torch.futures.Future
            >>>     tensors = [t / process_group.world_size for t in bucket.get_tensors()]
            >>>     encoded_tensors = encode(tensors) # encode gradients
            >>>     fut = process_group.allreduce(encoded_tensors).get_future()
            >>>     # Define the then callback to decode.
            >>>     def decode(fut):
            >>>         decoded_tensors = decode(fut.value()) # decode gradients
            >>>         return decoded_tensors
            >>>     return fut.then(decode)

            >>> ddp._register_comm_hook(state = None, hook = encode_and_decode)

        N)Ú_check_comm_hookrt   Ú_register_comm_hookrv   )rO   r€   r±   r   r   r   r³   x  s    T
z+DistributedDataParallel._register_comm_hookc                 C   s   t  | j|||¡ d S r%   )rt   Z_broadcast_coalescedr?   )rO   ÚtensorsÚbuffer_sizer5   r   r   r   rS   Ï  s    
ÿz8DistributedDataParallel._distributed_broadcast_coalescedc                 C   s   | j o| jot| jd ƒdkS rR   )rE   rB   r:   rs   )rO   r   r   r   rœ   Ö  s
    ÿýz0DistributedDataParallel.will_sync_module_buffersc                 C   sJ   t j|r|ndg| jd�}tj|tj| jd� | ¡ dkrBt	dƒ‚| ¡ S )Néÿÿÿÿr-   )Úopr„   z<BUG! Expected rank_cond to be true for at least one process.)
r   Útensorr.   rt   rˆ   r   ÚMAXr?   rš   rª   )rO   Z
input_rankZ	rank_condZrank_to_user   r   r   rž   Ý  s    þÿz)DistributedDataParallel._find_common_rankc           	      C   sŒ  t  ¡ ��l | jr´t| jƒdkr´t | jd | j| j¡}t|dd … | jdd … ƒD ]^\}}t||ƒD ]J\}}| 	|¡ |j
d urf|j
jd urš|j
 ¡  n|j
 d¡ |j
 ¡  qfqT|  ¡ �rh| jrÖ|  t ¡ d¡}nd}|  | jd | j|¡ | j�rht| jƒdk�rht | jd | j| j¡}t|dd … | jdd … ƒD ]*\}}t||ƒD ]\}}| |¡ �qN�q<W d   ƒ n1 �s~0    Y  d S )Nr   r   FT)r   rm   r=   r:   r   Zbroadcast_coalescedrr   rK   rl   rq   ZgradZgrad_fnZdetach_Zrequires_grad_Zzero_rœ   rF   rž   rt   r�   rS   rs   rn   )	rO   Úresultr´   Zmodule_paramsr¸   rx   r5   Zmodule_buffersÚbufferr   r   r   r�   ë  sJ    ýÿ


ýýÿz$DistributedDataParallel._sync_paramsc                 C   s`   t |ƒD ]R\}}| ¡ D ]@}t|tjjjƒr| jdks>J dƒ‚| | jrRt	| jƒnd¡ qqd S )Nr1   z/SyncBatchNorm layers only work with GPU modulesr   )
Ú	enumerater[   r   r   rg   ZSyncBatchNormr<   Z_specify_ddp_gpu_numr=   r:   )rO   Zmodule_copiesZdev_idxrA   Zlayerr   r   r   rw   '  s    ÿz6DistributedDataParallel._passing_sync_batchnorm_handlec                 C   sz   t |ƒstdƒ‚t |¡}|jd jtjkrF|jd jtjkrFt	dƒ‚|j
tjkrv|j
tjjkrv|j
tjjkrvt	dƒ‚d S )Nz$Communication hook must be callable.ZbucketzACommunication hook: bucket annotation should be dist._GradBucket.zXCommunication hook: return annotation should be torch.futures.Future or torch._C.Future.)ÚcallableÚ	TypeErrorÚinspectÚ	signaturer9   Ú
annotationÚ_emptyrt   Z_GradBucketrª   Úreturn_annotationr   ZfuturesZFutureZ_C)rO   r±   Úsigr   r   r   r²   /  s$    
ÿþÿÿþÿz(DistributedDataParallel._check_comm_hook)	NNr   TNr$   FFF)r   )T)TT)r   )"Ú__name__Ú
__module__Ú__qualname__Ú__doc__r7   rM   rN   r}   r~   ry   r   r‚   r•   r�   r   r   r—   r›   rŽ   r    r¢   r§   r¨   r°   Úobjectr½   r³   rS   rœ   rž   r�   rw   r²   Ú__classcell__r   r   rP   r   r#   ]   sN    q       úP
s
4		

 !X ÿ
<r#   )Ú
contextlibr   rz   r   r   r¿   r‹   rH   r   r   r   Ztorch.distributedZdistributedrt   Zis_availableZ"torch.distributed.distributed_c10dr   r   r[   r   r	   Zscatter_gatherr
   r   r   Ztorch._utilsr   r   r   r"   r#   r   r   r   r   Ú<module>   s(   9