a
    ==ic`o                     @   s\  d 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	m
Z
mZmZ ddl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mZ e ZedddZdd Z e!dddZ"e!dddZ#dd Z$e%dddZ&eeee	e!f e
e! f dddZ'e!e!dddZ(d d! Z)ed%d"d#Z*e+d$krXe*  dS )&a?  
``torchrun`` provides a superset of the functionality as ``torch.distributed.launch``
with the following additional functionalities:

1. Worker failures are handled gracefully by restarting all workers.

2. Worker ``RANK`` and ``WORLD_SIZE`` are assigned automatically.

3. Number of nodes is allowed to change between minimum and maximum sizes (elasticity).

.. note:: ``torchrun`` is a python
          `console script <https://packaging.python.org/en/latest/specifications/entry-points/#use-for-scripts>`_
          to the main module
          `torch.distributed.run <https://github.com/pytorch/pytorch/blob/master/torch/distributed/run.py>`_
          declared in the ``entry_points`` configuration in
          `setup.py <https://github.com/pytorch/pytorch/blob/master/setup.py>`_.
          It is equivalent to invoking ``python -m torch.distributed.run``.


Transitioning from torch.distributed.launch to torchrun
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


``torchrun`` supports the same arguments as ``torch.distributed.launch`` **except**
for ``--use_env`` which is now deprecated. To migrate from ``torch.distributed.launch``
to ``torchrun`` follow these steps:

1.  If your training script is already reading ``local_rank`` from the ``LOCAL_RANK`` environment variable.
    Then you need simply omit the ``--use_env`` flag, e.g.:

    +--------------------------------------------------------------------+--------------------------------------------+
    |         ``torch.distributed.launch``                               |                ``torchrun``                |
    +====================================================================+============================================+
    |                                                                    |                                            |
    | .. code-block:: shell-session                                      | .. code-block:: shell-session              |
    |                                                                    |                                            |
    |    $ python -m torch.distributed.launch --use_env train_script.py  |    $ torchrun train_script.py              |
    |                                                                    |                                            |
    +--------------------------------------------------------------------+--------------------------------------------+

2.  If your training script reads local rank from a ``--local_rank`` cmd argument.
    Change your training script to read from the ``LOCAL_RANK`` environment variable as
    demonstrated by the following code snippet:

    +-------------------------------------------------------+----------------------------------------------------+
    |         ``torch.distributed.launch``                  |                    ``torchrun``                    |
    +=======================================================+====================================================+
    |                                                       |                                                    |
    | .. code-block:: python                                | .. code-block:: python                             |
    |                                                       |                                                    |
    |                                                       |                                                    |
    |    import argparse                                    |     import os                                      |
    |    parser = argparse.ArgumentParser()                 |     local_rank = int(os.environ["LOCAL_RANK"])     |
    |    parser.add_argument("--local_rank", type=int)      |                                                    |
    |    args = parser.parse_args()                         |                                                    |
    |                                                       |                                                    |
    |    local_rank = args.local_rank                       |                                                    |
    |                                                       |                                                    |
    +-------------------------------------------------------+----------------------------------------------------+

The aformentioned changes suffice to migrate from ``torch.distributed.launch`` to ``torchrun``.
To take advantage of new features such as elasticity, fault-tolerance, and error reporting of ``torchrun``
please refer to:

* :ref:`elastic_train_script` for more information on authoring training scripts that are ``torchrun`` compliant.
* the rest of this page for more information on the features of ``torchrun``.


Usage
--------

Single-node multi-worker
++++++++++++++++++++++++++++++

::

    >>> torchrun
        --standalone
        --nnodes=1
        --nproc_per_node=$NUM_TRAINERS
        YOUR_TRAINING_SCRIPT.py (--arg1 ... train script args...)

Stacked single-node multi-worker
+++++++++++++++++++++++++++++++++++

To run multiple instances (separate jobs) of single-node, multi-worker on the
same host, we need to make sure that each instance (job) is
setup on different ports to avoid port conflicts (or worse, two jobs being merged
as a single job). To do this you have to run with ``--rdzv_backend=c10d``
and specify a different port by setting ``--rdzv_endpoint=localhost:$PORT_k``.
For ``--nodes=1``, its often convenient to let ``torchrun`` pick a free random
port automatically instead of manually assgining different ports for each run.

::

    >>> torchrun
        --rdzv_backend=c10d
        --rdzv_endpoint=localhost:0
        --nnodes=1
        --nproc_per_node=$NUM_TRAINERS
        YOUR_TRAINING_SCRIPT.py (--arg1 ... train script args...)


Fault tolerant (fixed sized number of workers, no elasticity, tolerates 3 failures)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

::

    >>> torchrun
        --nnodes=$NUM_NODES
        --nproc_per_node=$NUM_TRAINERS
        --max_restarts=3
        --rdzv_id=$JOB_ID
        --rdzv_backend=c10d
        --rdzv_endpoint=$HOST_NODE_ADDR
        YOUR_TRAINING_SCRIPT.py (--arg1 ... train script args...)

``HOST_NODE_ADDR``, in form <host>[:<port>] (e.g. node1.example.com:29400), specifies the node and
the port on which the C10d rendezvous backend should be instantiated and hosted. It can be any
node in your training cluster, but ideally you should pick a node that has a high bandwidth.

.. note::
   If no port number is specified ``HOST_NODE_ADDR`` defaults to 29400.

Elastic (``min=1``, ``max=4``, tolerates up to 3 membership changes or failures)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

::

    >>> torchrun
        --nnodes=1:4
        --nproc_per_node=$NUM_TRAINERS
        --max_restarts=3
        --rdzv_id=$JOB_ID
        --rdzv_backend=c10d
        --rdzv_endpoint=$HOST_NODE_ADDR
        YOUR_TRAINING_SCRIPT.py (--arg1 ... train script args...)

``HOST_NODE_ADDR``, in form <host>[:<port>] (e.g. node1.example.com:29400), specifies the node and
the port on which the C10d rendezvous backend should be instantiated and hosted. It can be any
node in your training cluster, but ideally you should pick a node that has a high bandwidth.

.. note::
   If no port number is specified ``HOST_NODE_ADDR`` defaults to 29400.

Note on rendezvous backend
------------------------------

For multi-node training you need to specify:

1. ``--rdzv_id``: A unique job id (shared by all nodes participating in the job)
2. ``--rdzv_backend``: An implementation of
   :py:class:`torch.distributed.elastic.rendezvous.RendezvousHandler`
3. ``--rdzv_endpoint``: The endpoint where the rendezvous backend is running; usually in form
   ``host:port``.

Currently ``c10d`` (recommended), ``etcd-v2``, and ``etcd`` (legacy)  rendezvous backends are
supported out of the box. To use ``etcd-v2`` or ``etcd``, setup an etcd server with the ``v2`` api
enabled (e.g. ``--enable-v2``).

.. warning::
   ``etcd-v2`` and ``etcd`` rendezvous use etcd API v2. You MUST enable the v2 API on the etcd
   server. Our tests use etcd v3.4.3.

.. warning::
   For etcd-based rendezvous we recommend using ``etcd-v2`` over ``etcd`` which is functionally
   equivalent, but uses a revised implementation. ``etcd`` is in maintenance mode and will be
   removed in a future version.

Definitions
--------------

1. ``Node`` - A physical instance or a container; maps to the unit that the job manager works with.

2. ``Worker`` - A worker in the context of distributed training.

3. ``WorkerGroup`` - The set of workers that execute the same function (e.g. trainers).

4. ``LocalWorkerGroup`` - A subset of the workers in the worker group running on the same node.

5. ``RANK`` - The rank of the worker within a worker group.

6. ``WORLD_SIZE`` - The total number of workers in a worker group.

7. ``LOCAL_RANK`` - The rank of the worker within a local worker group.

8. ``LOCAL_WORLD_SIZE`` - The size of the local worker group.

9. ``rdzv_id`` - A user-defined id that uniquely identifies the worker group for a job. This id is
   used by each node to join as a member of a particular worker group.

9. ``rdzv_backend`` - The backend of the rendezvous (e.g. ``c10d``). This is typically a strongly
   consistent key-value store.

10. ``rdzv_endpoint`` - The rendezvous backend endpoint; usually in form ``<host>:<port>``.

A ``Node`` runs ``LOCAL_WORLD_SIZE`` workers which comprise a ``LocalWorkerGroup``. The union of
all ``LocalWorkerGroups`` in the nodes in the job comprise the ``WorkerGroup``.

Environment Variables
----------------------

The following environment variables are made available to you in your script:

1. ``LOCAL_RANK`` -  The local rank.

2. ``RANK`` -  The global rank.

3. ``GROUP_RANK`` - The rank of the worker group. A number between 0 and ``max_nnodes``. When
   running a single worker group per node, this is the rank of the node.

4. ``ROLE_RANK`` -  The rank of the worker across all the workers that have the same role. The role
   of the worker is specified in the ``WorkerSpec``.

5. ``LOCAL_WORLD_SIZE`` - The local world size (e.g. number of workers running locally); equals to
   ``--nproc_per_node`` specified on ``torchrun``.

6. ``WORLD_SIZE`` - The world size (total number of workers in the job).

7. ``ROLE_WORLD_SIZE`` - The total number of workers that was launched with the same role specified
   in ``WorkerSpec``.

8. ``MASTER_ADDR`` - The FQDN of the host that is running worker with rank 0; used to initialize
   the Torch Distributed backend.

9. ``MASTER_PORT`` - The port on the ``MASTER_ADDR`` that can be used to host the C10d TCP store.

10. ``TORCHELASTIC_RESTART_COUNT`` - The number of worker group restarts so far.

11. ``TORCHELASTIC_MAX_RESTARTS`` - The configured maximum number of restarts.

12. ``TORCHELASTIC_RUN_ID`` - Equal to the rendezvous ``run_id`` (e.g. unique job id).

13. ``PYTHON_EXEC`` - System executable override. If provided, the python user script will
    use the value of ``PYTHON_EXEC`` as executable. The `sys.executable` is used by default.

Deployment
------------

1. (Not needed for the C10d backend) Start the rendezvous backend server and get the endpoint (to be
   passed as ``--rdzv_endpoint`` to the launcher script)

2. Single-node multi-worker: Start the launcher on the host to start the agent process which
   creates and monitors a local worker group.

3. Multi-node multi-worker: Start the launcher with the same arguments on all the nodes
   participating in training.

When using a job/cluster manager the entry point command to the multi-node job should be this
launcher.

Failure Modes
---------------

1. Worker failure: For a training job with ``n`` workers, if ``k<=n`` workers fail all workers
   are stopped and restarted up to ``max_restarts``.

2. Agent failure: An agent failure results in a local worker group failure. It is up to the job
   manager to fail the entire job (gang semantics) or attempt to replace the node. Both behaviors
   are supported by the agent.

3. Node failure: Same as agent failure.

Membership Changes
--------------------

1. Node departure (scale-down): The agent is notified of the departure, all existing workers are
   stopped, a new ``WorkerGroup`` is formed, and all workers are started with a new ``RANK`` and
   ``WORLD_SIZE``.

2. Node arrival (scale-up): The new node is admitted to the job, all existing workers are stopped,
   a new ``WorkerGroup`` is formed, and all workers are started with a new ``RANK`` and
   ``WORLD_SIZE``.

Important Notices
--------------------

1. This utility and multi-process distributed (single-node or
   multi-node) GPU training currently only achieves the best performance using
   the NCCL distributed backend. Thus NCCL backend is the recommended backend to
   use for GPU training.

2. The environment variables necessary to initialize a Torch process group are provided to you by
   this module, no need for you to pass ``RANK`` manually.  To initialize a process group in your
   training script, simply run:

::

 >>> import torch.distributed as dist
 >>> dist.init_process_group(backend="gloo|nccl")

3. In your training program, you can either use regular distributed functions
   or use :func:`torch.nn.parallel.DistributedDataParallel` module. If your
   training program uses GPUs for training and you would like to use
   :func:`torch.nn.parallel.DistributedDataParallel` module,
   here is how to configure it.

::

    local_rank = int(os.environ["LOCAL_RANK"])
    model = torch.nn.parallel.DistributedDataParallel(model,
                                                      device_ids=[local_rank],
                                                      output_device=local_rank)

Please ensure that ``device_ids`` argument is set to be the only GPU device id
that your code will be operating on. This is generally the local rank of the
process. In other words, the ``device_ids`` needs to be ``[int(os.environ("LOCAL_RANK"))]``,
and ``output_device`` needs to be ``int(os.environ("LOCAL_RANK"))`` in order to use this
utility


4. On failures or membership changes ALL surviving workers are killed immediately. Make sure to
   checkpoint your progress. The frequency of checkpoints should depend on your job's tolerance
   for lost work.

5. This module only supports homogeneous ``LOCAL_WORLD_SIZE``. That is, it is assumed that all
   nodes run the same number of local workers (per role).

6. ``RANK`` is NOT stable. Between restarts, the local workers on a node can be assgined a
   different range of ranks than before. NEVER hard code any assumptions about the stable-ness of
   ranks or some correlation between ``RANK`` and ``LOCAL_RANK``.

7. When using elasticity (``min_size!=max_size``) DO NOT hard code assumptions about
   ``WORLD_SIZE`` as the world size can change as nodes are allowed to leave and join.

8. It is recommended for your script to have the following structure:

::

  def main():
    load_checkpoint(checkpoint_path)
    initialize()
    train()

  def train():
    for batch in iter(dataset):
      train_step(batch)

      if should_checkpoint:
        save_checkpoint(checkpoint_path)

9. (Recommended) On worker errors, this tool will summarize the details of the error
   (e.g. time, rank, host, pid, traceback, etc). On each node, the first error (by timestamp)
   is heuristically reported as the "Root Cause" error. To get tracebacks as part of this
   error summary print out, you must decorate your main entrypoint function in your
   training script as shown in the example below. If not decorated, then the summary
   will not include the traceback of the exception and will only contain the exitcode.
   For details on torchelastic error handling see: https://pytorch.org/docs/stable/elastic/errors.html

::

  from torch.distributed.elastic.multiprocessing.errors import record

  @record
  def main():
      # do train
      pass

  if __name__ == "__main__":
      main()

    N)	REMAINDERArgumentParser)CallableListTupleUnion)	check_envenv)Std)record)_parse_rendezvous_config)macros)
get_logger)LaunchConfigelastic_launch)returnc                  C   s  t dd} | jdttddd | jdttdd	d | jd
ttddd | jdttddd | jdttddd | jdttddd | jdtdd | jdttddd | jdttddd | jdttdg d d!d" | jd#ttd$d%d | jd&d'td(d | jd)td*d | jd+td,d | jd-ttd.d/d | jd0d1ttd2d3d | jd4d5ttd2d6d | jd7ttdd8d9 | jd:d;ttd<d= | jd>d?ttd@d= | jdAtdBdC | jdDtdE | S )Fz1Helper function parsing the command line options.z+Torch Distributed Elastic Training Launcher)descriptionz--nnodesz1:1zONumber of nodes, or the range of nodes in form <minimum_nodes>:<maximum_nodes>.)actiontypedefaulthelpz--nproc_per_node1zDNumber of workers per node; supported values: [auto, cpu, gpu, int].z--rdzv_backendstaticzRendezvous backend.z--rdzv_endpoint z;Rendezvous backend endpoint; usually in form <host>:<port>.z	--rdzv_idnonezUser-defined group id.z--rdzv_confzJAdditional rendezvous configuration (<key1>=<value1>,<key2>=<value2>,...).z--standalonea	  Start a local standalone rendezvous backend that is represented by a C10d TCP store on port 29400. Useful when launching single-node, multi-worker job. If specified --rdzv_backend, --rdzv_endpoint, --rdzv_id are auto-assigned; any explicitly set values are ignored.)r   r   z--max_restartsr   z7Maximum number of worker group restarts before failing.z--monitor_interval   z6Interval, in seconds, to monitor the state of workers.z--start_methodspawn)r   forkZ
forkserverz:Multiprocessing start method to use when creating workers.)r   r   r   choicesr   z--roler   z"User-defined role for the workers.-mz--modulezwChange each process to interpret the launch script as a Python module, executing with the same behavior as 'python -m'.z--no_pythonz|Skip prepending the training script with 'python' - just execute it directly. Useful when the script is not a Python script.z
--run_pathzRun the training script with runpy.run_path in the same interpreter. Script must be provided as an abs path (e.g. /abs/path/script.py). Takes precedence over --no_python.z	--log_dirNzBase directory to use for log files (e.g. /var/log/torch/elastic). The same directory is re-used for multiple runs (a unique job-level sub-directory is created with rdzv_id as the prefix).z-rz--redirects0zRedirect std streams into a log file in the log directory (e.g. [-r 3] redirects both stdout+stderr for all workers, [-r 0:1,1:2] redirects stdout for local rank 0 and stderr for local rank 1).z-tz--teezQTee std streams into a log file and also to console (see --redirects for format).z--node_rankz5Rank of the node for multi-node distributed training.)r   r   r   r   z--master_addrz	127.0.0.1zAddress of the master node (rank 0). It should be either the IP address or the hostname of rank 0. For single node multi-proc training the --master_addr can simply be 127.0.0.1; IPv6 should have the pattern `[0:0:0:0:0:0:0:1]`.)r   r   r   r   z--master_porti<s  zZPort on the master node (rank 0) to be used for communication during distributed training.training_scriptzFull path to the (single GPU) training program/script to be launched in parallel, followed by all the arguments for the training script.)r   r   training_script_args)nargs)r   add_argumentr	   strr   intfloatr   )parser r)   f/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/torch/distributed/run.pyget_args_parser  s    
	
	r+   c                 C   s   t  }|| S N)r+   
parse_args)argsr(   r)   r)   r*   r-   H  s    r-   )nnodesc                 C   sf   |  d}t|dkr(t|d  }}n6t|dkrNt|d }t|d }ntd|  d||fS )N:   r      znnodes=z is not in "MIN:MAX" format)splitlenr&   RuntimeError)r/   Zarr	min_nodes	max_nodesr)   r)   r*   parse_min_max_nnodesM  s    
r8   )nproc_per_nodec                 C   s   zt d|  d t| W S  ty   | dkr@t }d}nh| dkrjtj sZtdd}tj	 }n>| dkrtj rtj	 }d}qt }d}ntd|  t
d|  d| d	t  d
|  | Y S 0 d S )NzUsing nproc_per_node=.cpuZgpuzCuda is not available.autoz"Unsupported nproc_per_node value: z, seting to z since the instance has  )logginginfor&   
ValueErroros	cpu_counttorchcudaZis_availableZdevice_countlog)r9   Znum_procZdevice_typer)   r)   r*   determine_local_world_size[  s:    



rF   c                 C   s(   | j dkr"| js"| j d| j S | jS )Nr   r0   )rdzv_backendrdzv_endpointZmaster_addrZmaster_portr.   r)   r)   r*   get_rdzv_endpointz  s    rJ   c                 C   s   t | dsdS | jS )a+  
    Retrieves ``use_env`` from the args.
    ``use_env`` is a legacy argument, if ``use_env`` is False, the
    ``--node_rank`` argument will be transferred to all worker processes.
    ``use_env`` is only used by the ``torch.distributed.launch`` and will
    be deprecated in future releases.
    use_envT)hasattrrK   rI   r)   r)   r*   get_use_env  s    
rM   c                 C   s  t | j\}}d|  k r"|ks(n J | jdks6J t| j}dtjvrv|dkrvd}td| d t	|tjd< t
| j}| jdkr| j|d< t| }t|||| j| j|| j|| j| j| jt| jt| j| jd}| j }g }	t| }
| jrt}|	| j nT|rJtd	t j!}|	d
 | j"r<|	d |	| j n| j"rZt#d| j}|
sx|	dt$j%  |	&| j' |||	fS )Nr   ZOMP_NUM_THREADSr1   zo
*****************************************
Setting OMP_NUM_THREADS environment variable for each process to be z in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. 
*****************************************r   Zrank)r6   r7   r9   Zrun_idrolerH   rG   rdzv_configsmax_restartsmonitor_intervalstart_method	redirectsteelog_dirZPYTHON_EXECz-ur   zODon't use both the '--no_python' flag and the '--module' flag at the same time.z--local_rank=)(r8   r/   rP   rF   r9   rA   environrE   warningr%   r   Z	rdzv_confrG   Z	node_rankrJ   r   rdzv_idrN   rQ   rR   r
   Zfrom_strrS   rT   rU   Z	no_pythonrM   run_pathrun_script_pathappendr!   getenvsys
executablemoduler@   r   Z
local_rankextendr"   )r.   r6   r7   r9   Zomp_num_threadsrO   rH   configZwith_pythoncmd_argsrK   cmdr)   r)   r*   config_from_args  sj    
	






rd   )r!   r"   c                 G   s8   ddl }ddl}| gg | |_|j|jd dd dS )z
    Runs the provided `training_script` from within this interpreter.
    Usage: `script_as_function("/abs/path/to/script.py", "--arg1", "val1")`
    r   N__main__)run_name)runpyr]   argvrY   )r!   r"   rg   r]   r)   r)   r*   rZ     s    rZ   c              	   C   sf   | j rDd| _d| _tt | _td| j d| j d| j d t	| \}}}t
||d|  d S )NZc10dzlocalhost:29400zH
**************************************
Rendezvous info:
--rdzv_backend=z --rdzv_endpoint=z --rdzv_id=z(
**************************************
)ra   
entrypoint)
standalonerG   rH   r%   uuiduuid4rX   rE   r?   rd   r   )r.   ra   rc   rb   r)   r)   r*   run  s(    	rm   c                 C   s   t | } t|  d S r,   )r-   rm   rI   r)   r)   r*   main  s    rn   re   )N),__doc__r>   rA   r]   rk   argparser   r   typingr   r   r   r   rC   Ztorch.distributed.argparse_utilr   r	   Z)torch.distributed.elastic.multiprocessingr
   Z0torch.distributed.elastic.multiprocessing.errorsr   Z*torch.distributed.elastic.rendezvous.utilsr   Ztorch.distributed.elastic.utilsr   Z'torch.distributed.elastic.utils.loggingr   Ztorch.distributed.launcher.apir   r   rE   r+   r-   r%   r8   rF   rJ   boolrM   rd   rZ   rm   rn   __name__r)   r)   r)   r*   <module>	   s>     l B$H
