a
    8Sicn6                    @   s  d dl Z d dlZd dlmZ d dlmZmZmZ d dlm	Z	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mZ d dlZd dlmZ d dlmZmZ d dlmZmZmZ d dlmZmZ d	Z e! rd d
l"m#Z#m$Z$m%Z% d dl&m'Z'm(Z( ejj)! r
dZ d dl*m+Z+ d dl,m-Z- ddl.m/Z/ ddl0m1Z1 ddl2m3Z3m4Z4m5Z5 e6e7Z8dd Z9dd Z:dd Z;dd Z<G dd de	Z=eG dd dZ>G d d! d!eZ?G d"d# d#eZ@G d$d% d%e/eZAdS )&    N)	dataclass)CallableAnyType)Enumauto)contextmanager)FunctionVariable)JoinJoinableJoinHook)tree_flattentree_unflattenF)$_verify_param_shape_across_processes_sync_module_states
_to_kwargs)ReduceOp_get_default_groupT)RRef_get_device_index   )Module   )#_ddp_with_replicated_tensor_enabled)gatheris_namedtuplescatter_kwargsc                 C   s:   t ot| t}|r$t|  \}}nt| \}}|||fS N)RPC_AVAILABLE
isinstancer   r   local_value)outputoutput_is_rrefoutput_tensor_listtreespec r'   Y/var/www/html/django/DPS/env/lib/python3.9/site-packages/torch/nn/parallel/distributed.py_tree_flatten_with_rref-   s
    r)   c                 C   s   t | |} |rt| } | S r   )r   r   )r#   r&   r$   r'   r'   r(   _tree_unflatten_with_rref8   s    
r*   c                 C   st   t r"t| tr"|  r"t|  S t| tjr4| gS t| tt	frRt
jtt|  S t| trpt
jtt|   S g S )zI
    Recursively find all tensors contained in the specified object.
    )r    r!   r   is_owner_find_tensorsr"   torchTensorlisttuple	itertoolschainmapdictvalues)objr'   r'   r(   r,   ?   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)/RANKZ
LOCAL_RANK
WORLD_SIZEMASTER_PORT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_FILEZNCCL_ASYNC_ERROR_HANDLING zN/Az
env:%s=%s
)osenvironprint)Zrelevant_env_varsZformatted_outputvarvaluer'   r'   r(   _dump_DDP_relevant_env_varsR   s    2rA   c                   @   s   e Zd Ze Ze ZdS )_BufferCommHookLocationN)__name__
__module____qualname__r   PRE_FORWARDPOST_FORWARDr'   r'   r'   r(   rB      s   rB   c                   @   s&   e Zd ZU eed< eed< eed< dS )_BufferCommHookbuffer_comm_hookbuffer_comm_hook_statebuffer_comm_hook_locationN)rC   rD   rE   r   __annotations__r   rB   r'   r'   r'   r(   rH      s   
rH   c                   @   s$   e Zd Zedd Zedd ZdS )_DDPSinkc                 G   s,   |  d || _|| _tdd |D }|S )NFc                 s   s&   | ]}t |tjr| n|V  qd S r   )r!   r-   r.   clone).0inpr'   r'   r(   	<genexpr>   s   

z#_DDPSink.forward.<locals>.<genexpr>)set_materialize_gradsreducer
state_dictr0   )ctxrS   rT   inputsretr'   r'   r(   forward   s    
z_DDPSink.forwardc                 G   s<   | j }| j d r.| j d dkr.tj| jj d d g|R S )Nstatic_graphnum_iterationsr   )rT   r
   _execution_enginequeue_callbackrS   _delay_all_reduce)rU   grad_outputsrT   r'   r'   r(   backward   s    z_DDPSink.backwardN)rC   rD   rE   staticmethodrX   r_   r'   r'   r'   r(   rM      s   
rM   c                       s2   e Zd Z fddZdd ZedddZ  ZS )_DDPJoinHookc                    s8   t |tsJ d|j  || _|| j_t   dS )z;
        Sets config variables for internal usage.
        zQDDP join hook requires passing in a DistributedDataParallel instance as the stateN)r!   DistributedDataParallellogger_set_uneven_input_joinddp_divide_by_initial_world_sizesuper__init__)selfre   divide_by_initial_world_size	__class__r'   r(   rh      s    
z_DDPJoinHook.__init__c                 C   sr   | j }|j  |  |jdd}|  | d  dk}||_|sNdS |	  |j
rd|  |j  dS )zq
        Shadows the DDP collective communication operations in the forward and
        backward passes.
        Tis_joined_rankr   N)re   rS   _rebuild_buckets_check_and_sync_module_buffers)_check_global_requires_backward_grad_syncwaitresultitemrequire_forward_param_sync_match_all_reduce_for_bwd_passfind_unused_parameters_match_unused_params_allreduce_push_all_rebuilt_params)ri   re   workZshould_sync_backwardsr'   r'   r(   	main_hook   s    
z_DDPJoinHook.main_hook)is_last_joinerc                 C   s   | j | dS )zj
        Syncs the final model to ensure that the model is the same across all
        processes.
        N)re   _sync_final_modelri   r|   r'   r'   r(   	post_hook   s    z_DDPJoinHook.post_hook)rC   rD   rE   rh   r{   boolr   __classcell__r'   r'   rk   r(   ra      s   %ra   c                
       s  e Zd ZdZdh fdd	Zd	d
 Zdd Zdd Zdd Z fddZ	dd Z
dd Zdd ZdiddZdd Zedd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zdj fd)d*	Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zdkeeed5d6d7Zd8d9 Zed:d; Z ed<d= Z!e"j#fe$d>d?d@Z%e&e$dAdBdCZ'dDdE Z(ddFe)dGdHdIZ*dldJdKZ+dLdM Z,dNdO Z-dPdQ Z.dRdS Z/dTdU Z0dVdW Z1dmdXdYZ2dZd[ Z3d\d] Z4ed^d_ Z5e6d`da Z7dbdc Z8ddde Z9dfdg Z:  Z;S )nrb   a=  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::
        ``DistributedDataParallel`` can be used in conjunction with
        :class:`torch.distributed.optim.ZeroRedundancyOptimizer` to reduce
        per-rank optimizer states memory footprint. Please refer to
        `ZeroRedundancyOptimizer recipe <https://pytorch.org/tutorials/recipes/zero_redundancy_optimizer.html>`__
        for more details.

    .. 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`` if the loss is summed (NOT
        averaged as usual) across instances in a batch (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. But in most
        cases, you can just treat a DistributedDataParallel wrapped model, a
        DataParallel wrapped model and an ordinary model on a single GPU as the
        same (E.g. using the same learning rate for equivalent batch size).

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

    .. note::
        DistributedDataParallel currently offers limited support for gradient
        checkpointing with :meth:`torch.utils.checkpoint`. DDP will work as
        expected when there are no unused parameters in the model and each layer
        is checkpointed at most once (make sure you are not passing
        `find_unused_parameters=True` to DDP). We currently do not support the
        case where a layer is checkpointed multiple times, or when there unused
        parameters in the checkpointed model.

        Example::

            >>> import torch.distributed.autograd as dist_autograd
            >>> from torch.nn.parallel import DistributedDataParallel as DDP
            >>> import torch
            >>> from torch import optim
            >>> from torch.distributed.optim import DistributedOptimizer
            >>> import torch.distributed.rpc as rpc
            >>> 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, target)
            >>>     dist_autograd.backward(context_id, [loss])
            >>>     dist_optim.step(context_id)

    .. note::
        To let a non-DDP model load a state dict from a DDP model,
        :meth:`~torch.nn.modules.utils.consume_prefix_in_state_dict_if_present`
        needs to be applied to strip the prefix "module." in the DDP state dict before loading.

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

    Args:
        module (Module): module to be parallelized
        device_ids (list of int or torch.device): CUDA devices.
                   1) For single-device modules, ``device_ids`` can
                   contain exactly one device id, which represents the only
                   CUDA device where the input module corresponding to this process resides.
                   Alternatively, ``device_ids`` can also be ``None``.
                   2) For multi-device modules and CPU modules,
                   ``device_ids`` must be ``None``.

                   When ``device_ids`` is ``None`` for both cases,
                   both the input data for the forward pass and the actual module
                   must be placed on the correct device.
                   (default: ``None``)
        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. In addition, parameters that may have
                               been used in the wrapped module's ``forward``
                               function but were not part of loss computation and
                               thus would also not receive gradients are
                               preemptively marked as ready to be reduced.
                               (default: ``False``)
        check_reduction: This argument is deprecated.
        gradient_as_bucket_view (bool): 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.
                      Note that gradients will be views after first iteration, so
                      the peak memory saving should be checked after first iteration.
        static_graph (bool): When set to ``True``, DDP knows the trained graph is
                     static. Static graph means 1) The set of used and unused
                     parameters will not change during the whole training loop; in
                     this case, it does not matter whether users set
                     ``find_unused_parameters = True`` or not. 2) How the graph is trained
                     will not change during the whole training loop (meaning there is
                     no control flow depending on iterations).
                     When static_graph is set to be ``True``, DDP will support cases that
                     can not be supported in the past:
                     1) Reentrant backwards.
                     2) Activation checkpointing multiple times.
                     3) Activation checkpointing when model has unused parameters.
                     4) There are model parameters that are outside of forward function.
                     5) Potentially improve performance when there are unused parameters,
                     as DDP will not search graph in each iteraton to detect unused
                     parameters when static_graph is set to be ``True``.
                     To check whether you can set static_graph to be ``True``, one way is to
                     check ddp logging data at the end of your previous model training,
                     if ``ddp_logging_data.get("can_set_static_graph") == True``, mostly you
                     can set ``static_graph = True`` as well.

                     Example::
                         >>> model_DDP = torch.nn.parallel.DistributedDataParallel(model)
                         >>> # Training loop
                         >>> .....
                         >>> ddp_logging_data = model_DDP._get_ddp_logging_data()
                         >>> static_graph = ddp_logging_data.get("can_set_static_graph")


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

    Example::

        >>> torch.distributed.init_process_group(backend='nccl', world_size=4, init_method='...')
        >>> net = torch.nn.parallel.DistributedDataParallel(model, pg)
    Nr   T   Fc              
      s  t t|   t|  d | _tdd | D s@| td |d ur`t	|dkr`| t
d t	dd | D dk| _dd | D }t	|dkr| t
d	| t|d
 | _|d u st	|d
ks| jdks| jr|s|r| t
d||dd | D  d | _d | _n.dd |D | _|d u r>|d
 }t|d| _|d u r^t | _n|| _d| _|| _|| _t| j d
 j| _|| _|| _d| _d| _|
| _t|dr|j| _ng | _t  | _!| "  |	rt#$d | D ]$}t%|t&j'j(j)r| td qt*d| _+t*|d d | _,t-j./dddk| _0| 1 \}}t2| j| t3| j| j| j+d
| jd | 4|}| 5|||| d| _6|r| 7  d S )Nc                 s   s   | ]}|j V  qd S r   )requires_gradrO   pr'   r'   r(   rQ         z3DistributedDataParallel.__init__.<locals>.<genexpr>zhDistributedDataParallel is not needed when a module doesn't have any parameter that requires a gradient.r   z8device_ids can only be None or contain a single element.c                 S   s   h | ]
}|j qS r'   devicer   r'   r'   r(   	<setcomp>)  r   z3DistributedDataParallel.__init__.<locals>.<setcomp>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   cpuzDistributedDataParallel device_ids and output_device arguments only work with single-device/multiple-device GPU modules or CPU modules, but got device_ids {}, output_device {}, and module parameters {}.c                 S   s   h | ]
}|j qS r'   r   r   r'   r'   r(   r   D  r   c                 S   s   g | ]}t |d qS )Tr   )rO   xr'   r'   r(   
<listcomp>K  r   z4DistributedDataParallel.__init__.<locals>.<listcomp>TF!_ddp_params_and_buffers_to_ignorezhThe `check_reduction` argument in `DistributedDataParallel` module is deprecated. Please avoid using it.zModules with uninitialized parameters can't be used with `DistributedDataParallel`. Run a dummy forward pass to correctly initialize the modulesi  i   ZPYTORCH_DDP_USE_SIDE_STREAM1moduleprocess_groupbroadcast_bucket_sizesrcparams_and_buffers_to_ignore)8rg   rb   rh   r   rc   any
parameters_log_and_throwRuntimeErrorlen
ValueErrorZis_multi_device_moduleformatr/   device_type
device_idsoutput_devicer   r   r   rY   dimr   r   broadcast_buffersrw   require_backward_grad_syncru   gradient_as_bucket_viewhasattrr   parameters_to_ignorer   _use_replicated_tensor_module_build_replicated_tensor_modulewarningswarnr!   r-   nn	parameterUninitializedParameterintr   bucket_bytes_capr<   r=   get!use_side_stream_for_tensor_copies_build_params_for_reducerr   r   "_build_debug_param_to_name_mapping_ddp_init_helper_has_rebuilt_buckets_set_static_graph)ri   r   r   r   r   r   r   Zbucket_cap_mbrw   Zcheck_reductionr   rY   Zdistinct_device_typesparamr   expect_sparse_gradientparam_to_name_mappingrk   r'   r(   rh     s    








z DistributedDataParallel.__init__c                 C   s*   | j r&ddlm} || j| j| jd< d S )Nr   )_replicate_module_replicated_tensor_module)r   Z_replicated_tensor_ddp_interopr   r   r   __dict__)ri   r   r'   r'   r(   r     s    z7DistributedDataParallel._build_replicated_tensor_modulec                 C   s0   | j d ur$| j t| d|  ||d S )Nz: )rc   set_error_and_logstr)ri   Zerr_typeerr_msgr'   r'   r(   r     s    
z&DistributedDataParallel._log_and_throwc           
      C   s  d| _ |du s| jdu r"tjg}ntj| jg}t|||\}}t|t	t
|t	t
|| j|| j| j| j|tj
| _t| j| _| j| j d}| j D ]}	t|	tjjrd} qq| j| jjj| jdu rg n| j| jdu rdn| j| j|| | | j dS )aA  
        Initialization helper function that does the following:
        (1) bucketing the parameters for reductions
        (2) resetting the bucketing states
        (3) registering the grad hooks
        (4) Logging construction-time DDP logging data
        (5) passing a handle of DDP to SyncBatchNorm Layer
        r   TFN)rZ   rw   sysmaxsizedist_DEFAULT_FIRST_BUCKET_BYTESr   "_compute_bucket_assignment_by_sizeReducerr/   reversedr   r   rS   Loggerrc   
set_loggerr   modulesr!   r-   r   SyncBatchNormset_construction_data_and_logrl   rC   r   r   r   _passing_sync_batchnorm_handle)
ri   r   r   r   rY   Zbucket_size_limitsZbucket_indicesZper_bucket_size_limitsZhas_sync_bnZ	submoduler'   r'   r(   r     sJ    
	


z(DistributedDataParallel._ddp_init_helperc                 C   s6   |    t| j}|d= |d= |d= | jr2|d= |S )Nr   rS   rc   r   )_check_default_groupcopyr   r   )ri   attrsr'   r'   r(   __getstate__   s    z$DistributedDataParallel.__getstate__c                    s   t  | _tt| | |   | jdd | jdd |  \}}| 	|}| 
|||| j | jr~| j  | j  d S )Nru   Tr   )r   r   rg   rb   __setstate__r   r   
setdefaultr   r   r   rY   rS   r   rc   )ri   stater   r   r   rk   r'   r(   r   
  s    


z$DistributedDataParallel.__setstate__c                    sp   fddj  D }t   fdd|D }tdd |D }dd tfdd|D }  ||fS )	Nc                    s:   g | ]2\ } fd d|j ddD D ]}||fq(qS )c                    s.   g | ]&\}}|j r  d | jvr|qS ).)r   r   )rO   
param_namer   )module_nameri   r'   r(   r   !  s   zPDistributedDataParallel._build_params_for_reducer.<locals>.<listcomp>.<listcomp>Frecurse)named_parameters)rO   r   r   ri   )r   r(   r     s
   

zEDistributedDataParallel._build_params_for_reducer.<locals>.<listcomp>c                    s*   g | ]"\}}| vr  |s||fqS r'   )add)rO   mr   )memor'   r(   r   /  s   c                 s   s   | ]\}}|V  qd S r   r'   )rO   _r   r'   r'   r(   rQ   7  r   zDDistributedDataParallel._build_params_for_reducer.<locals>.<genexpr>c                 S   s&   t | tjjst | tjjr"| jS dS NF)r!   r-   r   	EmbeddingEmbeddingBagsparse)r   r'   r'   r(   produces_sparse_gradient:  s
    zSDistributedDataParallel._build_params_for_reducer.<locals>.produces_sparse_gradientc                 3   s   | ]\}} |V  qd S r   r'   )rO   r   r   )r   r'   r(   rQ   C  r   )r   named_modulessetr/   _assign_modules_buffers)ri   Zmodules_and_parametersr   r   r'   )r   r   ri   r(   r     s    

	z1DistributedDataParallel._build_params_for_reducerc                    s<    fdd j  D }dd |D  _dd |D  _dS )aU  
        Assigns module buffers to self.modules_buffers which are then used to
        broadcast across ranks when broadcast_buffers=True. Note that this
        must be called every time buffers need to be synced because buffers can
        be reassigned by user module,
        see https://github.com/pytorch/pytorch/issues/63916.
        c                    s"   g | ]\}}| j vr||fqS r'   )r   )rO   buffer_namebufferr   r'   r(   r   R  s   
zCDistributedDataParallel._assign_modules_buffers.<locals>.<listcomp>c                 S   s   g | ]\}}|qS r'   r'   rO   r   r   r'   r'   r(   r   W  s   c                 S   s   i | ]\}}||qS r'   r'   r   r'   r'   r(   
<dictcomp>\  s   zCDistributedDataParallel._assign_modules_buffers.<locals>.<dictcomp>N)r   named_buffersmodules_buffersnamed_module_buffers)ri   r   r'   r   r(   r   I  s    	
z/DistributedDataParallel._assign_modules_buffersc                    s   t  t jjkri S  fddtt D }t }i }| j D ]h\}}|j	ddD ]R\}}| d| }	|	| j
vrX|jrX||vr| td|	 d || }
|	||
< qXqDt|t|kr| tdt| d	t| d
 |S )Nc                    s   i | ]} | |qS r'   r'   )rO   ir   r'   r(   r   d  r   zNDistributedDataParallel._build_debug_param_to_name_mapping.<locals>.<dictcomp>Fr   r   zParam with name zt found in module parameters, but not DDP parameters. This indicates a bug in DDP, please report an issue to PyTorch.zUExpected param to name mapping to cover all parameters, but got conflicting lengths: z vs zA. This indicates a bug in DDP, please report an issue to PyTorch.)r   get_debug_level
DebugLevelOFFranger   r   r   r   r   r   r   r   r   )ri   r   Zparam_to_param_indexZ	param_setZparam_index_to_param_fqnr   r   r   r   ZfqnZparam_indexr'   r   r(   r   `  s4    

z:DistributedDataParallel._build_debug_param_to_name_mappingc                 c   s8   dd }|r|  n|gD ]}||D ]
}|V  q&qdS )z:
        Returns a generator of module parameters
        c                 s   s4   t | dr| j n
| jdd}|D ]
}|V  q$d S )N_former_parametersFr   )r   r   r5   r   )r   Zpsr   r'   r'   r(   model_parameters  s    
zADistributedDataParallel._get_parameters.<locals>.model_parametersN)r   )ri   r   r   r   r   r'   r'   r(   _get_parameters  s    	z'DistributedDataParallel._get_parametersc                 C   sD   d}z| j t krd}W n ty.   d}Y n0 |r@| td d S )NFTzDDP 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   r   r   )ri   Zpickle_not_supportedr'   r'   r(   r     s    
z,DistributedDataParallel._check_default_groupc                 c   s*   | j }d| _ zdV  W || _ n|| _ 0 dS )aV  
        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.parallel.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)r   )ri   Zold_require_backward_grad_syncr'   r'   r(   no_sync  s
    zDistributedDataParallel.no_syncc                 O   sZ   | j r| jn| j}| jrHt||| jd | j\}}||d i |d S ||i |S d S Nr   )r   r   r   r   r   r   )ri   rV   kwargsZmodule_to_runr'   r'   r(   _run_ddp_forward  s    z(DistributedDataParallel._run_ddp_forwardc                 O   s   t jjd  t  rB| jrB| j  |  jd7  _| j	
  t| }|r`| j	|| j t  r| j	 rtd d| _t| d}|  r|   | jjr| jdd | j|i |}|  r|   t  r| jrd| _| jr| js| j	tt| n| j	g  nd| _W d    n1 s80    Y  | jrR| jrf| jr| jdkr| j| jd}t |\}}}	d	d
 t!t"|D }
t#|D ]*\}}t $|r|j%d u r||
|< qt&j'| j	|g|R  }t!t"|
D ] }|
| d u r|| |
|< qt(|
||	}|S )NDistributedDataParallel.forwardr   z4Reducer buckets have been rebuilt in this iteration.Tbuffer_hookFrm   )rY   rZ   c                 S   s   g | ]}d qS r   r'   )rO   r   r'   r'   r(   r     r   z3DistributedDataParallel.forward.<locals>.<listcomp>))r-   autogradprofilerrecord_functionis_grad_enabledr   rc   set_runtime_stats_and_logrZ   rS   prepare_for_forwardr   Znotify_join_context_set_forward_pass_work_handlerf   ro   infor   r   _check_sync_bufs_pre_fwd_sync_buffers_join_configenablerq   r   _check_sync_bufs_post_fwdru   rw   rY   prepare_for_backwardr/   r,   r)   r   r   	enumerate	is_tensorgrad_fnrM   applyr*   )ri   rV   r   rz   Zbuffer_hook_registeredr#   rT   r%   r&   r$   Zoutput_placeholdersr   Zpassthrough_tensor_listr'   r'   r(   rX     sn    





&
r   c                 C   s   t |||| jdS N)r   )r   r   )ri   rV   r   r   r'   r'   r(   scatter.  s    zDistributedDataParallel.scatterc                 C   s   t |||| jS r   )r   r   )ri   rV   r   Z	device_idr'   r'   r(   	to_kwargs1  s    
z!DistributedDataParallel.to_kwargsc                 C   s   t ||| jdS r  )r   r   )ri   outputsr   r'   r'   r(   r   7  s    zDistributedDataParallel.gatherc                    s&   t t| | | jr"| j| | S r   )rg   rb   trainr   r   )ri   moderk   r'   r(   r  :  s    zDistributedDataParallel.trainc                 C   sB   |s| j rtjd| jd}ntjd| jd}tj|| jdd}|S )Nr   r   T)groupasync_op)r   r-   onesr   zerosr   
all_reducer   )ri   rn   Zrequires_sync_tensorrz   r'   r'   r(   rq   B  s    
zADistributedDataParallel._check_global_requires_backward_grad_syncc                 C   s$   |   r | | jd}| | d S r   )r  _find_common_rank_distributed_rank_sync_module_buffersri   authoritative_rankr'   r'   r(   rp   O  s    z6DistributedDataParallel._check_and_sync_module_buffersc                 C   s0   |  | j|| _t| j| j| j| j| jd d S )Nr   )r  r  Z_authoritative_rankr   r   r   r   r   r~   r'   r'   r(   r}   V  s    z)DistributedDataParallel._sync_final_modelc                 C   sD   g }| j  }|D ]}| j |}|| q|D ]}|  q2d S r   )rS   _get_zeros_like_grad_buckets_run_comm_hookappendrr   )ri   Z	comm_workZgrad_bucketsZgrad_bucketrz   r'   r'   r(   rv   g  s    
z6DistributedDataParallel._match_all_reduce_for_bwd_passc                 C   s   | j  }| j| d S r   )rS   _get_local_used_mapr   	allreduce)ri   Zlocally_used_param_mapr'   r'   r(   rx   |  s    
z6DistributedDataParallel._match_unused_params_allreduce)rj   r  throw_on_early_terminationc                 C   s   t | g|||dS )a1  
        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. Alternatively, if the flag ``throw_on_early_termination`` is
        specified to be ``True``, all trainers will throw an error once one rank
        runs out of inputs, allowing these errors to be caught and handled
        according to application logic.

        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::
            If the model or training loop this context manager is wrapped around
            has additional distributed collective operations, such as
            ``SyncBatchNorm`` in the model's forward pass, then the flag
            ``throw_on_early_termination`` must be enabled. This is because this
            context manager is not aware of non-DDP collective communication.
            This flag will cause all ranks to throw when any one rank
            exhausts inputs, allowing these errors to be caught and recovered
            from across all ranks.

        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``.
            throw_on_early_termination (bool): Whether to throw an error
                or continue training when at least one rank has exhausted
                inputs. If ``True``, will throw upon the first rank reaching end
                of data. If ``False``, will continue training with a smaller
                effective world size until all ranks are joined. Note that if
                this flag is specified, then the flag
                ``divide_by_initial_world_size`` would be ignored. Default
                is ``False``.


        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)
        rj   )r   )ri   rj   r  r$  r'   r'   r(   join  s    dzDistributedDataParallel.joinc                 K   s   | dd}t| |dS )a  
        Returns the DDP join hook, which enables training on uneven inputs by
        shadowing the collective communications in the forward and backward
        passes.

        Arguments:
            kwargs (dict): a :class:`dict` containing any keyword arguments
                to modify the behavior of the join hook at run time; all
                :class:`Joinable` instances sharing the same join context
                manager are forwarded the same value for ``kwargs``.

        The hook supports the following keyword arguments:
            divide_by_initial_world_size (bool, optional):
                If ``True``, then gradients are divided by the initial world
                size that DDP was launched with.
                If ``False``, then gradients are divided by the effective world
                size (i.e. the number of non-joined processes), meaning that
                the uneven inputs contribute more toward the global gradient.
                Typically, this should be set to ``True`` if the degree of
                unevenness is small but can be set to ``False`` in extreme
                cases for possibly better results.
                Default is ``True``.
        rj   Tr%  )r   ra   )ri   r   rj   r'   r'   r(   	join_hook  s    z!DistributedDataParallel.join_hookc                 C   s   | j S r   r   r   r'   r'   r(   join_device  s    z#DistributedDataParallel.join_devicec                 C   s   | j S r   )r   r   r'   r'   r(   join_process_group  s    z*DistributedDataParallel.join_process_group)hookc                 C   s    t |sJ t|||d| _dS )a  
            Allows custom registration of hooks that define how buffer are
            synchronized across ranks. The hook takes in an optional state
            and is passed in a Dict[str, Tensor] corresponding to buffer names
            and the buffers, and can run arbitrary reductions on buffers as
            opposed to DDP's default broadcast from rank 0. This is useful for
            example if a counter needs to be summed or averaged across ranks
            every iteration.

            Args:
                state (Any): Optional state that is passed to the hook.
                hook (Callable): Callable with the following signature:
                                ``hook(state: object, buffers: Dict[str, torch.Tensor])
                                -> Optional[List[torch.futures.Future[torch.Tensor]]]``
                comm_hook_location (_BufferCommHookLocation): Enum value indicating
                                where to run the hook.
                                _BufferCommHookLocation.PRE_FORWARD means that the
                                hook will run _before_ the forward pass, and
                                _BufferCommHookLocation.POST_FORWARD means that the
                                hook will run _after_ the forward pass.

                hook (callable): Callable with the following signature:
                             ``hook(state: object, bucket: dist.GradBucket) -> torch.futures.Future[torch.Tensor]``:

                NOTE: To maximize performance, users can return a
                    List[torch.futures.Future] from their hook, and DDP will
                    install and await these hooks appropriately at the end of
                    the backward pass. This will ensure all buffers are
                    synchronized by the end of the backward pass. If this
                    setting is used, it is recommended to pass
                    comm_hook_location=_BufferCommHookLocation.POST_FORWARD,
                    which will trigger the hook after the forward pass.
                    If _BufferCommHookLocation.PRE_FORWARD is used, users must
                    ensure appropriate synchronization when manipulating GPU
                    buffers in the forward pass.
            )rI   rJ   rK   N)callablerH   r   )ri   r   r*  Zcomm_hook_locationr'   r'   r(   _register_buffer_comm_hook  s    *z2DistributedDataParallel._register_buffer_comm_hook)r   r*  c                 C   s,   |  | | j|j t| j|| dS )a  
        Registers 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.

        Args:
            state (object): Passed to the hook to maintain any state information during the training process.
                            Examples include error feedback in gradient compression,
                            peers to communicate with next in GossipGrad, etc.

                            It is locally stored by each worker
                            and shared by all the gradient tensors on the worker.
            hook (callable): Callable with the following signature:
                             ``hook(state: object, bucket: dist.GradBucket) -> torch.futures.Future[torch.Tensor]``:

                             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 still
                             must 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.
                             Note that the future's return type must be a single tensor.

                             We also provide an API called ``get_future`` to retrieve a
                             Future associated with the completion of ``c10d.ProcessGroup.Work``.
                             ``get_future`` is currently supported for NCCL and also supported for most
                             operations on GLOO and MPI, except for peer to peer operations (send/recv).

        .. 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 single tensor
            that has the same shape with the tensors inside grad bucket.

        .. warning ::
            ``get_future`` API supports NCCL, and partially GLOO and MPI backends (no support
            for peer-to-peer operations like send/recv) and will return a ``torch.futures.Future``.

        Example::
            Below is an example of a noop hook that returns the same tensor.

            >>> def noop(state: object, bucket: dist.GradBucket): -> torch.futures.Future[torch.Tensor]
            >>>     fut = torch.futures.Future()
            >>>     fut.set_result(bucket.buffer())
            >>>     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[torch.Tensor]
            >>>     encoded_tensor = encode(bucket.buffer()) # encode gradients
            >>>     fut = torch.distributed.all_reduce(encoded_tensor).get_future()
            >>>     # Define the then callback to decode.
            >>>     def decode(fut):
            >>>         decoded_tensor = decode(fut.value()[0]) # decode gradients
            >>>         return decoded_tensor
            >>>     return fut.then(decode)

            >>> ddp.register_comm_hook(state=None, hook=encode_and_decode)
        N)_check_comm_hookrc   _set_comm_hook_namerE   r   _register_comm_hookrS   )ri   r   r*  r'   r'   r(   register_comm_hookD  s    M
z*DistributedDataParallel.register_comm_hookc                 C   s"   | j t| t| j| dS )a  
        Registers a built-in communication hook that specifies how DDP
        aggregates gradients across multiple workers.
        The built-in hooks aim to provide efficient C++ implementations for certain hooks,
        which might not be as efficient if implemented in Python using a Python communication hook.

        Args:
            comm_hook_type (dist.BuiltinCommHookType): type of communication hook, such as ALLREDUCE, FP16_COMPRESS, etc.

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

        Example::
            Below is an example of a FP16 compression where gradients are
            compressed into 16-bit floating-point numbers before allreduce, and
            then decompressed after allreduce.

            >>> ddp._register_builtin_comm_hook(dist.BuiltinCommHookType.FP16_COMPRESS)

        N)rc   r.  r   r   _register_builtin_comm_hookrS   )ri   Zcomm_hook_typer'   r'   r(   r1    s    z3DistributedDataParallel._register_builtin_comm_hook)optim_params)optimc                O   s^   ddl m} |||g|R i |}z||  W n& tyX   t| d| dY n0 dS )a
  
        Registers an optimizer with DDP such that the optimization for a
        parameter will run immediately when that parameter's gradient is
        finished with reduction, instead of waiting for all parameters'
        gradients to finish reduction. This can result in a training speedup
        depending on your workload since the optimizer can run while gradient
        reduction for other parameters are still ongoing. In addition, this has
        the potential to reduce peak memory consumption during training, as it
        only needs to load the per-parameter optimizer states of a single
        parameter at a time, instead of loading all per-parameter optimizer
        states at once.

        Args:
            optim_cls (Type): a ``torch.optim.Optimizer`` class to be registered
            as a fused optimizer.
            *args (Sequence[Any]): Arguments to forward to `optim_cls`.
            optim_params (Optional[Iterable[torch.Tensor]]): Set of parameters
            to optimize, similar to `params` argument of traditional `torch.optim`
            Optimizers. If this is omitted, all DDP model parameters will be
            optimized.
            **kwargs: (Dict[str, Any]): Keyword arguments to forward to `optim_cls`.

    .. warning ::
        _register_fused_optim should only be called once on a DDP instance,
        and registering multiple fused optimizers for the same DDP model
        is not currently supported. Please ping
        https://github.com/pytorch/pytorch/issues/71595 if this is necessary
        for your use case.

    .. warning ::
        _register_fused_optim and register_comm_hook currently do not
        compose together, meaning that custom DDP communication hooks are
        not supported with overlapped optimizers. Please ping
        https://github.com/pytorch/pytorch/issues/71595 if this is necessary
        for your use case.

    .. warning ::
        Gradient accumulation and DDP `no_sync` are currently not supported
        with overlapped optimizer. Please ping
        https://github.com/pytorch/pytorch/issues/71595 if this is necessary
        for your use case.

    Example::

        >>> torch.distributed.init_process_group(backend='nccl', world_size=4, init_method='...')
        >>> net = torch.nn.parallel.DistributedDataParallel(model, pg)
        >>> lr = 1e-2
        >>> betas = (0.9, 0.99)
        >>> eps = 1e-6
        >>> net._register_fused_optim(torch.optim.Adam, lr, betas=betas, eps=eps)
        >>> # Example with subset of parameters
        >>> params_to_opt = [list(net.parameters())[0]]
        >>> net._register_fused_optim(
            torch.optim.Adam, lr, optim_params=params_to_opt,  betas=betas, eps=eps
        )
        r   )_as_overlapped_optimz] does not support overlapped DDP. Please file an issue to PyTorch or the respective owner of r   N)Z/torch.distributed.algorithms._optimizer_overlapr4  Zregister_ddpNotImplementedErrorr   )ri   r3  r2  argsr   r4  Zoverlapped_optimr'   r'   r(   _register_fused_optim  s    ;z-DistributedDataParallel._register_fused_optimc                 C   s   t | j||| d S r   )r   _broadcast_coalescedr   )ri   tensorsbuffer_sizer  r'   r'   r(    _distributed_broadcast_coalesced  s    
z8DistributedDataParallel._distributed_broadcast_coalescedc                 C   s    |   ot| do| jjtjkS Nr   )will_sync_module_buffersr   r   rK   rB   rG   r   r'   r'   r(   r	    s    z1DistributedDataParallel._check_sync_bufs_post_fwdc                 C   s"   |   o t| d p | jjtjkS r<  )r=  r   r   rK   rB   rF   r   r'   r'   r(   r    s    z0DistributedDataParallel._check_sync_bufs_pre_fwdc                 C   s   | j o| jot| jdkS r   )ru   r   r   r   r   r'   r'   r(   r=  	  s
    z0DistributedDataParallel.will_sync_module_buffersc                 C   sN   t j|r|ndg| jd}tj|tj| jd | dkrF| 	t
d | S )Nr   r   )opr  zuBUG! Expected rank_cond to be true for at least one process. This indicates a bug in PyTorch, please report an issue.)r-   tensorr   r   r  r   MAXr   rt   r   r   )ri   Z
input_rankZ	rank_condZrank_to_user'   r'   r(   r    s    z)DistributedDataParallel._find_common_rankc                 C   sZ   t  > | jjr"| | jd}nd}|   | | W d    n1 sL0    Y  d S )NTr   )r-   no_gradr  r  r  r  r   r  r  r'   r'   r(   r     s    
z%DistributedDataParallel._sync_buffersc                 C   sL   t | ds| j|d n0| jj}| jj}||| j}|d urH| j| d S )Nr   )r  )r   _default_broadcast_coalescedr   rI   rJ   r   rS   _install_post_backward_futures)ri   r  r*  r   Zfutsr'   r'   r(   r  3  s    
z,DistributedDataParallel._sync_module_buffersc                 C   s.   |du r| j }|du r| j}| ||| dS )z
        Broadcasts buffers from rank 0 to rest of workers. If bufs, bucket_size
        are None, default values self.modules_buffers and
        self.broadcast_bucket_size are used instead.
        N)r   r   r;  )ri   ZbufsZbucket_sizer  r'   r'   r(   rB  =  s    z4DistributedDataParallel._default_broadcast_coalescedc                 C   s8   |  D ]*}t|tjj jr| jdkr| td qd S )Nr   z/SyncBatchNorm layers only work with GPU modules)r   r!   r-   r   r   r   r   r   )ri   r   layerr'   r'   r(   r   P  s    
z6DistributedDataParallel._passing_sync_batchnorm_handlec                 C   s   t |s| td t|}|jd jtjkrN|jd jtj	krN| t
d |jtjkrz|jtjjtj krz| t
d |jdv rtjjd u sttjjdd dk st rt rtjj d	k r| td
 d S )Nz$Communication hook must be callable.bucketz@Communication hook: bucket annotation should be dist.GradBucket.zSCommunication hook: return annotation should be torch.futures.Future[torch.Tensor].)Zbf16_compress_hookZbf16_compress_wrapper_hookr   r      )r   
   zDBF16 all reduce communication hook required CUDA 11+ and NCCL 2.10+.)r+  r   	TypeErrorinspect	signaturer   
annotation_emptyr   
GradBucketr   return_annotationr-   futuresFuturer.   rC   versioncudar   splitis_availableis_nccl_availablenccl)ri   r*  sigr'   r'   r(   r-  X  s@    


z(DistributedDataParallel._check_comm_hookc                 C   s   t | jS r   )r   get_rankr   r   r'   r'   r(   r  |  s    z)DistributedDataParallel._distributed_rankc                 C   s
   || _ dS )a;  
        Sets parameters and buffers to be ignored by DDP. Expected format for
        parameters is the fully qualified name: {module_name}.{param_name}, and
        similarly, {module_name}.{buffer_name} for buffers. For example:
        params_to_ignore = []
        # NB: model here is vanilla PyTorch module, not yet wrapped with DDP.
        for module_name, module in model.named_modules():
            for param_name, param in module.named_parameters(recurse=False):
                if should_ignore(param):
                    # Create expected format
                    fqn = f"{module_name}.{param_name}"
                    params_to_ignore.append(fqn)
        torch.nn.parallel.DistributedDataParallel._set_params_and_buffers_to_ignore_for_model(
            model,
            params_to_ignore
        )
        N)r   )r   r   r'   r'   r(   +_set_params_and_buffers_to_ignore_for_model  s    zCDistributedDataParallel._set_params_and_buffers_to_ignore_for_modelc                 C   s   | j  }i |j|jS )a  
        This interface can be called after DistributedDataParallel() is
        constructed. It returns a dictionary of logging data. It could help
        for debugging and analysis. The loggind data includes DistributedDataParallel
        constructor input parameters, some internal states of DistributedDataParallel
        and performance metrics. Simply print the dictorinary and see what
        these metrics are.
        This is a prototype interface and subject to change in the future.
        )rc   _get_ddp_logging_datastrs_mapints_map)ri   Zddp_logging_datar'   r'   r(   rZ    s    

z-DistributedDataParallel._get_ddp_logging_datac                 C   s$   |dk r|  td | j| dS )a.  
        This interface allows users to set sample_rate of collecting
        runtime stats. The runtime stats will be recorded for the
        first 10 iterations, after 10 iteratons runtime stats will be
        recorded once every "sample_rate" training iterations. In
        default, runtime stats are recorded for the first 10 iterations,
        after 10 iterations runtime stats are recorded once every
        "kDDPRuntimeLoggingSampleRate=100" training iterations.
        This is a prototype interface and subject to change in the future.
        r   zADDP runtime logging sample rate should be equal or greater than 1N)r   r   rS   $_set_ddp_runtime_logging_sample_rate)ri   Zsample_rater'   r'   r(   r]    s    z<DistributedDataParallel._set_ddp_runtime_logging_sample_ratec                 C   sB   | j rtd dS d| _ | j  | j  | jr>td dS )z
        It is recommended to set static graph in the DDP constructor, which will
        call this private API internally.
        z<You've set static_graph to be True, no need to set it again.NTa'  You passed find_unused_parameters=true to DistributedDataParallel, `_set_static_graph` will detect unused parameters automatically, so you do not need to set find_unused_parameters=true, just be sure these unused parameters will not change during training loop while calling `_set_static_graph`.)rY   r   r   rS   r   rc   rw   r   r'   r'   r(   r     s    

z)DistributedDataParallel._set_static_graph)
NNr   TNr   FFFF)T)T)TTF)r   )NNr   )<rC   rD   rE   __doc__rh   r   r   r   r   r   r   r   r   r   r   r   r   r   rX   r  r  r   r  rq   rp   r}   rv   rx   r   r&  r'  propertyr(  r)  rB   rG   r+  r,  objectr0  r1  r   r7  r;  r	  r  r=  r  r  r  rB  r   r-  r  r`   rY  rZ  r]  r   r   r'   r'   rk   r(   rb      s                 Y
-$

a   k 

1QF 
 
$

rb   )Br   r   dataclassesr   typingr   r   r   enumr   r   rI  r1   loggingr<   r   
contextlibr   r-   Ztorch.distributeddistributedr   torch.autogradr	   r
   Z!torch.distributed.algorithms.joinr   r   r   torch.utils._pytreer   r   r    rT  Ztorch.distributed.utilsr   r   r   Z"torch.distributed.distributed_c10dr   r   rpctorch.distributed.rpcr   Ztorch._utilsr   r   r   Z_replicated_tensor_ddp_utilsr   scatter_gatherr   r   r   	getLoggerrC   rc   r)   r*   r,   rA   rB   rH   rM   ra   rb   r'   r'   r'   r(   <module>   sJ   
:	: