U
    Jºc  ã                   @   sn   U d Z ddlmZmZmZmZ ddlmZ ddlm	Z	 g Z
ee ed< G dd„ dƒZeej ed	œd
d„ZdS )z8Static skip connection layout of ``@skippable`` modules.é    )ÚDictÚIterableÚListÚTuple)Únné   )Ú	NamespaceÚ__all__c                   @   s¦   e Zd ZU dZeeeef eeef f e	d< e
e
eeeef   e	d< eeeeef eeef f ddœdd„Zeeeeeef  dœd	d
„Zeeedœdd„ZdS )Ú
SkipLayoutz6Represents a skip connection layout across partitions.Ú
by_ns_nameÚby_partitionN)Únum_partitionsÚskip_routesÚreturnc                 C   sb   || _ dd„ t|ƒD ƒ| _| ¡ D ]&\\}}\}}| j|  |||f¡ q"| jD ]}| ¡  qPd S )Nc                 S   s   g | ]}g ‘qS © r   )Ú.0Ú_r   r   úO/tmp/pip-unpacked-wheel-gikjz4vx/torch/distributed/pipeline/sync/skip/layout.pyÚ
<listcomp>   s     z'SkipLayout.__init__.<locals>.<listcomp>)r   Úranger   ÚitemsÚappendÚsort)Úselfr   r   ÚnsÚnameÚprev_jÚnext_jÚpr   r   r   Ú__init__   s    
zSkipLayout.__init__)r   r   c                 c   s0   | j | D ] \}}}||krq
|||fV  q
dS )züGenerates skip routes for the given destination partition number.
        The skip routes are sorted by source partition number in ascending
        order.

        Yields:
            Each tuple of (source partition number, namespace, name).

        N)r   )r   r   r   r   r   r   r   r   Úcopy_policy'   s    	zSkipLayout.copy_policy)r   r   r   c                 C   s   | j  ||fd¡\}}||kS )zbWhether the given namespace and name requires partition-to-partition
        copy or not.
        )éÿÿÿÿr!   )r   Úget)r   r   r   r   r   r   r   r   Úrequires_copy8   s    zSkipLayout.requires_copy)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   ÚstrÚintÚ__annotations__r   r   r   r    Úboolr#   r   r   r   r   r
      s   
 *r
   )Ú
partitionsr   c                    sn   ddl m‰  i ‰i ‰t| ƒD ]B\‰}‡ ‡‡‡fdd„}t|tjƒrV|D ]}||ƒ qFq||ƒ qtt| ƒˆƒS )z<Inspects the skip connection layout in the given partitions.r   )Ú	Skippablec                    s`   t | ˆ ƒsd S |  ¡ D ]\}}ˆˆ||f< q|  ¡ D ]&\}}ˆ ||f¡}|ˆfˆ||f< q4d S )N)Ú
isinstanceZ	stashableZpoppableÚpop)Úlayerr   r   r   ©r-   Újr   Z
stashed_atr   r   Úinspect_layerK   s    
z*inspect_skip_layout.<locals>.inspect_layer)Z	skippabler-   Ú	enumerater.   r   Ú
Sequentialr
   Úlen)r,   Ú	partitionr3   r0   r   r1   r   Úinspect_skip_layout@   s    
r8   N)r'   Útypingr   r   r   r   Ztorchr   Ú	namespacer   r	   r(   r*   r
   r5   r8   r   r   r   r   Ú<module>   s   /