3
I4W^·a  ã               @   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jZej	ƒ rJd 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 dd„ ZG dd„ deƒZdS )é    )ÚcontextmanagerN)Ú_get_default_groupé   )ÚModuleé   )Ú	replicate)Úscatter_kwargsÚgather)Úparallel_apply)Ú_get_device_indexc             C   sR   t | tjƒr| gS t | ttfƒr0tjtt| ƒŽ S t | t	ƒrNtjtt| j
ƒ ƒŽ 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   ú>/tmp/pip-build-e66j97b2/torch/torch/nn/parallel/distributed.pyr      s    
r   c                   s˜   e Zd ZdZd#‡ f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‡  ZS )%ÚDistributedDataParallelaì)  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-dataparallel-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`` can be used in the following two ways:

    (1) Single-Process Multi-GPU

    In this case, a single process will be
    spawned on each host/node and each process will operate on all the GPUs
    of the node where it's running. To use ``DistributedDataParallel`` in
    this way, you can simply construct the model as the following:

        >>> torch.distributed.init_process_group(backend="nccl")
        >>> model = DistributedDataParallel(model) # device_ids will include all GPU devices by default

    (2) Multi-Process Single-GPU

    This is the highly recommended way to use ``DistributedDataParallel``, with
    multiple processes, each of which operates on a single GPU. This is
    currently the fastest approach to do data parallel training using PyTorch
    and applies to both single-node(multi-GPU) and multi-node data
    parallel training. It is proven to be significantly faster than
    :class:`torch.nn.DataParallel` for single-node multi-GPU data
    parallel training.

    Here is how to use it: on each host with N GPUs, you should spawn up N
    processes, while ensuring that each process individually works on a single GPU
    from 0 to N-1. Therefore, it is your job to ensure that your training script
    operates on a single given GPU 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=4, 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:: ``nccl`` backend is currently the fastest and
        highly recommended backend to be used with Multi-Process Single-GPU
        distributed training and 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.
        Also note that ``nccl`` backend is currently the fastest and highly
        recommended backend for fp16/fp32 mixed-precision training.

    .. 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.

    .. warning::
        This module works only with the ``gloo`` and ``nccl`` backends.

    .. warning::
        Constructor, forward method, and differentiation of the output (or a
        function of the output of this module) is a distributed synchronization
        point. 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 all-reduction 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 assumes all buffers and gradients are dense.

    .. 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. In other words, 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 after
        the DistributedDataParallel construction, this is not supported and
        unexpected behaviors can happen, since some parameters' gradient
        reduction functions might not get called.

    .. 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.

    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 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 ```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 of 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: when setting to ``True``, it enables DistributedDataParallel
                         to automatically check if the previous iteration's
                         backward reductions were successfully issued at the
                         beginning of every iteration's forward function.
                         You normally don't need this option enabled unless you
                         are observing weird behaviors such as different ranks
                         are getting different gradients, which should not
                         happen if DistributedDataParallel is correctly used.
                         (default: ``False``)

    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| ƒjƒ  tdd„ |jƒ D ƒƒdk| _tdd„ |jƒ D ƒƒ| _| j sP| jrŠ| r\| s|tdj	||dd„ |jƒ D ƒƒƒ‚d | _
d | _nJ|d kr¤tttjjƒ ƒƒ}ttdd	„ |ƒƒ| _
|d krÈ|d
 }t|dƒ| _| jrü| jsütdj	dd„ |jƒ D ƒƒƒ‚|d k�rtƒ | _n|| _|| _|| _|| _|| _d| _d| _|	�r@d}
td|
 ƒ| _t||
 ƒ| _t| jjƒ jƒ ƒ}t|ƒd
k�rŽ| j || jƒ | j!ƒ  d S )Nc             S   s   h | ]
}|j ’qS r   )Údevice)Ú.0Úpr   r   r   ú	<setcomp>í   s    z3DistributedDataParallel.__init__.<locals>.<setcomp>r   c             S   s   g | ]}|j jd k‘qS )Úcuda)r   Útype)r   r   r   r   r   ú
<listcomp>î   s    z4DistributedDataParallel.__init__.<locals>.<listcomp>z¬DistributedDataParallel device_ids and output_device arguments only work with single-device CUDA modules, but got device_ids {}, output_device {}, and module parameters {}.c             S   s   h | ]
}|j ’qS r   )r   )r   r   r   r   r   r   õ   s    c             S   s
   t | dƒS )NT)r   )Úxr   r   r   Ú<lambda>þ   s    z2DistributedDataParallel.__init__.<locals>.<lambda>r   TzrDistributedDataParallel with multi-device module only works with CUDA devices, but module parameters locate in {}.c             S   s   h | ]
}|j ’qS r   )r   )r   r   r   r   r   r   	  s    i   éú   i   )"Úsuperr   Ú__init__ÚlenÚ
parametersZis_multi_device_moduleÚallÚis_cudaÚAssertionErrorÚformatÚ
device_idsÚoutput_devicer   Úranger   r   Zdevice_countr   r   r   Úprocess_groupÚdimÚmoduleÚbroadcast_buffersÚfind_unused_parametersÚrequire_backward_grad_syncÚrequire_forward_param_syncÚintÚbroadcast_bucket_sizeÚbucket_bytes_capZ
state_dictr   Ú _distributed_broadcast_coalescedÚ_ddp_init_helper)Úselfr2   r-   r.   r1   r3   r0   Zbucket_cap_mbr4   Zcheck_reductionZMBZmodule_states)Ú	__class__r   r   r&   å   sL    

z DistributedDataParallel.__init__c                s&  | j rxt| j ƒdkrxt| j| j dd�| _| j| jd< xL| jdd… D ].}x(t| jjƒ |jƒ ƒD ]\}}|j|_q^W qDW n
| jg| _dd„ | jD ƒ| _dd„ | jD ƒ| _	d	d„ | jD ƒ}d
d„ |D ƒ}dd„ ‰ ‡ fdd„|D ƒ}t
j|d d| jg|d ƒ}t
j|tt|ƒƒ| 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
        r   T)Údetachr   Nc             S   s   g | ]}t |jƒ ƒ‘qS r   )r   r(   )r   Úmr   r   r   r!   H  s    z<DistributedDataParallel._ddp_init_helper.<locals>.<listcomp>c             S   s   g | ]}t |jƒ ƒ‘qS r   )r   Úbuffers)r   r?   r   r   r   r!   I  s    c             S   s   g | ]}d d„ |j ƒ D ƒ‘qS )c             S   s0   g | ](}t d d„ |jdd�ƒD ]}||f‘qqS )c             S   s   | j S )N)Úrequires_grad)Ú	parameterr   r   r   r#   Q  s    zPDistributedDataParallel._ddp_init_helper.<locals>.<listcomp>.<listcomp>.<lambda>F)Zrecurse)Úfilterr(   )r   r2   rB   r   r   r   r!   N  s   zGDistributedDataParallel._ddp_init_helper.<locals>.<listcomp>.<listcomp>)Úmodules)r   Úreplicar   r   r   r!   M  s   c             S   s   g | ]}t d d„ |D ƒƒ‘qS )c             s   s   | ]\}}|V  qd S )Nr   )r   Ú_rB   r   r   r   ú	<genexpr>W  s    zFDistributedDataParallel._ddp_init_helper.<locals>.<listcomp>.<genexpr>)r   )r   rE   r   r   r   r!   W  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)r2   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 )Nr   )r   r2   rF   )rJ   r   r   rG   e  s    zFDistributedDataParallel._ddp_init_helper.<locals>.<listcomp>.<genexpr>)r   )r   rE   )rJ   r   r   r!   e  s   i   i   )r-   r'   r   r2   Ú_module_copiesÚzipr(   rA   Úmodules_paramsÚmodules_buffersÚdistZ"_compute_bucket_assignment_by_sizer9   ZReducerr   Úreversedr0   ÚreducerÚ_passing_sync_batchnorm_handle)r<   Zmodule_copyÚparamZ
copy_paramZmodules_and_parametersr(   Zexpect_sparse_gradientZbucket_indicesr   )rJ   r   r;   .  s4    






z(DistributedDataParallel._ddp_init_helperc             C   s$   | j ƒ  tj| jƒ}|d= |d= |S )Nr0   rQ   )Ú_check_default_groupÚcopyÚ__dict__)r<   Úattrsr   r   r   Ú__getstate__~  s
    z$DistributedDataParallel.__getstate__c                s@   t ƒ | _tt| ƒj|ƒ | jjddƒ | jjddƒ | jƒ  d S )Nr6   Tr5   )r   r0   r%   r   Ú__setstate__rV   Ú
setdefaultr;   )r<   Ústate)r=   r   r   rY   …  s
    z$DistributedDataParallel.__setstate__c             C   sB   d}y| j tƒ krd}W n tk
r0   d}Y nX |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)r0   r   ÚRuntimeError)r<   Zpickle_not_supportedr   r   r   rT   �  s    
z,DistributedDataParallel._check_default_groupc             c   s$   | j }d| _ z
dV  W d|| _ X 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)r5   )r<   Zold_require_backward_grad_syncr   r   r   Úno_syncœ  s
    
zDistributedDataParallel.no_syncc             O   sÌ   | j r| jƒ  | jrx| j||| jƒ\}}t| jƒdkrL| j|d |d Ž}q„| j| jd t|ƒ… ||ƒ}| j|| j	ƒ}n| j||Ž}t
jƒ rÂ| jrÂd| _ | jr´| jjtt|ƒƒƒ qÈ| jjg ƒ nd| _ |S )Nr   r   TF)r6   Ú_sync_paramsr-   Úscatterr'   r2   r
   rK   r	   r.   r   Zis_grad_enabledr5   r4   rQ   Zprepare_for_backwardr   r   )r<   ÚinputsÚkwargsÚoutputÚoutputsr   r   r   Úforward³  s     zDistributedDataParallel.forwardc             C   s   t |||| jd�S )N)r1   )r   r1   )r<   r`   ra   r-   r   r   r   r_   Ñ  s    zDistributedDataParallel.scatterc             C   s   t |||| jd t|ƒ… ƒS )N)r
   r-   r'   )r<   Zreplicasr`   ra   r   r   r   r
   Ô  s    z&DistributedDataParallel.parallel_applyc             C   s   t ||| jd�S )N)r1   )r	   r1   )r<   rc   r.   r   r   r   r	   ×  s    zDistributedDataParallel.gatherc                s6   t t| ƒj|ƒ x | jdd … D ]}|j|ƒ q W d S )Nr   )r%   r   ÚtrainrK   )r<   Úmoder2   )r=   r   r   re   Ú  s    zDistributedDataParallel.trainc             C   s   t j| j||ƒ d S )N)rO   Z_broadcast_coalescedr0   )r<   ÚtensorsÚbuffer_sizer   r   r   r:   ß  s    z8DistributedDataParallel._distributed_broadcast_coalescedc             C   sd  t jƒ ��P | jr¦t| jƒdkr¦t jjj| jd | j| jƒ}xht	|dd … | jdd … ƒD ]H\}}x>t	||ƒD ]0\}}|j
|ƒ |jd k	rn|jjƒ  |jjƒ  qnW qZW | jo¼t| jd ƒdk�rV| j| jd | jƒ | joæt| jƒdk�rVt jjj| jd | j| jƒ}xNt	|dd … | jdd … ƒD ].\}}x"t	||ƒD ]\}}|j
|ƒ �q8W �q$W W d Q R X d S )Nr   r   )r   Zno_gradr-   r'   r   ZcommZbroadcast_coalescedrM   r8   rL   Úset_ZgradZdetach_Zzero_r3   rN   r:   )r<   Úresultrg   Zmodule_paramsZtensorrS   Zmodule_buffersÚbufferr   r   r   r^   â  s4    


z$DistributedDataParallel._sync_paramsc             C   sd   x^t |ƒD ]R\}}xH|jƒ D ]<}t|tjjjƒr| js>tdƒ‚|j| j	rRt
| j	ƒndƒ qW q
W d S )Nz0SyncBatchNorm layers only work with CUDA modulesr   )Ú	enumeraterD   r   r   rH   ZSyncBatchNormr*   r+   Z_specify_ddp_gpu_numr-   r'   )r<   Zmodule_copiesZdev_idxr2   Zlayerr   r   r   rR     s    z6DistributedDataParallel._passing_sync_batchnorm_handle)NNr   TNr   FF)T)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r&   r;   rX   rY   rT   r   r]   rd   r_   r
   r	   re   r:   r^   rR   Ú__classcell__r   r   )r=   r   r   !   s(    D    EP*r   )Ú
contextlibr   rU   r   r   Ztorch.cuda.commZtorch.distributedZdistributedrO   Zis_availableZ"torch.distributed.distributed_c10dr   rD   r   r   Zscatter_gatherr   r	   r
   Ztorch.cuda._utilsr   r   r   r   r   r   r   Ú<module>   s   
