U
    ©Ê¹jú*  ã                   @   sj  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 d dlm  m  m  mZ d dl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 d d	lm Z  d d
l!m"Z" d dl#m$Z$ dddgZ%e$e&ƒZ'eG dd„ dƒƒZ(G 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ÚTupleÚUnion)ÚeventsÚmetrics)Ú
WorkerSpec)ÚLocalElasticAgent)ÚSignalExceptionÚStd)ÚChildFailedError)ÚRendezvousParameters)Úparse_rendezvous_endpoint)Ú
get_loggerÚLaunchConfigÚelastic_launchÚlaunch_agentc                   @   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Zee ed< dd„ ZdS )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).
        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.
        local_addr: address of the local node if any. If not set, a lookup on the local
                machine's FQDN will be performed.
    ..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_cfgÚ
local_addrc                 C   s4   d}| j dkr| j | jd< nd| jkr0|| jd< d S )Ni„  r"   Útimeout)r#   r!   )ÚselfZdefault_timeout© r1   ú]/var/www/html/bwave/python/venv/lib/python3.8/site-packages/torch/distributed/launcher/api.pyÚ__post_init__Z   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-   r.   r3   r1   r1   r1   r2   r      s&   
*c                   @   s2   e Zd ZdZeeeedf dœdd„Zdd„ Z	dS )r   a  
    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.
        outputs = elastic_launch(LaunchConfig, "script.py")(args)
        outputs = elastic_launch(LaunchConfig, "python")("script.py")
    N)ÚconfigÚ
entrypointc                 C   s   || _ || _d S ©N)Ú_configÚ_entrypoint)r0   r>   r?   r1   r1   r2   Ú__init__}   s    zelastic_launch.__init__c                 G   s   t | j| jt|ƒƒS r@   )r   rA   rB   Úlist)r0   Úargsr1   r1   r2   Ú__call__…   s    zelastic_launch.__call__)
r4   r5   r6   r7   r   r
   r   r:   rC   rF   r1   r1   r1   r2   r   b   s
   ý)r?   rE   Úreturnc                 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À  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                 s   s   | ]}|d  dkr|V  qdS )r   ú-Nr1   )Ú.0Úargr1   r1   r2   Ú	<genexpr>˜   s      z'_get_entrypoint_name.<locals>.<genexpr>r   N)Ú
isinstancer   r4   r:   ÚsysÚ
executableÚnext)r?   rE   r1   r1   r2   Ú_get_entrypoint_name‰   s    


rP   )Ú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   )rQ   rT   Úmaster_addrÚmaster_portr1   r1   r2   Ú_get_addr_and_portŸ   s    
ÿ
ÿrY   )r>   r?   rE   rG   c                 C   s¾  | j s&tt ¡ jƒ}t d|¡ || _ t||ƒ}t d|| j	| j
| j| j | j| j| j| j| j| j| jdœ¡ tf | j| j| j | j	| j
| jdœ| j—Ž}t|ƒ\}}t| j| j|t|ƒt |¡| j| j| j| j||| jd�}t|| j| jd�}	d}
z¶zLt! "t! #| j¡¡ |	 $¡ }t% &|	 '¡ ¡ | (¡ �r4t)||j*d�‚|j+W W ¢jS  t)k
�rV   ‚ Y nN t,k
�r~   d	}
t% &|	 -¡ ¡ ‚ Y n& t.k
�r¢   t% &|	 -¡ ¡ ‚ Y nX W 5 |
�r¸|j  ¡  X d S )
Nz3config has no run_id, generated a random run_id: %saê  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
)r?   r   r   r   r   r   r   r!   r%   r'   r*   r-   )rS   rT   r   r   r   r.   )r   Zlocal_world_sizer?   rE   Úrdzv_handlerr%   r'   r+   r,   rW   rX   r.   )Úspecr)   r*   T)ÚnameÚfailuresF)/r   r:   ÚuuidÚuuid4r8   ÚloggerÚwarningrP   Úinfor   r   r   r   r   r!   r%   r'   r*   r-   r   r.   rY   r   r   ÚtupleÚrdzv_registryZget_rendezvous_handlerr+   r,   r   r)   rZ   Úshutdownr   Zinitialize_metricsZMetricsConfigÚrunr   ÚrecordZget_event_succeededZ	is_failedr   r]   Zreturn_valuesr   Zget_event_failedÚ	Exception)r>   r?   rE   r   Zentrypoint_namerQ   rW   rX   r[   ZagentZshutdown_rdzvÚresultr1   r1   r2   r   ²   s’    
ôòúù
ô  ÿ
þ)/rM   r^   Údataclassesr   r   Útypingr   r   r   r   r   r	   r
   Z-torch.distributed.elastic.rendezvous.registryÚdistributedZelasticZ
rendezvousÚregistryrd   Ztorch.distributed.elasticr   r   Z*torch.distributed.elastic.agent.server.apir   Z:torch.distributed.elastic.agent.server.local_elastic_agentr   Z)torch.distributed.elastic.multiprocessingr   r   Z0torch.distributed.elastic.multiprocessing.errorsr   Z$torch.distributed.elastic.rendezvousr   Z*torch.distributed.elastic.rendezvous.utilsr   Z'torch.distributed.elastic.utils.loggingr   Ú__all__r4   r`   r   r   r:   rP   r8   rY   r   r1   r1   r1   r2   Ú<module>   s:   $
E( þþ
ü