launch.py 25.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
14
r"""
15
fleetrun is a module that spawns multiple distributed
16 17
process on each training node for gpu training and cpu training.
Usage:
18
    In both of single node training or multiple node training, this module
19 20 21 22 23 24 25 26
launch a process on each of the given gpu card or cpu machine.
    GPU training:
    1. for single node training with all visible gpu cards:
       fleetrun your_training_py (arg1 arg2 and all others)
    2. for single node training with [0,4) cards
       fleetrun --gpus="0,1,2,3" your_training_py (arg1 arg2 and all others)
    3. for multiple node training such as two node:192.168.0.16, 192.168.0.17
        on 192.168.0.16:
27
            fleetrun --ips="192.168.0.16,192.168.0.17" \
28 29 30 31 32 33
                your_training_py (arg1 arg2 and all others)
        on 192.168.0.17:
            fleetrun --ips="192.168.0.16,192.168.0.17" \
                your_training_py (arg1 arg2 and all others)
    CPU training:
    1. for single node training with multi servers and workers:
34
        fleetrun --server_num=2 --worker_num=2 your_training_py (arg1 arg2 and all others)
35
    2. for multiple node training such as two node:192.168.0.16, 192.168.0.17 \
36
        with 2 servers and 4 workers.
37
        on 192.168.0.16:
38 39
            fleetrun --servers="192.168.0.16:6170,192.168.0.17:6170" \
                --workers="192.168.0.16,192.168.0.17,192.168.0.16,192.168.0.17" \
40 41 42
                your_training_py (arg1 arg2 and all others)
        on 192.168.0.17:
            fleetrun --servers="192.168.0.16:6170,192.168.0.17:6171" \
43 44 45 46 47 48 49 50 51 52 53
                --workers="192.168.0.16,192.168.0.17,192.168.0.16,192.168.0.17" \
                your_training_py (arg1 arg2 and all others)
    3. use gloo backend for multiple node training such as two node:192.168.0.16, 192.168.0.17 \
        with 2 servers and 4 workers. (workers should set port)
        on 192.168.0.16:
            fleetrun --servers="192.168.0.16:6170,192.168.0.17:6170" \
                --workers="192.168.0.16:6171,192.168.0.17:6171,192.168.0.16:6172,192.168.0.17:6172" \
                your_training_py (arg1 arg2 and all others)
        on 192.168.0.17:
            fleetrun --servers="192.168.0.16:6170,192.168.0.17:6170" \
                --workers="192.168.0.16:6171,192.168.0.17:6171,192.168.0.16:6172,192.168.0.17:6172" \
54 55 56 57
                your_training_py (arg1 arg2 and all others)
"""

from __future__ import print_function
58 59

import shutil
60
import sys
61
import tempfile
62 63 64 65 66 67
from sys import version
import subprocess
import os
import time
import six
import copy
68
import argparse
69 70 71
from argparse import ArgumentParser, REMAINDER
import paddle
import paddle.fluid as fluid
72
from paddle.distributed.fleet import launch_utils
73

74
# TODO(danleifeng): Don't import * from a module
75
from paddle.distributed.fleet.launch_utils import *
76 77
from paddle.distributed.fleet import cloud_utils
from paddle.distributed.fleet import ascend_utils
78

K
kuizhiqing 已提交
79
from paddle.distributed.fleet.elastic import enable_elastic, launch_elastic
80

81 82
__all__ = []

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

def _print_arguments(args):
    print("-----------  Configuration Arguments -----------")
    for arg, value in sorted(six.iteritems(vars(args))):
        print("%s: %s" % (arg, value))
    print("------------------------------------------------")


def _parse_args():
    """
    Helper function parsing the command line options
    @retval ArgumentParser
    """
    parser = ArgumentParser(
        description='''start paddle training using multi-process mode.
see: http://www.paddlepaddle.org/documentation/docs/zh/1.6/user_guides/howto/training/cluster_howto.html#permalink-8--nccl2-
''')
100
    base_group = parser.add_argument_group("Base Parameters")
101

102 103
    base_group.add_argument(
        "--log_dir",
104
        type=str,
105
        default="log",
G
Guoxia Wang 已提交
106
        help="The path for each process's log. Default --log_dir=log/")
X
xiongkun 已提交
107 108 109 110 111 112
    base_group.add_argument(
        "--backend",
        type=str,
        default="auto",
        help="Specifize the backend, can be gloo|nccl|bkcl|auto. Default value is auto which perfers nccl or bkcl."
    )
113 114 115 116 117 118 119 120
    base_group.add_argument(
        "--nproc_per_node",
        type=int,
        default=None,
        help="The number of processes to launch on a node."
        "In gpu training, it should be less or equal to the gpus number of you system(or you set by --gpus). And so each process can"
        " bound to one or average number of gpus.")

121 122 123
    base_group.add_argument(
        "--run_mode",
        type=str,
G
gongweibao 已提交
124
        default=None,
125 126
        help="run mode of job, can be:collective/ps/ps-heter")

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    if fluid.core.is_compiled_with_cuda():
        base_group.add_argument(
            "--gpus",
            type=str,
            default=None,
            help="It's for gpu training."
            "For example:"
            "--gpus=\"0,1,2,3\" will launch four training processes each bound to one gpu."
        )
        base_group.add_argument("--selected_gpus", dest="gpus")

    if fluid.core.is_compiled_with_xpu():
        base_group.add_argument(
            "--xpus",
            type=str,
            default=None,
            help="It's for xpu training. For example: "
            "--xpus=\"0,1,2,3\" will launch four training processes each bound to one xpu."
        )
        base_group.add_argument("--selected_xpus", dest="xpus")
147

148
    base_group.add_argument(
149 150 151 152 153 154 155
        "training_script",
        type=str,
        help="The full path to the single GPU training "
        "program/script to be launched in parallel, "
        "followed by all the arguments for the "
        "training script")

156 157 158 159 160 161 162 163 164 165
    base_group.add_argument('training_script_args', nargs=REMAINDER)

    # Optional arguments for the launch helper
    # for collective
    collective_group = parser.add_argument_group("Collective Parameters")
    collective_group.add_argument(
        "--ips",
        type=str,
        default="127.0.0.1",
        help="Paddle cluster nodes ips, such as 192.168.0.16,192.168.0.17..")
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    collective_group.add_argument(
        "--rank_mapping_file",
        type=argparse.FileType('r'),
        default=sys.stdin,
        help="This rank mapping information in json format is used specifically "
        "for lazy launch for auto parallel. Some of the ranks in each node "
        "may not be used, and the indices of rank should be kept the same "
        "as the indices of sub-task splited by auto parallel. "
        " { "
        "   \"ip_ranks\": [ "
        "     { "
        "       \"ip\": \"127.0.0.1\", "
        "       \"ranks\": [0,1] "
        "     }, "
        "     { "
        "       \"ip\": \"127.0.0.2\", "
        "       \"ranks\": [2,3,4] "
        "     } "
        "   ] "
        " } ")
    collective_group.add_argument(
        "--enable_auto_mapping",
        type=bool,
        default=False,
        help="Set true to enable the lazy launch for auto-parallel scenario.")
191 192 193 194 195 196 197 198 199 200 201

    ps_group = parser.add_argument_group("Parameter-Server Parameters")
    # for parameter server
    ps_group.add_argument(
        "--servers", type=str, default="", help="User defined servers ip:port")
    ps_group.add_argument(
        "--workers", type=str, default="", help="User defined workers ip:port")
    ps_group.add_argument(
        "--heter_workers",
        type=str,
        default="",
202
        help="User defined heter workers in each stage ip1:port1;ip2:port2")
203 204 205 206
    ps_group.add_argument(
        "--heter_devices",
        type=str,
        default="",
207
        help="User defined heter devices in each stage cpu;gpu;cpu")
208 209 210 211

    ps_group.add_argument("--worker_num", type=int, help="number of workers")
    ps_group.add_argument("--server_num", type=int, help="number of servers")
    ps_group.add_argument(
212 213 214
        "--heter_worker_num",
        type=str,
        help="number of heter_workers in each stage 1;2;3")
215
    ps_group.add_argument("--http_port", type=int, help="Gloo http Port")
216

217 218 219 220 221 222 223 224 225 226 227 228
    # parameter elastic mode
    elastic_group = parser.add_argument_group("Elastic Parameters")
    elastic_group.add_argument(
        "--elastic_server", type=str, help="etcd server host:port")
    elastic_group.add_argument("--job_id", type=str, help="job unique id")
    elastic_group.add_argument("--np", type=int, help="job pod/node number")
    elastic_group.add_argument("--scale", type=int, default=0, help="scale np")
    elastic_group.add_argument(
        "--host", type=str, help="bind host, default to POD_IP env")
    elastic_group.add_argument(
        "--force", type=bool, default=False, help="update np force")

229 230 231
    return parser.parse_args()


232
def get_cluster_from_args(args, device_mode, devices_per_proc):
233 234 235 236
    node_ips = [x.strip() for x in args.ips.split(',')]
    if len(node_ips) == 1:
        node_ip = node_ips[0]
    else:
237 238 239 240
        if args.host:
            node_ip = args.host
        else:
            _, node_ip = get_host_name_ip()
241

242
    assert node_ip in node_ips, "Can't find your local ip {%s} in node_ips: {%s}" \
243
        % (node_ip, node_ips)
244 245
    node_rank = node_ips.index(node_ip)

246
    logger.debug("parsed from args: node_ips:{} node_ip:{} node_rank:{}".format(
247 248 249 250 251
        node_ips, node_ip, node_rank))

    free_ports = None
    if not cloud_utils.use_paddlecloud() and len(
            node_ips) <= 1 and os.environ.get('FLAGS_START_PORT') is None:
252
        free_ports = find_free_ports(len(devices_per_proc))
253 254 255 256 257
        if free_ports is not None:
            free_ports = list(free_ports)
    else:
        start_port = 6070
        if os.environ.get('FLAGS_START_PORT') is not None:
258
            start_port = int(os.environ.get('FLAGS_START_PORT'))
259

260 261 262
        free_ports = [
            x for x in range(start_port, start_port + len(devices_per_proc))
        ]
263

264 265 266
    trainer_endpoints = []
    for ip in node_ips:
        trainer_endpoints.append(["%s:%d" % (ip, port) for port in free_ports])
267 268
    return get_cluster(node_ips, node_ip, trainer_endpoints, device_mode,
                       devices_per_proc)
269 270


X
xiongkun 已提交
271 272 273 274 275 276 277 278 279 280 281 282
def cpuonly_check(args):
    if args.ips and len(args.ips.split(',')) > 1:
        raise RuntimeError(
            "CPUONLY launch only support single trainer, that is len(ips)=1, but got %s."
            % args.ips)
    if args.run_mode:
        assert args.run_mode == 'cpuonly', "CPUONLY launch only support run mode is CPUONLY"
    if args.servers:
        raise RuntimeError("CPUONLY launch can't have --servers as arguments.")
    return True


K
kuizhiqing 已提交
283 284
def launch_collective(args):
    # parse arguments, used for cloud-single-machine and local
X
xiongkun 已提交
285
    if args.backend == 'gloo': cpuonly_check(args)
K
kuizhiqing 已提交
286 287 288 289 290 291 292 293 294 295 296
    (device_mode, devices_per_proc) = launch_utils.get_device_proc_info(args)
    trainers_num = cloud_utils.get_trainers_num()
    logger.debug("parsed from args trainerss_num:{} mode:{} devices:{}".format(
        trainers_num, device_mode, devices_per_proc))

    cluster = None
    pod = None

    start_port = 6170
    if os.environ.get('FLAGS_START_PORT') is not None:
        start_port = os.environ.get('FLAGS_START_PORT')
297 298 299
    # lazy launch for auto-parallel
    if args.enable_auto_mapping == True:
        cluster, pod = get_mapped_cluster_from_args(args, device_mode)
K
kuizhiqing 已提交
300
    else:
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
        # for ascend
        if device_mode == DeviceMode.ASCEND_NPU:
            cluster, pod = ascend_utils.get_cloud_cluster(
                rank_table_file=os.getenv("RANK_TABLE_FILE", None),
                device_mode=device_mode,
                start_port=start_port)
        elif cloud_utils.use_paddlecloud() and trainers_num != 1:
            cluster, pod = cloud_utils.get_cloud_cluster(
                args.ips, device_mode, devices_per_proc, start_port)
            logger.debug("get cluster from cloud:{}".format(cluster))
        else:
            # trainers_num = 1 or not use paddlecloud ips="a,b"
            cluster, pod = get_cluster_from_args(args, device_mode,
                                                 devices_per_proc)
            logger.debug("get cluster from args:{}".format(cluster))
K
kuizhiqing 已提交
316 317 318 319 320 321 322

    global_envs = copy.copy(os.environ.copy())
    gloo_rendezvous_dir = tempfile.mkdtemp()
    # add gloo env
    global_envs["PADDLE_WITH_GLOO"] = str(os.getenv("PADDLE_WITH_GLOO", "0"))
    global_envs["PADDLE_GLOO_RENDEZVOUS"] = "3"
    global_envs["PADDLE_GLOO_FS_PATH"] = gloo_rendezvous_dir
X
xiongkun 已提交
323
    global_envs["PADDLE_DISTRI_BACKEND"] = args.backend
K
kuizhiqing 已提交
324 325 326 327 328 329 330 331 332 333 334

    procs = start_local_trainers(
        cluster,
        pod,
        training_script=args.training_script,
        training_script_args=args.training_script_args,
        log_dir=args.log_dir,
        envs=global_envs)

    for idx, proc in enumerate(procs):
        print("launch proc_id:{} idx:{}".format(proc.proc.pid, idx))
335

K
kuizhiqing 已提交
336
    while True:
K
kuizhiqing 已提交
337 338
        try:
            alive = watch_local_trainers(procs, cluster.trainers_nranks())
339

K
kuizhiqing 已提交
340 341 342 343
            if not alive:
                logger.info("Local processes completed.")
                logger.debug("POD info:{}".format(pod))
                break
344

K
kuizhiqing 已提交
345 346 347 348 349 350
            time.sleep(3)

        except:
            logger.warning("Terminating... exit")
            terminate_local_procs(procs)
            exit(1)
K
kuizhiqing 已提交
351 352 353

    if os.path.exists(gloo_rendezvous_dir):
        shutil.rmtree(gloo_rendezvous_dir)
354

355

356 357 358 359 360 361 362
def launch_ps(args, distribute_mode):
    cloud_flag = cloud_utils.use_paddlecloud()

    # for ps-cpu on paddlecloud
    if cloud_flag and distribute_mode == DistributeMode.PS:
        direct_start(args)
        return
363 364 365 366 367
    #elif cloud_flag and distribute_mode == DistributeMode.PS_HETER:
    #    cloud_ps_heter_env_set(args)
    #    args.workers = os.getenv("PADDLE_TRAINER_ENDPOINTS")
    #    args.servers = os.getenv("PADDLE_PSERVERS_IP_PORT_LIST")
    #    args.heter_workers = os.getenv("PADDLE_HETER_TRAINER_IP_PORT_LIST")
368 369 370 371 372 373

    ps_launcher = ParameterServerLauncher(args, distribute_mode)
    ps_launcher.start_ps()
    return


374 375 376 377 378 379 380 381 382 383 384 385
def infer_backend(args):
    if args.backend != "auto": return
    if fluid.core.is_compiled_with_cuda():
        args.backend = 'nccl'
    elif fluid.core.is_compiled_with_npu():
        args.backend = 'unknown'
    elif fluid.core.is_compiled_with_xpu():
        args.backend = 'bkcl'
    else:
        args.backend = 'gloo'


386
def which_distributed_mode(args):
387
    infer_backend(args)  # modify the args.backend
388 389 390 391 392 393 394 395 396 397
    if args.run_mode is not None:
        assert args.run_mode in ["collective", "ps", "ps-heter"]

    if args.run_mode == "collective":
        return DistributeMode.COLLECTIVE
    elif args.run_mode == "ps":
        return DistributeMode.PS
    elif args.run_mode == "ps-heter":
        return DistributeMode.PS_HETER

398
    ps_args = [
399
        '--worker_num', '--server_num', '--heter_worker_num', '--servers',
400
        '--workers', '--heter_workers', '--heter_devices', '--http_port'
401
    ]
402
    collective_args = ['--ips']
403

404
    ps_heter_args = ["--heter_worker_num", "--heter_workers", "--heter_devices"]
405 406 407 408 409 410 411 412

    has_ps_args = [
        ps_arg for ps_arg in ps_args if ps_arg in " ".join(sys.argv[1:-1])
    ]
    has_collective_args = [
        co_arg for co_arg in collective_args
        if co_arg in " ".join(sys.argv[1:-1])
    ]
413 414 415 416 417 418

    if len(has_ps_args) > 1 and len(has_collective_args) > 1:
        raise ValueError(
            "Only one mode(Collective or Parameter-Server) can be selected at the same time, but more than one configuration was received."
        )

419
    if fluid.core.is_compiled_with_cuda():
420
        accelerators = fluid.core.get_cuda_device_count()
B
Baibaifan 已提交
421 422
    elif fluid.core.is_compiled_with_npu():
        accelerators = fluid.core.get_npu_device_count()
423
    elif fluid.core.is_compiled_with_xpu():
424
        accelerators = fluid.core.get_xpu_device_count()
425
    else:
426
        accelerators = 0
427

428 429
    if len(has_ps_args) > 0:
        logger.info(
430 431
            "Run parameter-sever mode. pserver arguments:{}, accelerators count:{}".
            format(has_ps_args, accelerators))
432 433 434 435 436
        has_ps_heter_args = list(set(has_ps_args) & set(ps_heter_args))
        if len(has_ps_heter_args) > 0:
            return DistributeMode.PS_HETER
        else:
            return DistributeMode.PS
437
    elif len(has_collective_args) > 0:
438 439
        logger.info("Run collective mode. gpu arguments:{}, cuda count:{}".
                    format(has_collective_args, accelerators))
440
        return DistributeMode.COLLECTIVE
441
    else:
442 443
        if not fluid.core.is_compiled_with_cuda(
        ) and not fluid.core.is_compiled_with_xpu():
X
xiongkun 已提交
444 445 446 447 448 449 450
            if args.servers:
                logger.warning(
                    "Not found distinct arguments and not compiled with cuda or xpu. \
But found args.servers not empty, default use ps mode")
                return DistributeMode.PS
            else:
                return DistributeMode.COLLECTIVE
451 452
        else:
            logger.warning(
453
                "Not found distinct arguments and compiled with cuda or xpu. Default use collective mode"
454 455
            )
            return DistributeMode.COLLECTIVE
456 457 458


def launch():
G
Guoxia Wang 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    """
    Paddle distribution training entry ``python -m paddle.distributed.launch``.
    
    Usage:
        .. code-block:: bash
            :name: code-block-bash1

            python -m paddle.distributed.launch [-h] [--log_dir LOG_DIR] [--nproc_per_node NPROC_PER_NODE] [--run_mode RUN_MODE] [--gpus GPUS]
                             [--selected_gpus GPUS] [--ips IPS] [--servers SERVERS] [--workers WORKERS] [--heter_workers HETER_WORKERS]
                             [--worker_num WORKER_NUM] [--server_num SERVER_NUM] [--heter_worker_num HETER_WORKER_NUM]
                             [--http_port HTTP_PORT] [--elastic_server ELASTIC_SERVER] [--job_id JOB_ID] [--np NP] [--scale SCALE]
                             [--host HOST] [--force FORCE]
                             training_script ...    


    Base Parameters:
G
Guoxia Wang 已提交
475
        - ``--log_dir``: The path for each process's log. e.g., ``--log_dir=output_dir``. Default ``--log_dir=log``.
G
Guoxia Wang 已提交
476

G
Guoxia Wang 已提交
477
        - ``--nproc_per_node``: The number of processes to launch on a node. In gpu training, it should be less or equal to the gpus number of you system(or you set by --gpus).  e.g., ``--nproc_per_node=8``
G
Guoxia Wang 已提交
478

G
Guoxia Wang 已提交
479
        - ``--run_mode``: run mode of job, can be:collective/ps/ps-heter. e.g., ``--run_mode=ps``. Default ``--run_mode=collective``.
G
Guoxia Wang 已提交
480

G
Guoxia Wang 已提交
481
        - ``--gpus``: It's for gpu training. e.g., ``--gpus=0,1,2,3`` will launch four training processes each bound to one gpu.
G
Guoxia Wang 已提交
482 483 484

        - ``--selected_gpus``: gpus aliases, recommend to use ``--gpus``.
        
G
Guoxia Wang 已提交
485
        - ``--xpus``: It's for xpu training if xpu is available. e.g., ``--xpus=0,1,2,3``.
G
Guoxia Wang 已提交
486 487 488
        
        - ``--selected_xpus``: xpus aliases, recommend to use ``--xpus``.

G
Guoxia Wang 已提交
489
        - ``training_script``: The full path to the single GPU training program/script to be launched in parallel, followed by all the arguments for the training script. e.g., ``traing.py``
G
Guoxia Wang 已提交
490

G
Guoxia Wang 已提交
491
        - ``training_script_args``: The args of training_script. e.g., ``--lr=0.1``
G
Guoxia Wang 已提交
492 493

    Collective Parameters:
G
Guoxia Wang 已提交
494
        - ``--ips``: Paddle cluster nodes ips, e.g., ``--ips=192.168.0.16,192.168.0.17``. Default ``--ips=127.0.0.1``.
G
Guoxia Wang 已提交
495 496

    Parameter-Server Parameters:
G
Guoxia Wang 已提交
497
        - ``--servers``: User defined servers ip:port, e.g., ``--servers="192.168.0.16:6170,192.168.0.17:6170"``
G
Guoxia Wang 已提交
498

G
Guoxia Wang 已提交
499
        - ``--workers``: User defined workers ip:port, e.g., ``--workers="192.168.0.16:6171,192.168.0.16:6172,192.168.0.17:6171,192.168.0.17:6172"``
G
Guoxia Wang 已提交
500

501
        - ``--heter_workers``: User defined heter workers ip1:port1;ip2:port2, e.g., ``--heter_workers="192.168.0.16:6172;192.168.0.17:6172"``
G
Guoxia Wang 已提交
502 503 504 505 506

        - ``--worker_num``: Number of workers (It recommend to set when in the emulated distributed environment using single node)

        - ``--server_num``: Number of servers (It recommend to set when in the emulated distributed environment using single node)

507 508 509
        - ``--heter_worker_num``: Number of heter_workers in each stage (It recommend to set when in the emulated distributed environment using single node)
        
        - ``--heter_devices``: Type of heter_device in each stage
G
Guoxia Wang 已提交
510 511 512 513

        - ``--http_port``: Gloo http Port

    Elastic Parameters:
G
Guoxia Wang 已提交
514
        - ``--elastic_server``: etcd server host:port, e.g., ``--elastic_server=127.0.0.1:2379``
G
Guoxia Wang 已提交
515

G
Guoxia Wang 已提交
516
        - ``--job_id``: job unique id, e.g., ``--job_id=job1``
G
Guoxia Wang 已提交
517

G
Guoxia Wang 已提交
518
        - ``--np``: job pod/node number, e.g., ``--np=2``
G
Guoxia Wang 已提交
519 520 521 522 523 524 525 526 527 528 529

        - ``--host``: bind host, default to POD_IP env.


    Returns:
        ``None``

    Examples 1 (collective, single node):
        .. code-block:: bash
            :name: code-block-example-bash1
            
G
Guoxia Wang 已提交
530
            # For training on single node using 4 gpus.
G
Guoxia Wang 已提交
531 532 533 534 535 536 537

            python -m paddle.distributed.launch --gpus=0,1,2,3 train.py --lr=0.01
        
    Examples 2 (collective, multi node):
        .. code-block:: bash
            :name: code-block-example-bash2

G
Guoxia Wang 已提交
538 539 540
            # The parameters of --gpus and --ips must be consistent in each node.

            # For training on multiple nodes, e.g., 192.168.0.16, 192.168.0.17 
G
Guoxia Wang 已提交
541 542 543 544 545 546 547 548 549 550 551 552

            # On 192.168.0.16:

            python -m paddle.distributed.launch --gpus=0,1,2,3 --ips=192.168.0.16,192.168.0.17 train.py --lr=0.01

            # On 192.168.0.17:
            python -m paddle.distributed.launch --gpus=0,1,2,3 --ips=192.168.0.16,192.168.0.17 train.py --lr=0.01
        
    Examples 3 (ps, cpu, single node):
        .. code-block:: bash
            :name: code-block-example-bash3

G
Guoxia Wang 已提交
553
            # To simulate distributed environment using single node, e.g., 2 servers and 4 workers.
G
Guoxia Wang 已提交
554 555 556 557 558 559 560
            
            python -m paddle.distributed.launch --server_num=2 --worker_num=4 train.py --lr=0.01
        
    Examples 4 (ps, cpu, multi node):
        .. code-block:: bash
            :name: code-block-example-bash4

G
Guoxia Wang 已提交
561
            # For training on multiple nodes, e.g., 192.168.0.16, 192.168.0.17 where each node with 1 server and 2 workers.
G
Guoxia Wang 已提交
562 563 564 565 566 567 568 569 570 571 572 573 574

            # On 192.168.0.16:

            python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.16:6172,192.168.0.17:6171,192.168.0.17:6172" train.py --lr=0.01

            # On 192.168.0.17:

            python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.16:6172,192.168.0.17:6171,192.168.0.17:6172" train.py --lr=0.01

    Examples 5 (ps, gpu, single node):
        .. code-block:: bash
            :name: code-block-example-bash5

G
Guoxia Wang 已提交
575
           # To simulate distributed environment using single node, e.g., 2 servers and 4 workers, each worker use single gpu.
G
Guoxia Wang 已提交
576 577 578 579 580 581 582 583
            
            export CUDA_VISIBLE_DEVICES=0,1,2,3
            python -m paddle.distributed.launch --server_num=2 --worker_num=4 train.py --lr=0.01
            
    Examples 6 (ps, gpu, multi node):
        .. code-block:: bash
            :name: code-block-example-bash6

G
Guoxia Wang 已提交
584
            # For training on multiple nodes, e.g., 192.168.0.16, 192.168.0.17 where each node with 1 server and 2 workers.
G
Guoxia Wang 已提交
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599

            # On 192.168.0.16:

            export CUDA_VISIBLE_DEVICES=0,1
            python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.16:6172,192.168.0.17:6171,192.168.0.17:6172" train.py --lr=0.01

            # On 192.168.0.17:

            export CUDA_VISIBLE_DEVICES=0,1
            python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.16:6172,192.168.0.17:6171,192.168.0.17:6172" train.py --lr=0.01

    Examples 7 (ps-heter, cpu + gpu, single node):
        .. code-block:: bash
            :name: code-block-example-bash7

G
Guoxia Wang 已提交
600
            # To simulate distributed environment using single node, e.g., 2 servers and 4 workers, two workers use gpu, two workers use cpu.
G
Guoxia Wang 已提交
601 602 603 604 605 606 607 608
            
            export CUDA_VISIBLE_DEVICES=0,1
            python -m paddle.distributed.launch --server_num=2 --worker_num=2 --heter_worker_num=2 train.py --lr=0.01
            
    Examples 8 (ps-heter, cpu + gpu, multi node):
        .. code-block:: bash
            :name: code-block-example-bash8

G
Guoxia Wang 已提交
609
            # For training on multiple nodes, e.g., 192.168.0.16, 192.168.0.17 where each node with 1 server, 1 gpu worker, 1 cpu worker.
G
Guoxia Wang 已提交
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628

            # On 192.168.0.16:

            export CUDA_VISIBLE_DEVICES=0
            python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.17:6171" --heter_workers="192.168.0.16:6172,192.168.0.17:6172" train.py --lr=0.01

            # On 192.168.0.17:

            export CUDA_VISIBLE_DEVICES=0
            python -m paddle.distributed.launch --servers="192.168.0.16:6170,192.168.0.17:6170" --workers="192.168.0.16:6171,192.168.0.17:6171" --heter_workers="192.168.0.16:6172,192.168.0.17:6172" train.py --lr=0.01

    Examples 9 (elastic):
        .. code-block:: bash
            :name: code-block-example-bash9

            python -m paddle.distributed.launch --elastic_server=127.0.0.1:2379 --np=2 --job_id=job1  --gpus=0,1,2,3 train.py
        
    """

629 630 631 632
    args = _parse_args()
    logger = get_logger()
    _print_arguments(args)

X
xiongkun 已提交
633
    if args.backend == 'auto':
634 635
        distribute_mode = which_distributed_mode(
            args)  # which_distributed_mode must modify args.backend
X
xiongkun 已提交
636 637 638 639 640
    else:
        assert args.run_mode == 'collective' or args.run_mode == None, "When backend is not 'auto', run mode must be collective"
        check_backend(args.backend)
        distribute_mode = DistributeMode.COLLECTIVE

641 642
    assert args.backend in ['gloo', 'nccl', 'bkcl', 'unknown']

X
xiongkun 已提交
643 644
    if args.backend == 'gloo':
        logger.warning("launch start with CPUONLY mode")
645

646 647 648
    block_windows_and_macos(
        args.backend)  # raise error when using gloo on windows or macos

K
kuizhiqing 已提交
649 650 651
    if enable_elastic(args, distribute_mode):
        launch_elastic(args, distribute_mode)
        return
652

K
kuizhiqing 已提交
653 654
    if distribute_mode == DistributeMode.COLLECTIVE:
        launch_collective(args)
655
    else:
K
kuizhiqing 已提交
656
        launch_ps(args, distribute_mode)
657 658 659 660


if __name__ == "__main__":
    launch()