o
    h                     @   s$  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Zd dlZd dl	m
Z
m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mZmZmZmZ d dlZd dlm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( d dl)m*Z*m+Z+ d dl,m-Z-m.Z. dZ/e0 rd dl1m2Z2m3Z3m4Z4 d dl5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z; ej<0 rdZ/d dl=m>Z> erd dl?m@Z@ dgZAeBeCZDeG dd dZEdd ZFdd ZGdd ZHdd ZIdd ZJd d! ZKG d"d# d#eZLeG d$d% d%ZMG d&d' d'e!ZNG d(d) d)e&ZOG d*d de(e%ZPdS )+    N)defaultdictdeque)contextmanager)	dataclassfieldsis_dataclass)autoEnum)AnyCallableOptionalTYPE_CHECKING_get_device_index)FunctionVariable)JoinJoinableJoinHook)Module)gatherscatter_kwargs)tree_flattentree_unflattenF)_get_default_group_rank_not_in_groupReduceOp)_alloc_storage_cast_forward_inputs_free_storage_sync_module_states
_to_kwargs$_verify_param_shape_across_processesT)RRef)RemovableHandleDistributedDataParallelc                   @   sH   e Zd ZU dZdZeej ed< dZ	eej ed< dZ
eej ed< dS )_MixedPrecisiona  
    This configures DDP-native mixed precision training.

    Attributes:
        param_dtype (torch.dtype): This specifies the dtype for model
            parameters, inputs (when ``cast_forward_inputs`` is set to
            ``True``), and therefore the dtype for computation.
            However, outside the forward and backward passes, parameters are in
            full precision. Model checkpointing always happens in full
            precision.
        reduce_dtype (torch.dtype): This specifies the dtype for gradient
            reduction, which is permitted to differ from ``param_dtype``.
        buffer_dtype (torch.dtype): This specifies the dtype for buffers.

    .. note:: This API is experimental and subject to change.

    .. note:: Only floating point tensors are cast to their specified dtypes.

    .. note:: ``state_dict`` checkpoints parameters and buffers in full
        precision.

    .. note:: Each low precision dtype must be specified explicitly. For
        example, ``_MixedPrecision(reduce_dtype=torch.float16)`` only specifies
        the reduction dtype to be low precision, and DDP will not cast
        parameters or buffers.

    .. note:: If a ``reduce_dtype`` is not specified, then gradient reduction
        happens in ``param_dtype`` if specified or the original parameter dtype
        otherwise. For example, ``_MixedPrecision(param_dtype=torch.float16)``
        would result in communication occurring in fp16.
    Nparam_dtypereduce_dtypebuffer_dtype)__name__
__module____qualname____doc__r'   r   torchdtype__annotations__r(   r)    r1   r1   q/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/nn/parallel/distributed.pyr&   7   s
   
  r&   c                 C   s4   |  D ]}t|dr|jrq|j| jd|_qdS )z,Casts buffers to the given ``buffer_dtype``._ddp_ignored)r/   N)buffershasattrr3   tor)   data)mixed_precision_configroot_modulebufr1   r1   r2   _cast_buffersb   s
   r;   c                 C   sZ   |  D ]&}t|dr|jrqt|ds*tj||j| j|jd|_t	|j |j
|_qdS )z;Create and free storage for the mixed precision parameters.r3   	_mp_param)devicer/   requires_gradN)
parametersr5   r3   r.   
zeros_liker=   r'   r>   r<   r   r7   	_fp_param)r8   r9   paramr1   r1   r2   _setup_mixed_precision_paramsk   s   

rC   c                 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treespecr1   r1   r2   _tree_flatten_with_rref   s
   
rL   c                 C   s   t | |} |rt| } | S rD   )r   r#   )rH   rK   rI   r1   r1   r2   _tree_unflatten_with_rref   s   
rM   c                    s   t rt tr  rt  S t tjr gS t tt	fr*t
jtt S t tr:t
jtt  S t rPt
jtt fddt D S g S )z?Recursively find all tensors contained in the specified object.c                 3   s    | ]	}t  |jV  qd S rD   )getattrname).0fobjr1   r2   	<genexpr>   s    z _find_tensors.<locals>.<genexpr>)rE   rF   r#   is_owner_find_tensorsrG   r.   Tensorlisttuple	itertoolschainfrom_iterablemapdictvaluesr   r   rR   r1   rR   r2   rV      s   
rV   c                  C   sP   g d} d}| D ]}|t jv rt j| nd}|d| d| d7 }qt| d S )N)/RANK
LOCAL_RANK
WORLD_SIZEMASTER_PORTMASTER_ADDRCUDA_VISIBLE_DEVICESGLOO_SOCKET_IFNAMEGLOO_DEVICE_TRANSPORTNCCL_SOCKET_IFNAMETORCH_NCCL_BLOCKING_WAIT
NCCL_DEBUGNCCL_DEBUG_SUBSYSNCCL_IB_DISABLENCCL_P2P_DISABLENCCL_P2P_LEVELNCCL_SHM_DISABLENCCL_SOCKET_NTHREADSNCCL_NSOCKS_PERTHREADNCCL_BUFFSIZENCCL_NTHREADS
NCCL_RINGSNCCL_MAX_NCHANNELSNCCL_MIN_NCHANNELSNCCL_CHECKS_DISABLENCCL_CHECK_POINTERSNCCL_LAUNCH_MODENCCL_IB_HCANCCL_IB_TIMEOUTNCCL_IB_RETRY_CNTNCCL_IB_GID_INDEX
NCCL_IB_SL
NCCL_IB_TCNCCL_IB_AR_THRESHOLDNCCL_IB_CUDA_SUPPORTNCCL_NET_GDR_LEVELNCCL_NET_GDR_READNCCL_SINGLE_RING_THRESHOLDNCCL_LL_THRESHOLDNCCL_TREE_THRESHOLD	NCCL_ALGO
NCCL_PROTONCCL_IGNORE_CPU_AFFINITYNCCL_DEBUG_FILENCCL_COLLNET_ENABLENCCL_TOPO_FILENCCL_TOPO_DUMP_FILETORCH_NCCL_ASYNC_ERROR_HANDLING zN/Azenv:=
)osenvironprint)relevant_env_varsformatted_outputvarvaluer1   r1   r2   _dump_DDP_relevant_env_vars   s   2r   c                   @   s   e Zd Ze Ze ZdS )_BufferCommHookLocationN)r*   r+   r,   r   PRE_FORWARDPOST_FORWARDr1   r1   r1   r2   r      s    
r   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)r*   r+   r,   r   r0   r
   r   r1   r1   r1   r2   r      s   
 r   c                   @   s$   e Zd Zedd Zedd ZdS )_DDPSinkc                 G   s2   |  d || _|}| jrtdd |D }|S )NFc                 s   s(    | ]}t |tjr| n|V  qd S rD   )rF   r.   rW   clone)rP   inpr1   r1   r2   rT      s    
z#_DDPSink.forward.<locals>.<genexpr>)set_materialize_gradsddp_weakref_ddp_sink_clonerY   )ctxr   inputsretr1   r1   r2   forward   s   
z_DDPSink.forwardc                 G   sF   |   }|j}|j}|o|j}|r|stj|j d|_d g|R S NT)r   reducerstatic_graph&_static_graph_delay_allreduce_enqueuedr   _execution_enginequeue_callback_delay_all_reduce)r   grad_outputsr   r   r   delay_ar_enqueuedr1   r1   r2   backward   s   z_DDPSink.backwardN)r*   r+   r,   staticmethodr   r   r1   r1   r1   r2   r      s
    
r   c                       s2   e Zd Z fddZdd ZdefddZ  ZS )_DDPJoinHookc                    sF   t |ts	J d|jdusJ |j  || _|| j_t   dS )z(Set config variables for internal usage.zQDDP join hook requires passing in a DistributedDataParallel instance as the stateN)rF   r%   logger_set_uneven_input_joinddp_divide_by_initial_world_sizesuper__init__)selfr   divide_by_initial_world_size	__class__r1   r2   r     s   
z_DDPJoinHook.__init__c                 C   sV   | j }|j  |  |jdd}||_|sdS |  |jr$|  |j	  dS )zVShadow the DDP collective communication operations in the forward and backward passes.Tis_joined_rankN)
r   r   _rebuild_buckets_check_and_sync_module_buffers)_check_global_requires_backward_grad_syncrequire_forward_param_sync_match_all_reduce_for_bwd_passfind_unused_parameters_match_unused_params_allreduce_push_all_rebuilt_params)r   r   should_sync_backwardsr1   r1   r2   	main_hook  s   
z_DDPJoinHook.main_hookis_last_joinerc                 C      | j | dS )zOSync the final model to ensure that the model is the same across all processes.N)r   _sync_final_modelr   r   r1   r1   r2   	post_hookA  s   z_DDPJoinHook.post_hook)r*   r+   r,   r   r   boolr   __classcell__r1   r1   r   r2   r     s    "r   c                       s  e Zd ZU dZdZed  ed< 															ddee f fdd	Zd
d Z	dd Z
dd Zdd Zdd ZdededdfddZdededdf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dd)d*Zd+d, Zed-d. Zed/d0 Zeejdd1d2d3 Z d4d5 Z!d6d7 Z"d8d9 Z#d:d; Z$d<d= Z%d>d? Z&d@dA Z'dBdC Z(dDdE Z)d fdFdG	Z*dHdI Z+dJdK Z,dLdM Z-dNdO Z.dPdQ Z/			ddRe0dSe0dTe0fdUdVZ1dWdX Z2e3dYdZ Z4e3d[d\ Z5e6j7fd]e8fd^d_Z9d`e:d]e8fdadbZ;dcdd Z<ddedfe=fdgdhZ>	ddidjZ?dkdl Z@dmdn ZAdodp ZBdqdr ZCdsdt ZDdudv ZE	ddwdxZFdydz ZGd{d| ZHe3d}d~ ZIeJdddZKeJdd ZLdd ZMdd ZNdd ZOdd ZPdd ZQdd ZRdd ZSde0fddZT  ZUS )r%   aTC  Implement distributed data parallelism based on ``torch.distributed`` at module level.

    This container provides data parallelism by synchronizing gradients
    across each model replica. The devices to synchronize across are
    specified by the input ``process_group``, which is the entire world
    by default. Note that ``DistributedDataParallel`` does not chunk or
    otherwise shard the input across participating GPUs; the user is
    responsible for defining how to do so, for example through the use
    of a :class:`DistributedSampler`.

    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:

        >>> # xdoctest: +SKIP("undefined variables")
        >>> 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:

        >>> # xdoctest: +SKIP("undefined variables")
        >>> 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.

        Example::

            >>> # xdoctest: +SKIP("undefined variables")
            >>> 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::
        DistributedDataParallel currently offers limited support for gradient
        checkpointing with :meth:`torch.utils.checkpoint`.
        If the checkpoint is done with use_reentrant=False (recommended), DDP
        will work as expected without any limitations.
        If, however, the checkpoint is done with use_reentrant=True (the default),
        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.

    .. 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 reduction 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``)
        init_sync (bool): Whether to sync during initialization to verify param
                          shapes and broadcast parameters and buffers.
                          WARNING: if this is set to False the user is required
                          to ensure themselves that the weights are the same on
                          all ranks.
                          (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
                       MebiBytes (MiB). If ``None``, a default size of 25 MiB
                       will be used. (default: ``None``)
        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 iteration 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::
                         >>> # xdoctest: +SKIP("undefined variables")
                         >>> 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")
        delay_all_reduce_named_params (list of tuple of str and torch.nn.Parameter): a list
                    of named parameters whose all reduce will be delayed when the gradient of
                    the parameter specified in ``param_to_hook_all_reduce`` is ready. Other
                    arguments of DDP do not apply to named params specified in this argument
                    as these named params will be ignored by DDP reducer.
        param_to_hook_all_reduce (torch.nn.Parameter): a parameter to hook delayed all reduce
                    of parameters specified in ``delay_all_reduce_named_params``.


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

    Example::

        >>> # xdoctest: +SKIP("undefined variables")
        >>> torch.distributed.init_process_group(backend='nccl', world_size=4, init_method='...')
        >>> net = torch.nn.parallel.DistributedDataParallel(model)
    N_active_ddp_moduler   TFmixed_precisionc              
      sX  t    t  d  _t|d ut|d ukr td |r)|d ur)td|d u r6|d u r6t  _	n8|d u r>| _	n0|j
dkrKtd| d| _|jdd _	ddlm} ||}||krndd	lm} || g  _t|d
r}t|j _nt  _|d ur|D ]\}} j|  j| q fdd| D  _tdd  jD st jrtd n td |d urt|dkrψ td tdd  jD dk _dd  jD }t|dkr td| d tt | _!|d u st|dks j!dks jr4|s|r- td| d| ddd  jD  d d  _"d  _#ndd |D  _"|d u rE|d }t$|d _#d _%| _&| _'tt  jj( _(| _)|	 _*d _+d _,| _-| _. j.d ur|t/d j. |
rt0j1dt2d d!  jD ]}t3|t4j5j6j7r td" qt8d# _9|d u rd$}d _:nd _:t8|d% d%  _;t<j=>d&d'd'k _?d  _@g  _Ad _Bt jdkr jC|||d(  jBrd S  D \}}|r tE j	| tF j' j	 j9d j j)d)  G|} H|||| g  _I j.d urktJ j. j' tK j. j' t4L  _MtNtO _P j'jQ jRddd*  j'S D ]}|jQ jTddd* q=dd+lUmV}mW} |tXY t4L d,} Z||  j[\ j.j] d _^|ru _  d _`g  _at4jbjcd }|d-k _e jerdt4jfjg_h|t4jfjg_it4jbjjjkd. t4jbjjjlm   n  d _od S )/Nz[delay_all_reduce_named_params and param_to_hook_all_reduce need to be set at the same time.z<Cannot specify both process_group and device_mesh arguments.   z*Only 1D device mesh is supported, but got .r   )mesh_dim)_mesh_resources)_pre_dp_module_transform!_ddp_params_and_buffers_to_ignorec                    s   g | ]\}}| j vr|qS r1   parameters_to_ignore)rP   npr   r1   r2   
<listcomp>  s
    
z4DistributedDataParallel.__init__.<locals>.<listcomp>c                 s   s    | ]}|j V  qd S rD   )r>   rP   r   r1   r1   r2   rT     s    z3DistributedDataParallel.__init__.<locals>.<genexpr>z&Delay the AllReduce of all parameters.zhDistributedDataParallel is not needed when a module doesn't have any parameter that requires a gradient.z8device_ids can only be None or contain a single element.c                 S      h | ]}|j qS r1   r=   r   r1   r1   r2   	<setcomp>      z3DistributedDataParallel.__init__.<locals>.<setcomp>c                 S   s   h | ]}|j d ur|j jqS rD   )r=   typer   r1   r1   r2   r     s    zrDistributedDataParallel's input module must be on the same type of devices, but input module parameters locate in cpuzDistributedDataParallel device_ids and output_device arguments only work with single-device/multiple-device GPU modules or CPU modules, but got device_ids z, output_device z, and module parameters c                 S   r   r1   r   r   r1   r1   r2   r     r   c                 S   s   g | ]}t |d qS Tr   )rP   xr1   r1   r2   r         TFz"Received mixed precision config %szhThe `check_reduction` argument in `DistributedDataParallel` module is deprecated. Please avoid using it.   )
stacklevelzModules with uninitialized parameters can't be used with `DistributedDataParallel`. Run a dummy forward pass to correctly initialize the modulesi     i   PYTORCH_DDP_USE_SIDE_STREAM1)bucket_cap_mbparam_to_hook_all_reduce
device_idsmoduleprocess_groupbroadcast_bucket_sizesrcparams_and_buffers_to_ignorebroadcast_buffers)prependwith_kwargs)_AllreduceUpcastHookState"_reducer_allreduce_and_upcast_hook)r   upcast_streampython_reducerztorch.nn.parallel.distributed)pr   r   r   r   r   _log_and_throw
ValueErrorRuntimeErrorr   r   ndimdevice_mesh	get_grouptorch.distributed.device_meshr   get_root_mesh%torch.distributed.tensor.parallel.ddpr   _delay_all_reduce_paramsr5   setr   r   addappendnamed_parameters_module_parametersanyleninfois_multi_device_modulenextiterdevice_typer   output_devicer   r   dimr   r=   r   r   require_backward_grad_syncr   gradient_as_bucket_viewr   warningwarningswarnFutureWarningrF   r.   nn	parameterUninitializedParameterintr   bucket_bytes_cap_defaultbucket_bytes_capr   r   get!use_side_stream_for_tensor_copies_delay_grad_buffer_delay_grad_views_delay_all_reduce_all_params_register_delay_all_reduce_hook_build_params_for_reducerr"   r    "_build_debug_param_to_name_mapping_ddp_init_helper_comm_hooksrC   r;   Stream
_mp_streamr   r   _submodule_to_eventregister_forward_pre_hook_root_copy_hookmodules_module_wait_for_copy_hookAtorch.distributed.algorithms.ddp_comm_hooks.mixed_precision_hooksr   r   weakrefrefregister_comm_hookr    _set_mixed_precision_param_dtyper'   _has_rebuilt_buckets_set_static_graph_lazy_init_ran_accum_grad_hooks_dynamoutilsget_optimize_ddp_mode_use_python_reducer	_inductorconfig_fuse_ddp_communication_fuse_ddp_bucket_sizetrace_rulesLEGACY_MOD_INLINELISTget_legacy_mod_inlinelistcache_clear_register_accum_grad_hookr   )r   r   r   r  r  r   	init_syncr   r   r   check_reductionr  r   delay_all_reduce_named_paramsr   r   r  r   	root_meshr   rO   rB   distinct_device_typesr?   expect_sparse_gradientparam_to_name_mappingr   r   upcast_hook_stateoptimize_ddpr   r   r2   r   z  s  


















	




z DistributedDataParallel.__init__c              	      sb   dd l m  m  dtf fdd}tjD ]\}}|js qj|	t
j||d qd S )Nr   param_indexc                   sr   j sd S | jd u rd S jr!jD ]\}}||| j| f qd S | jj  } |dj}| j| d S )Nsum)r  gradr.  r   size
all_reducecopy_)rB   rU  hookstategradientfcolr   r1   r2   compiled_accum_grad_hook  s   
zSDistributedDataParallel._register_accum_grad_hook.<locals>.compiled_accum_grad_hook)rU  ))torch.distributed._functional_collectivesdistributed_functional_collectivesr"  	enumerater  r>   r>  r  "register_post_accumulate_grad_hook	functoolspartial)r   r`  indexrB   r1   r^  r2   rK    s    z1DistributedDataParallel._register_accum_grad_hookc                 C   s0   t | j}| j| t j| j| jdd}|S )NTgroupasync_op)distget_world_sizer   r'  div_rY  )r   rW  
world_size_r1   r1   r2   _delayed_all_reduce_hook  s   
z0DistributedDataParallel._delayed_all_reduce_hookc                 C   s  |d u r	t dn|d }t jtdd | jD |d| _dd | jD }t| j||d |	| j
 d}| jD ]}| j|||   |j}| j| ||  }q9| j D ]"\}	}
|
jdd	D ]\}}|jr}|	 d
| }|| jvr}  d S qfq\d| _d S )Nr   r   c                 s   s    | ]}|  V  qd S rD   )numelr   r1   r1   r2   rT     s    zJDistributedDataParallel._register_delay_all_reduce_hook.<locals>.<genexpr>r   c                 S   s   g | ]}|  qS r1   )detachr   r1   r1   r2   r         zKDistributedDataParallel._register_delay_all_reduce_hook.<locals>.<listcomp>Frecurser   T)r.   r=   zerosrV  r
  r'  rl  _broadcast_coalescedr   register_hookrq  rr  viewshaper(  r  r   named_modulesr  r>   r   r)  )r   r   r   r   r=   detached_paramsoffsetrB   	grad_viewmodule_namer   
param_name	full_namer1   r1   r2   r*    s0   


z7DistributedDataParallel._register_delay_all_reduce_hookc                 C   s   t dd | jD rDtjd tjjj}| jD ]}|	|g D ]}|
  q qt| }ddlm} | ||| jd | j  d S d S )Nc                 s   s    | ]}t |d V  qdS )_in_backward_optimizersN)r5   r   r1   r1   r2   rT     s    zHDistributedDataParallel._setup_in_backward_optimizers.<locals>.<genexpr>zddp.optimizer_in_backwardr   )_apply_optim_in_backward_hook)gradient_is_bucket_view)r  r  r.   _C_log_api_usage_oncerl  optimapply_optimizer_in_backwardparam_to_optim_hook_handle_mapr%  remover7  r8  Ctorch.distributed.algorithms.ddp_comm_hooks.optimizer_overlap_hooksr  r9  r  r   _set_optimizer_in_backward)r   param_to_handle_mapr   handler   r  r1   r1   r2   _setup_in_backward_optimizers  s$   


z5DistributedDataParallel._setup_in_backward_optimizersc                 G   r   )a7  
        Fire the reducer's autograd hook to allreduce params in a Reducer bucket.

        Note that this is only used during mixed precision training as the
        Reducer's hooks installed during construction time would not be called
        as we're working in the low precision parameter setting.
        N)r   _autograd_hook)r   idxunusedr1   r1   r2   _fire_reducer_autograd_hook  s   z3DistributedDataParallel._fire_reducer_autograd_hookargskwargsreturnc                 O   s   t t| _| ji | j D ]Z}|jddD ]A}t|dr!|jr!qt	|j
|  t  |j
|j |jdurD|j| jj|j_W d   n1 sNw   Y  |j
|_qt }|  | j| | qW d   dS 1 stw   Y  dS )a:  
        For DDP mixed precision, put low precision copies on separate stream and create events to wait for them.

        When training with DDP mixed precision, this root pre-forward hook kicks
        off low precision copies on a separate stream and creates respective
        events to wait for them.
        Fru  r3   N)r   r   r1  r0  r   r4  r?   r5   r3   r   r<   rX  r.   no_gradrZ  r7   rW  r6   r   r'   Eventrecordr  )r   r  r  	submodulerB   
copy_eventr1   r1   r2   r3  '  s*   




"z'DistributedDataParallel._root_copy_hookc           	      O   s   z	| j |  }W n
 ty   Y dS w |jtj d |jddD ]+}|jr0t	|dr1|j
r1q#||}|jjd d }|t| j|j}||f|_q#dS )zlBefore carrying out computation, wait on the appropriate event to ensure low precision copies have finished.N)streamFru  r3   r   )r1  popleft
IndexErrorwaitr.   acceleratorcurrent_streamr?   r>   r5   r3   	expand_asgrad_fnnext_functionsry  rf  rg  r  _idx_ddp_mp_hook_state)	r   r   r  r  eventr   tmpgrad_accr[  r1   r1   r2   r5  O  s    
z2DistributedDataParallel._module_wait_for_copy_hookc                 C   s,   | j d ur| j t| d|  ||)Nz: )r   set_error_and_logstr)r   err_typeerr_msgr1   r1   r2   r  l  s   
z&DistributedDataParallel._log_and_throwc                 C   sD  |du s	| j du rtjg}n| jrtj| jg}n| jg}t|||\}}| jdur6t	|D ]\}}	||	_
q.t|tt|tt|| j|| j| j | j|| jrStjn| j
| _t| j| _| j| j d}
| j D ]}t|tjjrzd}
 nqm| j| jjj| jdu rg n| j| jdu rdn| j| j|
| |  | j dS )a  
        DDP init helper function to manage parameters, grad hooks, logging, and SyncBatchNorm.

        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
        TFN)!r   sysmaxsizer#  rl  _DEFAULT_FIRST_BUCKET_BYTESr$  "_compute_bucket_assignment_by_sizer   rd  r  ReducerrX   reversedr   r  r   Loggerr   
set_loggerr   r4  rF   r.   r  SyncBatchNormset_construction_data_and_logr   r*   r   r  r   _passing_sync_batchnorm_handle)r   r?   rQ  rR  r   bucket_size_limitsbucket_indicesper_bucket_size_limitsir   has_sync_bnr  r1   r1   r2   r-  q  sb   $

	


z(DistributedDataParallel._ddp_init_helperc                 C   s*   |    t| j}|d= |d= |d= |S )Nr   r   r   )_check_default_groupcopy__dict__)r   attrsr1   r1   r2   __getstate__  s   z$DistributedDataParallel.__getstate__c                    s   t  | _t | | jdd | jdd |  \}}| |}| |||| j	 | j	rB| j
  | jd us;J | j  d S d S )Nr   Tr  )r   r   r   __setstate__r  
setdefaultr+  r,  r-  r   r   r<  r   )r   r\  r?   rQ  rR  r   r1   r2   r    s"   

z$DistributedDataParallel.__setstate__c                    sh   fddj  D }t   fdd|D }dd |D }dd fdd|D }  ||fS )Nc                    s:   g | ]\ } 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>   r   )rP   r  rB   )r  r   r1   r2   r     s    zPDistributedDataParallel._build_params_for_reducer.<locals>.<listcomp>.<listcomp>Fru  )r  )rP   r   r   r   )r  r2   r      s    
zEDistributedDataParallel._build_params_for_reducer.<locals>.<listcomp>c                    s*   g | ]\}}| vr  |s||fqS r1   )r  )rP   mr   )memor1   r2   r     s
    c                 S   s   g | ]\}}|qS r1   r1   )rP   rp  r   r1   r1   r2   r     rt  c                 S   s    t | tjjtjjfr| jS dS NF)rF   r.   r  	EmbeddingEmbeddingBagsparse)r   r1   r1   r2   produces_sparse_gradient  s   zSDistributedDataParallel._build_params_for_reducer.<locals>.produces_sparse_gradientc                    s   g | ]\}} |qS r1   r1   )rP   r   rp  )r  r1   r2   r   $  s    )r   r|  r  _assign_modules_buffers)r   modules_and_parametersr?   rQ  r1   )r  r  r   r2   r+    s   

	
z1DistributedDataParallel._build_params_for_reducerc                    s<    fdd j  D }dd |D  _dd |D  _dS )a  
        Assign self.module.named_buffers to self.modules_buffers.

        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 r1   r   )rP   buffer_namebufferr   r1   r2   r   7  s
    
zCDistributedDataParallel._assign_modules_buffers.<locals>.<listcomp>c                 S   s   g | ]\}}|qS r1   r1   rP   r  r  r1   r1   r2   r   <  s    c                 S   s   i | ]\}}||qS r1   r1   r  r1   r1   r2   
<dictcomp>@  s    
zCDistributedDataParallel._assign_modules_buffers.<locals>.<dictcomp>N)r   named_buffersmodules_buffersnamed_module_buffers)r   r  r1   r   r2   r  ,  s   
z/DistributedDataParallel._assign_modules_buffersc                    s    fddt t D }t }i }| j D ]4\}}|jddD ])\}}| d| }	|	| jvrK|jrK||vrC| t	d|	 d || }
|	||
< q"qt|t|krf| t	dt| d	t| d
 |S )Nc                    s   i | ]} | |qS r1   r1   )rP   r  r?   r1   r2   r  E  r   zNDistributedDataParallel._build_debug_param_to_name_mapping.<locals>.<dictcomp>Fru  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.)
ranger  r  r   r|  r  r   r>   r  r  )r   r?   param_to_param_index	param_setparam_index_to_param_fqnr  r   r  rB   fqnrU  r1   r  r2   r,  D  s4   

z:DistributedDataParallel._build_debug_param_to_name_mappingc                 c   s4    dd }|r|  n|gD ]	}||E dH  qdS )z(Return a generator of module parameters.c                 s   s0    t | dr| j n| jdd}|E d H  d S )N_former_parametersFru  )r5   r  r_   r?   )r  psr1   r1   r2   model_parametersh  s   
zADistributedDataParallel._get_parameters.<locals>.model_parametersN)r4  )r   r  rv  r  modr1   r1   r2   _get_parameterse  s
   z'DistributedDataParallel._get_parametersc                 C   sH   d}z
| j t krd}W n ty   d}Y nw |r"| td d S 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  )r   pickle_not_supportedr1   r1   r2   r  s  s   z,DistributedDataParallel._check_default_groupc                 c   s*    | j }d| _ z	dV  W || _ dS || _ w )a0  
        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::

            >>> # xdoctest: +SKIP("undefined variables")
            >>> 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

        .. warning::
            The forward pass should be included inside the context manager, or
            else gradients will still be synchronized.
        FN)r  )r   old_require_backward_grad_syncr1   r1   r2   no_sync  s   zDistributedDataParallel.no_syncc                 C      | j S )zL`TorchDynamo` requires DDP's status and module for cooperative optimization.)r   )clsr1   r1   r2   _get_active_ddp_module  s   z.DistributedDataParallel._get_active_ddp_module)	recursivec                 c   s$    | t _z	d V  W d t _d S d t _w rD   )r%   r   r   r1   r1   r2   _inside_ddp_forward  s
   z+DistributedDataParallel._inside_ddp_forwardc                 O   sR   | j r| j|i |S |   | j|i |W  d    S 1 s"w   Y  d S rD   )rB  r   r  )r   r   r  r1   r1   r2   _run_ddp_forward  s
   
$z(DistributedDataParallel._run_ddp_forwardc                 C   sp   | j d ur4tdd | jD }t| jD ]\}}|jd u r*| j| |_|s*|j  q|r6| j   d S d S d S )Nc                 s   s    | ]}|j d u V  qd S rD   )rW  )rP   rB   r1   r1   r2   rT     s    

z=DistributedDataParallel._clear_grad_buffer.<locals>.<genexpr>)r'  allr
  rd  rW  r(  zero_)r   all_param_grad_nonerh  rB   r1   r1   r2   _clear_grad_buffer  s   


z*DistributedDataParallel._clear_grad_bufferc                 C   s   |    d| _d S r   )r  r=  r   r1   r1   r2   
_lazy_init  s   
z"DistributedDataParallel._lazy_initc                 O   sd  | j r||fS | jstj s|   | jr||fS t r2| jr2| j	d us(J | j	
  | j  t| }|rA| j|| j t rR| j rRt	d d| _|  rZ|   | jjrd| jdd | jrt||t| j| jd | j\}}|d |d }}| jd urt| jj g|R i |\}}||fS | jd urt| jj g|R i |\}}||fS )Nz4Reducer buckets have been rebuilt in this iteration.TFr   r   )!rB  r=  r.   compileris_compilingr  r)  is_grad_enabledr  r   set_runtime_stats_and_logr   prepare_for_forwardr   notify_join_context_set_forward_pass_work_handler   r   r  r;  _check_sync_bufs_pre_fwd_sync_buffers_join_configenabler   r   r!   r=   r  r&  r   r   r'   )r   r   r  workmoved_inputsmoved_kwargsr  r1   r1   r2   _pre_forward  s`   








z$DistributedDataParallel._pre_forwardc                 C   s:  | j r|S | jr|   |S |  r|   t r8| jr8d| _| j	r1| j
s1| jtt| n
| jg  nd| _| j	rA| j
rG| j
r| jst|\}}}dd tt|D }t|D ]\}}t|ro|jd u ro|||< q]tjt| g|R  }tt|D ]}|| d u r|| ||< qt|||}|   |S )NTFc                 S   s   g | ]}d qS rD   r1   )rP   rp  r1   r1   r2   r   @  s    z9DistributedDataParallel._post_forward.<locals>.<listcomp>)rB  r)  r  _check_sync_bufs_post_fwdr  r.   r  r  r   r   r   r   prepare_for_backwardrX   rV   r   rL   r  r  rd  	is_tensorr  r   applyr7  r8  rM   )r   rH   rJ   rK   rI   output_placeholdersr  passthrough_tensor_listr1   r1   r2   _post_forward  sX   
z%DistributedDataParallel._post_forwardc                 O   sx   t jjd+ | j|i |\}}| jr| jj|i |n| j|i |}| 	|W  d    S 1 s5w   Y  d S )NDistributedDataParallel.forward)
r.   autogradprofilerrecord_functionr  r)  r   r   r  r  )r   r   r  rH   r1   r1   r2   r   _  s   $r  c                 C   s   t |||| jdS N)r  )r   r  )r   r   r  r   r1   r1   r2   scatteri  s   zDistributedDataParallel.scatterc                 C   s   t ||t| j|| jS rD   )r!   r.   r=   r  r&  )r   r   r  	device_idr1   r1   r2   	to_kwargsl  s   z!DistributedDataParallel.to_kwargsc                 C   s   t ||| jdS r
  )r   r  )r   outputsr  r1   r1   r2   r   u     zDistributedDataParallel.gatherc                    s   t  | | S rD   )r   train)r   moder   r1   r2   r  x  s   zDistributedDataParallel.trainc                 C   s^   |s| j rtjd| jd}ntjd| jd}tj|| jdd}|r-|  |	 dk}|S d S )Nr   r   Tri  r   )
r  r.   onesr=   rw  rl  rY  r   r  item)r   r   requires_sync_tensorr  r   r1   r1   r2   r   ~  s   
	zADistributedDataParallel._check_global_requires_backward_grad_syncc                 C   s(   |   r| | jd}| | d S d S r  )r  _find_common_rank_distributed_rank_sync_module_buffersr   authoritative_rankr1   r1   r2   r     s   z6DistributedDataParallel._check_and_sync_module_buffersc                 C   s4   |  | j|| _t| j| j| j| j| j| jd d S )Nr   )	r  r  _authoritative_rankr    r   r   r   r   r   r   r1   r1   r2   r     s   
z)DistributedDataParallel._sync_final_modelc                 C   sD   g }| j  }|D ]}| j |}|| q	|D ]}|  qd S rD   )r   _get_zeros_like_grad_buckets_run_comm_hookr  r  )r   	comm_workgrad_bucketsgrad_bucketr  r1   r1   r2   r     s   

z6DistributedDataParallel._match_all_reduce_for_bwd_passc                 C   s   | j  }| j| d S rD   )r   _get_local_used_mapr   	allreduce)r   locally_used_param_mapr1   r1   r2   r     s   
z6DistributedDataParallel._match_unused_params_allreducer   r  throw_on_early_terminationc                 C   s   t | g|||dS )a  
        Context manager for training with uneven inputs across processes in DDP.

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

            >>> # xdoctest: +SKIP("Distributed")
            >>> 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   )r   )r   r   r  r#  r1   r1   r2   join  s   czDistributedDataParallel.joinc                 K   s   | dd}t| |dS )a  
        DDP join hook enables training on uneven inputs by mirroring communications in 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``.
        r   Tr$  )r%  r   )r   r  r   r1   r1   r2   	join_hook2  s   z!DistributedDataParallel.join_hookc                 C   r  rD   r   r   r1   r1   r2   join_deviceP     z#DistributedDataParallel.join_devicec                 C   r  rD   )r   r   r1   r1   r2   join_process_groupT  r(  z*DistributedDataParallel.join_process_groupr[  c                 C   s    t |sJ t|||d| _dS )ab  
        Allow 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, bucket: dist.GradBucket) -> 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.

            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.
        )r   r   r   N)callabler   buffer_hook)r   r\  r[  comm_hook_locationr1   r1   r2   _register_buffer_comm_hookX  s   %z2DistributedDataParallel._register_buffer_comm_hookr\  c                 C   sJ   |  | | jdusJ | j|j | j||f t| j|| dS )a  
        Register communication hook for user-defined DDP aggregation of 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.

            >>> # xdoctest: +SKIP('undefined name')
            >>> 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.

            >>> # xdoctest: +SKIP('undefined name')
            >>> 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_hookr   _set_comm_hook_namer,   r.  r  rl  _register_comm_hookr   )r   r\  r[  r1   r1   r2   r9    s
   
Kz*DistributedDataParallel.register_comm_hookc                 C   s0   | j dusJ | j t| t| j| dS )a  
        Register 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.

            >>> # xdoctest: +SKIP('undefined name')
            >>> ddp._register_builtin_comm_hook(dist.BuiltinCommHookType.FP16_COMPRESS)

        N)r   r/  r  rl  _register_builtin_comm_hookr   )r   comm_hook_typer1   r1   r2   r1    s   z3DistributedDataParallel._register_builtin_comm_hook)optim_paramsr  c             
   O   sd   ddl m} |||g|R i |}z||  W dS  ty1 } zt| d| d|d}~ww )a  
        Register an optimizer in DDP to optimize parameter immediately after its gradient reduction.

        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 (Type): a ``torch.optim.Optimizer`` class to be registered
            as a fused optimizer.
            *args (Sequence[Any]): Arguments to forward to `optim`.
            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`.

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

            >>> # xdoctest: +SKIP("No rendezvous handler")
            >>> 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)/torch.distributed.algorithms._optimizer_overlapr4  register_ddpNotImplementedErrorr  )r   r  r3  r  r  r4  overlapped_optimer1   r1   r2   _register_fused_optim  s   >z-DistributedDataParallel._register_fused_optimc                 C   s   t | j||| d S rD   )rl  rx  r   )r   tensorsbuffer_sizer  r1   r1   r2    _distributed_broadcast_coalesced8  s   
z8DistributedDataParallel._distributed_broadcast_coalescedc                 C   s    |   ot| do| jjtjkS Nr+  )will_sync_module_buffersr5   r+  r   r   r   r   r1   r1   r2   r  ?  s   z1DistributedDataParallel._check_sync_bufs_post_fwdc                 C   s"   |   ot| d p| jjtjkS r>  )r?  r5   r+  r   r   r   r   r1   r1   r2   r  G  s   z0DistributedDataParallel._check_sync_bufs_pre_fwdc                 C   s   | j o| jot| jdkS )Nr   )r   r   r  r  r   r1   r1   r2   r?  N  s
   z0DistributedDataParallel.will_sync_module_buffersc                 C   sN   t j|r|ndg| jd}tj|tj| jd | dkr#| 	t
d | S )Nr  r   )oprj  zuBUG! Expected rank_cond to be true for at least one process. This indicates a bug in PyTorch, please report an issue.)r.   tensorr=   rl  rY  r   MAXr   r  r  r  )r   
input_rank	rank_condrank_to_user1   r1   r2   r  U  s   z)DistributedDataParallel._find_common_rankc                 C   s\   t    | jjr| | jd}nd}|   | | W d    d S 1 s'w   Y  d S )NTr   )r.   r  r  r  r  r  r  r  r  r1   r1   r2   r  e  s   
"z%DistributedDataParallel._sync_buffersc                 C   sR   t | ds| j|d d S | jj}| jj}||| j}|d ur'| j| d S d S )Nr+  )r  )r5   _default_broadcast_coalescedr+  r   r   r  r   _install_post_backward_futures)r   r  r[  r\  futsr1   r1   r2   r  x  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=  )r   bufsbucket_sizer  r1   r1   r2   rF    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)r4  rF   r.   r  r  r  r  r  )r   r   layerr1   r1   r2   r    s   
z6DistributedDataParallel._passing_sync_batchnorm_handlec                 C   s   t |s
| td t|}|jd jtjkr'|jd jtj	kr'| t
d |jtjkr=|jtjjtj kr=| t
d |jdv rytjjd upMtjjd u}t o]t o]tjj dk}t ojt ojtj }|ro|s}|s{| td d S d S d S 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].)bf16_compress_hookbf16_compress_wrapper_hook)r   
   zSBF16 all reduce communication hook required CUDA 11+ and NCCL 2.10+ or XPU and XCCL)r*  r  	TypeErrorinspect	signaturer?   
annotation_emptyrl  
GradBucketr  return_annotationr.   futuresFuturerW   r*   versioncudahipis_availableis_nccl_availablencclis_xccl_availablexpu)r   r[  sigcuda_supportednccl_supportedxpu_xccl_supportedr1   r1   r2   r.    sJ   



z(DistributedDataParallel._check_comm_hookc                 C   s   t | jS rD   )rl  get_rankr   r   r1   r1   r2   r    s   z)DistributedDataParallel._distributed_rankc                 c   s0    |s|   n|  D ]
}t|ds|V  qdS )z=Return a generator of parameters managed by a given DDP unit.r3   N)r?   r  r5   )r   named_paramsrB   r1   r1   r2   _get_data_parallel_params  s   
z1DistributedDataParallel._get_data_parallel_paramsc                 C   sJ   || _ |  D ]\}}||v rd|_q|  D ]\}}||v r"d|_qdS )a;  
        Set 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
        )
        TN)r   r  r3   r  )r   r   rO   rB   r  r1   r1   r2   +_set_params_and_buffers_to_ignore_for_model  s   zCDistributedDataParallel._set_params_and_buffers_to_ignore_for_modelc                 C   s(   | j dusJ | j  }i |j|jS )aB  
        Return a dictionary of logging data for debugging and analysis.

        This interface can be called after DistributedDataParallel() is
        constructed. It returns a dictionary of logging data. It could help
        for debugging and analysis. The logging data includes DistributedDataParallel
        constructor input parameters, some internal states of DistributedDataParallel
        and performance metrics. Simply print the dictionary and see what
        these metrics are.
        This is a prototype interface and subject to change in the future.
        N)r   _get_ddp_logging_datastrs_mapints_map)r   ddp_logging_datar1   r1   r2   ri    s   
z-DistributedDataParallel._get_ddp_logging_datac                 C   s$   |dk r
|  td | j| dS )ae  
        Set sample_rate of collecting runtime stats.

        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 iterations 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  r   $_set_ddp_runtime_logging_sample_rate)r   sample_rater1   r1   r2   rm  	  s   z<DistributedDataParallel._set_ddp_runtime_logging_sample_ratec                 C   sZ   | j r
td dS d| _ d| _| j  | jdusJ | j  | jr+td dS dS )z
        Set static graph for DDP.

        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.NTFa'  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`.)r   r  r  r   r   r<  r   r   r   r1   r1   r2   r<  	  s   

z)DistributedDataParallel._set_static_graphc                 C      | j   dS )zHRemove autograd hooks registered by the reducer on the model parameters.N)r   _remove_autograd_hooksr   r1   r1   r2   rp  4	  s   z.DistributedDataParallel._remove_autograd_hooksc                 C   ro  )a@  
        Check if the reducer has processed all buckets and finalized the backward appropriately.

        It is useful to call this method after calling .backward() in your training loop
        in order to avoid subsequent hard to debug errors down the road due to the
        reducer not finalizing backward.
        N)r   _check_reducer_finalizedr   r1   r1   r2   rq  8	  s   z0DistributedDataParallel._check_reducer_finalizedc                 C   s   | j | d S rD   )r   _set_sparse_metadata)r   global_unique_idsr1   r1   r2   rr  B	  r  z,DistributedDataParallel._set_sparse_metadatac                 C   s2   d| _ | j  t|s|| _| j| dS dS )a6  
        Dynamically updates the process group for DDP so that we can shrink/expand DDP
        world size without having to reinitialize DDP.

        NOTE: If you are using custom communications hooks via, register_comm_hook,
        you need to update the process groups for those hooks separately.
        FN)r;  r   _reset_stater   r   _update_process_group)r   new_process_groupr1   r1   r2   ru  E	  s   
z-DistributedDataParallel._update_process_groupvalc                 C   s
   || _ dS )a  
        Sets whether or not DDPSink should clone the output tensors or not.
        The default is True since if the loss is modified in place we run
        into the view is modified in-place error.

        Although, cloning the tensors can add significant memory and
        performance hit if the number and size of tensors are large. As
        a result, this can be set to False if you are not modifying the
        loss in place.
        N)r   )r   rw  r1   r1   r2   _set_ddp_sink_cloneX	  s   
z+DistributedDataParallel._set_ddp_sink_clone)NNr   TTNNFFFFNNNNr   )TTF)r   )NNr   )F)Vr*   r+   r,   r-   r   r   r0   r&   r   rK  rq  r*  r  r  r
   r3  r5  r  r-  r  r  r+  r  r,  r  r  r   r  classmethodr  r.   _disable_dynamor  r  r  r  r  r  r   r  r  r   r  r   r   r   r   r   r   r%  r&  propertyr'  r)  r   r   r   r-  objectr9  r1  r   r:  r=  r  r  r?  r  r  r  rF  r  r.  r  r   rg  rh  ri  rm  r<  rp  rq  rr  ru  rx  r   r1   r1   r   r2   r%   F  s   
   3  ("	))
(
p.
!


EE
	
j


,QI

	,

 
)Qr  rf  rQ  rZ   loggingr   r  r  r7  collectionsr   r   
contextlibr   dataclassesr   r   r   enumr   r	   typingr
   r   r   r   r.   torch.distributedrb  rl  torch._utilsr   torch.autogradr   r   !torch.distributed.algorithms.joinr   r   r   torch.nn.modulesr    torch.nn.parallel.scatter_gatherr   r   torch.utils._pytreer   r   rE   r\  "torch.distributed.distributed_c10dr   r   r   torch.distributed.utilsr   r   r   r    r!   r"   rpctorch.distributed.rpcr#   torch.utils.hooksr$   __all__	getLoggerr*   r   r&   r;   rC   rL   rM   rV   r   r   r   r   r   r%   r1   r1   r1   r2   <module>   s^    

*	:
!4