role_maker.py 40.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2020 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.
"""Defination of Role Makers."""
15
import os
16
import time
17
import numpy as np
18
import warnings
19
from multiprocessing import Process, Manager
20

21
import paddle
22
import paddle.fluid as fluid
23 24 25
from paddle.distributed.fleet.base.private_helper_function import (
    wait_server_ready,
)
26

27 28
__all__ = []

29 30 31 32

class Role:
    WORKER = 1
    SERVER = 2
33
    HETER_WORKER = 3
34
    ALL = 4
35
    COORDINATOR = 5
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53


class Gloo(object):
    """
    Gloo is a universal class for barrier and collective communication
    """

    class RENDEZVOUS:
        HDFS = 1
        FILE = 2
        HTTP = 3

    def __init__(self):
        self._worker_comm = None
        self._server_comm = None
        self._nodes_comm = None

        self._comm_world = ["worker", "server", "all"]
54 55 56
        self._err_init = (
            "gloo is not initialized, will not communicator with other nodes"
        )
57 58
        self._err_type = "gloo initialized error, please check arguments"
        self._err_world = "argument error, comm_world must in {}".format(
59 60
            self._comm_world
        )
61 62 63 64 65 66 67 68 69 70 71 72 73 74

        self._is_initialized = False
        self._init_timeout_seconds = 3600
        self._run_timeout_seconds = 9999999

        self._rendezvous = None
        self._role = None
        self._iface = None

        self._role_id = -1
        self._worker_num = -1
        self._server_num = -1
        self._need_init_all = False

75 76 77 78 79 80 81 82 83 84
    def init(
        self,
        rendezvous,
        role,
        role_id,
        worker_num,
        server_num,
        need_init_all=False,
        kwargs=None,
    ):
85 86 87 88 89 90 91

        self._rendezvous = rendezvous
        self._role = role
        self._role_id = role_id
        self._worker_num = worker_num
        self._server_num = server_num
        self._need_init_all = need_init_all
92
        self._iface = ""
93 94
        self._prefix = kwargs.get("store.prefix", "")

95
        http_server = None
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
        if self._rendezvous == Gloo.RENDEZVOUS.HDFS:
            dfs_name = kwargs.get("dfs.name", "")
            dfs_ugi = kwargs.get("dfs.ugi", "")
            dfs_path = kwargs.get("dfs.path", "")

            if not dfs_name or not dfs_ugi or not dfs_path:
                raise ValueError(self._err_type)
            self._init_dfs(dfs_name, dfs_ugi, dfs_path, self._prefix)

        elif self._rendezvous == Gloo.RENDEZVOUS.FILE:
            fs_path = kwargs.get("dfs.path", "")

            if not fs_path:
                raise ValueError(self._err_type)
            self._init_fs(fs_path, self._prefix)

        elif self._rendezvous == Gloo.RENDEZVOUS.HTTP:
            ip = kwargs.get("http.host", "")
            port = kwargs.get("http.port", "")
115 116
            start_http_server = kwargs.get("start_http_server", False)
            http_server_d = kwargs.get("http_server_d")
117 118 119

            if not ip or not port:
                raise ValueError(self._err_type)
120 121 122
            http_server = self._init_http(
                ip, port, self._prefix, start_http_server, http_server_d
            )
123 124 125 126
        else:
            raise ValueError(self._err_type)

        self._is_initialized = True
127
        self._http_server = http_server
128 129 130 131 132 133 134 135

    def _init_fs(self, fs_path, prefix):
        def init(rank, nodes, role):
            gloo = fluid.core.Gloo()
            gloo.set_rank(rank)
            gloo.set_size(nodes)
            gloo.set_prefix(prefix)
            gloo.set_iface(self._iface)
136 137 138
            gloo.set_timeout_seconds(
                self._init_timeout_seconds, self._run_timeout_seconds
            )
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
            gloo.set_hdfs_store(os.path.join(fs_path, role), "", "")
            gloo.init()
            return gloo

        if self._role == Role.WORKER:
            rank, nodes = self._get_rank_nodes(Role.WORKER)
            gloo = init(rank, nodes, "WORKER")
            self._worker_comm = gloo
        else:
            rank, nodes = self._get_rank_nodes(Role.SERVER)
            gloo = init(rank, nodes, "SERVER")
            self._server_comm = gloo

        if self._need_init_all:
            rank, nodes = self._get_rank_nodes(Role.ALL)
            gloo = init(rank, nodes, "ALL")
            self._nodes_comm = gloo

    def _init_dfs(self, dfs_name, dfs_ugi, dfs_path, prefix):
        def init(rank, nodes, role):
            gloo = fluid.core.Gloo()
            gloo.set_rank(rank)
            gloo.set_size(nodes)
            gloo.set_prefix(prefix)
            gloo.set_iface(self._iface)
164 165 166
            gloo.set_timeout_seconds(
                self._init_timeout_seconds, self._run_timeout_seconds
            )
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
            gloo.set_hdfs_store(os.path.join(dfs_path, role), dfs_name, dfs_ugi)
            gloo.init()
            return gloo

        if self._role == Role.WORKER:
            rank, nodes = self._get_rank_nodes(Role.WORKER)
            gloo = init(rank, nodes, "WORKER")
            self._worker_comm = gloo
        else:
            rank, nodes = self._get_rank_nodes(Role.SERVER)
            gloo = init(rank, nodes, "SERVER")
            self._server_comm = gloo

        if self._need_init_all:
            rank, nodes = self._get_rank_nodes(Role.ALL)
            gloo = init(rank, nodes, "ALL")
            self._nodes_comm = gloo

185
    def _init_http(self, ip, port, prefix, start_http_server, http_server_d):
186
        def __start_kv_server(http_server_d, size_d):
187
            print("start http_server: {}, {}".format(port, size_d))
188
            from paddle.distributed.fleet.utils.http_server import KVServer
189

190 191 192
            http_server = KVServer(port, size_d)
            http_server.start()
            wait_seconds = 5
193 194 195 196
            while (
                http_server_d.get("running", False)
                or not http_server.should_stop()
            ):
197 198 199
                time.sleep(wait_seconds)
            http_server.stop()

200
        def init_kv_server(http_server_d):
201
            worker_key = prefix + '_' + 'worker'
202 203 204
            size_d = {
                worker_key: self._worker_num,
            }
205
            print("worker_key:{}, size: {}".format(worker_key, size_d))
206

207
            http_server_d["running"] = True
208
            # child process for http server
209 210 211
            _http_server = Process(
                target=__start_kv_server, args=(http_server_d, size_d)
            )
212 213 214 215
            _http_server.daemon = True
            # set running status to True
            # start child process
            _http_server.start()
216
            return _http_server
217 218 219 220 221 222 223

        def init(rank, nodes, role):
            gloo = fluid.core.Gloo()
            gloo.set_rank(rank)
            gloo.set_size(nodes)
            gloo.set_prefix(prefix)
            gloo.set_iface(self._iface)
224 225 226
            gloo.set_timeout_seconds(
                self._init_timeout_seconds, self._run_timeout_seconds
            )
227
            gloo.set_http_store(ip, port, 'worker')
228 229 230
            ep = ":".join([ip, str(port)])
            wait_server_ready([ep])
            gloo.init()
231 232 233 234
            return gloo

        port = int(port)

235
        if start_http_server:
236
            print("to start http_server")
237
            http_server = init_kv_server(http_server_d)
238 239 240 241 242

        if self._role == Role.WORKER:
            rank, nodes = self._get_rank_nodes(Role.WORKER)
            gloo = init(rank, nodes, "WORKER")
            self._worker_comm = gloo
L
lilong12 已提交
243
        # TODO (sandyhouse): initialize gloo for server and all
244

245
        # the closing of kv server may cause gloo init failure
K
kuizhiqing 已提交
246 247 248 249 250 251 252
        # since it depend on the full mesh connection
        # e.g. 0 connected with 1,2,3 while 2-3 not connected yet
        # TODO(kuizhiqing)
        if start_http_server:
            http_server_d["running"] = False
            http_server.join()

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    def _get_rank_nodes(self, role):
        nodes = 0
        rank = -1

        if role == Role.WORKER:
            nodes = self._worker_num
            rank = self._role_id
        elif role == Role.SERVER:
            nodes = self._server_num
            rank = self._role_id
        elif role == Role.ALL:
            nodes = self._worker_num + self._server_num

            if self._role == Role.WORKER:
                rank = self._role_id
            else:
                rank = self._worker_num + self._role_id
        else:
            ValueError(self._err_type)

        return rank, nodes

    def __get_default_iface(self):
        """
        get default physical interface
        """
        default1 = self.__get_default_iface_from_gateway()
        default2 = self.__get_default_iface_from_interfaces()
        return default2 if default1 == "lo" else default1

    def __get_default_iface_from_gateway(self):
        """
        get default physical interface
        """
1
123malin 已提交
287 288 289 290 291 292 293 294 295
        res = os.popen("route -A inet").read().strip().split("\n")

        gateway_idx = None
        iface_idx = None
        for item in res:
            item = item.split()
            if "Gateway" in item and "Iface" in item:
                gateway_idx = item.index("Gateway")
                iface_idx = item.index("Iface")
296
            elif gateway_idx is not None and iface_idx is not None:
1
123malin 已提交
297 298 299
                gateway = None
                if len(item) > gateway_idx:
                    gateway = item[gateway_idx]
300 301 302 303 304 305
                if (
                    gateway
                    and gateway != '*'
                    and gateway != "0.0.0.0"
                    and len(item) > iface_idx
                ):
1
123malin 已提交
306
                    return item[iface_idx]
307 308 309 310 311 312
        return "lo"

    def __get_default_iface_from_interfaces(self):
        """
        get default physical interface
        """
313 314 315
        res = (
            os.popen("ip -f inet addr | awk NR%3==1").read().strip().split("\n")
        )
1
123malin 已提交
316 317 318
        for item in res:
            if "BROADCAST" in item:
                return item.split(":")[1].strip()
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
        return "lo"

    def barrier(self, comm_world):
        """
        dummy barrier, do nothing
        """
        if not self._is_initialized:
            warnings.warn(self._err_init)
            return

        if comm_world not in self._comm_world:
            raise ValueError(self._err_world)

        if comm_world == "worker":
            self._worker_comm.barrier()
        elif comm_world == "server":
            self._server_comm.barrier()
        else:
            self._nodes_comm.barrier()

    def all_reduce(self, input, mode="sum", comm_world="worker"):
        if not self._is_initialized:
            warnings.warn(self._err_init)
            return input

        if comm_world not in self._comm_world:
            raise ValueError(self._err_world)

        input = np.array(input)
        input_shape = input.shape
        input_list = input.reshape(-1).tolist()

        self.barrier(comm_world)

        if comm_world == "worker":
            ans = self._worker_comm.all_reduce(input_list, mode)
        elif comm_world == "server":
            ans = self._server_comm.all_reduce(input_list, mode)
        else:
            ans = self._nodes_comm.all_reduce(input_list, mode)

        output = np.array(ans).reshape(input_shape)
        return output

    def all_gather(self, input, comm_world="worker"):
        """
        dummy all gather, do nothing
        Args:
            obj(any): obj to do all gather
        """
        if not self._is_initialized:
            warnings.warn(self._err_init)
            return input

        if comm_world not in self._comm_world:
            raise ValueError(self._err_world)

        if comm_world == "worker":
            output = self._worker_comm.all_gather(input)
        elif comm_world == "server":
            output = self._server_comm.all_gather(input)
        else:
            output = self._nodes_comm.all_gather(input)

        return output
384 385 386 387 388 389 390 391 392 393 394 395 396


class RoleMakerBase(object):
    """
    RoleMakerBase is a base class for assigning a role to current process
    in distributed training.
    A paddle developer can implement RoleMakerBase to design a role maker
    for worker or pserver assignment.
    """

    def __init__(self):
        self._worker_endpoints = []
        self._server_endpoints = []
397
        self._cur_endpoint = ""
398 399 400 401
        self._role_is_generated = False
        self._role = None
        self._current_id = -1

402
    def _is_worker(self):
403 404 405 406 407
        """
        return is_worker() of current process
        """
        raise NotImplementedError("Please implement this method in child class")

408
    def _is_server(self):
409 410 411 412 413
        """
        return is_server() of current process
        """
        raise NotImplementedError("Please implement this method in child class")

414
    def _is_first_worker(self):
415 416 417 418 419 420 421 422
        """
        Check whether the node is the first instance of worker.
        Returns:
            bool: True if this is the first node of worker,
                  False if not.
        """
        raise NotImplementedError("Please implement this method in child class")

423
    def _worker_num(self):
424 425 426 427 428 429 430 431
        """
        Get current total worker number.

        Returns:
            int: worker number
        """
        raise NotImplementedError("Please implement this method in child class")

432
    def _server_num(self):
433 434 435 436 437 438 439 440
        """
        Get current total server number.

        Returns:
            int: server number
        """
        raise NotImplementedError("Please implement this method in child class")

441
    def _worker_index(self):
442 443 444 445 446 447 448 449
        """
        Get current worker id.

        Returns:
            int: node id
        """
        raise NotImplementedError("Please implement this method in child class")

450
    def _server_index(self):
451 452 453 454 455 456 457 458
        """
        Get current server id.

        Returns:
            int: node id
        """
        raise NotImplementedError("Please implement this method in child class")

459
    def _role_id(self):
460 461 462 463 464 465 466 467
        """
        Get current id.

        Returns:
            int: node id
        """
        raise NotImplementedError("Please implement this method in child class")

468
    def _node_num(self):
469 470 471 472 473 474 475
        """
        Get the training node number
        Returns:
            int: node num
        """
        raise NotImplementedError("Please implement this method in child class")

476
    def _get_trainer_endpoints(self):
477 478 479 480 481
        """
        return trainer endpoints
        """
        return self._worker_endpoints

482
    def _get_pserver_endpoints(self):
483 484 485 486 487 488 489
        """
        return pserver endpoints
        """
        return self._server_endpoints

    def to_string(self):
        return "role: {}, current_id: {}, worker_endpoints: {}, server_endpoints: {}".format(
490 491 492 493 494
            self._role,
            self._current_id,
            self._worker_endpoints,
            self._server_endpoints,
        )
495

496 497
    def _all_gather(self, input, comm_world="worker"):
        print("warning: RoleMakerBase does not have all gather worker.")
498 499
        return None

500
    def _all_reduce(self, input, mode="sum", comm_world="worker"):
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
        """
        Args:
            input(list/numpy.array): array of one dim
            output(list/numpy.array): array of one dim
            mode(str): "sum" or "min" or "max"
        """
        print("warning: RoleMakerBase does not have all reduce worker.")
        return None

    def _barrier(self, comm_world):
        """
        barrier between trainers if current role is TRAINER
        """
        print("warning: RoleMakerBase does not have barrier worker.")

516
    # def _is_heter_worker(self):
517 518 519 520 521
    #    """
    #    Return is_heter_worker() of current process
    #    """
    #    raise NotImplementedError("Please implement this method in child class")

522
    # def _heter_worker_num(self):
523 524 525 526 527 528 529 530
    #    """
    #    Get current total heter-worker number.
    #
    #    Returns:
    #        int: heter_worker number
    #    """
    #    raise NotImplementedError("Please implement this method in child class")

531
    # def _get_heter_worker_endpoints(self):
532 533 534 535 536 537
    #    """
    #    Returns:
    #        string: all heter_trainers'endpoints
    #    """
    #    raise NotImplementedError("Please implement this method in child class")

538
    # def _get_heter_worker_endpoint(self):
539 540 541 542 543
    #    """
    #    Returns:
    #        int: corresponding heter_trainer's endpoint
    #    """
    #    raise NotImplementedError("Please implement this method in child class")
544

545 546

class PaddleCloudRoleMaker(RoleMakerBase):
547
    def __init__(self, is_collective=False, **kwargs):
548 549
        super(PaddleCloudRoleMaker, self).__init__()
        self._is_collective = is_collective
550 551 552
        self._non_distributed = False

        self._kwargs = kwargs
553 554
        self._role_is_generated = False

555
        # for heterps
556 557 558 559 560
        self._stage_id = 1
        self._stage_num = 1
        self._next_heter_trainer_endpoints = []
        self._previous_heter_trainer_endpoints = []
        self._heter_trainer_endpoints = []
561 562
        self._heter_trainer_device = "cpu"
        self._heter_trainer_device_type = "cpu"
563 564 565
        self._is_heter_parameter_server_mode = False
        self._stage_trainers = []

566 567
        self._server_endpoints = []
        self._worker_endpoints = []
568 569
        self._coordinator_endpoints = None
        self._with_coordinator = False
570

571
        self._gloo = Gloo()  # gloo instance
572 573

    def _barrier(self, comm_world):
574
        self._gloo.barrier(comm_world)
575

576 577
    def _all_gather(self, input, comm_world="worker"):
        return self._gloo.all_gather(input, comm_world)
578

579 580
    def _all_reduce(self, input, mode="sum", comm_world="worker"):
        return self._gloo.all_reduce(input, mode, comm_world)
581

582 583 584 585 586 587 588 589
    def _heter_device(self):
        """
        return the heter device that current heter worker is using
        """
        if not self._role_is_generated:
            self._generate_role()
        return self._heter_trainer_device

590 591 592 593 594 595
    def _heter_device_type(self):
        """
        return the heter device type that current heter worker is using
        """
        if not self._role_is_generated:
            self._generate_role()
596
        return self._heter_trainer_device_type
597 598 599

    def _get_stage_id(self):
        """
600 601
        return stage id of current heter worker
        """
602 603 604 605 606 607
        if not self._role_is_generated:
            self._generate_role()
        return self._stage_id

    def _get_stage_trainers(self):
        """
608 609
        return trainer num of all stages
        """
610 611 612 613 614 615
        if not self._role_is_generated:
            self._generate_role()
        return self._stage_trainers

    def _get_num_stage(self):
        """
616 617
        return stage num
        """
618 619 620 621
        if not self._role_is_generated:
            self._generate_role()
        return self._stage_num

622
    def _is_worker(self):
623 624 625 626
        """
        whether current process is worker
        """
        if not self._role_is_generated:
627
            self._generate_role()
628 629
        return self._role == Role.WORKER

630
    def _is_server(self):
631 632 633 634
        """
        whether current process is server
        """
        if not self._role_is_generated:
635
            self._generate_role()
636 637
        return self._role == Role.SERVER

638 639 640 641 642
    def _is_coordinator(self):
        if not self._role_is_generated:
            self._generate_role()
        return self._role == Role.COORDINATOR

643
    def _is_first_worker(self):
644 645 646 647
        """
        whether current process is worker of rank 0
        """
        if not self._role_is_generated:
648
            self._generate_role()
649 650
        return self._role == Role.WORKER and self._current_id == 0

651
    def _worker_index(self):
652 653 654 655
        """
        get index of current worker
        """
        if not self._role_is_generated:
656
            self._generate_role()
657 658
        return self._current_id

659
    def _server_index(self):
660 661 662 663
        """
        get index of current server
        """
        if not self._role_is_generated:
664
            self._generate_role()
665 666
        return self._current_id

667
    def _role_id(self):
668 669 670
        """
        get index of current node
        """
671 672
        if not self._role_is_generated:
            self._generate_role()
673
        return self._current_id
674

675
    def _worker_num(self):
676 677 678 679
        """
        retrun the current number of worker
        """
        if not self._role_is_generated:
680
            self._generate_role()
681 682
        return self._trainers_num

683
    def _server_num(self):
684 685 686 687
        """
        return the current number of server
        """
        if not self._role_is_generated:
688
            self._generate_role()
689 690 691 692 693
        return (
            len(self._get_pserver_endpoints())
            if self._get_pserver_endpoints() is not None
            else 0
        )
694

695
    def _node_num(self):
696 697 698 699
        """
        return the training node number
        """
        if not self._role_is_generated:
700 701
            self._generate_role()
        return self._nodes_num
702

703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
    def _get_node_num(self):
        """
        return the training node number
        """
        if not self._role_is_generated:
            self._generate_role()
        return self._nodes_num

    def _get_local_rank(self):
        if not self._role_is_generated:
            self._generate_role()
        return self._local_rank

    def _get_local_device_ids(self):
        if not self._role_is_generated:
            self._generate_role()
        return self._local_device_ids

    def _get_world_device_ids(self):
        if not self._role_is_generated:
            self._generate_role()
        return self._world_device_ids

726
    def _get_trainer_endpoints(self):
727 728 729 730
        """
        get endpoint of all trainers
        """
        if not self._role_is_generated:
731
            self._generate_role()
732 733
        return self._worker_endpoints

734 735 736
    def _get_trainer_endpoint(self):
        if not self._role_is_generated:
            self._generate_role()
737 738 739
        assert (
            self._role == Role.WORKER
        ), "get_trainer_endpoint should be called by trainer"
740 741 742 743 744 745 746 747 748
        return self._cur_endpoint

    def _get_heter_worker_endpoints(self):
        """
        Returns:
            string: all heter_trainers'endpoints
        """
        if not self._role_is_generated:
            self._generate_role()
749 750 751
        assert (
            self._heter_trainer_endpoints != []
        ), "Heter Worker Endpoints Not initialized"
752 753 754 755 756 757 758 759 760
        return self._heter_trainer_endpoints

    def _get_heter_worker_endpoint(self):
        """
        Returns:
            int: corresponding heter_trainer's endpoint
        """
        if not self._role_is_generated:
            self._generate_role()
761 762 763
        assert (
            self._role == Role.HETER_WORKER
        ), "_get_heter_worker_endpoint should be invoked by heter worker"
764 765
        return self._cur_endpoint

766
    def _get_pserver_endpoints(self):
767 768 769 770
        """
        get endpoint of all pservers
        """
        if not self._role_is_generated:
771
            self._generate_role()
772 773
        return self._server_endpoints

774 775 776 777 778
    def _get_coordinator_endpoints(self):
        if not self._role_is_generated:
            self._generate_role()
        return self._coordinator_endpoints

779 780
    def _get_previous_trainers(self):
        """
781
        invoked by heter worker
782 783 784 785
        """
        if not self._role_is_generated:
            self._generate_role()
        assert self._role in (
786 787
            Role.WORKER,
            Role.HETER_WORKER,
788 789 790 791 792
        ), "_get_previous_trainers should be invoked by trainer or heter worker"
        return self._previous_heter_trainer_endpoints

    def _get_next_trainers(self):
        """
793
        invoked by heter worker
794 795 796 797
        """
        if not self._role_is_generated:
            self._generate_role()
        assert self._role in (
798 799
            Role.WORKER,
            Role.HETER_WORKER,
800 801 802
        ), "_get_next_trainers should be invoked by trainer or heter worker"
        return self._next_heter_trainer_endpoints

803 804 805 806 807 808
    def _is_non_distributed(self):
        """
        Return True if indispensable environment for fleetrun is not found
        (use python-run to launch fleet-code directly)
        """
        if not self._role_is_generated:
809
            self._generate_role()
810 811
        return self._non_distributed

812 813 814 815 816
    def _heter_worker_num(self):
        """
        get heter worker nums
        """
        if not self._role_is_generated:
817
            self._generate_role()
818 819 820 821 822 823 824
        return self._heter_trainers_num

    def _is_heter_worker(self):
        """
        whether current process is heter worker
        """
        if not self._role_is_generated:
825
            self._generate_role()
826 827
        return self._role == Role.HETER_WORKER

828
    def _ps_env(self):  # each role will execute it
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
        # Environment variable PADDLE_PSERVERS_IP_PORT_LIST must be set
        # format: string(ip:port,ip:port), eg. 127.0.0.1:6001,127.0.0.1:6002
        self._server_endpoints = os.getenv("PADDLE_PSERVERS_IP_PORT_LIST", None)

        if self._server_endpoints is None:
            # back to non_distributed execution.
            self._server_endpoints = ""
            self._trainers_num = 1
            self._role = Role.WORKER
            self._current_id = 0
            self._nodes_num = 1
            self._heter_trainers_num = 0
            self._heter_trainer_endpoints = None
            self._non_distributed = True
            return
844

845 846 847
        self._server_endpoints = self._server_endpoints.split(",")

        self._worker_endpoints = os.getenv("PADDLE_TRAINER_ENDPOINTS", None)
848
        if self._worker_endpoints is not None:
849 850 851 852
            self._worker_endpoints = self._worker_endpoints.split(",")
        else:
            self._worker_endpoints = []

853 854 855
        self._coordinator_endpoints = os.getenv(
            "PADDLE_COORDINATOR_ENDPOINTS", ""
        )
856 857 858 859 860 861
        if self._coordinator_endpoints == "":
            print("fl-ps > coordinator address is null!")
        else:
            self._with_coordinator = True
            self._coordinator_endpoints = self._coordinator_endpoints.split(",")

862
        trainers_num = os.getenv("PADDLE_TRAINERS_NUM", None)
863
        if trainers_num is None:
864 865 866 867 868 869
            raise ValueError(
                "Can not find PADDLE_TRAINERS_NUM, please check your environment."
            )
        trainers_num = int(trainers_num)

        training_role = os.getenv("TRAINING_ROLE", None)
870
        if training_role is None:
871
            raise ValueError(
872 873
                "Can not find TRAINING_ROLE, please check your environment."
            )
874

875
        if training_role not in [
876 877 878 879
            "TRAINER",
            "PSERVER",
            "HETER_TRAINER",
            "COORDINATOR",
880
        ]:
881
            raise ValueError(
882 883 884 885
                "TRAINING_ROLE must be PSERVER or TRAINER or HETER_TRAINER or COORDINATOR, but get {}, please check your environment.".format(
                    training_role
                )
            )
886

887 888
        # For Heter Parameter Server env setting
        next_heter_trainer_eplist = os.getenv(
889 890
            "PADDLE_NEXT_HETER_TRAINER_IP_PORT_LIST", ""
        )
891
        previous_heter_trainer_eplist = os.getenv(
892 893
            "PADDLE_PREVIOUS_HETER_TRAINER_IP_PORT_LIST", ""
        )
894
        all_heter_trainer_eplist = os.getenv(
895 896
            "PADDLE_ALL_HETER_TRAINER_IP_PORT_LIST", ""
        )
897

898 899
        if all_heter_trainer_eplist != "":
            self._heter_trainer_endpoints = all_heter_trainer_eplist.split(",")
900
            self._is_heter_parameter_server_mode = True
901 902 903 904
            self._heter_trainers_num = len(self._heter_trainer_endpoints)

            if previous_heter_trainer_eplist == "":
                assert training_role in (
905
                    "TRAINER",
906 907
                    "PSERVER",
                ), "training_role should be trainer or pserver"
908 909
            else:
                try:
910 911 912
                    self._previous_heter_trainer_endpoints = (
                        previous_heter_trainer_eplist.split(",")
                    )
913 914 915 916 917 918 919
                except:
                    raise ValueError(
                        "Can not Find PADDLE_PREVIOUS_HETER_TRAINER_IP_PORT_LIST in env or its format doesn't match the requirement: 'IP:PORT,IP:PORT' ."
                    )

            if next_heter_trainer_eplist == "":
                assert training_role in (
920 921
                    "HETER_TRAINER",
                    "PSERVER",
922 923 924
                ), "training_role should be heter trainer or pserver"
            else:
                try:
925 926 927
                    self._next_heter_trainer_endpoints = (
                        next_heter_trainer_eplist.split(",")
                    )
928 929 930 931 932
                except:
                    raise ValueError(
                        "Can not Find PADDLE_NEXT_HETER_TRAINER_IP_PORT_LIST in env or its format doesn't match the requirement: 'IP:PORT,IP:PORT' ."
                    )

933 934
        else:
            self._is_heter_parameter_server_mode = False
935 936
            self._heter_trainers_num = 0

937 938 939
        if training_role == "TRAINER":
            role = Role.WORKER
            current_id = os.getenv("PADDLE_TRAINER_ID", None)
940
            if current_id is None:
941
                raise ValueError(
942 943 944
                    "Can not find PADDLE_TRAINER_ID, please check your environment."
                )
            current_id = int(current_id)
945 946
            if self._is_heter_parameter_server_mode:
                self._stage_id = os.getenv("STAGE_ID", None)
947
                if self._stage_id is None:
948
                    raise ValueError(
949 950
                        "Can not find STAGE_ID, please check your environment."
                    )
951 952
                self._stage_id = int(self._stage_id)
                self._stage_num = os.getenv("STAGE_NUM", None)
953
                if self._stage_num is None:
954
                    raise ValueError(
955 956
                        "Can not find STAGE_NUM, please check your environment."
                    )
957
                self._stage_num = int(self._stage_num)
958 959 960
                self._stage_trainers = os.getenv(
                    "PADDLE_STAGE_TRAINERS_NUM", None
                )
961
                if self._stage_trainers is None:
962 963 964 965 966
                    raise ValueError(
                        "Can not find PADDLE_STAGE_TRAINERS_NUM, please check your environment."
                    )
                self._stage_trainers = eval(self._stage_trainers)
            cur_port = os.getenv("PADDLE_PORT", None)
967
            if cur_port is None:
968
                raise ValueError(
969 970
                    "Can not find PADDLE_PORT, please check your environment."
                )
971
            cur_ip = os.getenv("POD_IP", None)
972
            if cur_ip is None:
973
                raise ValueError(
974 975
                    "Can not find POD_IP, please check your environment."
                )
976 977
            curr_endpoint = ":".join([cur_ip, cur_port])
            self._cur_endpoint = curr_endpoint
978 979 980 981
        elif training_role == "COORDINATOR":
            print(">>> curr node is coordinator!")
            role = Role.COORDINATOR
            current_id = int(os.getenv("PADDLE_TRAINER_ID", "0"))
982 983
        elif training_role == "PSERVER":
            role = Role.SERVER
984
            cur_port = os.getenv("PADDLE_PORT", None)
985
            if cur_port is None:
986
                raise ValueError(
987 988
                    "Can not find PADDLE_PORT, please check your environment."
                )
989
            cur_ip = os.getenv("POD_IP", None)
990
            if cur_ip is None:
991
                raise ValueError(
992 993
                    "Can not find POD_IP, please check your environment."
                )
994 995
            curr_endpoint = ":".join([cur_ip, cur_port])
            self._cur_endpoint = curr_endpoint
996 997 998
            current_id = self._server_endpoints.index(self._cur_endpoint)
        elif training_role == "HETER_TRAINER":
            role = Role.HETER_WORKER
999
            self._stage_id = os.getenv("STAGE_ID", None)
1000
            if self._stage_id is None:
1001
                raise ValueError(
1002 1003
                    "Can not find STAGE_ID, please check your environment."
                )
1004 1005
            self._stage_id = int(self._stage_id)
            self._stage_num = os.getenv("STAGE_NUM", None)
1006
            if self._stage_num is None:
1007
                raise ValueError(
1008 1009
                    "Can not find STAGE_NUM, please check your environment."
                )
1010 1011 1012
            self._stage_num = int(self._stage_num)

            self._stage_trainers = os.getenv("PADDLE_STAGE_TRAINERS_NUM", None)
1013
            if self._stage_trainers is None:
1014 1015 1016 1017 1018
                raise ValueError(
                    "Can not find PADDLE_STAGE_TRAINERS_NUM, please check your environment."
                )
            self._stage_trainers = eval(self._stage_trainers)

1019 1020 1021
            self._heter_trainer_device_type = os.getenv(
                "HETER_DEVICE_TYPE", None
            )
1022
            if self._heter_trainer_device_type is None:
1023 1024 1025
                raise ValueError(
                    "Can not find HETER_DEVICE_TYPE, please check your environment."
                )
1026
            assert self._heter_trainer_device_type in (
1027 1028 1029 1030
                "cpu",
                "gpu",
                "xpu",
            ), "HETER_DEVICE_TYPE should be cpu,gpu or xpu"
1031 1032 1033
            if self._heter_trainer_device_type == "gpu":
                heter_device_id = os.getenv("FLAGS_selected_gpus", "0")
                self._heter_trainer_device = ":".join(
1034 1035
                    (self._heter_trainer_device_type, heter_device_id)
                )
1036 1037 1038
            if self._heter_trainer_device == "xpu":
                heter_device_id = os.getenv("FLAGS_selected_xpus", "0")
                self._heter_trainer_device = ":".join(
1039 1040
                    (self._heter_trainer_device_type, heter_device_id)
                )
1041

1042
            cur_port = os.getenv("PADDLE_PORT", None)
1043
            if cur_port is None:
1044
                raise ValueError(
1045 1046
                    "Can not find PADDLE_PORT, please check your environment."
                )
1047
            cur_ip = os.getenv("POD_IP", None)
1048
            if cur_ip is None:
1049
                raise ValueError(
1050 1051
                    "Can not find POD_IP, please check your environment."
                )
1052
            curr_endpoint = ":".join([cur_ip, cur_port])
1053
            self._cur_endpoint = curr_endpoint
1054 1055 1056 1057
            current_id = (
                all_heter_trainer_eplist.split(",").index(curr_endpoint)
                + trainers_num
            )
1058 1059 1060 1061

        self._trainers_num = trainers_num
        self._role = role
        self._current_id = current_id
1062
        self._nodes_num = len(
1063 1064
            set([x.split(':')[0] for x in self._worker_endpoints])
        )
1065 1066 1067 1068

    def _collective_env(self):
        self._current_id = int(os.getenv("PADDLE_TRAINER_ID", "0"))
        self._training_role = os.getenv("PADDLE_TRAINING_ROLE", "TRAINER")
1069
        assert self._training_role == "TRAINER"
1070
        self._role = Role.WORKER
1071 1072
        self._worker_endpoints = os.getenv("PADDLE_TRAINER_ENDPOINTS")
        self._cur_endpoint = os.getenv("PADDLE_CURRENT_ENDPOINT")
1073 1074 1075 1076 1077
        if self._worker_endpoints is None:
            # back to non_distributed execution.
            self._worker_endpoints = "127.0.0.1:6170"
            self._cur_endpoint = self._worker_endpoints
            self._non_distributed = True
1078 1079
        self._worker_endpoints = self._worker_endpoints.split(",")
        self._trainers_num = len(self._worker_endpoints)
1080
        self._nodes_num = len(
1081 1082
            set([x.split(':')[0] for x in self._worker_endpoints])
        )
1083 1084 1085
        self._local_rank = os.getenv("PADDLE_RANK_IN_NODE")
        self._local_device_ids = os.getenv("PADDLE_LOCAL_DEVICE_IDS")
        self._world_device_ids = os.getenv("PADDLE_WORLD_DEVICE_IDS")
1086

1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
    def _gloo_init(self):
        # PADDLE_WITH_GLOO 1: trainer barrier, 2: all barrier
        use_gloo = int(os.getenv("PADDLE_WITH_GLOO", "0"))
        if use_gloo not in [1, 2]:
            return

        # PADDLE_GLOO_RENDEZVOUS 1: HDFS 2: FILE 3: HTTP
        rendezvous_type = int(os.getenv("PADDLE_GLOO_RENDEZVOUS", "0"))
        prefix = os.getenv("SYS_JOB_ID", "")
        if rendezvous_type not in [
1097 1098 1099
            Gloo.RENDEZVOUS.HDFS,
            Gloo.RENDEZVOUS.HTTP,
            Gloo.RENDEZVOUS.FILE,
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
        ]:
            raise ValueError(self._gloo._err_type)

        need_init_all = True if use_gloo == 2 else False

        if rendezvous_type == Gloo.RENDEZVOUS.HDFS:
            dfs_name = os.getenv("PADDLE_GLOO_FS_NAME", "")
            dfs_ugi = os.getenv("PADDLE_GLOO_FS_UGI", "")
            dfs_path = os.getenv("PADDLE_GLOO_FS_PATH", "")
            kwargs = {
                "dfs.name": dfs_name,
                "dfs.ugi": dfs_ugi,
                "dfs.path": dfs_path,
                "store.prefix": prefix,
            }
        elif rendezvous_type == Gloo.RENDEZVOUS.HTTP:
1116
            start_http_server = False
1117 1118 1119
            manager = Manager()
            http_server_d = manager.dict()
            http_server_d["running"] = False
1120 1121 1122 1123 1124
            if self._is_collective:
                ep_rank_0 = self._worker_endpoints[0]
                if self._is_first_worker():
                    start_http_server = True
            else:
1125
                ep_rank_0 = os.getenv("PADDLE_GLOO_HTTP_ENDPOINT", "")
1126
                if self._is_server() and self._server_index() == 0:
1127 1128
                    start_http_server = True
            ip, port = ep_rank_0.split(':')
1129 1130 1131 1132
            kwargs = {
                "http.host": ip,
                "http.port": port,
                "store.prefix": prefix,
1133
                'start_http_server': start_http_server,
1134
                'http_server_d': http_server_d,
1135
            }
1136
        else:
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
            dfs_path = os.getenv("PADDLE_GLOO_FS_PATH", "")
            kwargs = {
                "dfs.path": dfs_path,
                "store.prefix": prefix,
            }

        if rendezvous_type == Gloo.RENDEZVOUS.HDFS:
            type = "HDFS"
        elif rendezvous_type == Gloo.RENDEZVOUS.HTTP:
            type = "HTTP"
        else:
            type = "FILE"
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
        print(
            "Gloo init with {}: need_init_all: {}, args: {}".format(
                type, need_init_all, kwargs
            )
        )

        self._gloo.init(
            rendezvous=rendezvous_type,
            role=self._role,
            role_id=self._role_id(),
            worker_num=self._worker_num(),
            server_num=self._server_num(),
            need_init_all=need_init_all,
            kwargs=kwargs,
        )
1164

1165 1166 1167
        if rendezvous_type == Gloo.RENDEZVOUS.HTTP:
            http_server_d['running'] = False

1168
    def _generate_role(self):
1169 1170 1171 1172 1173 1174 1175 1176 1177
        """
        generate role for role maker
        """
        if not self._role_is_generated:
            if not self._is_collective:
                self._ps_env()
            else:
                self._collective_env()
            self._role_is_generated = True
J
Jiabin Yang 已提交
1178
            if not paddle.fluid.framework._non_static_mode():
1179
                self._gloo_init()
1180 1181 1182 1183


class UserDefinedRoleMaker(PaddleCloudRoleMaker):
    def __init__(self, is_collective=False, init_gloo=False, **kwargs):
1184 1185 1186
        super(UserDefinedRoleMaker, self).__init__(
            is_collective=is_collective, init_gloo=init_gloo, **kwargs
        )
1187
        self._init_gloo = init_gloo
1188 1189 1190 1191 1192 1193 1194

    def _user_defined_ps_env(self):
        self._server_endpoints = self._kwargs.get("server_endpoints")
        self._worker_endpoints = self._kwargs.get("worker_endpoints", [])
        self._trainers_num = self._kwargs.get("worker_num", 0)

        if self._trainers_num == 0:
1195
            assert len(self._worker_endpoints) > 0
1196 1197 1198 1199 1200
            self._trainers_num = len(self._worker_endpoints)

        self._role = self._kwargs.get("role")
        self._current_id = self._kwargs.get("current_id")

1201 1202 1203 1204
        if (
            self._role == Role.WORKER
            and len(self._worker_endpoints) > self._current_id
        ):
1205 1206 1207
            self._cur_endpoint = self._worker_endpoints[self._current_id]
        elif self._role == Role.SERVER:
            self._cur_endpoint = self._server_endpoints[self._current_id]
1208
        self._nodes_num = len(
1209 1210
            set([x.split(':')[0] for x in self._worker_endpoints])
        )
1211 1212 1213 1214 1215

    def _user_defined_collective_env(self):
        self._worker_endpoints = self._kwargs.get("worker_endpoints")
        self._current_id = self._kwargs.get("current_id")
        self._trainers_num = len(self._worker_endpoints)
1216
        self._training_role = Role.WORKER
1217
        self._nodes_num = len(
1218 1219
            set([x.split(':')[0] for x in self._worker_endpoints])
        )
1220

1221
    def _generate_role(self):
1222 1223 1224 1225 1226 1227 1228 1229 1230
        """
        generate role for role maker
        """
        if not self._role_is_generated:
            if not self._is_collective:
                self._user_defined_ps_env()
            else:
                self._user_defined_collective_env()
            self._role_is_generated = True