Ë
    ÄÓ^j®#  ã                   ód  — U d Z ddlZddlZddlmZ ddlmZmZ ddlm	Z	 ddl
mZmZ ddlmZ ddlmc mc mc mZ  ej*                  «       Zi Zeeef   ed<   ded	efd
„Ze G d„ d«      «       Zded	ed   fd„Z G d„ dej>                  «      Z e G d„ de «      «       Z!e G d„ de «      «       Z"y)a/  
Barrier implementations for synchronizing distributed checkpoint operations.

This module provides abstract and concrete barrier implementations that ensure
all ranks in a distributed training environment complete their checkpoint operations
before proceeding, which is essential for data consistency.
é    N)ÚCounter)Ú	dataclassÚfield)Ú	timedelta)ÚAnyÚOptionalÚBARRIER_REGISTRYÚbarrier_classÚreturnc                 óD   — t        | d«      r| t        | j                  <   | S )z0Register a barrier class in the global registry.Úbarrier_type)Úhasattrr	   r   )r
   s    ú~/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/distributed/checkpoint/_experimental/barriers.pyÚregister_barrierr      s#   € äˆ}˜nÔ-Ø7DÔ˜×3Ñ3Ñ4ØÐó    c                   óL   — e Zd ZU dZdZedz  ed<    ee¬«      Z	eee
f   ed<   y)ÚBarrierConfiga&  
    Configuration for barrier construction.

    This class provides a flexible way to configure different barrier implementations
    with their specific constructor arguments. The barrier type will be looked up
    from a registry and instantiated with rank_info and barrier_args.

    Attributes:
        barrier_type: A string identifying the barrier type (e.g., "tcp_store").
                     If None, no barrier will be used.
        barrier_args: Dictionary of arguments to pass to the barrier constructor.
                     rank_info will be automatically injected as the first argument.

    Examples:
        # No barrier
        BarrierConfig()

        # TCPStore barrier
        BarrierConfig(
            barrier_type="tcp_store",
            barrier_args={
                'timeout_barrier_init_secs': 30,
                'barrier_prefix_list': ['checkpoint'],
                'use_checkpoint_barrier_tcpstore_libuv': False,
                'tcpstore_port': 12345,
                'master_address': 'localhost'
            }
        )
    Nr   )Údefault_factoryÚbarrier_args)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚstrÚ__annotations__r   Údictr   r   © r   r   r   r   "   s.   … ñð<  $€L�#˜‘*Ó#Ù#(¸Ô#>€L�$�s˜C�x‘.Ô>r   r   Úbarrier_configÚBarrierc           	      óö   — | j                   €y| j                   t        vr6t        d| j                   › dt        t        j	                  «       «      › �«      ‚t        | j                      } |di | j
                  ¤ŽS )a&  
    Create a barrier instance from BarrierConfig.

    Args:
        barrier_config: Configuration for barrier construction.

    Returns:
        Barrier instance or None if no barrier type is configured.

    Raises:
        ValueError: If the barrier_type is not found in the registry.
    NzUnknown barrier type: z. Available types: r   )r   r	   Ú
ValueErrorÚlistÚkeysr   )r   r
   s     r   Úcreate_barrier_from_configr$   F   s„   € ð ×"Ñ"Ð*Øà×"Ñ"Ô*:Ñ:ÜØ$ ^×%@Ñ%@Ð$Að B Ü $Ô%5×%:Ñ%:Ó%<Ó =Ð>ð@ó
ð 	
ô
 % ^×%@Ñ%@ÑA€MÙÑ7˜>×6Ñ6Ñ7Ð7r   c                   ój   — e Zd ZdZej
                  deeef   fd„«       Z	ej
                  dd„«       Z
y)r   a(  
    Abstract base class for synchronization barriers.

    A barrier ensures that all ranks in a distributed environment reach a certain
    point in execution before any rank proceeds further, which is essential for
    coordinating operations like checkpointing across multiple processes.
    Úkwargsc                  ó   — y)a+  
        Initialize a barrier.

        Args:
            **kwargs: Keyword arguments for specific barrier implementations.
                     Common arguments may include rank information, barrier prefixes,
                     timeout settings, and other barrier-specific configuration.
        Nr   )Úselfr&   s     r   Ú__init__zBarrier.__init__k   ó   � r   Nc                  ó   — y)z¸
        Execute a synchronization barrier.

        This method uses the barrier_prefix provided during initialization to
        coordinate synchronization across processes.
        Nr   ©r(   s    r   Úexecute_barrierzBarrier.execute_barrierw   r*   r   ©r   N)r   r   r   r   ÚabcÚabstractmethodr   r   r   r)   r-   r   r   r   r   r   b   sJ   „ ñð 	×Ñð  c¨3 h¡ò ó ðð 	×Ñòó ñr   c                   ó(   — e Zd ZdZdZ	 	 dd„Zdd„Zy)ÚDistBarriera2  
    A barrier implementation using PyTorch's distributed barrier for synchronization.

    This barrier uses the built-in torch.distributed.barrier() function to coordinate
    synchronization across multiple processes. It's simpler than TCPStoreBarrier but
    requires an initialized process group.
    Údist_barrierNc                 óB   — t        j                  «       st        d«      ‚y)a/  
        Initialize a DistBarrier.

        This barrier requires an initialized PyTorch distributed process group.
        No additional arguments are needed as it uses the current process group.

        Raises:
            AssertionError: If the distributed process group is not initialized.
        z2DistBarrier requires an initialized process group.N)ÚdistÚis_initializedÚAssertionErrorr,   s    r   r)   zDistBarrier.__init__�   s!   € ô ×"Ñ"Ô$Ü Ð!UÓVÐVð %r   c                 ó,   — t        j                  «        y)zd
        Execute a synchronization barrier using the prefix provided during initialization.
        N)r5   Úbarrierr,   s    r   r-   zDistBarrier.execute_barrierœ   s   € ô 	�‰�r   r.   )r   r   r   r   r   r)   r-   r   r   r   r2   r2   �   s"   „ ñð "€LðWà	óWôr   r2   c                   óD   — e Zd ZdZdZdedededededed	ed
efd„Zdd„Z	y)ÚTCPStoreBarrieraS  
    A barrier implementation using PyTorch's TCPStore for synchronization.

    This barrier uses a TCP-based distributed key-value store to coordinate
    synchronization across multiple processes. It uses a single TCP store
    for all barrier operations, with different prefixes to distinguish between
    different barrier types.
    Ú	tcp_storeÚglobal_rankÚglobal_world_sizeÚbarrier_prefixÚtimeout_barrier_init_secsÚ%use_checkpoint_barrier_tcpstore_libuvÚtcpstore_portÚmaster_addressÚtimeout_secsc	                 ó&  — t         j                  d||||||||«	       t        «       | _        || _        || _        || _        || _        t        j                  |t        |«      | j                  t        |¬«      | j
                  dk(  ¬«      | _        y)aÖ  
        Initialize a TCPStoreBarrier.

        Args:
            global_rank: The rank of the current process in the distributed environment.
            global_world_size: The total number of processes in the distributed environment.
            barrier_prefix: A string prefix to identify this specific barrier.
            timeout_barrier_init_secs: Timeout in seconds for initializing the TCPStore.
            use_checkpoint_barrier_tcpstore_libuv: Whether to use libuv for the TCPStore.
            tcpstore_port: Port number for the TCPStore.
            master_address: Address of the master node for the TCPStore.
            timeout_secs: Maximum time in seconds to wait for all ranks to reach the barrier.
        z¶Initializing TCPStore master_address=%s tcpstore_port=%s rank=%s world_size=%s barrier_prefix=%s timeout_barrier_init_secs=%s use_checkpoint_barrier_tcpstore_libuv=%s timeout_secs=%s)Úsecondsr   )Ú
world_sizeÚtimeoutÚ	is_masterN)ÚloggerÚinfor   Ú_tcp_store_barrier_seqÚ_barrier_prefixÚ_global_rankÚ_global_world_sizeÚ_timeout_secsr5   ÚTCPStoreÚintr   Ú
_tcp_store)	r(   r=   r>   r?   r@   rA   rB   rC   rD   s	            r   r)   zTCPStoreBarrier.__init__²   s›   € ô0 	�‰ðGð ØØØØØ%Ø1Øô	
ô 07«yˆÔ#Ø-ˆÔð (ˆÔØ"3ˆÔØ)ˆÔô Ÿ-™-ØÜ�ÓØ×.Ñ.ÜÐ&?Ô@Ø×(Ñ(¨AÑ-ô
ˆ�r   Nc           	      óº  — | j                   }t        j                  d|| j                  «       dt        dt
        fd„}| j                  j                   || j                  «      t        | j                  |   «      «       t        j                  | j                  | j                  |t        | j                  |   «      z   ¬«       | j                  |xx   dz  cc<   y)a;  
        Execute a synchronization barrier using the prefix provided during initialization.

        The implementation uses a sequence number that is incremented every time
        a barrier is reached. The sequence number is per barrier prefix to allow
        different barriers to operate concurrently.
        z3Executing barrier barrier_prefix=%s timeout_secs=%sÚrankr   c                 ó   — d| › �S )NrU   r   )rU   s    r   Ú	_rank_keyz2TCPStoreBarrier.execute_barrier.<locals>._rank_keyú   s   € Ø˜$˜�=Ð r   )ÚstorerG   Ú
key_prefixé   N)rM   rJ   rK   rP   rR   r   rS   ÚsetrN   rL   Ú
store_utilr9   rO   )r(   r?   rW   s      r   r-   zTCPStoreBarrier.execute_barrierê   sÂ   € ð ×-Ñ-ˆä�‰ØAØØ×Ñô	
ð	!œCð 	!¤Có 	!ð 	�‰×ÑÙ�d×'Ñ'Ó(Ü�×+Ñ+¨NÑ;Ó<ô	
ô 	×ÑØ—/‘/Ø×.Ñ.à¤ T×%@Ñ%@ÀÑ%PÓ!QÑQõ		
ð 	×#Ñ# NÓ3°qÑ8Ô3r   r.   )
r   r   r   r   r   rR   r   Úboolr)   r-   r   r   r   r;   r;   ¥   sg   „ ñð €Lð6
àð6
ð ð6
ð ð	6
ð
 $'ð6
ð 04ð6
ð ð6
ð ð6
ð ó6
ôp!9r   r;   )#r   r/   ÚloggingÚcollectionsr   Údataclassesr   r   Údatetimer   Útypingr   r   Útorch.distributedÚdistributedr5   Ú%torch.distributed.elastic.utils.storeÚelasticÚutilsrX   r\   Ú	getLoggerrJ   r	   r   r   Útyper   r   r   r$   ÚABCr   r2   r;   r   r   r   ú<module>rk      sß   ðòó Û Ý ß (Ý ß  å  ß :Ö :ð 
ˆ×	Ñ	Ó	€ð %'Ð �$�s˜D�y‘/Ó &ð Dð ¨Tó ð ÷ ?ð  ?ó ð ?ðF8Ø!ð8àˆiÑó8ô8ˆc�g‰gô ð> ô �'ó  ó ð ðF ôe9�gó e9ó ñe9r   