
    sg                     2   d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dl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ZmZmZmZmZmZmZmZ d dlmZ d dlmZ d dlmZ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+m,Z,m-Z- g dZ. ej^                  e0      Z1d@dZ2eZ3	  G d de	      Z4 G d d      Z5 eddd       G d d             Z6 eddd       G d d             Z7 G d d      Z8 G d d      Z9de9de6d dfd!Z: G d" d#e	      Z; G d$ d%e;      Z< G d& d'e      Z= G d( d)      Z> G d* d+e	      Z? G d, d-e?      Z@d.e>d eAfd/ZB G d0 d1      ZC G d2 d3      ZD G d4 d5      ZE G d6 d7      ZF G d8 d9e%      ZGd:e'd;eHd ee   fd<ZId=ed>e4d:e'd eGfd?ZJy)A    N)ABCabstractmethod)	dataclass)datetime	timedelta)Enum)AnyCallablecastDictListOptionalSetTuple)Store)construct_and_record_rdzv_event	NodeState   )	RendezvousClosedErrorRendezvousErrorRendezvousGracefulExitErrorRendezvousHandlerRendezvousInfoRendezvousParametersRendezvousStateErrorRendezvousStoreInfoRendezvousTimeoutError)_delay_PeriodicTimer)RendezvousBackendRendezvousTimeoutRendezvousSettingsDynamicRendezvousHandlercreate_handlerc                     t        t        j                               | kD  r!t        j                         |    j                  S y)Nno_method_name)leninspectstackfunction)depths    j/var/www/html/venv/lib/python3.12/site-packages/torch/distributed/elastic/rendezvous/dynamic_rendezvous.pyget_method_namer-   3   s/    
7==?e#}}u%...    c                       e Zd ZdZeedefd              Zedee	e
ef      fd       Ze	 d	de
dee   dee	e
eef      fd       Zy)
r    z4Represent a backend that holds the rendezvous state.returnc                      y)zGet the name of the backend.N selfs    r,   namezRendezvousBackend.name@       r.   c                      y)a  Get the rendezvous state.

        Returns:
            A tuple of the encoded rendezvous state and its fencing token or
            ``None`` if no state is found in the backend.

        Raises:
            RendezvousConnectionError:
                The connection to the backend has failed.
            RendezvousStateError:
                The rendezvous state is corrupt.
        Nr2   r3   s    r,   	get_statezRendezvousBackend.get_stateE   r6   r.   Nstatetokenc                      y)a  Set the rendezvous state.

        The new rendezvous state is set conditionally:

          - If the specified ``token`` matches the fencing token stored in the
            backend, the state will be updated. The new state will be returned
            to the caller along with its fencing token.
          - If the specified ``token`` does not match the fencing token stored
            in the backend, the state won't be updated; instead the existing
            state along with its fencing token will be returned to the caller.
          - If the specified ``token`` is ``None``, the new state will be set
            only if there is no existing state in the backend. Either the new
            state or the existing state along with its fencing token will be
            returned to the caller.

        Args:
            state:
                The encoded rendezvous state.
            token:
                An optional fencing token that was retrieved by a previous call
                to :py:meth:`get_state` or ``set_state()``.

        Returns:
            A tuple of the serialized rendezvous state, its fencing token, and
            a boolean value indicating whether our set attempt succeeded.

        Raises:
            RendezvousConnectionError:
                The connection to the backend has failed.
            RendezvousStateError:
                The rendezvous state is corrupt.
        Nr2   )r4   r9   r:   s      r,   	set_statezRendezvousBackend.set_stateT   r6   r.   N)__name__
__module____qualname____doc__propertyr   strr5   r   r   bytesTokenr8   boolr<   r2   r.   r,   r    r    =   s    >+c +  + 8E%,$78   59""#+E?"	%ud*+	," "r.   r    c                   8   e Zd ZU dZ ed      Z ed       ed       ed       ed      dZeed<   eed	<   eed
<   eed<   	 	 	 	 ddee   dee   dee   dee   ddf
dZ	e
defd       Ze
defd       Ze
defd       Ze
defd       Zdee   fdZy)r!   a  Hold the timeout configuration of a rendezvous.

    Args:
        join:
            The time within which the rendezvous is expected to complete.
        last_call:
            An additional wait amount before completing the rendezvous once the
            rendezvous has the minimum number of required participants.
        close:
            The time within which the rendezvous is expected to close after a
            call to :py:meth:`RendezvousHandler.set_closed` or
            :py:meth:`RendezvousHandler.shutdown`.
        keep_alive:
            The time within which a keep-alive heartbeat is expected to
            complete.
    r   iX  seconds      join	last_callclose	heartbeat_join
_last_call_close
_heartbeatNrM   rN   rO   rP   r0   c                 .    | j                  ||||       y )NrL   )_set_timeouts)r4   rM   rN   rO   rP   s        r,   __init__zRendezvousTimeout.__init__   s      	%9 	 	
r.   c                     | j                   S )zGet the join timeout.)rQ   r3   s    r,   rM   zRendezvousTimeout.join   s     zzr.   c                     | j                   S )zGet the last call timeout.)rR   r3   s    r,   rN   zRendezvousTimeout.last_call        r.   c                     | j                   S )zGet the close timeout.)rS   r3   s    r,   rO   zRendezvousTimeout.close        {{r.   c                     | j                   S )z%Get the keep-alive heartbeat timeout.)rT   r3   s    r,   rP   zRendezvousTimeout.heartbeat   rZ   r.   timeoutsc                     |j                         D ]G  \  }}|| j                  |   }|| j                  k  rt        d| d| d      t	        | d|z   |       I y )NzThe z
 timeout (z) must be positive._)items_DEFAULT_TIMEOUTS_ZERO
ValueErrorsetattr)r4   r^   r5   timeouts       r,   rV   zRendezvousTimeout._set_timeouts   sh    %^^- 	/MD'006$**$ 4vZy@S!TUUD#*g.	/r.   )NNNN)r>   r?   r@   rA   r   rc   rb   __annotations__r   rW   rB   rM   rN   rO   rP   rV   r2   r.   r,   r!   r!   z   s*   " aLE #&r*2&q)	  %))-%))-	
y!	
 I&	
 	"		

 I&	
 
	
 i   9   y   9  /(; /r.   r!   FT)repreqfrozenc                   N    e Zd ZU dZeed<   eed<   eed<   eed<   eed<   eed<   y)	r"   a  Hold the settings of the rendezvous.

    Attributes:
        run_id:
            The run id of the rendezvous.
        min_nodes:
            The minimum number of nodes to admit to the rendezvous.
        max_nodes:
            The maximum number of nodes to admit to the rendezvous.
        timeout:
            The timeout configuration of the rendezvous.
        keep_alive_interval:
            The amount of time a node waits before sending a heartbeat to keep
            it alive in the rendezvous.
        keep_alive_max_attempt:
            The maximum number of failed heartbeat attempts after which a node
            is considered dead.
    run_id	min_nodes	max_nodesrf   keep_alive_intervalkeep_alive_max_attemptN)	r>   r?   r@   rA   rC   rg   intr!   r   r2   r.   r,   r"   r"      s*    & KNN""r.   r"   )ri   orderrj   c                   <    e Zd ZU dZeed<   eed<   eed<   defdZy)	_NodeDesca  Describe a node in the rendezvous.

    Attributes:
        addr:
            The FQDN of the node or user specified local node address.
        pid:
            The id of the process in which the rendezvous handler runs.
        local_id:
            A process-wide unique id.
    addrpidlocal_idr0   c                 R    | j                    d| j                   d| j                   S )Nr`   )ru   rv   rw   r3   s    r,   __repr__z_NodeDesc.__repr__   s%    ))AdhhZq88r.   N)r>   r?   r@   rA   rC   rg   rq   ry   r2   r.   r,   rt   rt      s$    	 I	HM9# 9r.   rt   c                   Z    e Zd ZU dZej
                  ed<   eed<   d	dZd
de	e
   defdZy)_NodeDescGeneratorzGenerate node descriptors.

    A node descriptor is a combination of an FQDN, a process id, and an auto-
    incremented integer that uniquely identifies a node in the rendezvous.
    _lock	_local_idr0   Nc                 D    t        j                         | _        d| _        y )Nr   )	threadingLockr|   r}   r3   s    r,   rW   z_NodeDescGenerator.__init__   s    ^^%
 r.   
local_addrc                     | j                   5  | j                  }| xj                  dz  c_        d d d        t        |xs t        j                         t        j                               S # 1 sw Y   >xY w)Nr   )r|   r}   rt   socketgetfqdnosgetpid)r4   r   rw   s      r,   generatez_NodeDescGenerator.generate  sZ     ZZ 	 ~~HNNaN	 
 7v~~'7hOO	  	 s   "A,,A5r0   Nr=   )r>   r?   r@   rA   r   r   rg   rq   rW   r   rC   rt   r   r2   r.   r,   r{   r{      s7     >>NP8C= PI Pr.   r{   c                       e Zd ZU dZeed<   eed<   ee   ed<   eed<   e	e
ef   ed<   ee
   ed<   ee
   ed<   e	e
ef   ed	<   ddZy
)_RendezvousStatea  Hold the state of a rendezvous.

    Attributes:
        round:
            The current round of the rendezvous.
        complete:
            A boolean value indicating whether the current round of the
            rendezvous is complete.
        deadline:
            The time at which the current round of the rendezvous will be
            considered complete if it is still waiting for nodes to join.
        closed:
            A boolean value indicating whether the rendezvous is closed.
        participants:
            A dictionary of the participants and their corresponding ranks.
        wait_list:
            A set of nodes that are waiting to participate in the next round of
            the rendezvous.
        redundancy_list:
            A set of nodes that are redundant in the current round and can join
            the next rendezvous without triggering re-rendezvous.
        last_heartbeats:
            A dictionary containing each node's last heartbeat time.
    roundcompletedeadlineclosedparticipants	wait_listredundancy_listlast_heartbeatsNc                     d| _         d| _        d | _        d| _        i | _        t               | _        t               | _        i | _        y )Nr   F)	r   r   r   r   r   setr   r   r   r3   s    r,   rW   z_RendezvousState.__init__2  sA    
"u!r.   r   )r>   r?   r@   rA   rq   rg   rF   r   r   r   rt   r   rW   r2   r.   r,   r   r     s[    2 JNx  Ly#~&&9~^#)X-.."r.   r   r9   settingsr0   c                 h   | j                   rA| j                  s4d}t        j                  |       d| _         | xj                  dz  c_        y y t        | j                        |j                  k  rCdt        | j                         d|j                   d}t        j                  |       d | _        y y )NzHNo participants left in the rendezvous, marking rendezvous as incompleteFr   zNumber of participants z) less thanmin_nodes z, clearning deadline in state)r   r   loggerdebugr   r'   rm   r   )r9   r   msgs      r,   _remove_participant_epiloguer   =  s     ~~!!\CLL"ENKK1K " u!!"X%7%77)#e.@.@*A)B C%//00MO  LL!EN 8r.   c                   ^    e Zd ZdZeedefd              Zedee	   fd       Z
edd       Zy)_RendezvousStateHolderz9Hold the shared rendezvous state synced with other nodes.r0   c                      y)zGet the local state.Nr2   r3   s    r,   r9   z_RendezvousStateHolder.stateU  r6   r.   c                      y)zRead or writes the latest state.

        Returns:
            A boolean value indicating whether the local state, in case marked
            as dirty, was successfully synced with other nodes.
        Nr2   r3   s    r,   syncz_RendezvousStateHolder.syncZ  r6   r.   Nc                      y)zMark the local state as dirty.Nr2   r3   s    r,   
mark_dirtyz!_RendezvousStateHolder.mark_dirtyc  r6   r.   r   )r>   r?   r@   rA   rB   r   r   r9   r   rF   r   r   r2   r.   r,   r   r   R  sZ    C#' #  # htn   - -r.   r   c            	           e Zd ZU dZeed<   eed<   eed<   eed<   e	ed<   e
ed<   eed<   ee   ed	<   	 dd
edededdfdZej                   fdedefdZedefd       Zdee
   fdZddZddZy)_BackendRendezvousStateHolderac  Hold the rendezvous state synced with other nodes via a backend.

    Args:
        backend:
            The rendezvous backend to use.
        settings:
            The rendezvous settings.
        cache_duration:
            The amount of time, in seconds, to cache the last rendezvous state
            before requesting it from the backend again.
    _backend_state	_settings_cache_duration_token_dirty_last_sync_time_dead_nodesbackendr   cache_durationr0   Nc                     || _         t               | _        || _        || _        d | _        d| _        d| _        g | _        y )NF)	r   r   r   r   r   r   r   r   r   )r4   r   r   r   s       r,   rW   z&_BackendRendezvousStateHolder.__init__~  sB      &(!-!r.   message
node_statec                     t        | j                  j                   dt                | j                  j
                  ||       y )N.)r5   rl   r   r   )r   	__class__r>   r-   r   rl   r4   r   r   s      r,   _recordz%_BackendRendezvousStateHolder._record  s:    'NN++,Ao.?-@A>>((!		
r.   c                     | j                   S See base class.)r   r3   s    r,   r9   z#_BackendRendezvousStateHolder.state  r\   r.   c                    d}d}| j                   rPd}t        j                  | j                        }| j                  j                  || j                        }|r|\  }}}nkd}| j                  dkD  r9| j                  t        t        j                         | j                  z
  d      k\  ry| j                  j                         }||\  }}|	 t        j                  |      | _        nt!               | _        |r| j"                  rt$        j'                  t(        j*                        rfdj-                  d | j"                  D              }d| d| j.                  j0                   d	}| j3                  |
       t$        j5                  |       || _        d| _         t        j                         | _        | j7                          |S # t        j                  $ r}t        d      |d}~ww xY w)r   NFr   zAThe rendezvous state is corrupt. See inner exception for details.z, c              3   (   K   | ]
  }d | d   yw)'Nr2   ).0	dead_nodes     r,   	<genexpr>z5_BackendRendezvousStateHolder.sync.<locals>.<genexpr>  s     !UyAi["2!Us   z*As part of the sync operation the node(s) z( have been removed from the rendezvous 'z' since they had no heartbeat.r   )r   pickledumpsr   r   r<   r   r   r   maxtime	monotonicr8   loadsPickleErrorr   r   r   r   isEnabledForloggingDEBUGrM   r   rl   r   r   	_sanitize)	r4   
state_bitsr:   has_setset_responseget_responseexc	node_listr   s	            r,   r   z"_BackendRendezvousStateHolder.sync  s   &*
 ;;Gdkk2J==22:t{{KL'-9*
E7G##a' ''3NN$t';';;Q,   ==224L'$0!
E!$ll:6 +,DKt''F,?,?,N		!UDDTDT!UUI =YK H#~~4455SU  LLL%LL#~~/3 %% *Ws   G	 	G-G((G-c                    | j                   }t        j                         | j                  j                  | j                  j
                  z  z
  }|j                  j                         D cg c]  \  }}||k  r| c}}| _        d}| j                  D ]r  }d| d}t        j                  |       |j                  |= 	 |j                  |= d}	 |j                  j                  |       	 |j                  j                  |       t |rt!        || j                         y y c c}}w # t        $ r Y ew xY w# t        $ r Y Xw xY w# t        $ r Y w xY w)NFzDetected dead node 'z"', removing it from the rendezvousT)r   r   utcnowr   ro   rp   r   ra   r   r   r   r   KeyErrorr   remover   r   )r4   r9   expire_timenodelast_heartbeatparticipant_removedr   r   s           r,   r   z'_BackendRendezvousStateHolder._sanitize  sX   oo'NN..1V1VV
 ).(=(=(C(C(E
$n+ 
 $)) 	I(3UVCLL%%i0&&y1&*#&&y1%%,,Y7%	,  )? =
"  
  
  s<   ,D# D)D8,E)	D54D58	EE	EEc                     d| _         y)a  See base class.

        If the local rendezvous state is dirty, the next sync call will try to
        write the changes back to the backend. However this attempt might fail
        if another node, which had the same state, also made changes and wrote
        them before us.
        TN)r   r3   s    r,   r   z(_BackendRendezvousStateHolder.mark_dirty  s     r.   )r   r   )r>   r?   r@   rA   r    rg   r   r"   rq   rE   rF   floatr   rt   rW   r   RUNNINGrC   r   rB   r9   r   r   r   r   r2   r.   r,   r   r   h  s    
  !!MLi   	" % 	
 
 =F<M<M 
s 
	 
 '  ;htn ;z)@Vr.   r   c                   D    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZy)_ActionzDSpecifies the possible actions based on the state of the rendezvous.r            rK            	   
            N)r>   r?   r@   rA   
KEEP_ALIVEADD_TO_PARTICIPANTSADD_TO_WAIT_LISTADD_TO_REDUNDANCY_LISTREMOVE_FROM_PARTICIPANTSREMOVE_FROM_WAIT_LISTREMOVE_FROM_REDUNDANCY_LISTMARK_RENDEZVOUS_COMPLETEMARK_RENDEZVOUS_CLOSEDSYNCERROR_CLOSEDERROR_TIMEOUTFINISHr2   r.   r,   r   r     sN    NJ "# DLMFr.   r   c                   H    e Zd ZU dZeed<   eed<   eed<   dedededdfdZy)_RendezvousContexta$  Holds the context of the rendezvous.

    Attributes:
        node:
            The node descriptor associated with the current rendezvous handler
            instance.
        state:
            The current state of the rendezvous.
        settings:
            The rendezvous settings.
    r   r9   r   r0   Nc                 .    || _         || _        || _        y r=   )r   r9   r   )r4   r   r9   r   s       r,   rW   z_RendezvousContext.__init__0  s     	
 r.   )	r>   r?   r@   rA   rt   rg   r   r"   rW   r2   r.   r,   r   r     s?    
 O  !!&6!BT!	!r.   r   c                   V    e Zd ZdZe	 ddeeegef   dede	ee
gef      ddfd       Zy)	_RendezvousOpExecutorzExecute rendezvous operations.Nstate_handlerr   update_deadliner0   c                      y)a  Execute a rendezvous operation.

        An operation is run inside a state machine and is expected to transition
        the rendezvous from one state to another.

        Args:
            state_handler:
                A callable that is expected to return the next state transition
                action based on the current state of the rendezvous.
            deadline:
                The time, in seconds, at which the operation will be considered
                timed-out.
            update_deadline:
                Function to generate a new operation deadline if the current
                node may participate in the next rendezvous.
        Nr2   )r4   r   r   r   s       r,   runz_RendezvousOpExecutor.run;  r6   r.   r=   )r>   r?   r@   rA   r   r
   r   r   r   r   r   r   r2   r.   r,   r   r   8  se    (
 CG	!3U ;W DE  "(I;+=">?	
 
 r.   r   c            
          e Zd ZU dZeed<   eed<   eed<   eed<   dededed	d
fdZ	e
j                  fdede
d	d
fdZ	 ddeeegef   dedeeegef      d	d
fdZddZddZddZddZddZddZddZddZddZy
) _DistributedRendezvousOpExecutorao  Execute rendezvous operations using a shared state.

    Args:
        node:
            The node descriptor associated with the current rendezvous handler
            instance.
        state_holder:
            The ``RendezvousStateHolder`` to use to sync the rendezvous state
            with other nodes.
        settings:
            The rendezvous settings.
    _noder   _state_holderr   r   state_holderr   r0   Nc                 .    || _         || _        || _        y r=   )r  r  r   )r4   r   r  r   s       r,   rW   z)_DistributedRendezvousOpExecutor.__init__g  s     
)!r.   r   r   c           	      
   t        | j                  j                   dt                | j                  j
                  ||| j                  j                  | j                  j                  | j                  j                         y )Nr   )r5   rl   r   r   hostnamerv   rw   )
r   r   r>   r-   r   rl   r  ru   rv   rw   r   s      r,   r   z(_DistributedRendezvousOpExecutor._recordq  s]    'NN++,Ao.?-@A>>((!ZZ__

ZZ((	
r.   r   r   r   c                     d}|t         j                  k7  r| j                  j                         }|x|r(d| j                   d| j
                  j                   d}n'd| j                   d| j
                  j                   d}| j                  |       t        j                  |       | j                  j                  | _        t        | j                  | j                  | j
                        } |||      }|t         j                  k(  r|t         j                  k(  rt        |t         j                  k(  rt         |t         j"                  k(  rt%        d       n|t         j&                  k(  r| j)                          nH|t         j*                  k(  r| j-                          n#|t         j.                  k(  r| j1                          n|t         j2                  k(  r| j5                          n|t         j6                  k(  r| j9                          n|t         j:                  k(  r| j=                          n|t         j>                  k(  r9| jA                          |rn || j
                  jB                  jD                        }nG|t         jF                  k(  r| jI                          n#|t         jJ                  k(  r| jM                          | j                  jO                          |t         j                  k7  ryy)	r   N
The node 'zP' has successfully synced its local changes with other nodes in the rendezvous ''.z]' has a stale state and failed to sync its local changes with other nodes in the rendezvous 'r   r   rH   )(r   r   r  r   r  r   rl   r   r   r   r9   r   r   r   r   r   r   r   r   r   _keep_aliver   _add_to_participantsr   _add_to_wait_listr   _add_to_redundancy_listr   _remove_from_participantsr   _remove_from_wait_listr   _remove_from_redundancy_listrf   rM   r   _mark_rendezvous_completer   _mark_rendezvous_closedr   )r4   r   r   r   actionr   r   ctxs           r,   r   z$_DistributedRendezvousOpExecutor.run|  sa    & ((--/G"$TZZL 1::>..:O:O9PPRT  %TZZL 1GGK~~G\G\F]]_a 
 S)S!,,22DK$TZZdnnMC #31F'---++...,,% q!W///$$&w:::--/w777**,w===002w???224w<<<//1wBBB557&#24>>3I3I3N3N#Ow???224w===002 ""--/C &r.   c                 
   d| j                    d| j                  j                   d}| j                  |       t        j                  |       t        j                         | j                  j                  | j                   <   y )Nr	  z<' updated its keep-alive heartbeat time for the rendezvous ''. Pending sync.r   )
r  r   rl   r   r   r   r   r   r   r   r4   r   s     r,   r  z,_DistributedRendezvousOpExecutor._keep_alive  sj     %%%&&68 	 	S!S2://2C##DJJ/r.   c                    d| j                    d| j                  j                   d| j                  j                   d}| j                  |       t        j                  |       | j                  }	 |j                  j                  | j                          d|j                  | j                   <   | j                          t        |j                        | j                  j                  k(  r:t        j                          | j                  j"                  j$                  z   |_        t        |j                        | j                  j(                  k(  r| j+                          y y # t        $ r Y w xY w)Nr	  z,' added itself to the participants of round  of the rendezvous 'r  r   r   )r  r   r   r   rl   r   r   r   r   r   r   r   r  r'   rm   r   r   rf   rN   r   rn   r  r4   r   r9   s      r,   r  z5_DistributedRendezvousOpExecutor._add_to_participants  s$   $P{{  !!5dnn6K6K5LL\^ 	 	S!S	OO""4::. *+4::&u!!"dnn&>&>>%__.1G1G1Q1QQENu!!"dnn&>&>>**, ?  		s   3%E% %	E10E1c                    d| j                    d| j                  j                  dz    d| j                  j                   d}| j                  |       t        j                  |       | j                   | j                  j                  v r/| j                  j                  j                  | j                          | j                  j                  j                  | j                          | j                          y )Nr	  z)' added itself to the wait list of round r   r  r  r   )r  r   r   r   rl   r   r   r   r   r   r   addr  r  s     r,   r  z2_DistributedRendezvousOpExecutor._add_to_wait_list  s    $M{{  1$%%9$..:O:O9PP`b 	 	S!S::444KK''..tzz:!!$**-r.   c                 R   d| j                    d| j                  j                  dz    d| j                  j                   d}| j                  |       t        j                  |       | j                  j                  j                  | j                          | j                          y )Nr	  z/' added itself to the redundancy list of round r   r  r  r   )r  r   r   r   rl   r   r   r   r   r  r  r  s     r,   r  z8_DistributedRendezvousOpExecutor._add_to_redundancy_list  s    $S{{  1$%%9$..:O:O9PP`b 	 	S!S##''

3r.   c                 n   d| j                    d| j                  j                   d| j                  j                   d}| j                  |       t        j                  |       | j                  }|j                  | j                   = |j                  | j                   = t        || j                         y )Nr	  z0' removed itself from the participants of round r  r  r   )r  r   r   r   rl   r   r   r   r   r   r   r  s      r,   r  z:_DistributedRendezvousOpExecutor._remove_from_participants  s    $T{{  !!5dnn6K6K5LL\^ 	 	S!Stzz*!!$**- 	%UDNN;r.   c                 t   d| j                    d| j                  j                  dz    d| j                  j                   d}| j                  |       t        j                  |       | j                  j                  j                  | j                          | j                  j                  | j                   = y )Nr	  z-' removed itself from the wait list of round r   r  r  r   )r  r   r   r   rl   r   r   r   r   r   r   r  s     r,   r  z7_DistributedRendezvousOpExecutor._remove_from_wait_list  s    $Q{{  1$%%9$..:O:O9PP`b 	 	S!S$$TZZ0KK''

3r.   c                 t   d| j                    d| j                  j                  dz    d| j                  j                   d}| j                  |       t        j                  |       | j                  j                  j                  | j                          | j                  j                  | j                   = y )Nr	  z1' removed itself from the redunant list of round r   r  r  r   )r  r   r   r   rl   r   r   r   r   r   r   r  s     r,   r  z=_DistributedRendezvousOpExecutor._remove_from_redundancy_list$  s    $U{{  1$%%9$..:O:O9PP`b 	 	S!S##**4::6KK''

3r.   c                    d| j                    d| j                  j                   d| j                  j                   d}| j                  |t        j                         t        j                  |       | j                  }d|_
        d |_        t        t        |j                              D ]  \  }}||j                  |<    y )Nr	  z' marked round r  z' as complete. Pending sync.r   r   T)r  r   r   r   rl   r   r   	SUCCEEDEDr   r   r   r   	enumeratesortedr   )r4   r   r9   rankr   s        r,   r  z:_DistributedRendezvousOpExecutor._mark_rendezvous_complete0  s    ODKK4E4E3F G%%&&BD 	 	SY-@-@AS $F5+=+=$>? 	,JD$'+Et$	,r.   c                     d| j                    d| j                  j                   d}| j                  |t        j
                         t        j                  |       d| j                  _	        y )Nr	  z' marked the rendezvous 'z' as closed. Pending sync.r#  T)
r  r   rl   r   r   r$  r   r   r   r   r  s     r,   r  z8_DistributedRendezvousOpExecutor._mark_rendezvous_closedA  s_    $=dnn>S>S=T U  	 	SY-@-@AS!r.   r=   r   )r>   r?   r@   rA   rt   rg   r   r   r"   rW   r   r   rC   r   r
   r   r   r   r   r   r   r  r  r  r  r  r  r  r  r  r2   r.   r,   r  r  T  s     ))!!"" -" %	"
 
" =F<M<M 	
s 	
	 	
RV 	
 CG	I0!3U ;W DEI0 I0 "(I;+=">?	I0
 
I0VD-6
<$
4
4,""r.   r  r  c                     	 | j                   j                  | j                     }|t	        j
                         | j                  j                  z
  k  S # t        $ r Y yw xY w)z8Determine whether a keep-alive heartbeat should be sent.F)r9   r   r   r   r   r   r   ro   )r  r   s     r,   _should_keep_aliver*  L  sV    22388< X__.1Q1QQQQ  s   #A 	AAc                   $    e Zd ZdZdededefdZy)_RendezvousExitOpz&Represent a rendezvous exit operation.r  r   r0   c                     |j                   |j                  j                  v r7t        j                         |kD  rt
        j                  S t
        j                  S t
        j                  S r=   )	r   r9   r   r   r   r   r   r   r   r4   r  r   s      r,   __call__z_RendezvousExitOp.__call__Y  sI    88syy---~~(*,,,333~~r.   Nr>   r?   r@   rA   r   r   r   r/  r2   r.   r,   r,  r,  V  s     0. % G r.   r,  c                   $    e Zd ZdZdededefdZy)_RendezvousJoinOpz&Represent a rendezvous join operation.r  r   r0   c                    |j                   }|j                  rM|j                  |j                  v r%d|j                  j
                   d}t        |      t        j                  S |j                  |j                  v rd|j                   d}t        j                  |       t        |j                        |j                  j                  k(  r+t        |      rt        j                  S t        j                   S d|j                   d}t        j                  |       t        j"                  S |j                  |j                  v }|j$                  r|rt        j&                  S t)        j*                         }||kD  rTd}|||z   k  r:|rt        j,                  S |j                  |j.                  v rt        j0                  S t        j2                  S |j$                  rt        |j                        |j                  j                  k  r)|j                  |j.                  vrt        j4                  S t        |j                        |j                  j                  k\  r]|j                  |j                  vrD|j                  |j.                  vr+t        j6                  S |rt        |j                        |j                  j8                  k\  rt        |j                        |j                  j                  k  rt;        t<        |j>                        t=        j@                         k  r5d|j                   d}t        j                  |       t        jB                  S d|j                   d	}t        j                  |       n6d|j                   d
}t        j                  |       nt        jD                  S t        |      rt        j                  S t        j                   S )NzThe rendezvous 'z,' is closed, terminating pending rendezvous.z	The node z is in redunancy listz is removed from redunancy listrK   r	  zE' marking the rendezvous complete, quorum established within deadlinez-' can't complete rendezvous: deadline reachedz4' can't complete rendezvous: not enough participants)#r9   r   r   r   r   rl   r   r   r   r   r   r'   r   rn   r*  r   r   r   r   r   r   r   r   r   r   r   r   r   rm   r   r   r   r   r   r   )r4   r  r   r9   r   is_participantnowrollback_periods           r,   r/  z_RendezvousJoinOp.__call__d  s   		 <<xx5000()<)<(==ij1#66'''88u,,,chhZ'<=CLL5%%&#,,*@*@@%c*"---"<<' "#((+JKS!:::U%7%77 >>n>>!nn>O h00 "";;; 88u."888(((>> 5%%&)?)??885??2"333U''(CLL,B,BBHHE$9$997"999
 E&&'3<<+A+AA**+s||/E/EE%..1HOO4EE$SXXJ /= >  LL%";;;&sxxj0]^CLL%"388*,`aS! ...c"%%% ||r.   Nr0  r2   r.   r,   r2  r2  a  s$    0a. a% aG ar.   r2  c                   $    e Zd ZdZdededefdZy)_RendezvousCloseOpz'Represent a rendezvous close operation.r  r   r0   c                     |j                   j                  rt        j                  S t	        j
                         |kD  rt        j                  S t        j                  S r=   )r9   r   r   r   r   r   r   r   r.  s      r,   r/  z_RendezvousCloseOp.__call__  s@    99>>!>>h&(((---r.   Nr0  r2   r.   r,   r8  r8    s     1.. .% .G .r.   r8  c                   $    e Zd ZdZdededefdZy)_RendezvousKeepAliveOpz3Represent a rendezvous keep-alive update operation.r  r   r0   c                     t        |      r7t        j                         |kD  rt        j                  S t        j
                  S t        j                  S r=   )r*  r   r   r   r   r   r   r.  s      r,   r/  z_RendezvousKeepAliveOp.__call__  s;    c"~~(*,,,%%%~~r.   Nr0  r2   r.   r,   r;  r;    s     =. % G r.   r;  c                   2   e Zd ZU dZ e       Zeed<   eed<   e	ed<   e
ed<   eed<   eed<   ej                  ed<   ee   ed	<   e	 	 d0de	de
dedededee	   dee   fd       Zdedede	de
dedd
fdZej0                  d
fde	dedee   dd
fdZdej6                  fdZedefd       Zde	fdZede fd        Z!de"fd!Z#de fd"Z$d1d#Z%defd$Z&de	fd%Z'de fd&Z(d1d'Z)e*d1d(       Z+d1d)Z,d1d*Z-d1d+Z.de/eef   fd,Z0de
de
fd-Z1de
fd.Z2de3de4fd/Z5y
)2r#   zCRepresent a handler that sets up a rendezvous among a set of nodes.
_this_noder   _backend_name_storer  _op_executor_heartbeat_lock_keep_alive_timerNrl   storer   rm   rn   r   rf   c           	          | j                   j                  |      }t        ||||xs
 t               t	        d      d      }	t        ||	      }
 | ||	|j                  ||
      S )a  Create a new :py:class:`DynamicRendezvousHandler`.

        Args:
            run_id:
                The run id of the rendezvous.
            store:
                The C10d store to return as part of the rendezvous.
            backend:
                The backend to use to hold the rendezvous state.
            min_nodes:
                The minimum number of nodes to admit to the rendezvous.
            max_nodes:
                The maximum number of nodes to admit to the rendezvous.
            local_addr:
                The local node address.
            timeout:
                The timeout configuration of the rendezvous.
        rK   rH   r   )ro   rp   )_node_desc_generatorr   r"   r!   r   r   r5   )clsrl   rD  r   rm   rn   r   rf   r   r   r  s              r,   from_backendz%DynamicRendezvousHandler.from_backend  si    < ''00<%*(* )! 4#$
 5WhG47<<EEr.   r   r   backend_namer  r0   c                    |j                   st        d      |j                  dk  rt        d|j                   d      |j                  |j                  k  r&t        d|j                   d|j                   d      || _        || _        || _        || _        || _        t        | j                  | j                  | j
                        | _
        t        j                         | _        d | _        d | _        d | _        y )Nz&The run id must be a non-empty string.r   zThe minimum number of nodes (z) must be greater than zero.zThe maximum number of nodes (z@) must be greater than or equal to the minimum number of nodes (z).)rl   rd   rm   rn   r>  r   r?  r@  r  r  rA  r   r   rB  rC  _shared_tcp_store_server_bootstrap_store_info)r4   r   r   rI  rD  r  s         r,   rW   z!DynamicRendezvousHandler.__init__  s    EFF!/0B0B/CC_`   2 22/0B0B/C D33;3E3E2FbJ 
 !))<OOT//
  )~~/!% ?C%DH"r.   r   r   r'  c           
         t        | j                  j                   dt                | j                  j
                  ||| j                  j                  | j                  j                  | j                  j                  |       y )Nr   )r5   rl   r   r   r  rv   rw   r'  )
r   r   r>   r-   r   rl   r>  ru   rv   rw   )r4   r   r   r'  s       r,   r   z DynamicRendezvousHandler._recordG  sf     	(NN++,Ao.?-@A>>((!__))##__--		
r.   c                 \    t        j                  |j                  |j                  dd      S )NT)	is_mastermulti_tenant)distTCPStoremaster_addrmaster_port)r4   bootstrap_store_infos     r,   _create_tcp_store_serverz1DynamicRendezvousHandler._create_tcp_store_serverX  s+    }} ,, ,,	
 	
r.   c                     | j                   S )z#Get the settings of the rendezvous.)r   r3   s    r,   r   z!DynamicRendezvousHandler.settings`  s     ~~r.   c                     | j                   S r   )r?  r3   s    r,   get_backendz$DynamicRendezvousHandler.get_backende  s    !!!r.   c                 4    t        j                  dd      dk7  S )r   "TORCH_DISABLE_SHARE_RDZV_TCP_STORE01)r   getenvr3   s    r,   use_agent_storez(DynamicRendezvousHandler.use_agent_storei  s     yy=sCsJJr.   c                    d| j                    d| j                  j                   d}| j                  |       t        j                  |       	 | j                          | j                  j                  j                  dk(  rt        d       t               }t               }| j                  | j                  j                  j                        }| j                   j#                  ||       | j                   j#                  ||| j                         | j%                          | j'                         \  }}| j)                         }d| j                    d| j                  j                  j                   d| j                  j                   d| d| d}| j                  ||       t        j                  |       t7        j8                  dd      dk(  r:t;        j<                  ||| j                   j>                        }	tA        ||||	      S | jB                  tE        | jF                  tH        jJ                        rU| jF                  jL                  }
| jF                  jN                  }t;        |
|      | _!        |dk(  rh| jF                  | _(        nVt;        j<                  ||| j                   j>                        | _!        |dk(  r | jS                  | jB                        | _(        | jB                  J |dk(  r| jP                  J tA        |||| jB                        S # t*        $ rH}| j                  t-        |      j.                   dt1        |       t2        j4                  	        d
}~ww xY w)r   r	  z5' attempts to join the next round of the rendezvous 'r
  r   r   )r   g333333?rH   : r#  Nz' has joined round r  z
' as rank z in a world of size r   )r   r'  r[  r\  r]  )r   )rS  rT  )*r>  r   rl   r   r   info_stop_heartbeatsr  r9   r   r   r,  r2  _get_deadlinerf   rM   rA  r   _start_heartbeats
_get_world
_get_store	Exceptiontyper>   rC   r   FAILEDr   r^  r   buildru   r   rL  
isinstancer@  rQ  rR  hostportrK  rV  )r4   r   exit_opjoin_opr   r'  
world_sizerD  erU  ru   rn  s               r,   next_rendezvousz(DynamicRendezvousHandler.next_rendezvousn  s$    ) *%%&b* 	 	S!C	!!#
 !!''--2x(')G')G))$..*@*@*E*EFH!!'84!!'8T5G5GH""$#0D*OO%E ))<T=O=O=U=U=[=[<\ ]#~~445ZvEYl! 	
 	St,C 9993?3F#6#<#<e(<(<$  "$	  %%-$++t}}5{{''{{''-@ $$.* 1948KKD1 .A-F-F%DOO,@,@.* 19484Q4Q225D1 ))5551900<<<&&	
 	
g  	LL7++,Bs1vh7$++   	s   C8L% %	M6.AM11M6c                 d   	 | j                   5  | j                  j                          | j                  j                  j                  cddd       S # 1 sw Y   yxY w# t
        $ rH}| j                  t        |      j                   dt        |       t        j                          d}~ww xY wr   Nra  r#  )rB  r  r   r9   r   rh  r   ri  r>   rC   r   rj  r4   rr  s     r,   	is_closedz"DynamicRendezvousHandler.is_closed  s    	%% 7""'')))//667 7 7
  	LL7++,Bs1vh7$++   	s5   A :A	A AA A 	B/'AB**B/c                    	 | j                   5  | j                          ddd       y# 1 sw Y   yxY w# t        $ rH}| j                  t	        |      j
                   dt        |       t        j                          d}~ww xY wru  )	rB  rS   rh  r   ri  r>   rC   r   rj  rv  s     r,   
set_closedz#DynamicRendezvousHandler.set_closed  sy    	%%    	LL7++,Bs1vh7$++   	s)   4 (4 14 4 	BAB  Bc                 v   	 | j                   5  | j                  j                          t        | j                  j                  j
                        cddd       S # 1 sw Y   yxY w# t        $ rH}| j                  t        |      j                   dt        |       t        j                          d}~ww xY wru  )rB  r  r   r'   r9   r   rh  r   ri  r>   rC   r   rj  rv  s     r,   num_nodes_waitingz*DynamicRendezvousHandler.num_nodes_waiting  s    	%% ?""'')4--33==>? ? ?
  	LL7++,Bs1vh7$++   	s6   A' AA	A' A$ A' $A' '	B80AB33B8c                 .    | j                   j                  S r   )r   rl   r3   s    r,   
get_run_idz#DynamicRendezvousHandler.get_run_id  s    ~~$$$r.   c           	         | j                          	 | j                          y# t        $ r}}d| j                   d| j                  j
                   dt        |      j                   d}| j                  |t        j                         t        j                  |       Y d}~yd}~wt        $ rH}| j                  t        |      j                   d	t        |       t        j                          d}~ww xY w)
r   Tr	  z)' has failed to shutdown the rendezvous '' due to an error of type r   r#  NFra  )rc  rS   r   r>  r   rl   ri  r>   r   r   rj  r   warningrh  rC   )r4   exr   rr  s       r,   shutdownz!DynamicRendezvousHandler.shutdown  s    	KKM 	T__- .NN))**DT"XEVEVDWWXZ  LL1A1ALBNN3 	LL7++,Bs1vh7$++   	s"   # 	C8A3B$$C80AC33C8c                 h   t               }| j                  | j                  j                  j                        }| j
                  j                  ||       d| j                   d| j                  j                   d}| j                  |t        j                         t        j                  |       y )Nr	  z' has closed the rendezvous 'r
  r#  )r8  rd  r   rf   rO   rA  r   r>  rl   r   r   r$  r   rb  )r4   opr   r   s       r,   rS   zDynamicRendezvousHandler._close  s    !%%dnn&<&<&B&BCb(+4??++HI^I^H__abSY-@-@ACr.   c                 8     |        }||j                          y y r=   )r  )	weak_selfr4   s     r,   _keep_alive_weakz)DynamicRendezvousHandler._keep_alive_weak  s     { r.   c           	         | j                   j                          t               }| j                  | j                  j
                  j                        }	 | j                  j                  ||       d| j                   d| j                  j                   d}| j                  |       t        j                  |       | j                   j)                          y # t        $ r}}d| j                   d| j                  j                   dt        |      j                    d}| j                  |t"        j$                         t        j'                  |       Y d }~d }~ww xY w# | j                   j)                          w xY w)	Nr	  z5' has sent a keep-alive heartbeat to the rendezvous 'r
  r   z?' has failed to send a keep-alive heartbeat to the rendezvous 'r  r   r#  )rB  acquirer;  rd  r   rf   rP   rA  r   r>  rl   r   r   r   r   ri  r>   r   rj  r  release)r4   r  r   r   r  s        r,   r  z$DynamicRendezvousHandler._keep_alive  sH   $$&#%%%dnn&<&<&F&FG	+!!"h/ T__- .NN))*".  LLL%LL   ((*  	 T__- .#~~4455OPTUWPXPaPaObbce  LL1A1ALBNN3	    ((*s,   A*C 	E #A3EE# E  E# #E?c                 "   t        | j                  j                  | j                  t	        j
                  |             | _        | j                  j                  d| j                  j                          | j                  j                          y )NRendezvousKeepAliveTimer_)r   r   ro   r  weakrefrefrC  set_namer>  rw   startr3   s    r,   re  z*DynamicRendezvousHandler._start_heartbeats7  so    !/NN..0E0Ew{{SWGX"
 	'''(@(@'AB	
 	$$&r.   c                 R    | j                   y | j                   j                          y r=   )rC  cancelr3   s    r,   rc  z)DynamicRendezvousHandler._stop_heartbeatsB  s#    !!)%%'r.   c                     | j                   j                  }|j                  | j                     t	        |j                        fS r=   )r  r9   r   r>  r'   )r4   r9   s     r,   rf  z#DynamicRendezvousHandler._get_worldH  s8    ""((!!$//2C8J8J4KKKr.   c                     d| j                   j                   d| j                  j                  j                   }t        j                  ||      S )Nztorch.rendezvous.r   )r   rl   r  r9   r   rQ  PrefixStore)r4   rD  
key_prefixs      r,   _wrap_storez$DynamicRendezvousHandler._wrap_storeM  sJ     5 56a8J8J8P8P8V8V7WX 	 
E22r.   c                 8    | j                  | j                        S r=   )r  r@  r3   s    r,   rg  z#DynamicRendezvousHandler._get_storeT  s    ,,r.   c                 L    t        j                         |j                         z   S r=   )r   r   total_seconds)r4   rf   s     r,   rd  z&DynamicRendezvousHandler._get_deadlineW  s    ~~'"7"7"999r.   )NNr   )6r>   r?   r@   rA   r{   rF  rt   rg   r"   rC   r   r   r   r   r   r   r   classmethodr    rq   r!   rH  rW   r   r   r   rQ  rR  rV  rB   r   rY  rF   r_  r   rs  rw  ry  r{  r}  r  rS   staticmethodr  r  re  rc  r   rf  r  rg  r   r   rd  r2   r.   r,   r#   r#     sH   M ./!!M))''^^#// %)/3*F*F *F #	*F
 *F *F SM*F +,*F *FX+I+I %+I 	+I
 +I -+I 
+I` !* 1 1"	

 
 sm	

 

"
 
 ,  "S " K K KV
 V
p4 
3 %C %$ 0	  
+4	'(LE#s(O L
3 35 3-E -:Y :5 :r.   r#   paramskeyc                 H    | j                  |dz         }|y t        |      S )N_timeoutrH   )
get_as_intr   )r  r  rf   s      r,   _get_timeoutr  [  s*    j 01GW%%r.   rD  r   c           	         	 t        t        |d      t        |d      t        |d            }t        j                  |j                  | ||j
                  |j                  |j                  |      S # t        $ rM}t        t        |      j                   dt        |       |j                  t        j                          d}~ww xY w)a_  Create a new :py:class:`DynamicRendezvousHandler` from the specified parameters.

    Args:
        store:
            The C10d store to return as part of the rendezvous.
        backend:
            The backend to use to hold the rendezvous state.

    +-------------------+------------------------------------------------------+
    | Parameter         | Description                                          |
    +===================+======================================================+
    | join_timeout      | The total time, in seconds, within which the         |
    |                   | rendezvous is expected to complete. Defaults to 600  |
    |                   | seconds.                                             |
    +-------------------+------------------------------------------------------+
    | last_call_timeout | An additional wait amount, in seconds, before        |
    |                   | completing the rendezvous once the minimum number of |
    |                   | nodes has been reached. Defaults to 30 seconds.      |
    +-------------------+------------------------------------------------------+
    | close_timeout     | The time, in seconds, within which the rendezvous is |
    |                   | expected to close after a call to                    |
    |                   | :py:meth:`RendezvousHandler.set_closed` or           |
    |                   | :py:meth:`RendezvousHandler.shutdown`. Defaults to   |
    |                   | 30 seconds.                                          |
    +-------------------+------------------------------------------------------+
    rM   rN   rO   ra  )r   rl   r   N)r!   r  r#   rH  rl   rm   rn   r   rh  r   ri  r>   rC   r   rj  )rD  r   r  rf   rr  s        r,   r$   r$   b  s    :#(-)
 (44MM
 	
  'Aw''(3q6(3== ''	

 	s   A-A0 0	C9ACC)r   )Kr(   r   r   r   r   r   r   r  abcr   r   dataclassesr   r   r   enumr   typingr	   r
   r   r   r   r   r   r   torch.distributeddistributedrQ  r    torch.distributed.elastic.eventsr   r   apir   r   r   r   r   r   r   r   r   utilsr   r   __all__	getLoggerr>   r   r-   rE   r    r!   r"   rt   r{   r   r   r   r   r   r   r   r  rF   r*  r,  r2  r8  r;  r#   rC   r  r$   r2   r.   r,   <module>r     s     	      # ! (  H H H   # W
 
 
 * 
		8	$ 	 G: :zE/ E/P %-    . 8 d$t,9 9 -9(P P6+" +"\""'9"	"*-S -,b$: bJd $! !2C 8u"'< u"pR. R4 R d dN. . z:0 z:z&- &C &HY<O &33,36J33r.   