launch.py 29.9 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
                your_training_py (arg1 arg2 and all others)
"""

57 58 59
import copy
import os
import pathlib
60
import shutil
61
import sys
62
import tempfile
63
import time
64 65
from argparse import REMAINDER, ArgumentParser

66
from paddle import framework
67 68
from paddle.distributed.fleet import ascend_utils, cloud_utils, launch_utils
from paddle.distributed.fleet.elastic import enable_elastic, launch_elastic
69
from paddle.distributed.fleet.launch_utils import (
70 71 72 73
    DeviceMode,
    DistributeMode,
    ParameterServerLauncher,
    block_windows_and_macos,
74 75 76 77 78 79 80 81 82 83
    check_backend,
    direct_start,
    find_free_ports,
    get_cluster,
    get_host_name_ip,
    get_logger,
    logger,
    start_local_trainers,
    terminate_local_procs,
    watch_local_trainers,
84
)
85

86 87
__all__ = []

88 89 90

def _print_arguments(args):
    print("-----------  Configuration Arguments -----------")
91
    for arg, value in sorted(vars(args).items()):
92 93 94 95 96 97 98 99 100 101 102 103
        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-
104 105
'''
    )
106
    base_group = parser.add_argument_group("Base Parameters")
107

108 109
    base_group.add_argument(
        "--log_dir",
110
        type=str,
111
        default="log",
112 113
        help="The path for each process's log. Default --log_dir=log/",
    )
X
xiongkun 已提交
114 115 116
    base_group.add_argument(
        "--backend",
        type=str,
K
kuizhiqing 已提交
117 118
        default=os.environ.get('PADDLE_DISTRI_BACKEND', 'auto'),
        help="Specifize the backend, can be gloo|nccl|bkcl|auto|hccl|heter. "
119 120
        "Default value is auto which perfers nccl or bkcl.",
    )
121 122 123 124 125 126
    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"
127 128
        " bound to one or average number of gpus.",
    )
129

130 131 132
    base_group.add_argument(
        "--run_mode",
        type=str,
G
gongweibao 已提交
133
        default=None,
134 135
        help="run mode of job, can be:collective/ps/ps-heter",
    )
136

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

148
    if framework.core.is_compiled_with_xpu():
149 150 151 152 153
        base_group.add_argument(
            "--xpus",
            type=str,
            default=None,
            help="It's for xpu training. For example: "
154
            "--xpus=\"0,1,2,3\" will launch four training processes each bound to one xpu.",
155 156
        )
        base_group.add_argument("--selected_xpus", dest="xpus")
157

158
    if framework.core.is_compiled_with_npu():
K
kuizhiqing 已提交
159 160 161 162 163
        base_group.add_argument(
            "--npus",
            type=str,
            default=None,
            help="It's for xpu training. For example: "
164
            "--npus=\"0,1,2,3\" will launch four training processes each bound to one npu.",
K
kuizhiqing 已提交
165 166 167
        )
        base_group.add_argument("--selected_npus", dest="npus")

168
    if framework.core.is_compiled_with_mlu():
Z
zn 已提交
169 170 171 172 173
        base_group.add_argument(
            "--mlus",
            type=str,
            default=None,
            help="It's for mlu training. For example: "
174
            "--mlus=\"0,1,2,3\" will launch four training processes each bound to one mlu.",
Z
zn 已提交
175 176 177
        )
        base_group.add_argument("--selected_mlus", dest="mlus")

178 179 180 181 182 183 184 185
    base_group.add_argument(
        "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",
    )
186

187 188 189 190 191 192 193 194 195
    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",
196 197
        help="Paddle cluster nodes ips, such as 192.168.0.16,192.168.0.17..",
    )
198
    collective_group.add_argument(
199 200 201 202
        "--cluster_topo_path",
        type=str,
        default=None,
        help="A json format file will be stored in this path which is used"
203 204
        "to represent the cluster topology information for auto parallel.",
    )
205 206 207 208 209
    collective_group.add_argument(
        "--rank_mapping_path",
        type=str,
        default=None,
        help="A json format file will be stored in this path which is used"
210 211
        "to map processes to machines for auto parallel.",
    )
212 213 214 215
    collective_group.add_argument(
        "--enable_auto_mapping",
        type=bool,
        default=False,
216 217
        help="Set true to enable the lazy launch for auto-parallel scenario.",
    )
218 219 220

    ps_group = parser.add_argument_group("Parameter-Server Parameters")
    # for parameter server
221 222 223 224 225 226 227 228 229 230 231 232
    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(
        "--coordinators",
        type=str,
        default="",
        help="User defined coordinators ip:port",
    )
233 234 235 236
    ps_group.add_argument(
        "--heter_workers",
        type=str,
        default="",
237 238
        help="User defined heter workers in each stage ip1:port1;ip2:port2",
    )
239 240 241 242
    ps_group.add_argument(
        "--heter_devices",
        type=str,
        default="",
243 244
        help="User defined heter devices in each stage cpu;gpu;cpu",
    )
245 246

    ps_group.add_argument("--worker_num", type=int, help="number of workers")
247 248 249
    ps_group.add_argument(
        "--coordinator_num", type=int, help="number of coordinators"
    )
250
    ps_group.add_argument("--server_num", type=int, help="number of servers")
251 252 253 254 255
    ps_group.add_argument(
        "--heter_worker_num",
        type=str,
        help="number of heter_workers in each stage 1;2;3",
    )
256
    ps_group.add_argument("--http_port", type=int, help="Gloo http Port")
257

258 259
    # parameter elastic mode
    elastic_group = parser.add_argument_group("Elastic Parameters")
260 261 262 263 264 265
    elastic_group.add_argument(
        "--elastic_server", type=str, help="etcd server host:port"
    )
    elastic_group.add_argument(
        "--elastic_pre_hook", type=str, help="elastic pre_hook shell cmd"
    )
266

267 268 269
    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")
270 271 272 273 274 275
    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"
    )
276

K
kuizhiqing 已提交
277 278
    known_args, _ = parser.parse_known_args()
    return known_args
279 280


281
def get_cluster_from_args(args, device_mode, devices_per_proc):
282 283 284 285
    node_ips = [x.strip() for x in args.ips.split(',')]
    if len(node_ips) == 1:
        node_ip = node_ips[0]
    else:
286 287 288 289
        if args.host:
            node_ip = args.host
        else:
            _, node_ip = get_host_name_ip()
290

291 292 293
    assert (
        node_ip in node_ips
    ), "Can't find your local ip {%s} in node_ips: {%s}" % (node_ip, node_ips)
294 295
    node_rank = node_ips.index(node_ip)

296 297 298 299 300
    logger.debug(
        "parsed from args: node_ips:{} node_ip:{} node_rank:{}".format(
            node_ips, node_ip, node_rank
        )
    )
301 302

    free_ports = None
303 304 305 306 307
    if (
        not cloud_utils.use_paddlecloud()
        and len(node_ips) <= 1
        and os.environ.get('FLAGS_START_PORT') is None
    ):
308
        free_ports = find_free_ports(len(devices_per_proc))
309 310
        if free_ports is not None:
            free_ports = list(free_ports)
G
gongweibao 已提交
311
            logger.info("find free ports:{}".format(free_ports))
312 313 314
    else:
        start_port = 6070
        if os.environ.get('FLAGS_START_PORT') is not None:
315
            start_port = int(os.environ.get('FLAGS_START_PORT'))
316

317
        free_ports = list(range(start_port, start_port + len(devices_per_proc)))
318

319 320 321
    trainer_endpoints = []
    for ip in node_ips:
        trainer_endpoints.append(["%s:%d" % (ip, port) for port in free_ports])
322 323 324
    return get_cluster(
        node_ips, node_ip, trainer_endpoints, device_mode, devices_per_proc
    )
325 326


X
xiongkun 已提交
327 328 329 330
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."
331 332
            % args.ips
        )
X
xiongkun 已提交
333
    if args.run_mode:
334 335 336
        assert (
            args.run_mode == 'cpuonly'
        ), "CPUONLY launch only support run mode is CPUONLY"
X
xiongkun 已提交
337 338 339 340 341
    if args.servers:
        raise RuntimeError("CPUONLY launch can't have --servers as arguments.")
    return True


342
def get_cluster_info(args):
K
kuizhiqing 已提交
343
    # parse arguments, used for cloud-single-machine and local
344 345
    if args.backend == 'gloo':
        cpuonly_check(args)
346 347 348
    if args.enable_auto_mapping:
        (device_mode, devices_per_proc) = (DeviceMode.GPU, [])
    else:
349 350 351
        (device_mode, devices_per_proc) = launch_utils.get_device_proc_info(
            args
        )
K
kuizhiqing 已提交
352
    trainers_num = cloud_utils.get_trainers_num()
353 354 355 356 357
    logger.debug(
        "parsed from args trainerss_num:{} mode:{} devices:{}".format(
            trainers_num, device_mode, devices_per_proc
        )
    )
K
kuizhiqing 已提交
358

359 360
    cuda_visible_devices = os.getenv("CUDA_VISIBLE_DEVICES")

K
kuizhiqing 已提交
361 362 363 364 365 366
    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')
367
    # auto mapping between processes and devices for auto-parallel
368
    if args.enable_auto_mapping:
369 370 371
        assert (
            args.cluster_topo_path is not None
        ), "The cluster topology must be provied when enabling auto mapping."
372
        rank_mapping_path = args.rank_mapping_path or os.getenv(
373 374
            "PADDLE_RANK_MAPPING_PATH"
        )
375 376 377
        if not rank_mapping_path:
            os.environ["PADDLE_NEED_RANK_MAPPING"] = str(True)
            os.environ["PADDLE_ENABLE_ELASTIC"] = str(
378 379
                enable_elastic(args, device_mode)
            )
380
            cwd = pathlib.Path().resolve()
381 382 383
            rank_mapping_path = os.path.join(
                cwd, "auto_parallel_rank_mapping.json"
            )
384 385 386 387 388 389
            os.environ["PADDLE_RANK_MAPPING_PATH"] = str(rank_mapping_path)

            original_args = sys.argv[1:]
            os.environ["PADDLE_ORIGINAL_CMD_ARGS"] = " ".join(original_args)
            os.environ["PADDLE_CLUSTER_TOPO_PATH"] = str(args.cluster_topo_path)
            os.environ["PADDLE_ENABLE_AUTO_MAPPING"] = str(
390 391 392 393 394 395 396 397
                args.enable_auto_mapping
            )
            (
                cluster,
                pod,
            ) = launch_utils.get_mapped_cluster_from_args_without_rank_mapping(
                args, device_mode
            )
398 399 400
        else:
            os.environ["PADDLE_NEED_RANK_MAPPING"] = str(False)
            os.environ["PADDLE_ENABLE_ELASTIC"] = str(
401 402
                enable_elastic(args, device_mode)
            )
403 404 405 406

            os.environ["PADDLE_CLUSTER_TOPO_PATH"] = str(args.cluster_topo_path)
            os.environ["PADDLE_RANK_MAPPING_PATH"] = str(rank_mapping_path)
            os.environ["PADDLE_ENABLE_AUTO_MAPPING"] = str(
407 408 409 410 411 412 413 414
                args.enable_auto_mapping
            )
            (
                cluster,
                pod,
            ) = launch_utils.get_mapped_cluster_from_args_with_rank_mapping(
                args, device_mode
            )
K
kuizhiqing 已提交
415
    elif cloud_utils.use_paddlecloud() and trainers_num != 1:
416 417 418
        cluster, pod = cloud_utils.get_cloud_cluster(
            args.ips, device_mode, devices_per_proc, start_port
        )
K
kuizhiqing 已提交
419 420
        logger.debug("get cluster from cloud:{}".format(cluster))
    elif device_mode == DeviceMode.ASCEND_NPU:
421
        # for ascend
422 423 424 425 426
        cluster, pod = ascend_utils.get_cloud_cluster(
            rank_table_file=os.getenv("RANK_TABLE_FILE", None),
            device_mode=device_mode,
            start_port=start_port,
        )
K
kuizhiqing 已提交
427 428
    else:
        # trainers_num = 1 or not use paddlecloud ips="a,b"
429 430 431
        cluster, pod = get_cluster_from_args(
            args, device_mode, devices_per_proc
        )
K
kuizhiqing 已提交
432
        logger.debug("get cluster from args:{}".format(cluster))
433 434
    return cluster, pod

435

436
def get_global_envs(args, tmp_dir):
K
kuizhiqing 已提交
437 438 439 440
    global_envs = copy.copy(os.environ.copy())
    # add gloo env
    global_envs["PADDLE_WITH_GLOO"] = str(os.getenv("PADDLE_WITH_GLOO", "0"))
    global_envs["PADDLE_GLOO_RENDEZVOUS"] = "3"
441
    global_envs["PADDLE_GLOO_FS_PATH"] = tmp_dir
X
xiongkun 已提交
442
    global_envs["PADDLE_DISTRI_BACKEND"] = args.backend
443 444 445 446 447 448 449
    return global_envs


def launch_collective(args):
    tmp_dir = tempfile.mkdtemp()
    cluster, pod = get_cluster_info(args)
    global_envs = get_global_envs(args, tmp_dir)
K
kuizhiqing 已提交
450

451 452 453 454 455 456 457 458
    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,
    )
K
kuizhiqing 已提交
459 460 461

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

K
kuizhiqing 已提交
463
    while True:
K
kuizhiqing 已提交
464 465
        try:
            alive = watch_local_trainers(procs, cluster.trainers_nranks())
466

K
kuizhiqing 已提交
467 468 469 470
            if not alive:
                logger.info("Local processes completed.")
                logger.debug("POD info:{}".format(pod))
                break
471

K
kuizhiqing 已提交
472 473 474 475 476
            time.sleep(3)

        except:
            logger.warning("Terminating... exit")
            terminate_local_procs(procs)
477
            sys.exit(1)
K
kuizhiqing 已提交
478

479 480
    if os.path.exists(tmp_dir):
        shutil.rmtree(tmp_dir)
481

482

483 484 485 486 487 488 489
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
490
    # elif cloud_flag and distribute_mode == DistributeMode.PS_HETER:
491 492 493 494
    #    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")
495 496 497 498 499 500

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


501
def infer_backend(args):
502 503
    if args.backend != "auto":
        return
504
    if framework.core.is_compiled_with_cuda():
505
        args.backend = 'nccl'
506
    elif framework.core.is_compiled_with_npu():
507
        args.backend = 'unknown'
508
    elif framework.core.is_compiled_with_xpu():
509
        args.backend = 'bkcl'
510
    elif framework.core.is_compiled_with_mlu():
Z
zn 已提交
511
        args.backend = 'cncl'
512 513 514 515
    else:
        args.backend = 'gloo'


516
def which_distributed_mode(args):
517
    infer_backend(args)  # modify the args.backend
518 519 520 521 522 523 524 525 526 527
    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

528
    ps_args = [
529 530 531 532 533 534 535 536
        '--worker_num',
        '--server_num',
        '--heter_worker_num',
        '--servers',
        '--workers',
        '--heter_workers',
        '--heter_devices',
        '--http_port',
537
    ]
538
    collective_args = ['--ips']
539

540
    ps_heter_args = ["--heter_worker_num", "--heter_workers", "--heter_devices"]
541

542 543
    coordinator_args = ["--coordinator_num", "--coordinators"]

544 545 546 547
    has_ps_args = [
        ps_arg for ps_arg in ps_args if ps_arg in " ".join(sys.argv[1:-1])
    ]
    has_collective_args = [
548 549
        co_arg
        for co_arg in collective_args
550 551
        if co_arg in " ".join(sys.argv[1:-1])
    ]
552 553 554 555 556 557

    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."
        )

558 559 560 561 562 563 564 565
    if framework.core.is_compiled_with_cuda():
        accelerators = framework.core.get_cuda_device_count()
    elif framework.core.is_compiled_with_npu():
        accelerators = framework.core.get_npu_device_count()
    elif framework.core.is_compiled_with_xpu():
        accelerators = framework.core.get_xpu_device_count()
    elif framework.core.is_compiled_with_mlu():
        accelerators = framework.core.get_mlu_device_count()
566
    else:
567
        accelerators = 0
568

569 570
    if len(has_ps_args) > 0:
        logger.info(
571 572 573 574
            "Run parameter-sever mode. pserver arguments:{}, accelerators count:{}".format(
                has_ps_args, accelerators
            )
        )
575
        has_ps_heter_args = list(set(has_ps_args) & set(ps_heter_args))
576
        has_coordinator_args = list(set(has_ps_args) & set(coordinator_args))
577 578 579 580
        if len(has_ps_heter_args) > 0:
            return DistributeMode.PS_HETER
        else:
            return DistributeMode.PS
581
    elif len(has_collective_args) > 0:
582 583
        logger.info(
            "Run collective mode. gpu arguments:{}, cuda count:{}".format(
584 585 586
                has_collective_args, accelerators
            )
        )
587
        return DistributeMode.COLLECTIVE
588
    else:
589
        if (
590 591 592
            not framework.core.is_compiled_with_cuda()
            and not framework.core.is_compiled_with_xpu()
            and not framework.core.is_compiled_with_mlu()
593
        ):
X
xiongkun 已提交
594 595
            if args.servers:
                logger.warning(
Z
zn 已提交
596
                    "Not found distinct arguments and not compiled with cuda or xpu or npu or mlu. "
597 598
                    "But found args.servers not empty, default use ps mode"
                )
X
xiongkun 已提交
599 600 601
                return DistributeMode.PS
            else:
                return DistributeMode.COLLECTIVE
602 603
        else:
            logger.warning(
Z
zn 已提交
604
                "Not found distinct arguments and compiled with cuda or xpu or npu or mlu. "
605 606
                "Default use collective mode"
            )
607
            return DistributeMode.COLLECTIVE
608 609 610


def launch():
G
Guoxia Wang 已提交
611 612
    """
    Paddle distribution training entry ``python -m paddle.distributed.launch``.
613

G
Guoxia Wang 已提交
614 615 616 617 618 619 620 621 622
    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]
623
                             training_script ...
G
Guoxia Wang 已提交
624 625 626


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

G
Guoxia Wang 已提交
629
        - ``--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 已提交
630

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

G
Guoxia Wang 已提交
633
        - ``--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 已提交
634 635

        - ``--selected_gpus``: gpus aliases, recommend to use ``--gpus``.
636

G
Guoxia Wang 已提交
637
        - ``--xpus``: It's for xpu training if xpu is available. e.g., ``--xpus=0,1,2,3``.
638

G
Guoxia Wang 已提交
639 640
        - ``--selected_xpus``: xpus aliases, recommend to use ``--xpus``.

Z
zn 已提交
641 642 643 644
        - ``--mlus``: It's for mlu training. e.g., ``--mlus=0,1,2,3`` will launch four training processes each bound to one mlu.

        - ``--selected_mlus``: mlus aliases, recommend to use ``--mlus``.

645
        - ``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., ``training.py``
G
Guoxia Wang 已提交
646

G
Guoxia Wang 已提交
647
        - ``training_script_args``: The args of training_script. e.g., ``--lr=0.1``
G
Guoxia Wang 已提交
648 649

    Collective Parameters:
G
Guoxia Wang 已提交
650
        - ``--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 已提交
651 652

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

G
Guoxia Wang 已提交
655
        - ``--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 已提交
656

657
        - ``--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 已提交
658 659 660 661 662

        - ``--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)

663
        - ``--heter_worker_num``: Number of heter_workers in each stage (It recommend to set when in the emulated distributed environment using single node)
664

665
        - ``--heter_devices``: Type of heter_device in each stage
G
Guoxia Wang 已提交
666 667 668 669

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

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

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

G
Guoxia Wang 已提交
674
        - ``--np``: job pod/node number, e.g., ``--np=2``
G
Guoxia Wang 已提交
675 676 677 678 679 680 681 682 683 684

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


    Returns:
        ``None``

    Examples 1 (collective, single node):
        .. code-block:: bash
            :name: code-block-example-bash1
685

G
Guoxia Wang 已提交
686
            # For training on single node using 4 gpus.
G
Guoxia Wang 已提交
687 688

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

G
Guoxia Wang 已提交
690 691 692 693
    Examples 2 (collective, multi node):
        .. code-block:: bash
            :name: code-block-example-bash2

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

696
            # For training on multiple nodes, e.g., 192.168.0.16, 192.168.0.17
G
Guoxia Wang 已提交
697 698 699 700 701 702 703

            # 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
704

G
Guoxia Wang 已提交
705 706 707 708
    Examples 3 (ps, cpu, single node):
        .. code-block:: bash
            :name: code-block-example-bash3

G
Guoxia Wang 已提交
709
            # To simulate distributed environment using single node, e.g., 2 servers and 4 workers.
710

G
Guoxia Wang 已提交
711
            python -m paddle.distributed.launch --server_num=2 --worker_num=4 train.py --lr=0.01
712

G
Guoxia Wang 已提交
713 714 715 716
    Examples 4 (ps, cpu, multi node):
        .. code-block:: bash
            :name: code-block-example-bash4

G
Guoxia Wang 已提交
717
            # 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 已提交
718 719 720 721 722 723 724 725 726 727 728 729 730

            # 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 已提交
731
           # To simulate distributed environment using single node, e.g., 2 servers and 4 workers, each worker use single gpu.
732

G
Guoxia Wang 已提交
733 734
            export CUDA_VISIBLE_DEVICES=0,1,2,3
            python -m paddle.distributed.launch --server_num=2 --worker_num=4 train.py --lr=0.01
735

G
Guoxia Wang 已提交
736 737 738 739
    Examples 6 (ps, gpu, multi node):
        .. code-block:: bash
            :name: code-block-example-bash6

G
Guoxia Wang 已提交
740
            # 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 已提交
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755

            # 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 已提交
756
            # To simulate distributed environment using single node, e.g., 2 servers and 4 workers, two workers use gpu, two workers use cpu.
757

G
Guoxia Wang 已提交
758 759
            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
760

G
Guoxia Wang 已提交
761 762 763 764
    Examples 8 (ps-heter, cpu + gpu, multi node):
        .. code-block:: bash
            :name: code-block-example-bash8

G
Guoxia Wang 已提交
765
            # 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 已提交
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781

            # 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
782

G
Guoxia Wang 已提交
783 784
    """

785 786 787 788
    args = _parse_args()
    logger = get_logger()
    _print_arguments(args)

X
xiongkun 已提交
789
    if args.backend == 'auto':
790
        distribute_mode = which_distributed_mode(
791 792
            args
        )  # which_distributed_mode must modify args.backend
X
xiongkun 已提交
793
    else:
794
        assert (
795
            args.run_mode == 'collective' or args.run_mode is None
796
        ), "When backend is not 'auto', run mode must be collective"
X
xiongkun 已提交
797 798 799
        check_backend(args.backend)
        distribute_mode = DistributeMode.COLLECTIVE

800
    # assert args.backend in ['gloo', 'nccl', 'bkcl', 'cncl', 'heter', 'unknown']
801

X
xiongkun 已提交
802 803
    if args.backend == 'gloo':
        logger.warning("launch start with CPUONLY mode")
804

805
    block_windows_and_macos(
806 807
        args.backend
    )  # raise error when using gloo on windows or macos
808

K
kuizhiqing 已提交
809 810 811
    if enable_elastic(args, distribute_mode):
        launch_elastic(args, distribute_mode)
        return
812

K
kuizhiqing 已提交
813 814
    if distribute_mode == DistributeMode.COLLECTIVE:
        launch_collective(args)
815
    else:
K
kuizhiqing 已提交
816
        launch_ps(args, distribute_mode)
817 818 819 820


if __name__ == "__main__":
    launch()