
    Ph7              
          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 g d	Zee   Zeeef   Zed
   Zeeee   ef   Z erejB                  ee ef      Z"nejB                  Z" edd      Z# G d dejB                        Z$	 dde	e%   de	e%   deee"   gee$   f   fdZ& G d d      Z' G d d      Z(dejR                  ddfdZ*y)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            	       R    e Zd ZU dZeee      ed<   eee	      ed<   eee	      ed<   de
de
ddf fd	Zde	fd
Zde	deee	f   fdZdeeee	f      fdZdeeee	f      fdZdddededeee	      defdZdee	ee   gdf   dee	gee   f   fdZdeee
   ef   defdZ x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_namesargskwargsreturnNc                 ^    t         |            | j                  |i || _        i | _        y N)super__init__r#   module
namespaces)selfr&   r'   	__class__s      yC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\torch/distributed/pipeline/sync/skip/skippable.pyr,   zSkippable.__init__?   s,    %doot6v602    c                 "    d| j                    dS )Nz@skippable())r-   )r/   s    r1   __repr__zSkippable.__repr__D   s    T[[M++r2   namec                 `    | j                   j                  |      }t        t        |      }||fS )z*Prepend namespace for the given skip name.)r.   getr   r   )r/   r6   nss      r1   
namespacedzSkippable.namespacedG   s,    __  &)R Dzr2   c              #   T   K   | j                   D ]  }| j                  |        yw)z1Iterate over namespaced skip names to be stashed.N)r$   r:   r/   r6   s     r1   	stashablezSkippable.stashableM   s%     ((D//$'' )   &(c              #   T   K   | j                   D ]  }| j                  |        yw)z0Iterate over namespaced skip names to be popped.N)r%   r:   r<   s     r1   poppablezSkippable.poppableR   s%     ''D//$'' (r>   )onlyr/   r9   rA   c                    || j                   | j                  z  }nt        |      }|D ]  }|| j                  |<    | S )a  Isolate a specified subset or the whole set of skip tensors.

        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

        )r$   r%   setr.   )r/   r9   rA   namesr6   s        r1   isolatezSkippable.isolateW   sH    b <((4+>+>>EIED$&DOOD!  r2   handle_stash
handle_popc                    | j                  |      }t        |t              s|}|S 	 t        |      }	 t        |t              r) ||j
                  |j                         t        |      }:t        |t              r$ ||j
                        }|j                  |      }nt        |d      # t        $ r}|j                  d   }|cY d}~S d}~ww xY w)z}Dispatch :class:`stash` or :class:`pop` commands.

        The commands are generated by the module's ``forward()``.
        z! is not a command from @skippabler   N)r-   
isinstancer	   nextr   r6   tensorr   send	TypeErrorStopIterationr&   )	r/   inputrF   rG   	generatoroutputoprK   stops	            r1   dispatchzSkippable.dispatch   s     KK&	)Y/FM	iBb%( "))4iBb#&'0F"/B2&(I JKK 	YYq\FM	s   BB. .	C7CCCrO   c                     t               }i i t        |      } j                         D ]  \  }}	 |j                  |||      |<    |j                  }dt        dt        t           ddf fd}dt        dt        t           f fd} j                  |||      }	 j                  j                         z
  }
|
r&d	j                  d
 |
D              }t        | d      j                         }|r&d	j                  d |D              }t        | d      t        |	      } j                         D ]  \  }}|   }|j                  ||||         |j                  }	|	S # t        $ r}t        d| d      |d}~ww xY w)a  Perform 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 stashedNr6   rK   r(   c                 J    | j                   vrt        d|  d      || <   y )NrV   z$' has not been declared as stashable)r$   RuntimeError)r6   rK   r/   stashed_tensorss     r1   rF   z'Skippable.forward.<locals>.handle_stash   s0    4///"Qtf,P#QRR$*OD!r2   c                 `    | j                   vrt        d|  d      j                  |       S )NrV   z#' has not been declared as poppable)r%   rX   r   )r6   poppable_tensorsr/   s    r1   rG   z%Skippable.forward.<locals>.handle_pop   s7    4..."Qtf,O#PQQ#''--r2   z, c              3   (   K   | ]
  }d | d   ywrV   N .0ns     r1   	<genexpr>z$Skippable.forward.<locals>.<genexpr>   s     #Bkas!Hk   z must be stashed but have notc              3   (   K   | ]
  }d | d   ywr]   r^   r_   s     r1   rb   z$Skippable.forward.<locals>.<genexpr>   s     #Ajas!Hjrc   z must be popped but have not)r   r   r@   loadKeyErrorrX   valuesstrr   r   rT   r$   keysjoinr=   save)r/   rO   skip_trackerbatchr9   r6   erF   rG   rQ   not_stashedcomma_names
not_poppedrK   r[   rY   s   `             @@r1   forwardzSkippable.forward   s    ,-79 eHBL)5):):5"d)K & (
 	+s 	+HV,< 	+ 	+
	.S 	.Xf%5 	.
 ulJ? **_-A-A-CC))#Bk#BBK+.KLMM%**,
))#Aj#AAK+.JKLL f(HB$T*FeRv6 ) G  L"Qtf,B#CD!KLs   E((	F1FF)__name__
__module____qualname____doc__r   r   SkippableModule__annotations__r   rh   r   r,   r5   r   r   r:   r
   r=   r@   r   r   rE   r   r   rT   r   r   TensorOrTensorsrr   __classcell__)r0   s   @r1   r    r    3   sA    o.//in--Ys^,,3c 3S 3T 3
,# ,s uY^'< (8E)S.$9: (
((5C#89 (
 LP 9a 9Y 9(3-1H 9TU 9v# Xf%56<=# cUHV$445	#J7U49f#45 7/ 7r2   r   r   r(   c                 x    t        |       t        |      dt        t           dt        t           ffd}|S )a  Define a decorator to create :class:`nn.Module <torch.nn.Module>` with skip connections.

    These 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                 P    | j                   }t        f}| d}t        |||      S )N)r#   r$   r%   )rs   r    type)r#   r6   basesattrsr%   r$   s       r1   extend_skippablez#skippable.<locals>.extend_skippable)  s1    "")oaopD%''r2   )	frozensetr   rw   r    )r   r   r   r%   r$   s      @@r1   r   r      s=    h  &Os^N(T/%: (tI ( r2   c                   .    e Zd ZdZdZdedee   ddfdZy)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

    r6   rK   r6   rK   r(   Nc                      || _         || _        y r*   r   )r/   r6   rK   s      r1   r,   zstash.__init__C  s    	r2   )	rs   rt   ru   rv   	__slots__rh   r   r   r,   r^   r2   r1   r   r   2  s-     #IS (6*: t r2   c                   $    e Zd ZdZdZdeddfdZy)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

    r6   r6   r(   Nc                     || _         y r*   r   r<   s     r1   r,   zpop.__init__[  s	    	r2   )rs   rt   ru   rv   r   rh   r,   r^   r2   r1   r   r   H  s!      IS T r2   r-   Nc                 8   t               }t               }g }| j                         D ]&  \  }}t        |t              s|j                  |j
                  z  D ]  }d| d| d}|j                  |        |j                         D ]H  \  }}||j
                  v r||f|v rd| d| d}|j                  |       6|j                  ||f       J |j                         D ]i  \  }}||j                  v r||f|v rd| d| d}|j                  |       6||f|vrd| d| d}|j                  |       W|j                  ||f       k ) ||z
  D ]  \  }	}d| d	}|j                  |        |r$t        d
dj                  d |D              z        y)u  Verify 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.

    rV   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              3   &   K   | ]	  }d |z    yw)z* %sNr^   )r`   xs     r1   rb   z$verify_skippables.<locals>.<genexpr>  s     SmhlcdTZ]^T^hls   N)rC   named_childrenrI   r    r$   r%   appendr=   addr@   rM   rj   )
r-   stashedpoppedmsgs
layer_namelayerr6   msgr9   _s
             r1   r   r   _  s   D +.%G),FD#224
E%+))E,@,@@Dj\dV3VWCKK A )HBu+++DzW$*^D69efC KKT
# * (HBu,,,DzV#*^D69deC Dz(*\$7[\C JJDz" )' 5F v%	D$TF*CDC & G$))SmhlSmJmm
 	
 r2   )r^   r^   )+rv   typingr   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   torchr   r   
microbatchr   	namespacer   trackerr   __all__Tensorsry   StashPopStashPopGeneratorModulerw   r   r    rh   r   r   r   
Sequentialr   r^   r2   r1   <module>r      s$   5    (     )
< 6
( h(8/IJ ii&7&H IJOiiOC{#{		 {@ 57=C==$,SM=tO$%tI67=@ , .P
bmm P
 P
r2   