
    ^jA                        d dl 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
Z
d dlmc mc mc mZ d dlmZ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mZmZ d d
l m!Z!m"Z"m#Z# d dl$m%Z% d dl&m'Z' d dl(m)Z) d dl*m+Z+ d dl,m-Z- g dZ. e+e/      Z0e G d d             Z1 G d d      Z2dee3z  dz  de4e	   de3fdZ5de'de6e3dz  e7dz  f   fdZ8	 dde1dee3z  dz  de4e	   dedz  de9e7e	f   f
dZ:y)    N)Callable)	dataclassfield)Any)get_default_numa_optionsjustknobs_check)eventsmetrics)
WorkerSpec)create_healthcheck_serverHealthCheckServer)_AliveCallbackProxyLocalElasticAgentTORCHELASTIC_HEALTH_CHECK_PORT)DefaultLogsSpecs	LogsSpecsSignalException)ChildFailedError)RendezvousParameters)parse_rendezvous_endpoint)
get_logger)NumaOptions)LaunchConfigelastic_launchlaunch_agentc                      e Zd ZU dZeed<   eed<   eed<   dZedz  ed<   dZe	ed<   d	Z
e	ed
<   dZe	ed<   dZe	ed<    ee      Zee	ef   ed<   dZeed<   dZeed<   dZeed<   dZe	ed<   dZe	dz  ed<    ee      Zee	e	f   ed<   dZe	dz  ed<   dZe	ed<   dZedz  ed<   dZe	ed<   dZee	   dz  ed <   dZee	   dz  ed!<   d"Z e!ed#<   dZ"edz  ed$<   d% Z#y)&r   a  
    Creates a rendezvous config.

    Args:
        min_nodes: Minimum amount of nodes that the user function will
                        be launched on. Elastic agent ensures that the user
                        function start only when the min_nodes amount enters
                        the rendezvous.
        max_nodes: Maximum amount of nodes that the user function
                        will be launched on.
        nproc_per_node: On each node the elastic agent will launch
                            this amount of workers that will execute user
                            defined function.
        rdzv_backend: rdzv_backend to use in the rendezvous (zeus-adapter, etcd).
        rdzv_endpoint: The endpoint of the rdzv sync. storage.
        rdzv_configs: Key, value pair that specifies rendezvous specific configuration.
        rdzv_timeout: Legacy argument that specifies timeout for the rendezvous. It is going
            to be removed in future versions, see the note below. The default timeout is 900 seconds.
        run_id: The unique run id of the job (if not passed a unique one will be
                deduced from run environment - flow workflow id in flow - or auto generated).
        role: User defined role of the worker (defaults to "trainer").
        max_restarts: The maximum amount of restarts that elastic agent will conduct
                    on workers before failure.
        monitor_interval: The interval in seconds that is used by the elastic_agent
                        as a period of monitoring workers.
        start_method: The method is used by the elastic agent to start the
                    workers (spawn, fork, forkserver).
        metrics_cfg: configuration to initialize metrics.
        local_addr: address of the local node if any. If not set, a lookup on the local
                machine's FQDN will be performed.
        local_ranks_filter: ranks for which to show logs in console. If not set, show from all.
        event_log_handler: name of the event logging handler as registered in
          `elastic/events/handlers.py <https://docs.pytorch.org/docs/stable/elastic/events.html>`_.
        duplicate_stdout_filters: If non-empty, duplicates stdout to a file containing only lines
                                that match _any_ of the filter strings.
        duplicate_stderr_filters: If non-empty, duplicates stderr to a file containing only lines
                                that match _any_ of the filter strings.
        virtual_local_rank: Enable virtual local rank mode for workers (defaults to False).
                           When enabled, LOCAL_RANK is set to 0 for all workers and
                           CUDA_VISIBLE_DEVICES is adjusted so each worker accesses its
                           assigned GPU at device index 0.
        shutdown_timeout: Time in seconds to wait for graceful shutdown of workers before
                        sending SIGKILL. Can also be set via TORCH_ELASTIC_SHUTDOWN_TIMEOUT
                        environment variable. Defaults to 30 seconds.


    .. note::
        `rdzv_timeout` is a legacy argument that will be removed in future.
        Set the timeout via `rdzv_configs['timeout']`

    	min_nodes	max_nodesnproc_per_nodeN
logs_specs run_iddefault_rolerolerdzv_endpointetcdrdzv_backend)default_factoryrdzv_configsrdzv_timeout   max_restartsg?monitor_intervalspawnstart_methodlog_line_prefix_templatemetrics_cfg
local_addrnullevent_log_handlernuma_optionszSIGTERM,SIGINT,SIGHUP,SIGQUITsignals_to_handleduplicate_stdout_filtersduplicate_stderr_filtersFvirtual_local_rankshutdown_timeoutc                    d}| j                   dk7  r| j                   | j                  d<   nd| j                  vr|| j                  d<   | j                  t               | _        | j                  xt
        j                  j                         rZt
        j                  j                         | j                  k(  r/t               | _        t        j                  d| j                         | j                  /t        t        j                   j#                  dd            | _        y | j                  dk  rt%        d| j                         y )	Ni  r*   timeoutzUsing default numa options = %rTORCH_ELASTIC_SHUTDOWN_TIMEOUT30r   z+shutdown_timeout must be non-negative, got )r+   r)   r    r   r6   torchcudais_availabledevice_countr   r   loggerinfor;   intosenvironget
ValueError)selfdefault_timeouts     i/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/distributed/launcher/api.py__post_init__zLaunchConfig.__post_init__}   s   "+/+<+<Di(d///+:Di( ??".0DO %

'')

'')T-@-@@ 8 :DKK94;L;LM   ($'

?F%D! ""Q&=d>S>S=TU  '    )$__name__
__module____qualname____doc__rF   __annotations__r    r   r"   strr$   r%   r'   r   dictr)   r   r+   r-   r.   floatr0   r1   r2   r3   r5   r6   r   r7   r8   listr9   r:   boolr;   rN    rO   rM   r   r   /   s1   2h NN#'J	D 'FCD#M3L##(#>L$sCx.>L#L#!e!L#+/cDj/"'"=Kc3h=!Jd
!#s#'+L+$+<s<15d3i$.515d3i$.5$$#'cDj'rO   r   c                   @    e Zd ZdZ	 ddedeez  dz  dedz  fdZd Z	y)	r   a  
    Launches a torchelastic agent on the container that invoked the entrypoint.

        1. Pass the ``entrypoint`` arguments as non ``kwargs`` (e.g. no named parameters)/
           ``entrypoint`` can be a function or a command.
        2. The return value is a map of each worker's output mapped
           by their respective global rank.

    Usage

    ::

    def worker_fn(foo):
        # ...

    def main():
        # entrypoint is a function.
        outputs = elastic_launch(LaunchConfig, worker_fn)(foo)
        # return rank 0's output
        return outputs[0]

        # entrypoint is a command and ``script.py`` is the python module.
        outputs = elastic_launch(LaunchConfig, "script.py")(args)
        outputs = elastic_launch(LaunchConfig, "python")("script.py")
    Nconfig
entrypointhealth_check_serverc                 .    || _         || _        || _        y N)_config_entrypoint_health_check_server)rK   r\   r]   r^   s       rM   __init__zelastic_launch.__init__   s     %$7!rO   c                 n    t        | j                  | j                  t        |      | j                        S )N)r^   )r   ra   rb   rX   rc   )rK   argss     rM   __call__zelastic_launch.__call__   s/    LLJ $ 9 9	
 	
rO   r`   )
rP   rQ   rR   rS   r   r   rU   r   rd   rg   rZ   rO   rM   r   r      s@    < 9=	88 sNT)8 /5	8
rO   r   r]   rf   returnc                     t        | t              r| j                  S t        | t              r(| t        j
                  k(  rt        d |D        d      S | S y)a  Retrieve entrypoint name with the rule:
    1. If entrypoint is a function, use ``entrypoint.__qualname__``.
    2. If entrypoint is a string, check its value:
        2.1 if entrypoint equals to ``sys.executable`` (like "python"), use the first element from ``args``
            which does not start with hifen letter (for example, "-u" will be skipped).
        2.2 otherwise, use ``entrypoint`` value.
    3. Otherwise, return empty string.
    c              3   2   K   | ]  }|d    dk7  s|  yw)r   -NrZ   ).0args     rM   	<genexpr>z'_get_entrypoint_name.<locals>.<genexpr>   s     >A#>s   r!   )
isinstancer   rP   rU   sys
executablenext)r]   rf   s     rM   _get_entrypoint_namers      sL     *h'"""	J	$'>>CCrO   rdzv_parametersc                     | j                   dk7  ry| j                  }|j                         }|st        d      t	        |d      \  }}|dk(  rt        d| d      ||fS )Nstatic)NNzKEndpoint is missing in endpoint. Try to add --master-addr and --master-portr*   )default_portzport is missing in endpoint: z. Try to specify --master-port)backendendpointstriprJ   r   )rt   ry   master_addrmaster_ports       rM   _get_addr_and_portr}      s     (*''H~~HY
 	
  9PRSKb+H:5ST
 	
 %%rO   r\   r^   c                 	   | j                   sDt        t        j                         j                        }t
        j                  d|       || _         t        ||      }t
        j                  di d|d| j                  d| j                  d| j                  d| j                   d| j                  d	| j                  d
| j                  d| j                  d| j                   d| j"                  j$                  d| j&                  d| j(                  d| j*                  d| j,                  d| j.                  d| j0                         t3        d"| j                  | j                  | j                   | j                  | j                  | j4                  d| j                  }t7        |      \  }}| j,                  t8        j:                  d<   |nt9        j<                  t>              }	|	StA        dd      rF	 tC        tE               t	        |	      d      }|jG                          t
        j                  d|	       tK        | jL                  | j                  |tO        |      tQ        jR                  |      | j                  | j                   ||| j4                  | j(                  | j*                  | j.                  | j0                  | jT                        }
tW        |
| j"                  | jX                  | jZ                  | j\                  |       }|7|j^                  }ta        |tD              r|jc                  |jd                         d}	 tg        jh                  tg        jj                  | j&                               |jm                         }to        jp                  |js                         | j(                         |ju                         rtw        ||jx                  !      |jz                  |r|
j|                  j                          S S # tH        $ r t
        j                  dd       d }Y w xY w# tv        $ r  t        $ r2 d}to        jp                  |j                         | j(                          tH        $ r0 to        jp                  |j                         | j(                          w xY w# |r|
j|                  j                          w w xY w)#Nz3config has no run_id, generated a random run_id: %saR  Starting elastic_operator with launch configs:
  entrypoint               : %(entrypoint)s
  min_nodes                : %(min_nodes)s
  max_nodes                : %(max_nodes)s
  nproc_per_node           : %(nproc_per_node)s
  run_id                   : %(run_id)s
  rdzv_backend             : %(rdzv_backend)s
  rdzv_endpoint            : %(rdzv_endpoint)s
  rdzv_configs             : %(rdzv_configs)s
  max_restarts             : %(max_restarts)s
  monitor_interval         : %(monitor_interval)s
  log_dir                  : %(log_dir)s
  metrics_cfg              : %(metrics_cfg)s
  event_log_handler        : %(event_log_handler)s
  numa_options             : %(numa_options)s
  signals_to_handle        : %(signals_to_handle)s
  duplicate_stdout_filters : %(duplicate_stdout_filters)s
  duplicate_stderr_filters : %(duplicate_stderr_filters)s
r]   r   r   r   r"   r'   r%   r)   r-   r.   log_dirr2   r5   r6   r7   r8   r9   )rx   ry   r"   r   r   r3   TORCHELASTIC_SIGNALS_TO_HANDLEzNai_infra/pytorch_distributed:torchelastic_enable_healthcheck_before_rendezvousF)default<   )alive_callbackportr=   z>Started early health check server on port %s before rendezvousz)Failed to start early health check serverT)exc_info)r$   local_world_sizer]   rf   rdzv_handlerr-   r.   r{   r|   r3   r5   r6   r8   r9   r:   )specr    r0   r1   r;   r^   )namefailuresrZ   )Br"   rU   uuiduuid4rF   rD   warningrs   rE   r   r   r   r'   r%   r)   r-   r.   r    root_log_dirr2   r5   r6   r7   r8   r9   r   r3   r}   rG   rH   getenvr   r   r   r   start	Exceptionr   r$   tuplerdzv_registryget_rendezvous_handlerr:   r   r0   r1   r;   r   ro   set_delegate_get_alive_timer
   initialize_metricsMetricsConfigrunr	   recordget_event_succeeded	is_failedr   r   return_valuesr   shutdownr   get_event_failed)r\   r]   rf   r^   r"   entrypoint_namert   r{   r|   healthcheck_portr   agentcbshutdown_rdzvresults                  rM   r   r      s    ==TZZ\%%&LfU*:t<O
KK	F$	
/	
))	
 ))	
 f33		

 fmm	
 F//	
 V11	
 F//	
 F//	
  7 7	
 v((55	
 6--	
  !9!9	
 F//	
  !9!9	
  '(G(G!	
" '(G(G#	
'&P + ##%%}}""""$$ 

O  2/BK 4:3K3KBJJ/0 "99%CD'O\-
+&?#6#8-.'#
 $))+T$ [[..4["99/J((00$$ 22((!'!@!@!'!@!@!44D$ $$((!'!@!@00/E & //b-.OOE112M )""7#8#89K9K#LMe//163K3KL
 #$ 
 ## &&( M  +?$   '+#	+r    e,,.0H0HI e,,.0H0HI &&( s-   >AP B"P; "P87P8;A;R66R9 9Sr`   );rG   rp   r   collections.abcr   dataclassesr   r   typingr   r@   -torch.distributed.elastic.rendezvous.registrydistributedelastic
rendezvousregistryr   torch._utils_internalr   r   torch.distributed.elasticr	   r
   *torch.distributed.elastic.agent.server.apir   :torch.distributed.elastic.agent.server.health_check_serverr   r   :torch.distributed.elastic.agent.server.local_elastic_agentr   r   r   )torch.distributed.elastic.multiprocessingr   r   r   0torch.distributed.elastic.multiprocessing.errorsr   $torch.distributed.elastic.rendezvousr   *torch.distributed.elastic.rendezvous.utilsr   'torch.distributed.elastic.utils.loggingr   torch.numa.bindingr   __all__rP   rD   r   r   rU   rX   rs   r   rF   r}   rV   r   rZ   rO   rM   <module>r      s6   
 
  $ (   E E K 5 A 
 
 N E P > * =	H	 i i iX+
 +
\X^d%: $s) PS (&)&
3:sTz!"&. 59	b)b)3%b) s)b) +T1	b)
 
#s(^b)rO   