U
    dE                     @   s  d Z ddlmZ ddlmZmZmZmZmZm	Z	m
Z
mZmZ ddlZddlmZmZ ddlmZ ddlZddlZddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZm Z  dgZ!e	ej"e#e$f Z%e	ee% ee% f Z&e
e Z'e	ee'f Z(erej)e( Z)ee$e)f Z*n
ej)Z)eZ*e$e$dddZ+ej,ddddZ-ej,eej, eej" ddddZ.G dd de/Z0ej)ej"dddZ1G dd dej,Z2G dd dej)Z3eej) d d!d"Z4ej,eeej, eej" f d#d$d%Z5e6d&Z7G d'd de)Z8dS )(zThe Pipe interface.    )OrderedDict)	TYPE_CHECKINGAnyIterableListOptionalUnionSequenceTuplecastN)Tensornn)RRef   )
microbatch)DeferredBatchNorm)Pipeline)inspect_skip_layout)verify_skippables)AbstractStream
new_streamPipe)messagereturnc                 C   s
   |  dS )zBExpands a message with recommendation to :mod:`torchpipe.balance`.a  

If your model is still under development, its optimal balance would change
frequently. In this case, we highly recommend 'torch.distributed.pipeline.sync.balance' for
naive automatic balancing:

  from torch.distributed.pipeline.sync import Pipe
  from torch.distributed.pipeline.sync.balance import balance_by_time

  partitions = torch.cuda.device_count()
  sample = torch.empty(...)
  balance = balance_by_time(partitions, model, sample)

  model = Pipe(model, balance, ...)
 )r   r   r   H/tmp/pip-unpacked-wheel-ua33x9lu/torch/distributed/pipeline/sync/pipe.py_recommend_auto_balance*   s    r   )moduler   c                 C   s<   t | tjstdt|  }t|t| kr8tdd S )Nz.module must be nn.Sequential to be partitionedz/module with duplicate children is not supported)
isinstancer   
Sequential	TypeErrorlistnamed_childrenlen
ValueError)r   r"   r   r   r   _verify_module=   s
    r%   )r   
partitionsdevicesr   c                 C   s   t t|  }tdd |  D }||kr2d S tt |D ]j}t|d t |D ]R}|| }|| }|| || krzqT| D ]"}	| D ]}
|	|
krtdqqqTq>d S )Nc                 s   s   | ]}t t| V  qd S N)r#   r!   
parameters).0childr   r   r   	<genexpr>J   s     z$_verify_splitting.<locals>.<genexpr>r   zEmodule with duplicate parameters on distinct devices is not supported)r#   r!   r)   sumchildrenranger$   )r   r&   r'   Znum_parametersZnum_child_parametersijZpartiZpartjpqr   r   r   _verify_splittingF   s    r4   c                   @   s   e Zd ZdS )BalanceErrorN)__name__
__module____qualname__r   r   r   r   r5   Z   s   r5   c                 C   sP   d}|   D ],}|dkr |j}q||jkrtd| q|dk	rF|S tdS )a=  Validates all parameters in the Module have the same device and returns
    the appropriate device.

    Args:
        An ``nn.Module`` to process.

    Returns:
        ``torch.Device`` for the entire module.

    Raises:
        ValueError:
            If devices for ``nn.Module`` parameters are not all same.
    Nzunn.Module: {}, should have all parameters on a single device, please use .to() to place the module on a single devicecpu)r)   devicer$   formattorch)r   r:   Z	parameterr   r   r   _retrieve_device^   s    
r=   c                   @   s   e Zd ZdZdd ZdS )PipeSequentialzK
    Pipe variant of ``nn.Sequential`` which supports multiple inputs.
    c                 G   s*   | D ] }t |tr|| }q||}q|S r(   )r   r
   )selfinputsr   r   r   r   forward~   s
    


zPipeSequential.forwardN)r6   r7   r8   __doc__rA   r   r   r   r   r>   y   s   r>   c                       sL   e Zd ZdZejejd fddZdd Z	e
dd Ze
d	d
 Z  ZS )
WithDevicea  
    Wraps an ``nn.Module`` which is part of ``nn.Sequential`` passed into :class:`Pipe`
    that overrides the device for that module. In cases where :class:`Pipe`
    can't implicitly determine the device for the module and places it on CPU,
    this wrapper can be used to override the implicit behavior and explicitly
    specify which device a module should run on.

    The provided module is also moved to the given device via ``.to(device)``
    by :class:`Pipe`

    Args:
        module(:class:`torch.nn.Module`): The module to be wrapped.
        device(:class:`torch.device`): The device to run the module on.

    Example::
        >>> fc1 = nn.Linear(16, 8).cuda(0)
        >>> fc2 = nn.Linear(8, 4).cuda(1)
        >>> dropout = nn.Dropout()
        >>>
        >>> # Dropout does not have any parameters/buffers, but we want to
        >>> # run it on cuda:1 to avoid any GPU to CPU transfers.
        >>> model = nn.Sequential(fc1, fc2, WithDevice(dropout, 'cuda:1'))
        >>> model = Pipe(model, chunks=8)
    )r   r:   c                    s$   t t|   || _t|| _d S r(   )superrC   __init___moduler<   r:   _device)r?   r   r:   	__class__r   r   rE      s    zWithDevice.__init__c                 O   s   | j ||S r(   rF   r?   argskwargsr   r   r   rA      s    zWithDevice.forwardc                 C   s   | j S r(   rJ   r?   r   r   r   r      s    zWithDevice.modulec                 C   s   | j S r(   )rG   rN   r   r   r   r:      s    zWithDevice.device)r6   r7   r8   rB   r   Moduler<   r:   rE   rA   propertyr   __classcell__r   r   rH   r   rC      s   
rC   )modulesc                 C   s<   g }| D ]*}t |tjr(||  q|| qt| S r(   )r   r   r   extendr.   appendr>   )rR   Zmodules_listr   r   r   r   _assemble_partition   s    rU   )rR   r   c                 C   s   g }g }g }d }|   D ]v\}}t|trB|j}|j}|| nt|}|d k	r||ksd|jdkr|t	| || g }|}|| q|d k	r|t	| || t
ttj t|}||fS )Nr9   )r"   r   rC   r:   r   tor=   typerT   rU   r   r   r   r   Z
ModuleList)rR   r&   r'   Zcurrent_partitionZcurrent_devicenamer   r:   r   r   r   _split_module   s*    


rY   zRdenied to move parameters and buffers, because Pipe should manage device placementc                       s   e Zd ZdZdejeeedd fddZ	ed	d
dZ
eejdddZeej d	ddZdee d dddZd d	ddZeed d fddZeee  d	ddZed	ddZ  ZS )r   a  Wraps an arbitrary :class:`nn.Sequential <torch.nn.Sequential>` module
    to train on using synchronous pipeline parallelism. If the module requires
    lots of memory and doesn't fit on a single GPU, pipeline parallelism is a
    useful technique to employ for training.

    The implementation is based on the torchgpipe_ paper.

    .. _torchgpipe: https://arxiv.org/abs/2004.09910

    Pipe combines pipeline parallelism with checkpointing to reduce peak
    memory required to train while minimizing device under-utilization.

    You should place all the modules on the appropriate devices and wrap them
    into an :class:`nn.Sequential <torch.nn.Sequential>` module defining the
    desired order of execution. If a module does not contain any
    parameters/buffers, it is assumed this module should be executed on CPU
    and appropriate input tensors to the module are moved to CPU before
    execution. This behavior can be overridden by the :class:`WithDevice`
    wrapper which can be used to explicitly specify which device a module
    should run on.

    Args:
        module (:class:`nn.Sequential <torch.nn.Sequential>`):
            sequential module to be parallelized using pipelining. Each module
            in the sequence has to have all of its parameters on a single
            device. Each module in the sequence has to either be an nn.Module
            or :class:`nn.Sequential <torch.nn.Sequential>` (to combine multiple
            sequential modules on a single device)
        chunks (int):
            number of micro-batches (default: ``1``)
        checkpoint (str):
            when to enable checkpointing, one of ``'always'``,
            ``'except_last'``, or ``'never'`` (default: ``'except_last'``).
            ``'never'`` disables checkpointing completely, ``'except_last'``
            enables checkpointing for all micro-batches except the last one
            and ``'always'`` enables checkpointing for all micro-batches.
        deferred_batch_norm (bool):
            whether to use deferred ``BatchNorm`` moving statistics (default:
            :data:`False`). If set to :data:`True`, we track statistics across
            multiple micro-batches to update the running statistics per
            mini-batch.

    Raises:
        TypeError:
            the module is not a :class:`nn.Sequential <torch.nn.Sequential>`.
        ValueError:
            invalid arguments

    Example::
        Pipeline of two FC layers across GPUs 0 and 1.

        >>> # Need to initialize RPC framework first.
        >>> os.environ['MASTER_ADDR'] = 'localhost'
        >>> os.environ['MASTER_PORT'] = '29500'
        >>> torch.distributed.rpc.init_rpc('worker', rank=0, world_size=1)
        >>>
        >>> # Build pipe.
        >>> fc1 = nn.Linear(16, 8).cuda(0)
        >>> fc2 = nn.Linear(8, 4).cuda(1)
        >>> model = nn.Sequential(fc1, fc2)
        >>> model = Pipe(model, chunks=8)
        >>> input = torch.rand(16, 16).cuda(0)
        >>> output_rref = model(input)

    .. note::
        You can wrap a :class:`Pipe` model with
        :class:`torch.nn.parallel.DistributedDataParallel` only when the
        checkpoint parameter of :class:`Pipe` is ``'never'``.

    .. note::
        :class:`Pipe` only supports intra-node pipelining currently, but
        will be expanded to support inter-node pipelining in the future.
        The forward function returns an :class:`~torch.distributed.rpc.RRef`
        to allow for inter-node pipelining in the future, where the output
        might be on a remote host. For intra-node pipelinining you can use
        :meth:`~torch.distributed.rpc.RRef.local_value` to retrieve the
        output locally.

    .. warning::
        :class:`Pipe` is experimental and subject to change.
    r   except_lastFN)r   chunks
checkpointdeferred_batch_normr   c                    s   t    tjj stdt|}t|}|dkr>t	d|dkrNt	dt
| t| || _|| _|rzt||}t|\| _| _t|| j| j g | _t| j| _|  }| j| jd dd| j }t| j| j|| j|| _d S )NzMPlease initialize RPC framework for Pipe using torch.distributed.rpc.init_rpcr   z)number of chunks must be positive integer)alwaysrZ   neverz<checkpoint is not one of 'always', 'except_last', or 'never'r   )rD   rE   r<   ZdistributedZrpcZ_is_current_rpc_agent_setRuntimeErrorintstrr$   r%   r   r[   r\   r   Zconvert_deferred_batch_normrY   r&   r'   r4   _copy_streamsr   Z_skip_layout_ensure_copy_streamsr   pipeline)r?   r   r[   r\   r]   Zcopy_streamsZcheckpoint_stoprH   r   r   rE   /  s0    
zPipe.__init__)r   c                 C   s   t dd | jD S )z6Counts the length of the underlying sequential module.c                 s   s   | ]}t |V  qd S r(   )r#   )r*   r2   r   r   r   r,   b  s     zPipe.__len__.<locals>.<genexpr>)r-   r&   rN   r   r   r   __len__`  s    zPipe.__len__)indexr   c              	   C   st   | j }|dk r|ddd }|D ]J}z|| W   S  tk
rF   Y nX t|}|dk rb||7 }q ||8 }q tdS )z1Gets a layer in the underlying sequential module.r   N)r&   
IndexErrorr#   )r?   rg   r&   	partitionshiftr   r   r   __getitem__d  s    

zPipe.__getitem__c                 c   s   | j D ]}|E dH  qdS )z;Iterates over children of the underlying sequential module.N)r&   )r?   rj   r   r   r   __iter__y  s    
zPipe.__iter__)r:   r   c                 C   s   t d S r(   MOVING_DENIED)r?   r:   r   r   r   cuda  s    z	Pipe.cudac                 C   s   t d S r(   rn   rN   r   r   r   r9     s    zPipe.cpu)rL   rM   r   c                    sR   d|ksd|krt |rDt|d tjttfr2t t|d rDt t j||S )Nr:   Ztensorr   )	ro   r   r<   r:   ra   rb   Z	is_tensorrD   rV   rK   rH   r   r   rV     s    
zPipe.toc                    s8   | j s2| jD ]$ | j  fddt| jD  q| j S )a  Ensures that :class:`Pipe` caches CUDA streams for copy.

        It's worth to cache CUDA streams although PyTorch already manages a
        pool of pre-allocated CUDA streams, because it may reduce GPU memory
        fragementation when the number of micro-batches is small.

        c                    s   g | ]}t  qS r   )r   )r*   _r:   r   r   
<listcomp>  s     z-Pipe._ensure_copy_streams.<locals>.<listcomp>)rc   r'   rT   r/   r[   rN   r   rr   r   rd     s    
"zPipe._ensure_copy_streamsc                 G   sp   t | jdkr| jd ntd}tj|f|  | js@t| S tj|d| ji}| j	
| t|}t|S )a  
        Processes a single input mini-batch through the pipe and returns an
        :class:`~torch.distributed.rpc.RRef` pointing to the output.
        :class:`Pipe` is a fairly transparent module wrapper. It doesn't
        modify the input and output signature of the underlying module. But
        there's type restriction. Input and output have to contain at least one
        tensor. This restriction is applied at partition boundaries too.

        The sequence of inputs are fed into the first stage of the pipeline as
        ``*inputs``. As a result the positional args for this function should
        match the positional args for the first stage of the pipeline. The same
        condition applies for output of one stage of the pipeline which is the
        input for the next stage.

        The input tensor is split into multiple micro-batches based on the
        ``chunks`` parameter used to initialize :class:`Pipe`. The batch size
        is assumed to be the first dimension of the tensor and if the batch
        size is less than ``chunks``, the number of micro-batches is equal to
        the batch size.

        Only tensors are split into multiple micro-batches, non-Tensor inputs
        are just replicated as-is in each micro-batch. For non-Tensor outputs
        in the last stage of the pipeline, they are aggregated as a ``List``
        and returned the user. For example, if you have 2 micro-batches
        returning the integer 5, the user would receive the consolidated
        output of `[5, 5]`

        All the input tensors need to be on the same device as the first
        partition of the pipeline.

        If a tensor is wrapped with the :class:`NoChunk` wrapper, the tensor
        is not split across micro-batches and is replicated as-is similar to
        non-tensors.

        Args:
            inputs: input mini-batch

        Returns:
            :class:`~torch.distributed.rpc.RRef` to the output of the mini-batch

        Raises:
            TypeError: input doesn't contain at least one tensor

        r   r9   r[   )r#   r'   r<   r:   r   checkr   Zscatterr[   re   runZgather)r?   r@   Zfirst_partition_deviceZbatchesoutputr   r   r   rA     s    -"
zPipe.forward)r   rZ   F)N)r6   r7   r8   rB   r   r   ra   rb   boolrE   rf   rO   rl   r   rm   r   Devicerp   r9   r   rV   r   r   rd   r   rA   rQ   r   r   rH   r   r      s&   U   1)9rB   collectionsr   typingr   r   r   r   r   r   r	   r
   r   r<   r   r   Ztorch.distributed.rpcr   Ztorch.autogradZ
torch.cuda r   Z	batchnormr   re   r   Zskip.layoutr   Zskip.skippabler   streamr   r   __all__r:   ra   rb   rx   ZDevicesZTensorsZTensorOrTensorsrO   ZNamedModulesr   r   r%   r4   r$   r5   r=   r>   rC   rU   rY   r    ro   r   r   r   r   r   <module>   sL   ,

  *	&