U
    Jce6                     @   sZ  d Z ddlmZmZmZmZmZmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZ ddlmZmZ ddlmZ ddlmZ ddlmZ d	d
ddgZee Zeeef Zed Zeeee ef Z erej!ee ef  Z"nej!Z"edddZ#G dd dej!Z$de	e% e	e% eee" gee$ f ddd	Z&G dd
 d
Z'G dd dZ(ej)ddddZ*dS )z.The user interface to define skip connections.    )TYPE_CHECKINGAnyCallableClassVarDict	FrozenSet	GeneratorIterableListOptionalSetSequenceTupleTypeTypeVarUnioncast)Tensornn   )Batch   )	Namespace)current_skip_tracker	skippablestashpopverify_skippables)r   r   T	Skippable)boundc                       s"  e Zd ZU dZeee  ed< eee	  ed< eee	  ed< e
e
dd fddZe	d	d
dZe	eee	f dddZeeee	f  d	ddZeeee	f  d	ddZddeeeee	  edddZee	ee gdf ee	gee f dddZeee
 ef edddZ  ZS )r   zThe base class for skippable modules.

    Do not use this class directly. Define a subclass by :func:`skippable`
    instead.

    
module_clsstashable_namespoppable_namesN)argskwargsreturnc                    s"   t    | j||| _i | _d S N)super__init__r!   module
namespaces)selfr$   r%   	__class__ R/tmp/pip-unpacked-wheel-gikjz4vx/torch/distributed/pipeline/sync/skip/skippable.pyr)   @   s    
zSkippable.__init__)r&   c                 C   s   d| j  dS )Nz@skippable())r*   )r,   r/   r/   r0   __repr__E   s    zSkippable.__repr__namer&   c                 C   s   | j |}tt|}||fS )z+Prepends namespace for the given skip name.)r+   getr   r   )r,   r4   nsr/   r/   r0   
namespacedH   s    
zSkippable.namespacedc                 c   s   | j D ]}| |V  qdS )z2Iterates over namespaced skip names to be stashed.N)r"   r7   r,   r4   r/   r/   r0   	stashableN   s    
zSkippable.stashablec                 c   s   | j D ]}| |V  qdS )z1Iterates over namespaced skip names to be popped.N)r#   r7   r8   r/   r/   r0   poppableS   s    
zSkippable.poppable)only)r,   r6   r;   r&   c                C   s6   |dkr| j | jB }nt|}|D ]}|| j|< q"| S )a  Isolates a specified subset or the whole set of skip tensors into a
        namespace. In a single sequential module, skip tensors with the same
        name are not allowed unless they are isolated by different namespaces.

        Here's an example using the same name for skip tensors twice. Each pair
        of ``Layer1`` and ``Layer2`` is isolated with its own namespace ``ns1``
        and ``ns2``. There is no conflict anymore::

            ns1 = Namespace()
            ns2 = Namespace()

            model = nn.Sequential(
                Layer1().isolate(ns1),
                Layer1().isolate(ns2),
                Layer2(),
                Layer3().isolate(ns2),
                Layer3().isolate(ns1),
            )

        When `only` parameter is omitted, all skip tensors are isolated. You
        can isolate a subset of skip tensors by passing `only` parameter::

            ns_alice = Namespace()
            ns_bob = Namespace()

            model = nn.Sequential(
                ...
                StashStashPop().isolate(ns_alice, only=['alice']) \
                               .isolate(ns_bob, only=['bob']),
                ...
            )

        Args:
            ns (Namespace):
                namespace for isolation

        Keyword Args:
            only (iterable of strs):
                names of specific skip tensors to be isolated (omit this option
                to isolate all skip tensors declared in this module)

        Returns:
            this module itself

        N)r"   r#   setr+   )r,   r6   r;   namesr4   r/   r/   r0   isolateX   s    0zSkippable.isolate)handle_stash
handle_popc           	   
   C   s   |  |}t|ts|}|S z\t|}t|trH||j|j t|}q&t|trh||j}||}q&t	d| q&W n4 t
k
r } z|jd }| W Y S d}~X Y nX dS )zlDispatches :class:`stash` or :class:`pop` commands generated by the
        module's ``forward()``.
        z#%r is not a command from @skippabler   N)r*   
isinstancer   nextr   r4   tensorr   send	TypeErrorStopIterationr$   )	r,   inputr?   r@   	generatoroutputoprC   stopr/   r/   r0   dispatch   s$    	






zSkippable.dispatch)rG   r&   c              	      sP  t  }i i  t|} D ]D\}}z|||| |< W q tk
r`   td| dY qX q|j}ttt	 ddfdd}ttt	 d fdd	}
|||}j  }	|	rd
dd |	D }
t|
 d  }|rd
dd |D }
t|
 dt|} D ]"\}}| }||||| q"|j}|S )a  Performs the forward propagation. :class:`stash` or :class:`pop`
        commands will be handled by portals silently. The portals won't be
        exposed to users.

        Raises:
            RuntimeError:
                illegal 'stash' or 'pop' is found.

        'z' has not been stashedNr4   rC   r&   c                    s&   |  j krtd|  d|| < d S )NrM   z$' has not been declared as stashable)r"   RuntimeErrorr4   rC   )r,   stashed_tensorsr/   r0   r?      s    
z'Skippable.forward.<locals>.handle_stashr3   c                    s$   | j krtd|  d | S )NrM   z#' has not been declared as poppable)r#   rO   r   r4   )poppable_tensorsr,   r/   r0   r@      s    
z%Skippable.forward.<locals>.handle_popz, c                 s   s   | ]}d | V  qdS z'%s'Nr/   .0nr/   r/   r0   	<genexpr>   s     z$Skippable.forward.<locals>.<genexpr>z must be stashed but have notc                 s   s   | ]}d | V  qdS rT   r/   rU   r/   r/   r0   rX      s     z must be popped but have not)r   r   r:   loadKeyErrorrO   valuesstrr   r   rL   r"   keysjoinr9   save)r,   rG   Zskip_trackerbatchr6   r4   r?   r@   rI   Znot_stashedZcomma_namesZ
not_poppedrC   r/   )rS   r,   rQ   r0   forward   s6    
zSkippable.forward)__name__
__module____qualname____doc__r   r   SkippableModule__annotations__r   r\   r   r)   r2   r   r   r7   r	   r9   r:   r   r   r>   r   r   rL   r   r
   TensorOrTensorsra   __classcell__r/   r/   r-   r0   r   4   s   
"=$r/   )r   r   r&   c                    s2   t | t | tt tt d fdd}|S )a  The decorator to define a :class:`nn.Module <torch.nn.Module>` with skip
    connections. Decorated modules are called "skippable". This functionality
    works perfectly fine even when the module is not wrapped by
    :class:`~torch.distributed.pipeline.sync.Pipe`.

    Each skip tensor is managed by its name. Before manipulating skip tensors,
    a skippable module must statically declare the names for skip tensors by
    `stash` and/or `pop` parameters. Skip tensors with pre-declared name can be
    stashed by ``yield stash(name, tensor)`` or popped by ``tensor = yield
    pop(name)``.

    Here is an example with three layers. A skip tensor named "1to3" is stashed
    and popped at the first and last layer, respectively::

        @skippable(stash=['1to3'])
        class Layer1(nn.Module):
            def forward(self, input):
                yield stash('1to3', input)
                return f1(input)

        class Layer2(nn.Module):
            def forward(self, input):
                return f2(input)

        @skippable(pop=['1to3'])
        class Layer3(nn.Module):
            def forward(self, input):
                skip_1to3 = yield pop('1to3')
                return f3(input) + skip_1to3

        model = nn.Sequential(Layer1(), Layer2(), Layer3())

    One skippable module can stash or pop multiple skip tensors::

        @skippable(stash=['alice', 'bob'], pop=['carol'])
        class StashStashPop(nn.Module):
            def forward(self, input):
                yield stash('alice', f_alice(input))
                yield stash('bob', f_bob(input))
                carol = yield pop('carol')
                return input + carol

    Every skip tensor must be associated with exactly one pair of `stash` and
    `pop`. :class:`~torch.distributed.pipeline.sync.Pipe` checks this
    restriction automatically when wrapping a module. You can also check the
    restriction by :func:`verify_skippables`
    without :class:`~torch.distributed.pipeline.sync.Pipe`.

    )r!   r&   c                    s$   | j }tf}|  d}t|||S )N)r!   r"   r#   )rb   r   type)r!   r4   basesattrsr#   r"   r/   r0   extend_skippable'  s    z#skippable.<locals>.extend_skippable)	frozensetr   rf   r   )r   r   rn   r/   rm   r0   r      s    4c                   @   s*   e Zd ZdZdZeee ddddZdS )r   a  The command to stash a skip tensor.

    ::

        def forward(self, input):
            yield stash('name', input)
            return f(input)

    Args:
        name (str): name of skip tensor
        input (torch.Tensor or None): tensor to pass to the skip connection

    rP   NrN   c                 C   s   || _ || _d S r'   rP   )r,   r4   rC   r/   r/   r0   r)   A  s    zstash.__init__)	rb   rc   rd   re   	__slots__r\   r   r   r)   r/   r/   r/   r0   r   0  s   c                   @   s$   e Zd ZdZdZeddddZdS )r   a+  The command to pop a skip tensor.

    ::

        def forward(self, input):
            skip = yield pop('name')
            return f(input) + skip

    Args:
        name (str): name of skip tensor

    Returns:
        the skip tensor previously stashed by another layer under the same name

    rR   Nr3   c                 C   s
   || _ d S r'   rR   r8   r/   r/   r0   r)   Y  s    zpop.__init__)rb   rc   rd   re   rp   r\   r)   r/   r/   r/   r0   r   F  s   N)r*   r&   c           
      C   s  t  }t  }g }|  D ]\}}t|ts.q|j|j@ D ] }d| d| d}|| q:| D ]L\}}||jkrxqd||f|krd| d| d}|| qd|||f qd|	 D ]x\}}||jkrq||f|krd| d| d}|| q||f|kr$d| d| d}|| q|||f qq|| D ] \}	}d| d	}|| q>|rt
d
ddd |D  dS )u  Verifies if the underlying skippable modules satisfy integrity.

    Every skip tensor must have only one pair of `stash` and `pop`. If there
    are one or more unmatched pairs, it will raise :exc:`TypeError` with the
    detailed messages.

    Here are a few failure cases. :func:`verify_skippables` will report failure
    for these cases::

        # Layer1 stashes "1to3".
        # Layer3 pops "1to3".

        nn.Sequential(Layer1(), Layer2())
        #               └──── ?

        nn.Sequential(Layer2(), Layer3())
        #                   ? ────┘

        nn.Sequential(Layer1(), Layer2(), Layer3(), Layer3())
        #               └───────────────────┘       ^^^^^^

        nn.Sequential(Layer1(), Layer1(), Layer2(), Layer3())
        #             ^^^^^^      └───────────────────┘

    To use the same name for multiple skip tensors, they must be isolated by
    different namespaces. See :meth:`isolate()
    <torchpipe.skip.skippable.Skippable.isolate>`.

    Raises:
        TypeError:
            one or more pairs of `stash` and `pop` are not matched.

    rM   z' declared 'z#' both as stashable and as poppablez' redeclared 'z,' as stashable but not isolated by namespacez+' as poppable but not isolated by namespacez$' as poppable but it was not stashedzno module declared 'z' as poppable but stashedz4one or more pairs of stash and pop do not match:

%s
c                 s   s   | ]}d | V  qdS )z* %sNr/   )rV   xr/   r/   r0   rX     s     z$verify_skippables.<locals>.<genexpr>N)r<   Znamed_childrenrA   r   r"   r#   appendr9   addr:   rE   r^   )
r*   ZstashedpoppedZmsgsZ
layer_nameZlayerr4   msgr6   _r/   r/   r0   r   ]  sH    "





)r/   r/   )+re   typingr   r   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   Ztorchr   r   Z
microbatchr   	namespacer   trackerr   __all__ZTensorsrh   ZStashPopZStashPopGeneratorModulerf   r   r   r\   r   r   r   Z
Sequentialr   r/   r/   r/   r0   <module>   s4   L >    @