a
    –¥»a+)  ã                   @   st  d dl Z d dl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 d dlm  m  m  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 d dlmZ d d	l m!Z! d d
l"m#Z# d dl$m%Z% e%ƒ Z&eG dd„ dƒƒZ'G dd„ dƒZ(e'ej)dœdd„Z*eee+df e	e e+dœdd„Z,e!ee
e+ e
e- f dœdd„Z.e'eee+df e	e ee-ef dœdd„Z/dS )é    N)Ú	dataclassÚfield)ÚAnyÚCallableÚDictÚListÚOptionalÚUnionÚcastÚTuple)ÚeventsÚmetrics)Ú
WorkerSpecÚWorkerState)ÚLocalElasticAgent)ÚStd)ÚChildFailedError)ÚRendezvousParameters)Úparse_rendezvous_endpoint)Ú
get_loggerc                   @   s  e Zd ZU dZeed< eed< eed< dZeed< dZeed< dZ	eed	< d
Z
eed< eed�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e ed< ejZeeeeef f ed< ejZeeeeef f ed< eed�Zeeef ed< dd„ ZdS )ÚLaunchConfiga	  
    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.
        rdzv_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).
        log_dir: base log directory where log files are written. If not set,
                one is created in a tmp dir but NOT removed on exit.
        redirects: configuration to redirect stdout/stderr to log files.
                Pass a single ``Std`` enum to redirect all workers,
                or a mapping keyed by local_rank to selectively redirect.
        tee: configuration to "tee" stdout/stderr to console + log file.
        metrics_cfg: configuration to initialize metrics.

    ..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_nodeÚ Úrun_idZdefault_roleÚroleÚrdzv_endpointZetcdÚrdzv_backend)Údefault_factoryÚrdzv_configséÿÿÿÿÚrdzv_timeouté   Úmax_restartsé   Úmonitor_intervalÚspawnÚstart_methodNÚlog_dirÚ	redirectsÚteeÚmetrics_cfgc                 C   s4   d}| j dkr| j | jd< nd| jvr0|| jd< d S )Ni„  r!   Útimeout)r"   r    )ÚselfZdefault_timeout© r/   úX/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/distributed/launcher/api.pyÚ__post_init__W   s
    

zLaunchConfig.__post_init__)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚintÚ__annotations__r   Ústrr   r   r   r   Údictr    r   r   r"   r$   r&   Úfloatr(   r)   r   r   ÚNONEr*   r	   r+   r,   r1   r/   r/   r/   r0   r      s$   
)r   c                   @   s2   e Zd ZdZeeeedf dœdd„Zdd„ Z	dS )Úelastic_launcha  
    Launches an 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.
        ouptuts = elestic_launch(LaunchConfig, "script.py")(args)
        ouptuts = elestic_launch(LaunchConfig, "python")("script.py")
    N)ÚconfigÚ
entrypointc                 C   s   || _ || _d S ©N)Ú_configÚ_entrypoint)r.   r=   r>   r/   r/   r0   Ú__init__z   s    zelastic_launch.__init__c                 G   s   t | j| jt|ƒƒS r?   )Úlaunch_agentr@   rA   Úlist)r.   Úargsr/   r/   r0   Ú__call__‚   s    zelastic_launch.__call__)
r2   r3   r4   r5   r   r	   r   r8   rB   rF   r/   r/   r/   r0   r<   _   s
   ýr<   )r=   Úreturnc                 C   s6   | j | j| jdœ}tjdtjjttt	tj
f |ƒd�S )N)r   r   r   z&torch.distributed.elastic.launch_agent)ÚnameÚsourceÚmetadata)r   r   r   r   ÚEventZEventSourceZAGENTr
   r   r8   ZEventMetadataValue)r=   rJ   r/   r/   r0   Ú_construct_event†   s    ýýrL   )r>   rE   rG   c                 C   sF   t | tƒr| jS t | tƒr>| tjkr8tdd„ |D ƒdƒS | S ndS dS )a¾  Retrive entrypoint name with the rule:
    1. If entrypoint is a function, use ``entrypont.__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                 s   s   | ]}|d  dkr|V  qdS )r   ú-Nr/   )Ú.0Úargr/   r/   r0   Ú	<genexpr>¢   ó    z'_get_entrypoint_name.<locals>.<genexpr>r   N)Ú
isinstancer   r2   r8   ÚsysÚ
executableÚnext)r>   rE   r/   r/   r0   Ú_get_entrypoint_name“   s    


rV   )Úrdzv_parametersrG   c                 C   sX   | j dkrdS | j}| ¡ }|s(tdƒ‚t|dd�\}}|dkrPtd|› d�ƒ‚||fS )NZ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ÚstripÚ
ValueErrorr   )rW   rZ   Úmaster_addrÚmaster_portr/   r/   r0   Ú_get_addr_and_port©   s    
ÿ
ÿr_   )r=   r>   rE   rG   c                 C   sü  | j s*tt ¡ jƒ}t d|› �¡ || _ t||ƒ}t d|› d| j	› d| j
› d| j› d| j › d| j› d| j› d	| j› d
| j› d| j› d| j› d| j› d�¡ tf | j| j| j | j	| j
dœ| j¤Ž}d }t |¡}t|ƒ\}}	�zz¬t| j| j|t|ƒ|| j| j| j| j||	d�}
| j�r&t | j¡nd }t |¡ t|
| j | jd�}| !¡ }t" #| $t%j&¡¡ | '¡ �rzt(||j)d�‚n|j*W W | +¡  S W nR t(�y¤   ‚ Y n> t,�yà   |�rÌt" #| $t%j-¡¡ nt" #t.| ƒ¡ ‚ Y n0 W | +¡  n
| +¡  0 d S )Nz*config has no run_id, generate a new one: zDStarting elastic_operator with launch configs:
  entrypoint       : z
  min_nodes        : z
  max_nodes        : z
  nproc_per_node   : z
  run_id           : z
  rdzv_backend     : z
  rdzv_endpoint    : z
  rdzv_configs     : z
  max_restarts     : z
  monitor_interval : z
  log_dir          : z
  metrics_cfg      : Ú
)rY   rZ   r   r   r   )r   Zlocal_world_sizer>   rE   Úrdzv_handlerr$   r&   r*   r+   r]   r^   )Úspecr(   r)   )rH   Úfailures)/r   r8   ÚuuidÚuuid4r6   ÚloggerÚwarningrV   Úinfor   r   r   r   r   r    r$   r&   r)   r,   r   Úrdzv_registryZget_rendezvous_handlerr_   r   r   Útupler*   r+   r   ZMetricsConfigZinitialize_metricsr   r(   Úrunr   ÚrecordZget_agent_status_eventr   Z	SUCCEEDEDZ	is_failedr   rc   Zreturn_valuesÚshutdownÚ	ExceptionZFAILEDrL   )r=   r>   rE   r   Zentrypoint_namerW   Zagentra   r]   r^   rb   ÚcfgÚresultr/   r/   r0   rC   ¾   s¢    
ÿþýüûúùø	÷
öõôÿûú	
õ

ÿ
þ
ö
rC   )0rS   rd   Zdataclassesr   r   Útypingr   r   r   r   r   r	   r
   r   Z-torch.distributed.elastic.rendezvous.registryZdistributedZelasticZ
rendezvousÚregistryri   Ztorch.distributed.elasticr   r   Z*torch.distributed.elastic.agent.server.apir   r   Z:torch.distributed.elastic.agent.server.local_elastic_agentr   Z)torch.distributed.elastic.multiprocessingr   Z0torch.distributed.elastic.multiprocessing.errorsr   Z$torch.distributed.elastic.rendezvousr   Z*torch.distributed.elastic.rendezvous.utilsr   Z'torch.distributed.elastic.utils.loggingr   rf   r   r<   rK   rL   r8   rV   r6   r_   rC   r/   r/   r/   r0   Ú<module>   s8   (C'þþ
ü